MPMinus/Util.pm untested

filter: Statementstmt 0.0% 0 / 135 Branchbran 0.0% 0 / 82 Conditioncond 0.0% 0 / 41 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 29 Podpod 0.0% 0 / 21 totaltotal 0.0% 0 / 308 SCAR 75.0
CC
42
Cov
0%
log
420.0
syslog
132.0
_log_flush
30.0
CRAP 1806.0
1 package MPMinus::Util; # $Id: Util.pm 128 2013-05-08 12:35:26Z minus $
2 use strict;
3
4 =head1 NAME
5
6 MPMinus::Util - Utility functions
7
8 =head1 VERSION
9
10 Version 1.12
11
12 =head1 SYNOPSIS
13
14 use base qw/ MPMinus::Util /;
15
16 =head1 DESCRIPTION
17
18 The module works with the fundamental tools for the configuration mod_perl level
19
20 =over 8
21
22 =item B<exception>
23
24 my $excstat = exception( $message );
25
26 Write exception information to file and sending e-mail messages if its text contains the
27 substring "[SENDMAIL]" and on the flag _errorsendmail_
28
29 $message - Log (exception) message
30
31 =item B<debug>
32
33 my $debugstat = debug( $message, $verbose, $file );
34
35 Write debugging information to file
36
37 $message - Log (debug) message
38
39 $verbose - System information flag. 1 - verbose mode, on / 0 - regular mode, off
40
41 $file - Log file (absolute). Default as: <modperl_root>/mpminus-<prefix>_debug.log.
42 If the flag _syslog_ the value is ignored - the message is written to the Apache logfile.
43
44 It should be noted that if the flag is omitted then the output information _debug_ be ignored.
45
46 =item B<log>
47
48 my $logstat = $m->log( $message, $level, $file, $separator );
49
50 Main logging method
51
52 $message - Log message
53
54 $level - logging level. It may be either a numeric or string value of the form:
55
56 debug -- 0 (default)
57 info -- 1
58 notice -- 2
59 warning -- 3
60 error -- 4
61 crit -- 5
62 alert -- 6
63 emerg -- 7
64 fatal -- 8
65 except -- 9
66
67 $file - Log File (absolute). Default as: <modperl_root>/mpminus-<prefix>_error.log.
68 If the flag _syslog_ the value is ignored - the message is written to the Apache logfile
69
70 $separator - Log-record separator char's string. Default as char(32): ' '
71
72 =item B<log_debug>
73
74 Alias for call: $m->log( $message, 'debug' )
75
76 =item B<log_info>
77
78 Alias for call: $m->log( $message, 'info' )
79
80 =item B<log_notice>
81
82 Alias for call: $m->log( $message, 'notice' )
83
84 =item B<log_warning>
85
86 Alias for call: $m->log( $message, 'warning' )
87
88 =item B<log_warn>
89
90 Alias for call: $m->log( $message, 'warning' )
91
92 =item B<log_error>
93
94 Alias for call: $m->log( $message, 'error' )
95
96 =item B<log_err>
97
98 Alias for call: $m->log( $message, 'error' )
99
100 =item B<log_crit>
101
102 Alias for call: $m->log( $message, 'crit' )
103
104 =item B<log_alert>
105
106 Alias for call: $m->log( $message, 'alert' )
107
108 =item B<log_emerg>
109
110 Alias for call: $m->log( $message, 'emerg' )
111
112 =item B<log_fatal>
113
114 Alias for call: $m->log( $message, 'fatal' )
115
116 =item B<log_except>
117
118 Alias for call: $m->log( $message, 'except' )
119
120 =item B<log_exception>
121
122 Alias for call: $m->log( $message, 'except' )
123
124 =item B<sendmail, send_mail>
125
126 my $sendstatus = $m->sendmail(
127 -to => $m->conf('server_admin'),
128 -cc => 'foo@example.com', ### OPTIONAL
129 -from => sprintf('"%s" <%s>',$m->conf('server_name'),$m->conf('server_admin')),
130 -subject => 'Subject',
131 -message => 'Message',
132
133 # Encoding/Types
134 -type => 'text/plain', ### OPTIONAL
135 -charset => 'windows-1251', ### OPTIONAL
136
137 # Program sendmail
138 -sendmail => '/usr/sbin/sendmail',### OPTIONAL
139 -flags => '-t', ### OPTIONAL
140
141 # SMTP
142 -smtp => ($m->conf('smtp_host') || ''), ### OPTIONAL
143 -smtpuser => ($m->conf('smtp_user') || ''), ### OPTIONAL
144 -smtppass => ($m->conf('smtp_password') || ''),### OPTIONAL
145
146 # Attaches
147 -attach => [ ### OPTIONAL
148 {
149 Type=>'text/plain',
150 Data=>'document 1 content',
151 Filename=>'doc1.txt',
152 Disposition=>'attachment',
153 },
154
155 {
156 Type=>'text/plain',
157 Data=>'document 2 content',
158 Filename=>'doc2.txt',
159 Disposition=>'attachment',
160 },
161
162 ### ... ###
163 ],
164 );
165
166 If you need to send a letter with only one attachment:
167
168 -attach => {
169 Type=>'text/html',
170 Data=>$att,
171 Filename=>'response.htm',
172 Disposition=>'attachment',
173 },
174
175 or
176
177 -attach => {
178 Type=>'image/gif',
179 Path=>'aaa000123.gif',
180 Filename=>'logo.gif',
181 Disposition=>'attachment',
182 },
183
184 Sending mail via L<CTK::Util/sendmail>
185
186 =item B<syslog, logsys>
187
188 my $logstat = $m->syslog( $message, $level );
189
190 Apache logging to the Apache logfile (ErrorLog of your virtualhost)
191
192 $level can take the following values:
193
194 debug (default), info, notice, warning, error, crit, alert, emerg, fatal, except
195
196 The function returns work status
197
198 =back
199
200 =head1 HISTORY
201
202 =over 8
203
204 =item B<1.00 / 27.02.2008>
205
206 Init version on base mod_main 1.00.0002
207
208 =item B<1.10 / 01.04.2008>
209
210 Module is merged into the global module level
211
212 =item B<1.11 / Wed Apr 24 14:53:38 2013 MSK>
213
214 General refactoring
215
216 =back
217
218 =head1 AUTHOR
219
220 Serz Minus (Lepenkov Sergey) L<http://serzik.ru> E<lt>minus@mail333.comE<gt>
221
222 =head1 COPYRIGHT
223
224 Copyright (C) 1998-2013 D&D Corporation. All Rights Reserved
225
226 =head1 LICENSE
227
228 This program is free software: you can redistribute it and/or modify
229 it under the terms of the GNU General Public License as published by
230 the Free Software Foundation, either version 3 of the License, or
231 (at your option) any later version.
232
233 This program is distributed in the hope that it will be useful,
234 but WITHOUT ANY WARRANTY; without even the implied warranty of
235 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
236 GNU General Public License for more details.
237
238 See C<LICENSE> file
239
240 =cut
241
242 use vars qw($VERSION);
243 $VERSION = 1.12;
244
245 use constant {
246 LOGLEVELS => {
247 'debug' => 0,
248 'info' => 1,
249 'notice' => 2,
250 'warning' => 3,
251 'error' => 4,
252 'crit' => 5,
253 'alert' => 6,
254 'emerg' => 7,
255 'fatal' => 8,
256 'except' => 9,
257 },
258 };
259
260 use Apache2::Const qw/ :log /;
261 use MPMinus::MainTools;
262 use CTK::Util qw/ :BASE /; # Óòèëèòàðèé
263 use MIME::Lite;
264 use FileHandle;
265
266 sub log {
267 #
268 # Ïðîöåäóðà ëîãèðîâàíèÿ äàííûõ.
269 # !!! Èñïîëüçóåòñÿ äëÿ ÏÐÈÊËÀÄÍÛÕ à íå ñèñòåìíûõ íóæä
270 #
271 # IN:
272 # message - ñîîáùåíèå.
273 # level - Óðîâåíü çàïèñè ëîãà (ñì. ïðîöåäóðó syslog())
274 # file - ÀÁÑÎËÞÒÍÛÉ ïóòü è èìÿ ôàéëà êóäà ïèñàòü. Ïî óìîë÷àíèþ èñïîëüçóåòñÿ ôàéë default.log TEMP-äèðåêòîðèè
275 # sep - Ðàçäåëèòåëü çíà÷åíèé. Ïî óìîë÷àíèþ ïðîáåë
276 #
277 my $self = shift;
278 my $message = shift;
279 $message = '' unless defined $message;
280 my $level = shift || 'debug';
281 my $file = shift || $self->conf('errorlog');
282 my $sep = shift;
283 $sep = ' ' unless defined $sep;
284
285 my $usesyslog = $self->conf('_syslog_') ? 1 : 0;
286
287 # Îïðåäåëÿåì óðîâåíü
288 my $loglevels = LOGLEVELS;
289 my %levels = %$loglevels;
290 my %rlevels = reverse %$loglevels;
291 my $ll;
292 if (defined($level) && ($level =~ /^[0-9]+$/) && defined $rlevels{$level}) {
293 $ll = $rlevels{$level};
294 } elsif (defined($level) && ($level =~ /^[a-z0-9]+$/i) && defined $levels{lc($level)}) {
295 $ll = lc($level);
296 } else {
297 $ll = 'debug'; # Îáðàáîò÷èê ïî óìîë÷àíèþ
298 }
299 my $llc = $levels{$ll} || 0; # ÷èñëîâîå çíà÷åíè
300
301 # Ñìîòðèì íà óðîâåíü ëîãà f($ll), åñëè îí óñòàíîâëåí < ÷åì LogLevl çàäàííûé êîíôèãóðàöèåé òî ïðîñòî âûõîäèì
302 my $llsys = $self->r->server->loglevel();
303 $llsys = Apache2::Const::LOG_EMERG unless defined $llsys;
304 my $llcalc = 0; # debug (default)
305 if ($llsys == Apache2::Const::LOG_DEBUG) { $llcalc = 0 }
306 elsif ($llsys == Apache2::Const::LOG_INFO) { $llcalc = 1 }
307 elsif ($llsys == Apache2::Const::LOG_NOTICE) { $llcalc = 2 }
308 elsif ($llsys == Apache2::Const::LOG_WARNING) { $llcalc = 3 }
309 elsif ($llsys == Apache2::Const::LOG_ERR) { $llcalc = 4 }
310 elsif ($llsys == Apache2::Const::LOG_CRIT) { $llcalc = 5 }
311 elsif ($llsys == Apache2::Const::LOG_ALERT) { $llcalc = 6 }
312 elsif ($llsys == Apache2::Const::LOG_EMERG) { $llcalc = 7 }
313 else { $llcalc = 7 }
314
315 unless (($llc == 0) && $self->conf('_debug_')) { # åñëè ïåðåäàí level=debug è óñòàíîâëåí ôëàã äåáàãà - ïðîïñêàåì ïðîâåðêó!
316 return 0 if $llc < $llcalc;
317 }
318
319 # Ôîðìèðóåì âûõîäíóþ ñòðîêó
320 my @sl;
321 unless ($usesyslog) {
322 @sl = (
323 sprintf('[%s]',dtf("%w %MON %DD %hh:%mm:%ss %YYYY")), # Tue Feb 02 16:15:18 2013
324 sprintf('[%s]',$ll),
325 sprintf('[client %s]',$self->conf('remote_addr')),
326 );
327 }
328 push @sl, sprintf('[sid %s]',$self->conf('sid'));
329 push @sl, sprintf('[user %s]',$self->conf('remote_user')) if $self->conf('remote_user');
330 push @sl, sprintf('[uri %s]',$self->conf('request_uri'));
331 push @sl, $message;
332 my $logstring = join($sep, @sl);
333
334 # Çàïèñü!
335 return syslog($self,$logstring,$level) if $usesyslog; # Â ñèñòåìíûé ëîã
336 return _log_flush($file, $logstring); #  ñâîé ëîã. Òóò ñëîæíåå, èäåò çàìîðî÷êà ñ ôàéëàìè
337 }
338 sub log_debug { shift->log(shift,'debug') };
339 sub log_info { shift->log(shift,'info') };
340 sub log_notice { shift->log(shift,'notice') };
341 sub log_warning { shift->log(shift,'warning') };
342 sub log_warn { goto &log_warning };
343 sub log_error { shift->log(shift,'error') };
344 sub log_err { goto &log_error };
345 sub log_crit { shift->log(shift,'crit') };
346 sub log_alert { shift->log(shift,'alert') };
347 sub log_emerg { shift->log(shift,'emerg') };
348 sub log_fatal { shift->log(shift,'fatal') };
349 sub log_except { shift->log(shift,'except') };
350 sub log_exception { goto &log_except };
351 sub _log_flush {
352 # ñáðàñûâàåì áóôåð â ôàéë, âîçâðàùàÿ ñòàòóñ îïåðàöèè
353 my $fn = shift;
354 my $buffer = shift;
355 return 0 unless defined $fn;
356
357 my $fh = FileHandle->new($fn,'a');
358 unless ($fh) {
359 carp(defined($!) ? $! : "Can't open file \"$fn\"");
360 return 0;
361 }
362
363 $fh->print(defined($buffer) ? $buffer : '',"\n");
364 $fh->close();
365
366 return 1;
367 }
368 sub syslog {
369 #
370 # Ïðîöåäóðà èñïîëüçóåò ôóíêöèþ àïà÷à äëÿ âñòàâêè çàïèñåé â ëîã
371 #
372 # IN:
373 # message - ñîîáùåíèå.
374 # level - Óðîâåíü çàïèñè ëîãà (ñì. ïðîöåäóðó syslog())
375 #
376 my $self = shift;
377 my $message = shift;
378 my $level = shift || 'debug'; # emerg(), alert(), crit(), error(), warn(), notice(), info(), debug()
379 my $msg = translate(defined($message) ? $message : '');
380
381 my $r = Apache2::RequestUtil->request;
382 my $rlog = $r->log;
383
384 if ($level eq 'except') { # 9 exception (emerg alias)
385 $rlog->emerg($msg);
386 } elsif ($level eq 'fatal') { # 8 fatal (emerg alias)
387 $rlog->emerg($msg);
388 } elsif ($level eq 'emerg') { # 7 system is unusable
389 $rlog->emerg($msg);
390 } elsif ($level eq 'alert') { # 6 action must be taken immediately
391 $rlog->alert($msg);
392 } elsif ($level eq 'crit') { # 5 critical conditions
393 $rlog->crit($msg);
394 } elsif ($level eq 'error' or $level eq 'err') { # 4 error conditions
395 $rlog->error($msg);
396 } elsif ($level eq 'warn' or $level eq 'warning') { # 3 warning conditions
397 $rlog->warn($msg);
398 } elsif ($level eq 'notice') { # 2 normal but significant condition
399 $rlog->notice($msg);
400 } elsif ($level eq 'info') { # 1 informational
401 $rlog->info($msg);
402 } else { # 0 debug-level messages (default)
403 $rlog->debug($msg);
404 }
405 return 1;
406
407 }
408 sub logsys { goto &syslog };
409 sub debug {
410 #
411 # Ïðîöåäóðà îòëàäêè. Çàïèñûâàåò â îòëàäî÷íûé ôàéë èíôîðìàöèþ.
412 # !!! Èñïîëüçóåòñÿ äëÿ ÏÐÈÊËÀÄÍÛÕ à íå ñèñòåìíûõ íóæä
413 #
414 # IN:
415 # $message - ñîîáùåíèå
416 # $verbose - ôëàã ñèñòåìíîé èíôîðìàöèè. 1 - âêëþ÷èòü äîáàâëåíèå ñèñòåìíîé èíôîðìàöèè / 0 - âûêë
417 # $file - ÈÌß ôàéëà äëÿ îòëàäêè. Ïî óìîë÷àíèþ - $CONF{file_debug}
418 #
419 my $self = shift;
420 my $message = shift;
421 $message = '' unless defined $message;
422 my $verbose = shift || 0;
423 my $file = shift || $self->conf('debuglog');
424
425 return 0 unless $self->conf('_debug_');
426
427 # Áåðåì çíà÷åíèå ïî óìîë÷àíèþ åñëè îíî íå çàäàíî
428 my $buff = '';
429 if ($verbose) {
430 my ($pkg, $fn, $ln) = caller;
431 my $tm = sprintf "%+.*f",4, (getHiTime() - $self->conf('hitime'));
432 $buff = "[time $tm] [package $pkg] [file $fn] [line $ln]".($message ? ' ' : '').$message;
433 } else {
434 $buff = $message;
435 }
436 $self->log($buff,'debug',$file);
437
438 }
439 sub exception {
440 # Ïðîöåäóðà ðåàãèðîâàíèÿ íà exception
441 my $self = shift;
442 my $message = shift;
443 $message = '' unless defined $message;
444
445 # Àíàëèç @_ è åñëè ïåðâûé ýëåìåíò ñïèñêà ñîäåðæèò ïðåôôèêñ [SENDMAIL],
446 if ($message =~ /\[SENDMAIL\]/) {
447 $message =~ s/\[SENDMAIL\]//;
448
449 # Îòïðàâëÿåì ïèñüìî àäìèíèñòðàòîðó
450 CTK::Util::send_mail(
451 -to => $self->conf('server_admin'),
452 -from => sprintf('"%s" <%s>',$self->conf('server_name'),$self->conf('server_admin')),
453 -subject => sprintf('MPMinus internal error on "%s"',$self->conf('server_name')),
454 -message => $message,
455 -type => 'text/html',
456 -smtp => ($self->conf('smtp_host') || ''),
457 -smtpuser => ($self->conf('smtp_user') || ''),
458 -smtppass => ($self->conf('smtp_password') || ''),
459 ) if $self->conf('_errorsendmail_');
460 }
461 $self->log_except($message);
462 }
463 sub sendmail {
464 # Îòïðàâêà ïèñüìà ñ ïîìîùüþ ìîäóëÿ CTK::Util::send_mail
465 my $self = shift;
466 return 0 unless $self->conf('_sendmail_'); # Åñëè çàïðåù¸íî îòïðàâëÿòü ïèñüìà òî âûõîä ñî ñòàòóñîì 0
467 return CTK::Util::send_mail(@_);
468 }
469 sub send_mail { goto &sendmail };
470 1;