Logfile.pm 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972
  1. package Pisg::Parser::Logfile;
  2. # Copyright and license, as well as documentation(POD) for this module is
  3. # found at the end of the file.
  4. use strict;
  5. $^W = 1;
  6. # the log cache
  7. use Data::Dumper;
  8. $Data::Dumper::Indent = 1;
  9. my $cache;
  10. # test for Text::Iconv
  11. my $have_iconv = 1;
  12. eval 'use Text::Iconv';
  13. $have_iconv = 0 if $@;
  14. sub new
  15. {
  16. my $type = shift;
  17. my $self = shift; # get cfg and users
  18. # Import common functions in Pisg::Common
  19. require Pisg::Common;
  20. Pisg::Common->import();
  21. bless($self, $type);
  22. # Pick our parser.
  23. $self->{parser} = $self->_choose_format($self->{cfg}->{format});
  24. if($self->{cfg}->{logcharsetfallback} and not $self->{cfg}->{logcharset}) {
  25. print "LogCharset undefined, assuming LogCharset = LogCharsetFallback\n"
  26. unless ($self->{cfg}->{silent});
  27. $self->{cfg}->{logcharset} = $self->{cfg}->{logcharsetfallback};
  28. }
  29. if($self->{cfg}->{logcharset}) {
  30. if($have_iconv) {
  31. # use converter if charsets differ or there is a fallback charset
  32. # (in the latter case the converter is also used to test if the
  33. # line is in the proper charset)
  34. if(($self->{cfg}->{logcharset} ne $self->{cfg}->{charset}) or $self->{cfg}->{logcharsetfallback}) {
  35. $self->{iconv} = Text::Iconv->new($self->{cfg}->{logcharset}, $self->{cfg}->{charset});
  36. }
  37. if($self->{cfg}->{logcharsetfallback}) {
  38. $self->{iconvfallback} = Text::Iconv->new($self->{cfg}->{logcharsetfallback}, $self->{cfg}->{charset});
  39. }
  40. } else {
  41. print "Text::Iconv is not installed, skipping charset conversion of logfiles\n"
  42. unless ($self->{cfg}->{silent});
  43. }
  44. }
  45. # precompile the regexps used (we can't use /o since the config might be different per channel)
  46. $self->{foulwords_regexp} = qr/($self->{cfg}->{foulwords})/i if $self->{cfg}->{foulwords};
  47. $self->{ignorewords_regexp} = qr/$self->{cfg}->{ignorewords}/i if $self->{cfg}->{ignorewords};
  48. $self->{violentwords_regexp} = qr/^($self->{cfg}->{violentwords}) (\S+)(.*)/i if $self->{cfg}->{violentwords};
  49. $self->{chartsregexp} = qr/^$self->{cfg}->{chartsregexp}/i if $self->{cfg}->{chartsregexp};
  50. return $self;
  51. }
  52. # The function to choose which module to use.
  53. sub _choose_format
  54. {
  55. my $self = shift;
  56. my $format = shift;
  57. $self->{parser} = undef;
  58. eval <<_END;
  59. use lib '$self->{cfg}->{modules_dir}';
  60. use Pisg::Parser::Format::$format;
  61. \$self->{parser} = new Pisg::Parser::Format::$format(
  62. cfg => \$self->{cfg},
  63. );
  64. _END
  65. if ($@) {
  66. print STDERR "Could not load parser for '$format': $@\n";
  67. return undef;
  68. }
  69. return $self->{parser};
  70. }
  71. sub analyze
  72. {
  73. my $self = shift;
  74. unless (defined $self->{parser}) {
  75. print STDERR "Skipping channel '$self->{cfg}->{channel}' due to lack of parser.\n";
  76. return undef
  77. }
  78. my $starttime = time();
  79. my @logfiles = @{$self->{cfg}->{logfile}};
  80. # expand wildcards
  81. @logfiles = map { if(/[\[*?]/) { glob; } else { $_; } } @logfiles;
  82. foreach my $logdir (@{$self->{cfg}->{logdir}}) {
  83. push @logfiles, $self->_parse_dir($logdir); # get all files in dir
  84. }
  85. my $count = @logfiles;
  86. my $shift = 0;
  87. if($self->{cfg}->{nfiles} > 0) { # chop list to maximal length
  88. $shift = @logfiles - $self->{cfg}->{nfiles};
  89. splice(@logfiles, 0, $shift) if $shift > 0;
  90. }
  91. unless ($self->{cfg}->{silent}) {
  92. my $msg = "";
  93. $msg = ", parsing the last $self->{cfg}->{nfiles}" if ($shift > 0);
  94. print "$count logfile(s) found$msg, using $self->{cfg}->{format} format...\n\n"
  95. }
  96. my (%stats, %lines);
  97. %stats = (
  98. oldtime => 24,
  99. days => 0,
  100. lastnick => '',
  101. monocount => 0,
  102. day_lines => [ undef ],
  103. day_times => [ undef ],
  104. parsedlines => 0,
  105. totallines => 0,
  106. );
  107. if ($self->{cfg}->{cachedir} and not -d $self->{cfg}->{cachedir}) {
  108. print STDERR "CacheDir \"$self->{cfg}->{cachedir}\" not found. Skipping caching.\n";
  109. delete $self->{cfg}->{cachedir};
  110. }
  111. foreach my $logfile (@logfiles) {
  112. # Run through the logfile
  113. print "Analyzing log $logfile... " unless ($self->{cfg}->{silent});
  114. my $s = {
  115. oldtime => 24,
  116. days => 0,
  117. firsttime => 0,
  118. lastnick => '',
  119. parsedlines => 0,
  120. totallines => 0,
  121. };
  122. my $l = {};
  123. if ($self->{cfg}->{cachedir} and $self->_read_cache(\$s, \$l, $logfile)) {
  124. # take care of false nicks/words, this only happens with cache
  125. foreach (keys %{$s->{lastvisited}}) {
  126. find_alias($_);
  127. }
  128. } else {
  129. $self->_parse_file($s, $l, $logfile);
  130. if ($self->{cfg}->{cachedir}) {
  131. $self->_update_cache($s, $l, $logfile);
  132. }
  133. }
  134. $self->_merge_stats(\%stats, $s); # merge per-file stats into global stats
  135. $self->_merge_lines(\%lines, $l);
  136. print "$stats{days} days, $stats{parsedlines} lines total\n"
  137. unless ($self->{cfg}->{silent});
  138. }
  139. if ($self->{cfg}->{statsdump}) {
  140. open C, "> $self->{cfg}->{statsdump}" or die "$self->{cfg}->{statsdump}: $!";
  141. print C Data::Dumper->Dump([\%stats, \%lines], ["stats", "lines"]);
  142. close C;
  143. }
  144. $self->_pick_random_lines(\%stats, \%lines);
  145. _uniquify_nicks(\%stats);
  146. my ($sec,$min,$hour) = gmtime(time() - $starttime);
  147. my $processtime = sprintf('%02d hours, %02d minutes and %02d seconds', $hour, $min, $sec);
  148. $stats{processtime}{hours} = sprintf('%02d', $hour);
  149. $stats{processtime}{mins} = sprintf('%02d', $min);
  150. $stats{processtime}{secs} = sprintf('%02d', $sec);
  151. print "Channel analyzed successfully in $processtime on ",
  152. scalar localtime(time()), "\n\n"
  153. unless ($self->{cfg}->{silent});
  154. return \%stats;
  155. }
  156. sub _parse_dir
  157. {
  158. my $self = shift;
  159. my $logdir = shift;
  160. # Add trailing slash when it's not there..
  161. $logdir =~ s/([^\/])$/$1\//;
  162. unless ($self->{cfg}->{silent}) {
  163. print "Looking for logfiles in $logdir...\n\n"
  164. }
  165. my @filesarray;
  166. opendir(LOGDIR, $logdir) or
  167. die("Can't opendir ${logdir}: $!");
  168. unless(@filesarray = grep {
  169. /^[^\.]/ && /^$self->{cfg}->{logprefix}/ && -f "$logdir/$_"
  170. } readdir(LOGDIR)) {
  171. print ("No files in \"$logdir\" matched prefix \"$self->{cfg}->{logprefix}\"\n");
  172. return;
  173. }
  174. closedir(LOGDIR);
  175. if ($self->{cfg}->{logsuffix} ne '') {
  176. my @temparray;
  177. my %months = (
  178. 'jan' => '0',
  179. 'feb' => '1',
  180. 'mar' => '2',
  181. 'apr' => '3',
  182. 'may' => '4',
  183. 'jun' => '5',
  184. 'jul' => '6',
  185. 'aug' => '7',
  186. 'sep' => '8',
  187. 'oct' => '9',
  188. 'nov' => '10',
  189. 'dec' => '11',
  190. );
  191. my ($mreg, $dreg, $yreg) = split(/\|\|/, $self->{cfg}->{logsuffix});
  192. my (@month, @day, @year);
  193. for my $file (@filesarray) {
  194. LOOPSTART:
  195. if ($file =~ /$mreg/) {
  196. my $month = $1;
  197. $month = lc $month;
  198. $month = $months{$month}
  199. if (defined $months{$month});
  200. push @month, $month;
  201. } else {
  202. splice(@filesarray,$#month + 1, 1);
  203. if ($file = $filesarray[$#month + 1]) {
  204. goto LOOPSTART;
  205. } else {
  206. last;
  207. }
  208. }
  209. if ($file =~ /$dreg/) {
  210. push @day, $1;
  211. } else {
  212. splice(@filesarray,$#day + 1, 1);
  213. splice(@month,$#day + 1);
  214. if ($file = $filesarray[$#day + 1]) {
  215. goto LOOPSTART;
  216. } else {
  217. last;
  218. }
  219. }
  220. if ($file =~ /$yreg/) {
  221. push @year, $1;
  222. } else {
  223. splice(@filesarray,$#year + 1, 1);
  224. splice(@month,$#year + 1);
  225. splice(@day,$#year + 1);
  226. if ($file = $filesarray[$#year + 1]) {
  227. goto LOOPSTART;
  228. } else {
  229. last;
  230. }
  231. }
  232. }
  233. @filesarray = @filesarray[ sort {
  234. $year[$a] <=> $year[$b]
  235. ||
  236. $month[$a] <=> $month[$b]
  237. ||
  238. $day[$a] <=> $day[$b]
  239. } 0..$#filesarray ];
  240. } else {
  241. @filesarray = sort {lc($a) cmp lc($b)} @filesarray;
  242. }
  243. return map { "$logdir$_" } @filesarray;
  244. }
  245. # This parses the file...
  246. sub _parse_file
  247. {
  248. my $self = shift;
  249. my ($stats, $lines, $file) = @_;
  250. if ($file =~ /.bz2?$/ && -f $file) {
  251. open (LOGFILE, "bunzip2 -c $file |") or
  252. die("$0: Unable to open logfile($file): $!\n");
  253. } elsif ($file =~ /.gz$/ && -f $file) {
  254. open (LOGFILE, "gunzip -c $file |") or
  255. die("$0: Unable to open logfile($file): $!\n");
  256. } elsif ($file =~ /.xz$/ && -f $file) {
  257. open (LOGFILE, "unxz -c $file |") or
  258. die("$0: Unable to open logfile($file): $!\n");
  259. } else {
  260. open (LOGFILE, $file) or
  261. die("$0: Unable to open logfile($file): $!\n");
  262. }
  263. while(my $line = <LOGFILE>) {
  264. $line = _strip_mirccodes($line);
  265. $line =~ s/\r+$//; # Strip DOS Formatting
  266. if($self->{iconv}) { # iconv is defined only if LogCharset is set
  267. my $line2 = $self->{iconv}->convert($line);
  268. if(not $line2 and $self->{iconvfallback}) {
  269. $line2 = $self->{iconvfallback}->convert($line);
  270. }
  271. if($line2) {
  272. $line = $line2;
  273. } else {
  274. print "Charset conversion failed for '$line'\n"
  275. unless ($self->{cfg}->{silent});
  276. }
  277. }
  278. my $hashref;
  279. # Match normal lines.
  280. if ($hashref = $self->{parser}->normalline($line, $.)) {
  281. my $repeated = 0;
  282. if (defined $hashref->{repeated}) {
  283. $repeated = $hashref->{repeated};
  284. }
  285. my ($hour, $nick, $saying, $i);
  286. for ($i = 0; $i <= $repeated; $i++) {
  287. if ($i > 0) {
  288. $hashref = $self->{parser}->normalline($stats->{lastnormal}, $.);
  289. #Increment number of lines for repeated lines
  290. }
  291. $hour = $self->_adjusttimeoffset($hashref->{hour});
  292. $nick = find_alias($hashref->{nick});
  293. checkname($hashref->{nick}, $nick, $stats) if ($self->{cfg}->{showmostnicks});
  294. $saying = $hashref->{saying};
  295. if ($hour < $stats->{oldtime}) {
  296. $stats->{firsttime} = $hour if $stats->{oldtime} == 24; # save stamp for merging
  297. $stats->{days}++;
  298. @{$stats->{day_times}[$stats->{days}]} = (0, 0, 0, 0);
  299. $stats->{day_lines}->[$stats->{days}] = 0;
  300. }
  301. $stats->{oldtime} = $hour;
  302. if (!is_ignored($nick)) {
  303. $stats->{parsedlines}++;
  304. # Timestamp collecting
  305. $stats->{times}{$hour}++;
  306. $stats->{day_times}[$stats->{days}][int($hour/6)]++;
  307. $stats->{day_lines}->[$stats->{days}]++;
  308. $stats->{lines}{$nick}++;
  309. $stats->{lastvisited}{$nick} = $stats->{days};
  310. $stats->{line_times}{$nick}[int($hour/6)]++;
  311. # Count up monologues
  312. if ($stats->{lastnick} eq $nick) {
  313. $stats->{monocount}++;
  314. if ($stats->{monocount} == 5) {
  315. $stats->{monologues}{$nick}++;
  316. }
  317. } else {
  318. $stats->{monocount} = 0;
  319. }
  320. $stats->{lastnick} = $nick;
  321. my $len = length($saying);
  322. if ($len > $self->{cfg}->{minquote} && $len < $self->{cfg}->{maxquote}) {
  323. push @{ $lines->{sayings}{$nick} }, $saying;
  324. } elsif (!$lines->{sayings}{$nick}) {
  325. # Just fill the users first saying in if he hasn't
  326. # said anything yet, to get rid of empty quotes.
  327. if ($len > $self->{cfg}->{maxquote} - 3) {
  328. push @{ $lines->{sayings}{$nick} }, substr($saying, 0, $self->{cfg}->{maxquote} - 3) . '...';
  329. } else {
  330. push @{ $lines->{sayings}{$nick} }, $saying;
  331. }
  332. }
  333. $stats->{lengths}{$nick} += $len;
  334. $stats->{questions}{$nick}++
  335. if (index($saying, '?') > -1);
  336. $stats->{shouts}{$nick}++
  337. if (index($saying, '!') > -1);
  338. if ($saying !~ /[a-z]/o && $saying =~ /[A-Z]/o) {
  339. # Ignore single smileys on a line. eg. '<user> :P'
  340. if ($saying !~ /^[8;:=][ ^-o]?[)pPD\}\]>]$/o) {
  341. $stats->{allcaps}{$nick}++;
  342. push @{ $lines->{allcaplines}{$nick} }, $line;
  343. }
  344. }
  345. if ($self->{foulwords_regexp} and my @foul = $saying =~ /$self->{foulwords_regexp}/) {
  346. $stats->{foul}{$nick} += scalar @foul;
  347. push @{ $lines->{foullines}{$nick} }, $line;
  348. }
  349. # Who smiles the most?
  350. my $e = '[8;:=%]'; # eyes
  351. my $n = '[-oc*^]'; # nose
  352. # smileys including asian-style (^^ ^_^' ^^; \o/)
  353. if ($saying =~ /(>?$e'?$n[\)pPD\}\]>]|[\(\{\[<]$n'?$e<?|[;:][\)pPD\}\]\>]|\([;:]|\^[_o-]*\^[';]|\\[o.]\/)/o) {
  354. $stats->{smiles}{$nick}++;
  355. $stats->{smileys}{$1}++;
  356. $stats->{smileynicks}{$1} = $nick;
  357. }
  358. # asian frown: ;_;
  359. if ($saying =~ /($e'?$n[\(\[\\\/\{|]|[\)\]\\\/\}|]$n'?$e|[;:][\(\/]|[\)D]:|;_+;|T_+T|-[._]+-)/o and
  360. $saying !~ /\w+:\/\//o) {
  361. $stats->{frowns}{$nick}++;
  362. $stats->{smileys}{$1}++;
  363. $stats->{smileynicks}{$1} = $nick;
  364. }
  365. # require 2 chars (catches C++), nick must not end in [+=-]
  366. if ($saying =~ /^(\S+[^\s+=-])(\+\+|==|--)$/) {
  367. my $thing = lc $1;
  368. my $k = $2 eq "++" ? 1 : ($2 eq "==" ? 0 : -1);
  369. $stats->{karma}{$thing}{$nick} = $k
  370. if $thing =~ /\w\W*?\w/ and !is_ignored($thing) and $thing ne lc($nick);
  371. }
  372. # Find URLs
  373. if (my @urls = match_urls($saying)) {
  374. foreach my $url (@urls) {
  375. if(!url_is_ignored($url)) {
  376. $stats->{urlcounts}{$url}++;
  377. $stats->{urlnicks}{$url} = $nick;
  378. }
  379. }
  380. }
  381. if ($saying =~ /$self->{chartsregexp}/i) {
  382. $self->_charts($stats, $1, $nick);
  383. }
  384. if (my $s = $self->{users}->{sex}{$nick}) {
  385. $stats->{sex_lines}{$s}++;
  386. $stats->{sex_line_times}{$s}[int($hour/6)]++;
  387. }
  388. _parse_words($stats, $saying, $nick, $self->{ignorewords_regexp}, $hour);
  389. } # ignored
  390. } # repeated
  391. $stats->{lastnormal} = $line;
  392. $repeated = 0;
  393. } # normal lines
  394. # Match action lines.
  395. elsif ($hashref = $self->{parser}->actionline($line, $.)) {
  396. $stats->{parsedlines}++;
  397. my ($hour, $nick, $saying);
  398. $hour = $self->_adjusttimeoffset($hashref->{hour});
  399. $nick = find_alias($hashref->{nick});
  400. checkname($hashref->{nick}, $nick, $stats) if ($self->{cfg}->{showmostnicks});
  401. $saying = $hashref->{saying};
  402. if ($hour < $stats->{oldtime}) {
  403. $stats->{firsttime} = $hour if $stats->{oldtime} == 24; # save stamp for merging
  404. $stats->{days}++;
  405. @{$stats->{day_times}[$stats->{days}]} = (0, 0, 0, 0);
  406. $stats->{day_lines}->[$stats->{days}] = 0;
  407. }
  408. $stats->{oldtime} = $hour;
  409. if (!is_ignored($nick)) {
  410. # Timestamp collecting
  411. $stats->{times}{$hour}++;
  412. $stats->{day_times}[$stats->{days}][int($hour/6)]++;
  413. $stats->{day_lines}->[$stats->{days}]++;
  414. $stats->{actions}{$nick}++;
  415. push @{ $lines->{actionlines}{$nick} }, $line;
  416. $stats->{lines}{$nick}++;
  417. $stats->{lastvisited}{$nick} = $stats->{days};
  418. $stats->{line_times}{$nick}[int($hour/6)]++;
  419. if ($self->{violentwords_regexp} and $saying =~ /$self->{violentwords_regexp}/) {
  420. my $victim;
  421. unless ($victim = is_nick($2)) {
  422. foreach my $trynick (split(/\s+/, $3)) {
  423. last if ($victim = is_nick($trynick));
  424. }
  425. unless ($victim) {
  426. $victim = $2;
  427. }
  428. }
  429. if (!is_ignored($victim)) {
  430. $stats->{violence}{$nick}++;
  431. $stats->{attacked}{$victim}++;
  432. push @{ $lines->{violencelines}{$nick} }, $line;
  433. push @{ $lines->{attackedlines}{$victim} }, $line;
  434. }
  435. }
  436. if ($saying =~ /$self->{chartsregexp}/i) {
  437. $self->_charts($stats, $1, $nick);
  438. }
  439. $stats->{lengths}{$nick} += length($saying);
  440. if (my $s = $self->{users}->{sex}{$nick}) {
  441. $stats->{sex_lines}{$s}++;
  442. $stats->{sex_line_times}{$s}[int($hour/6)]++;
  443. }
  444. _parse_words($stats, $saying, $nick, $self->{ignorewords_regexp}, $hour);
  445. } # ignored
  446. } # action lines
  447. # Match *** lines.
  448. elsif (($hashref = $self->{parser}->thirdline($line, $.)) and $hashref->{nick}) {
  449. $stats->{parsedlines}++;
  450. my ($hour, $min, $nick, $kicker, $newtopic, $newmode, $newjoin);
  451. my ($newnick);
  452. $hour = $self->_adjusttimeoffset($hashref->{hour});
  453. $min = $hashref->{min};
  454. $nick = find_alias($hashref->{nick});
  455. checkname($hashref->{nick}, $nick, $stats) if ($self->{cfg}->{showmostnicks});
  456. $kicker = find_alias($hashref->{kicker})
  457. if ($hashref->{kicker});
  458. $newtopic = $hashref->{newtopic};
  459. $newmode = $hashref->{newmode};
  460. $newjoin = $hashref->{newjoin};
  461. $newnick = $hashref->{newnick};
  462. if ($hour < $stats->{oldtime}) {
  463. $stats->{firsttime} = $hour if $stats->{oldtime} == 24; # save stamp for merging
  464. $stats->{days}++;
  465. @{$stats->{day_times}[$stats->{days}]} = (0, 0, 0, 0);
  466. $stats->{day_lines}->[$stats->{days}] = 0;
  467. }
  468. $stats->{oldtime} = $hour;
  469. if (!is_ignored($nick)) {
  470. # Timestamp collecting
  471. $stats->{times}{$hour}++;
  472. $stats->{day_times}[$stats->{days}][int($hour/6)]++;
  473. $stats->{day_lines}->[$stats->{days}]++;
  474. $stats->{lastvisited}{$nick} = $stats->{days};
  475. if (defined($kicker)) {
  476. if (!is_ignored($kicker)) {
  477. $stats->{kicked}{$kicker}++;
  478. $stats->{gotkicked}{$nick}++;
  479. push @{ $lines->{kicklines}{$nick} }, $line;
  480. }
  481. } elsif (defined($newtopic) && $newtopic ne '') {
  482. push @{$stats->{topics}}, {
  483. topic => $newtopic,
  484. nick => $nick,
  485. hour => $hour,
  486. min => $min,
  487. days => $stats->{days},
  488. };
  489. } elsif (defined($newmode)) {
  490. _modechanges($stats, $newmode, $nick);
  491. } elsif (defined($newjoin)) {
  492. $stats->{joins}{$nick}++;
  493. } elsif (defined($newnick) and ($self->{cfg}->{nicktracking} == 1)) {
  494. # Resolve new nick to the correct alias (this will create a hard-alias if it is using a regex)
  495. $newnick = find_alias($newnick);
  496. add_alias($nick, $newnick);
  497. checkname($nick, $newnick, $stats) if ($self->{cfg}->{showmostnicks});
  498. }
  499. }
  500. } # *** lines
  501. unless ($stats->{parsedlines} % 10000) { # keep only recent quotes to save memory
  502. $self->_trim_lines($lines);
  503. }
  504. } # while(my $line = <LOGFILE>)
  505. $self->_trim_lines($lines);
  506. my $wordcount = sqrt(sqrt(keys %{$stats->{wordcounts}})); # remove less frequent words
  507. foreach my $word (keys %{$stats->{wordcounts}}) {
  508. if ($stats->{wordcounts}->{$word} < $wordcount) {
  509. next if defined $stats->{chartcounts}{$word};
  510. delete $stats->{wordcounts}->{$word};
  511. delete $stats->{wordnicks}->{$word};
  512. delete $stats->{word_upcase}->{$word};
  513. }
  514. }
  515. $stats->{totallines} = $.;
  516. close(LOGFILE);
  517. }
  518. sub _modechanges
  519. {
  520. my $stats = shift;
  521. my $newmode = shift;
  522. my $nick = shift;
  523. my (@voice, @halfops, @ops, $plus);
  524. foreach (split(//, $newmode)) {
  525. if ($_ eq 'o') {
  526. $ops[$plus]++;
  527. } elsif ($_ eq 'h') {
  528. $halfops[$plus]++;
  529. } elsif ($_ eq 'v') {
  530. $voice[$plus]++;
  531. } elsif ($_ eq '+') {
  532. $plus = 0;
  533. } elsif ($_ eq '-') {
  534. $plus = 1;
  535. }
  536. }
  537. $stats->{gaveops}{$nick} += $ops[0] if $ops[0];
  538. $stats->{tookops}{$nick} += $ops[1] if $ops[1];
  539. $stats->{gavehalfops}{$nick} += $halfops[0] if $halfops[0];
  540. $stats->{tookhalfops}{$nick} += $halfops[1] if $halfops[1];
  541. $stats->{gavevoice}{$nick} += $voice[0] if $voice[0];
  542. $stats->{tookvoice}{$nick} += $voice[1] if $voice[1];
  543. }
  544. sub _parse_words
  545. {
  546. my ($stats, $saying, $nick, $ignorewords_regexp, $hour) = @_;
  547. # Cache time of day
  548. my $tod = int($hour/6);
  549. foreach my $word (split(/[\s,!?.:;)(\"]+/o, $saying)) {
  550. # ignore if $word is empty
  551. next if $word eq "";
  552. $stats->{words}{$nick}++;
  553. $stats->{word_times}{$nick}[$tod]++;
  554. # remove uninteresting words
  555. next if $ignorewords_regexp and $word =~ m/$ignorewords_regexp/i;
  556. # ignore contractions
  557. next if ($word =~ m/'.{1,2}$/o);
  558. # Also ignore stuff from URLs.
  559. next if ($word =~ m/^https?$|^\/\//o);
  560. my $lcword = lc $word;
  561. $stats->{wordcounts}{$lcword}++;
  562. $stats->{wordnicks}{$lcword} = $nick;
  563. $stats->{word_upcase}{$lcword} ||= $word; # remember first-seen case
  564. }
  565. }
  566. sub _charts
  567. {
  568. my ($self, $stats, $Song, $nick) = @_;
  569. unless (defined $Song) {
  570. warn "Your ChartsRegexp is b0rked. Read the manual! This happened";
  571. return;
  572. }
  573. $Song =~ s/_/ /g;
  574. $Song =~ s/\d+ ?- ?//;
  575. $Song =~ s/\.(mp3|ogg|wma)//ig;
  576. $Song =~ s/\[[^\] ]*\]/ /g; # strip stuff in brackets [44kbps]
  577. $Song =~ s/^ *[^\w]* *| *[^\w]* *$//g;
  578. return unless length $Song;
  579. my $song = lc $Song;
  580. $stats->{word_upcase}{$song} = $Song;
  581. $stats->{chartcounts}{$song}++;
  582. $stats->{chartnicks}{$song} = $nick;
  583. }
  584. sub _trim_lines
  585. {
  586. my ($self, $lines) = @_;
  587. foreach my $n (keys %{$lines->{sayings}}) {
  588. my $x = @{$lines->{sayings}->{$n}};
  589. splice(@{$lines->{sayings}->{$n}}, 0, ($x - 15)) if ($x > 30);
  590. }
  591. foreach my $n (keys %{$lines->{actionlines}}) {
  592. my $x = @{$lines->{actionlines}->{$n}};
  593. splice(@{$lines->{actionlines}->{$n}}, 0, ($x - 15)) if ($x > 30);
  594. }
  595. }
  596. sub _pick_random_lines
  597. {
  598. my ($self, $stats, $lines) = @_;
  599. foreach my $key (keys %{ $lines }) {
  600. foreach my $nick (keys %{ $lines->{$key} }) {
  601. $stats->{$key}{$nick} = $self->_random_line($lines, $key, $nick);
  602. }
  603. }
  604. }
  605. sub _random_line
  606. {
  607. my ($self, $lines, $key, $nick) = @_;
  608. my $count = 0;
  609. my ($random, $out, $out2) = ("", "", "");
  610. #warn "$nick did not say anything" unless @{ $lines->{$key}{$nick} };
  611. while (++$count < 20) {
  612. $random = ${ $lines->{$key}{$nick} }[rand @{ $lines->{$key}{$nick} }];
  613. if (length($random) < $self->{cfg}->{minquote} or length($random) > $self->{cfg}->{maxquote}) {
  614. $out2 = $random; # 2nd best choice
  615. next;
  616. }
  617. next if ($self->{cfg}->{noignoredquotes} and $self->{ignorewords_regexp} and
  618. $random =~ /$self->{ignorewords_regexp}/i);
  619. $out = $random;
  620. }
  621. return $out || $out2;
  622. }
  623. sub _uniquify_nicks {
  624. my ($stats) = @_;
  625. foreach my $word (keys %{ $stats->{wordcounts} }) {
  626. if (my $realnick = lc(is_nick($word))) {
  627. if ($realnick ne $word) { # word is always lc
  628. $stats->{wordcounts}{$realnick} += $stats->{wordcounts}{$word};
  629. $stats->{wordnicks}{$realnick} ||= $stats->{wordnicks}{$word};
  630. $stats->{word_upcase}{$realnick} ||= $stats->{word_upcase}{$word};
  631. delete $stats->{wordcounts}{$word};
  632. delete $stats->{wordnicks}{$word};
  633. delete $stats->{word_upcase}{$word};
  634. }
  635. }
  636. }
  637. }
  638. sub _strip_mirccodes
  639. {
  640. my $line = shift;
  641. # boldcode = chr(2) = oct 001
  642. # colorcode = chr(3) = oct 003
  643. # plaincode = chr(15) = oct 017
  644. # reversecode = chr(22) = oct 026
  645. # underlinecode = chr(31) = oct 037
  646. # Strip mIRC color codes
  647. $line =~ s/\003\d{1,2},\d{1,2}//go;
  648. $line =~ s/\003\d{0,2}//go;
  649. # Strip mIRC bold, plain, reverse and underline codes
  650. $line =~ s/[\002\017\026\037]//go;
  651. return $line;
  652. }
  653. sub checkname {
  654. # This function tracks nickchanges and puts them all in a hash->array,
  655. # so we can show all nicks that a user had later (only works properly
  656. # when nicktracking is enabled)
  657. my ($nick, $newnick, $stats) = @_;
  658. $stats->{nicks}{$newnick}{lc($nick)} = $nick;
  659. }
  660. sub _adjusttimeoffset
  661. {
  662. my ($self, $hour) = @_;
  663. if ($self->{cfg}{timeoffset} != 0) {
  664. # Adjust time
  665. $hour += $self->{cfg}{timeoffset};
  666. $hour = $hour % 24;
  667. }
  668. return sprintf('%02d', $hour);
  669. }
  670. sub _read_cache
  671. {
  672. my ($self, $statsref, $linesref, $logfile) = @_;
  673. my $csum = (split(' ', `cksum $logfile`))[0];
  674. my $cachefile = $logfile;
  675. $cachefile =~ s/[^\w-]/_/g;
  676. $cachefile = "$self->{cfg}->{cachedir}/$cachefile";
  677. return undef unless -e $cachefile;
  678. open C, $cachefile or die "$cachefile: $!";
  679. local $/;
  680. my $str = <C>;
  681. close C;
  682. my ($stats, $lines);
  683. eval $str;
  684. return undef if $stats->{version} and $stats->{version} ne $self->{cfg}->{version};
  685. return undef unless $stats->{logfile} eq $logfile; # the name might be ambigous
  686. return undef if $stats->{logfile_csum} != $csum; # file has changed
  687. print "cached, " unless $self->{cfg}->{silent};
  688. $$statsref = $stats;
  689. $$linesref = $lines;
  690. return 1;
  691. }
  692. sub _update_cache
  693. {
  694. my ($self, $stats, $lines, $logfile) = @_;
  695. my $csum = (split(' ', `cksum $logfile`))[0];
  696. my $cachefile = $logfile;
  697. $cachefile =~ s/[^\w-]/_/g;
  698. $cachefile = "$self->{cfg}->{cachedir}/$cachefile";
  699. #print "Writing cache $cachefile...";
  700. $stats->{logfile} = $logfile;
  701. $stats->{logfile_csum} = $csum;
  702. unless (open C, ">$cachefile") {
  703. die "$cachefile: $!";
  704. }
  705. $stats->{version} = $self->{cfg}->{version};
  706. print C Data::Dumper->Dump([$stats], ["stats"]);
  707. print C Data::Dumper->Dump([$lines], ["lines"]);
  708. close C;
  709. }
  710. sub _merge_stats
  711. {
  712. my ($self, $stats, $s) = @_;
  713. my $days_offset = $stats->{days};
  714. my $days_rollover = $stats->{oldtime} > $s->{firsttime};
  715. $stats->{days} += $s->{days} - 1 + $days_rollover;
  716. foreach my $key (keys %$s) {
  717. #print "$key -> $s->{$key}\n";
  718. if ($key =~ /^(logfile|firsttime|days|version)/) { # don't merge these
  719. next;
  720. } elsif ($key =~ /^(oldtime|lastnick|lastnormal|monocount)$/) { # {key} = int/str: copy
  721. $stats->{$key} = $s->{$key};
  722. } elsif ($key =~ /^(parsedlines|totallines)$/) { # {key} = int: add
  723. $stats->{$key} += $s->{$key};
  724. } elsif ($key =~ /^(wordnicks|word_upcase|urlnicks|chartnicks|smileynicks)$/) { # {key}->{} = str: copy
  725. foreach my $subkey (keys %{$s->{$key}}) {
  726. $stats->{$key}->{$subkey} = $s->{$key}->{$subkey};
  727. }
  728. } elsif ($key =~ /^(nicks|karma)$/) { # {key}->{}->{} = str: copy
  729. foreach my $subkey (keys %{$s->{$key}}) {
  730. foreach my $value (keys %{$s->{$key}->{$subkey}}) {
  731. $stats->{$key}->{$subkey}->{$value} = $s->{$key}->{$subkey}->{$value};
  732. }
  733. }
  734. } elsif ($key =~ /^(word|line|sex_line)_times$/) { # {key}->{}->[] = int: add
  735. foreach my $subkey (keys %{$s->{$key}}) {
  736. foreach my $pos (0 .. @{$s->{$key}->{$subkey}} - 1) {
  737. $stats->{$key}->{$subkey}->[$pos] += $s->{$key}->{$subkey}->[$pos]
  738. if $s->{$key}->{$subkey}->[$pos];
  739. }
  740. }
  741. } elsif ($key eq 'lastvisited') { # {key}->{} = int: copy
  742. foreach my $nick (keys %{$s->{lastvisited}}) {
  743. $stats->{lastvisited}->{$nick} =
  744. $days_offset + $s->{lastvisited}->{$nick} - 1 + $days_rollover;
  745. }
  746. } elsif ($s->{$key} =~ /^HASH/) { # {key}->{} = int: add
  747. foreach my $subkey (keys %{$s->{$key}}) {
  748. die "$key -> $subkey" unless $s->{$key}->{$subkey} =~ /^\d+/; # assert
  749. $stats->{$key}->{$subkey} += $s->{$key}->{$subkey};
  750. }
  751. } elsif ($key =~ /^topics$/) { # {key}->[] = topic hash: append
  752. push @{$stats->{$key}}, map {
  753. my %a = %$_; $a{days} += $days_offset - 1 + $days_rollover; \%a; # make new hash
  754. } @{$s->{$key}};
  755. } elsif ($key =~ /^day_lines$/) { # {key}->[] = int: append
  756. my @list = @{$s->{day_lines}};
  757. die if splice @list, 0, 1; # first element is always undef
  758. unless ($days_rollover) {
  759. $stats->{day_lines}->[$days_offset] += splice @list, 0, 1;
  760. }
  761. push @{$stats->{day_lines}}, @list;
  762. } elsif ($key =~ /^day_times$/) { # {key}->[]->[] = int: append outer list
  763. my @list = @{$s->{day_times}};
  764. die if splice @list, 0, 1;
  765. if (not $days_rollover) {
  766. my @first = @{splice @list, 0, 1};
  767. foreach my $pos (0 .. @first - 1) {
  768. $stats->{day_times}[$days_offset][$pos] += $first[$pos];
  769. }
  770. }
  771. push @{$stats->{day_times}}, map { my @a = @$_; \@a; } @list;
  772. } else {
  773. die "unknown key format $key -> $s->{$key}";
  774. }
  775. }
  776. }
  777. sub _merge_lines
  778. {
  779. my ($self, $lines, $l) = @_;
  780. foreach my $key (keys %$l) { # sayings, actionlines, etc.
  781. foreach my $subkey (keys %{$l->{$key}}) {
  782. push @{$lines->{$key}->{$subkey}}, @{$l->{$key}->{$subkey}};
  783. my $x = @{$lines->{$key}->{$subkey}};
  784. splice(@{$lines->{$key}->{$subkey}}, 0, ($x - 15)) if ($x > 30);
  785. }
  786. }
  787. }
  788. 1;
  789. __END__
  790. =head1 NAME
  791. Pisg::Parser::Logfile - class to parse a normal logfile
  792. =head1 DESCRIPTION
  793. C<Pisg::Parser::Logfile> parses a logfile using the configuration variables set in the 'cfg' option passed to the constructor.
  794. =head1 SYNOPSIS
  795. use Pisg::Parser::Logfile;
  796. $analyzer = new Pisg::Parser::Logfile(
  797. { cfg => $self->{cfg}, users => $self->{users} }
  798. );
  799. =head1 CONSTRUCTOR
  800. =over 4
  801. =item new ( [ OPTIONS ] )
  802. This is the constructor for a new Pisg::Parser::Logfile object.
  803. The first option must be a reference to a hash containing the cfg and users structures.
  804. =back
  805. =head1 AUTHOR
  806. Morten Brix Pedersen <morten@wtf.dk>
  807. Christoph Berg <cb@df7cb.de>
  808. James "HM2K" <james@hm2k.org>
  809. =head1 COPYRIGHT
  810. Copyright (C) 2001-2012 The pisg project. All rights reserved.
  811. This program is free software; you can redistribute it and/or modify it
  812. under the terms of the GPL, license is included with the distribution of
  813. this file.
  814. =cut