blib/lib/Lemonldap/NG/Common/Notifications/DBI.pm untested

filter: Statementstmt 0.0% 0 / 141 Branchbran 0.0% 0 / 46 Conditioncond 0.0% 0 / 23 MC/DCmcdc 0.0% 0 / 8 Subroutinesub 0.0% 0 / 18 Podpod 0.0% 0 / 12 totaltotal 0.0% 0 / 248 CC 24 SCAR 27.2
CC
24
Cov
0%
get
30.0
_dbh
30.0
getAccepted
20.0
CRAP 15.1
1 ## @file
2 # DBI storage methods for notifications
3  
4 ## @class
5 # DBI storage methods for notifications
6 package Lemonldap::NG::Common::Notifications::DBI;
7  
8 use strict;
9 use Mouse;
10 use Time::Local;
11 use DBI;
12 use Encode;
13 use Lemonldap::NG::Common::Lib::DBI qw(check_dbh);
14  
15 our $VERSION = '2.23.0';
16  
17 extends 'Lemonldap::NG::Common::Notifications';
18  
19 sub import {
20 shift;
21 return Lemonldap::NG::Common::Notifications->import(@_);
22 }
23  
24 has dbiTable => (
25 is => 'ro',
26 lazy => 1,
27 default => sub { $_[0]->{table} || 'notifications' }
28 );
29  
30 has dbiChain => (
31 is => 'ro',
32 required => 1
33 );
34  
35 has dbiUser => (
36 is => 'ro',
37 lazy => 1,
38 default => sub {
39 $_[0]->{p}->logger->warn('Warning: "dbiUser" parameter is not set');
40 return '';
41 }
42 );
43  
44 has dbiPassword => ( is => 'ro', default => '' );
45  
46 # Current query
47 has sth => ( is => 'rw' );
48  
49 # Returns notifications corresponding to the user $uid.
50 # If $ref is set, returns only notification corresponding to this reference.
51 sub get {
52 my ( $self, $uid, $ref ) = @_;
53 return () unless ($uid);
54 $self->_execute(
55 "SELECT * FROM "
56 . $self->dbiTable
57 . " WHERE done IS NULL AND uid=?"
58 . ( $ref ? " AND ref=?" : '' )
59 . " ORDER BY date",
60 $uid,
61 ( $ref ? $ref : () )
62 ) or return ();
63 my $result;
64 while ( my $h = $self->sth->fetchrow_hashref() ) {
65  
66 # Get XML message
67 my $xml = $h->{xml};
68  
69 # Decode it to get the correct uncoded string
70 Encode::from_to( $xml, "utf8", "iso-8859-1", Encode::FB_CROAK );
71  
72 # Store message in result
73 my $identifier =
74 &getIdentifier( $self, $h->{uid}, $h->{ref}, $h->{date} );
75 $result->{$identifier} = $xml;
76 }
77 $self->logger->warn( $self->sth->err() ) if ( $self->sth->err() );
78 return $result;
79 }
80  
81 # Returns accepted notifications corresponding to the user $uid.
82 # If $ref is set, returns only notification corresponding to this reference.
83 sub getAccepted {
84 my ( $self, $uid, $ref ) = @_;
85 return () unless ($uid);
86 $self->_execute(
87 "SELECT * FROM "
88 . $self->dbiTable
89 . " WHERE uid=? AND ref=? ORDER BY date",
90 $uid,
91 ( $ref ? $ref : () )
92 ) or return ();
93 my $result;
94 while ( my $h = $self->sth->fetchrow_hashref() ) {
95  
96 # Get XML message
97 my $xml = $h->{xml};
98  
99 # Decode it to get the correct uncoded string
100 Encode::from_to( $xml, "utf8", "iso-8859-1", Encode::FB_CROAK );
101  
102 # Store message in result
103 my $identifier =
104 &getIdentifier( $self, $h->{uid}, $h->{ref}, $h->{date} );
105 $result->{$identifier} = $xml;
106 }
107 $self->logger->warn( $self->sth->err() ) if ( $self->sth->err() );
108 return $result;
109 }
110  
111 ## @method hashref getAll()
112 # Return all pending notifications.
113 # @return hashref where keys are internal reference and values are hashref with
114 # keys date, uid, ref and condition.
115 sub getAll {
116 my $self = shift;
117 $self->_execute( 'SELECT * FROM '
118 . $self->dbiTable
119 . ' WHERE done IS NULL ORDER BY date' );
120 my $result;
121 while ( my $h = $self->sth->fetchrow_hashref() ) {
122 $result->{"$h->{date}#$h->{uid}#$h->{ref}"} = {
123 date => $h->{date},
124 uid => $h->{uid},
125 ref => $h->{ref},
126 condition => $h->{cond}
127 };
128 }
129 $self->logger->warn( $self->sth->err() ) if ( $self->sth->err() );
130 return $result;
131 }
132  
133 ## @method hashref getExisting()
134 # Return all notifications.
135 # @return hashref where keys are internal reference and values are hashref with
136 # keys date, uid, ref and condition.
137 sub getExisting {
138 my $self = shift;
139 $self->_execute( 'SELECT * FROM ' . $self->dbiTable . ' ORDER BY date' );
140 my $result;
141 while ( my $h = $self->sth->fetchrow_hashref() ) {
142 $result->{"$h->{date}#$h->{uid}#$h->{ref}"} = {
143 date => $h->{date},
144 uid => $h->{uid},
145 ref => $h->{ref},
146 condition => $h->{cond}
147 };
148 }
149 $self->logger->warn( $self->sth->err() ) if ( $self->sth->err() );
150 return $result;
151 }
152  
153 ## @method boolean delete(string myref)
154 # Mark a notification as done.
155 # @param $myref identifier returned by get() or getAll()
156 sub delete {
157 my ( $self, $myref ) = @_;
158 my ( $d, $u, $r );
159 unless ( ( $d, $u, $r ) = ( $myref =~ /^([^#]+)#(.+?)#(.+)$/ ) ) {
160 $self->logger->warn("Bad reference $myref");
161 return 0;
162 }
163 my @ts = localtime();
164 $ts[5] += 1900;
165 $ts[4]++;
166 return $self->_execute( 'UPDATE '
167 . $self->dbiTable
168 . " SET done='$ts[5]-$ts[4]-$ts[3] $ts[2]:$ts[1]' "
169 . 'WHERE done IS NULL AND uid=? AND ref=? AND date=?',
170 $u, $r, $d );
171 }
172  
173 ## @method boolean purge(string myref, boolean force)
174 # Purge notification (really delete record)
175 # @param $myref identifier returned by get or getAll
176 # @param $force force purge for not deleted session
177 # @return true if something was deleted
178 sub purge {
179 my ( $self, $myref, $force ) = @_;
180 my ( $d, $u, $r );
181 unless ( ( $d, $u, $r ) = ( $myref =~ /^([^#]+)#(.+?)#(.+)$/ ) ) {
182 $self->logger->warn("Bad reference $myref");
183 return 0;
184 }
185 unless ( $d =~ s/^(\d{4})(\d{2})(\d{2}).*$/$1-$2-$3/
186 or $d =~ s/^(\d{4}-\d{2}-\d{2}).*$/$1/ )
187 {
188 $self->logger->warn("Bad date $d");
189 return 0;
190 }
191  
192 my $clause;
193 $clause = "done IS NOT NULL AND" unless ($force);
194  
195 return $self->_execute( 'DELETE FROM '
196 . $self->dbiTable
197 . " WHERE $clause uid=? AND ref=? AND date=?",
198 $u, $r, $d );
199 }
200  
201 ## @method boolean newNotif(string date, string uid, string ref, string condition, string xml)
202 # Insert a new notification
203 # @param date Date
204 # @param uid UID
205 # @param ref Reference of the notification
206 # @param condition Condition for the notification
207 # @param xml XML notification
208 # @return true if succeed
209 sub newNotif {
210 my ( $self, $date, $uid, $ref, $condition, $xml ) = @_;
211 my @t = split( /\D+/, $date );
212 $t[1]--;
213 eval {
214 timelocal( $t[5] || 0, $t[4] || 0, $t[3] || 0, $t[2], $t[1], $t[0] );
215 };
216 return ( 0, "Bad date" ) if ($@);
217 my $res =
218 $condition =~ /.+/
219 ? $self->_execute( 'INSERT INTO '
220 . $self->dbiTable
221 . ' (date,uid,ref,cond,xml) VALUES(?,?,?,?,?)',
222 $date, $uid, $ref, $condition, $xml )
223 : $self->_execute( 'INSERT INTO '
224 . $self->dbiTable
225 . ' (date,uid,ref,xml) VALUES(?,?,?,?)',
226 $date, $uid, $ref, $xml );
227 return $res;
228 }
229  
230 ## @method hashref getDone()
231 # Returns a list of notification that have been done
232 # @return hashref where keys are internal reference and values are hashref with
233 # keys notified, uid and ref.
234 sub getDone {
235 my ($self) = @_;
236 $self->_execute( 'SELECT * FROM '
237 . $self->dbiTable
238 . ' WHERE done IS NOT NULL ORDER BY done' );
239 my $result;
240 while ( my $h = $self->sth->fetchrow_hashref() ) {
241 my @t = split( /\D+/, $h->{date} );
242 $t[1]--;
243 my $done = eval {
244 timelocal( $t[5] || 0, $t[4] || 0, $t[3] || 0, $t[2], $t[1],
245 $t[0] );
246 };
247 if ($@) {
248 $self->logger->warn("Bad date: $h->{date}");
249 return {};
250 }
251 $result->{"$h->{date}#$h->{uid}#$h->{ref}"} = {
252 notified => $done,
253 uid => $h->{uid},
254 ref => $h->{ref},
255 condition => $h->{cond}
256 };
257 }
258 $self->logger->warn( $self->sth->err() ) if ( $self->sth->err() );
259 return $result;
260 }
261  
262 ## @method private object _execute(string query, array args)
263 # Execute a query and catch errors
264 # @return number of lines touched or 1 if select succeed
265 sub _execute {
266 my ( $self, $query, @args ) = @_;
267 my $dbh = $self->_dbh or die "DB connection unavailable";
268 $self->logger->debug("Notification DBI proccessing query: $query");
269 unless ( $self->sth( $dbh->prepare($query) ) ) {
270 $self->logger->warn( $dbh->errstr() );
271 return 0;
272 }
273 my $tmp;
274 unless ( $tmp = $self->sth->execute(@args) ) {
275 $self->logger->warn( $self->sth->errstr() );
276 return 0;
277 }
278 return $tmp;
279 }
280  
281 ## @method string getIdentifier(string uid, string ref, string date)
282 # Get notification identifier
283 # @param $uid uid
284 # @param $ref ref
285 # @param $date date
286 # @return the notification identifier
287 sub getIdentifier {
288 my ( $self, $uid, $ref, $date ) = @_;
289 return $date . "#" . $uid . "#" . $ref;
290 }
291  
292 sub _dbh {
293 my $self = shift;
294 my $dbh = check_dbh( $self->{_dbh} );
295 return $dbh if $dbh;
296 delete $self->{_dbh};
297 $self->logger->debug("Notification DBI connection lost, getting a new one");
298 $self->{_dbh} = DBI->connect_cached( $self->{dbiChain}, $self->{dbiUser},
299 $self->{dbiPassword}, { RaiseError => 1, AutoCommit => 1, } );
300 if ( $self->{dbiChain} =~ /^dbi:sqlite/i ) {
301 $self->{_dbh}->{sqlite_unicode} = 1;
302 }
303 elsif ( $self->{dbiChain} =~ /^dbi:mysql/i ) {
304 eval {
305 $self->{_dbh}->{mysql_enable_utf8} = 1;
306 $self->{_dbh}->do("set names 'utf8'");
307 };
308 }
309  
310 elsif ( $self->{dbiChain} =~ /^dbi:pg/i ) {
311 $self->{_dbh}->{pg_enable_utf8} = 1;
312 }
313  
314 return $self->{_dbh};
315 }
316  
317 1;