Logfile.pm 40 KB

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