blib/lib/Lemonldap/NG/Portal/Lib/Notifications/XML.pm untested

filter: Statementstmt 0.0% 0 / 218 Branchbran 0.0% 0 / 72 Conditioncond 0.0% 0 / 31 MC/DCmcdc 0.0% 0 / 18 Subroutinesub 0.0% 0 / 13 Podpod 0.0% 0 / 6 totaltotal 0.0% 0 / 358 CC 35 SCAR 50.0
CC
35
Cov
0%
getNotifBack
306.0
checkForNotifications
132.0
viewNotification
42.0
CRAP 149.0
1 package Lemonldap::NG::Portal::Lib::Notifications::XML;
2  
3 use strict;
4 use Mouse;
5 use XML::LibXML;
6 use XML::LibXSLT;
7 use POSIX qw(strftime);
8  
9 our $VERSION = '2.23.0';
10  
11 # Lemonldap::NG::Portal::Main::Plugin provides addAuthRoute() and
12 # addUnauthRoute() methods in addition of Lemonldap::NG::Common::Module.
13 extends 'Lemonldap::NG::Portal::Main::Plugin';
14  
15 # PROPERTIES
16  
17 # XML parser
18 has parser => (
19 is => 'rw',
20 builder => sub {
21 return XML::LibXML->new( load_ext_dtd => 0, expand_entities => 0 );
22 }
23 );
24  
25 # XSLT document
26 has stylesheet => (
27 is => 'rw',
28 lazy => 1,
29 builder => sub {
30 my $self = $_[0];
31 my $xslt = XML::LibXSLT->new();
32 my $styleFile =
33 ( $self->conf->{notificationXSLTfile}
34 and -e $self->conf->{notificationXSLTfile} )
35 ? $self->conf->{notificationXSLTfile}
36 : $self->conf->{templateDir} . '/common/notification.xsl';
37 unless ( -e $styleFile ) {
38 $self->{logger}->error("$styleFile not found, aborting");
39 die "$styleFile not found";
40 }
41 return $xslt->parse_stylesheet( $self->parser->parse_file($styleFile) );
42 }
43 );
44  
45 # Underlying notifications storage object (File, DBI, LDAP,...)
46 has notifObject => ( is => 'rw' );
47  
48 # Notification server accessors
49 has imported => ( is => 'rw', default => 0 );
50 has server => ( is => 'rw' );
51  
52 # INITIALIZATION
53  
54 sub init {
55 return 1;
56 }
57  
58 # Search for notifications and if any, returns HTML fragment.
59 sub checkForNotifications {
60 my ( $self, $req ) = @_;
61  
62 # Look for pending notifications in database
63 my $uid = $req->sessionInfo->{ $self->notifObject->notifField };
64 my ( $notifs, $forUser ) = $self->notifObject->getNotifications($uid);
65 my $form;
66 unless ($notifs) {
67 $self->logger->info("No notification found");
68 return 0;
69 }
70  
71 # Transform notifications
72 my $i = 0; # Files count
73 my $now = strftime "%Y-%m-%d", localtime;
74  
75 foreach my $file ( values %$notifs ) {
76 my $xml = $self->parser->parse_string($file);
77 my $j = 0; # Notifications count
78 LOOP: foreach my $notif (
79 eval {
80 $xml->documentElement->getElementsByTagName('notification');
81 }
82 )
83 {
84  
85 # Get the reference
86 my $reference = $notif->getAttribute('reference');
87 $self->logger->debug("Get reference $reference");
88  
89 # Check it in session
90 if ( exists $req->{sessionInfo}->{"notification_$reference"} ) {
91  
92 # The notification was already accepted
93 $self->logger->debug(
94 "Notification $reference was already accepted");
95  
96 # Remove it from XML
97 $notif->unbindNode();
98 next LOOP;
99 }
100  
101 # Check date
102 my $date = $notif->getAttribute('date');
103 $self->logger->debug("Get date: $date");
104 unless ( $date and $date =~ /\b\d{4}-\d{2}-\d{2}\b/ ) {
105 $self->logger->error('Malformed date');
106 $notif->unbindNode();
107 next LOOP;
108 }
109 unless ( $date le $now ) {
110 $self->logger->debug('Notification date not reached');
111  
112 # Remove it from XML
113 $notif->unbindNode();
114 next LOOP;
115 }
116  
117 # Check condition if any
118 if ( my $condition = $notif->getAttribute('condition') ) {
119 $self->logger->debug("Get condition $condition");
120 $condition = $self->p->HANDLER->substitute($condition);
121 unless ( $condition = $self->p->HANDLER->buildSub($condition) )
122 {
123 $self->logger->error( 'Notification condition error: '
124 . $self->p->HANDLER->tsv->{jail}->error );
125  
126 # Remove it from XML
127 $notif->unbindNode();
128 next LOOP;
129 }
130 unless ( $condition->( $req, $req->sessionInfo ) ) {
131 $self->logger->debug(
132 'Notification condition not authorized');
133  
134 # Remove it from XML
135 $notif->unbindNode();
136 next LOOP;
137 }
138 }
139 $j++;
140 }
141  
142 # Go to next file if no notification found
143 next unless $j;
144 $i++;
145  
146 # Transform XML into HTML
147 my $results = $self->stylesheet->transform( $xml, start => $i );
148 $form .= $self->stylesheet->output_string($results);
149 }
150 if ($@) {
151 $self->userLogger->warn(
152 "Bad XML file: a notification for $uid was not done ($@)");
153 return 0;
154 }
155  
156 # Stop here if nothing to display
157 return 0 unless $i;
158 $self->userLogger->info("$i pending notification(s) found for $uid");
159  
160 # Returns HTML fragment
161 return $form;
162 }
163  
164 # Search for accepted notification and if any, returns HTML fragment.
165 sub viewNotification {
166 my ( $self, $req, $ref, $epoch ) = @_;
167  
168 # Look for pending notifications in database
169 my $uid = $req->userData->{ $self->notifObject->notifField };
170 my ( $notifs, $forUser ) =
171 $self->notifObject->getAcceptedNotifs( $uid, $ref );
172 my $form;
173 unless ($notifs) {
174 $self->logger->info("No accepted notification found");
175 return 0;
176 }
177  
178 # Transform notifications
179 my $i = 0; # Files count
180  
181 foreach my $file ( values %$notifs ) {
182 my $xml = $self->parser->parse_string($file);
183 my $j = 0; # Notifications count
184 LOOP: foreach my $notif (
185 eval {
186 $xml->documentElement->getElementsByTagName('notification');
187 }
188 )
189 {
190  
191 # Get the reference
192 my $reference = $notif->getAttribute('reference');
193 $self->logger->debug("Get reference $reference");
194  
195 # Check it in session
196 unless ( exists $req->userData->{"notification_$reference"}
197 and $req->userData->{"notification_$reference"} eq $epoch
198 and $reference eq $ref )
199 {
200  
201 # The notification is not already accepted
202 $self->logger->debug(
203 "Notification $reference was already accepted");
204  
205 # Remove it from XML
206 $notif->unbindNode();
207 next LOOP;
208 }
209 $j++;
210 }
211  
212 # Go to next file if no notification found
213 next unless $j;
214 $i++;
215  
216 # Transform XML into HTML
217 my $results = $self->stylesheet->transform( $xml, start => $i );
218 $form .= $self->stylesheet->output_string($results);
219 }
220 if ($@) {
221 $self->userLogger->warn(
222 "Bad XML file: a notification for $uid was not done ($@)");
223 return 0;
224 }
225  
226 # Stop here if nothing to display
227 return 0 unless $i;
228 $self->userLogger->info("$i accepted notification(s) found for $uid");
229  
230 # Returns HTML fragment
231 return $form;
232 }
233  
234 sub getNotifBack {
235 my ( $self, $req, $name ) = @_;
236  
237 # Search for Lemonldap::NG cookie (ciphered)
238 my $id;
239 return $self->p->sendError( $req, 'No cookie found', 401 )
240 unless ( $id = $req->cookies->{ $self->{conf}->{cookieName} } );
241  
242 if ( $req->param('cancel') ) {
243 $self->logger->debug('Cancel called -> remove ciphered cookie');
244 $req->addCookie(
245 $self->p->genDomainCookie(
246 $req,
247 name => $self->conf->{cookieName},
248 value => 0,
249 secure => $self->conf->{securedCookie},
250 expires => 'Wed, 21 Oct 2015 00:00:00 GMT'
251 )
252 );
253 $req->mustRedirect(1);
254 return $self->p->do( $req, [] );
255 }
256  
257 # Look if all notifications have been accepted.
258 # If not, redirect to Portal
259  
260 # Try to decrypt Lemonldap::NG ciphered cookie
261 $id = $self->p->HANDLER->tsv->{cipher}->decrypt($id)
262 or return $self->sendError( $req, 'Unable to decrypt ciphered id', 400 );
263  
264 # Check that session exists
265 $req->userData( $self->p->HANDLER->retrieveSession( $req, $id ) )
266 or return $self->sendError( $req, 'Unknown session', 401 );
267  
268 # Restore data
269 $self->p->importHandlerData($req);
270 my $uid = $req->sessionInfo->{ $self->notifObject->notifField };
271  
272 # ALL notifications are returned here => Need to check active ones only
273 my ( $notifs, $forUser ) =
274 eval { $self->notifObject->getNotifications($uid) };
275 return $self->p->sendError( $req, $@, 500 ) if ($@);
276  
277 if ($notifs) {
278  
279 # Get accepted notifications
280 my ( $refs, $checks ) = ( {}, {} );
281 my $prms = $req->parameters;
282 foreach ( keys %$prms ) {
283 my $v = $prms->{$_};
284 if (s/^reference//) {
285 $refs->{$v} = $_;
286 }
287 elsif ( s/^check// and /^(\d+x\d+)x(\d+)$/ and $v eq 'accepted' ) {
288 push @{ $checks->{$1} }, $2;
289 }
290 }
291  
292 my $result = 1;
293 my $now = strftime "%Y-%m-%d", localtime;
294 foreach my $fileName ( keys %$notifs ) {
295 my $file = $notifs->{$fileName};
296 my $fileResult = 1;
297 my $xml = $self->parser->parse_string($file);
298  
299 # Get pending notifications and verify that they have been accepted
300 LOOP:
301 foreach my $notif (
302 $xml->documentElement->getElementsByTagName('notification') )
303 {
304 my $reference = $notif->getAttribute('reference');
305  
306 # Check date
307 my $date = $notif->getAttribute('date');
308 $self->logger->debug("Get date: $date");
309 unless ( $date and $date =~ /\b\d{4}-\d{2}-\d{2}\b/ ) {
310 $self->logger->error('Malformed date');
311 next LOOP;
312 }
313 unless ( $date le $now ) {
314 $self->logger->debug('Notification date not reached');
315 $fileResult = 0; # Do not delete notification
316 next LOOP;
317 }
318  
319 # Check condition if any
320 if ( my $condition = $notif->getAttribute('condition') ) {
321 $self->logger->debug("Get condition $condition");
322 $condition = $self->p->HANDLER->substitute($condition);
323 unless ( $condition =
324 $self->p->HANDLER->buildSub($condition) )
325 {
326 $self->logger->error( 'Notification condition error: '
327 . $self->p->HANDLER->tsv->{jail}->error );
328 next LOOP;
329 }
330 unless ( $condition->( $req, $req->sessionInfo ) ) {
331 $self->logger->debug(
332 'Notification condition not authorized');
333 $fileResult = 0; # Do not delete notification
334 next LOOP;
335 }
336 }
337  
338 # Check if this pending notification has been seen
339 if ( my $refId = $refs->{$reference} ) {
340  
341 # Verity that checkboxes have been checked
342 my @toCheck = $notif->getElementsByTagName('check');
343 if ( my $toCheckCount = @toCheck ) {
344 unless ($checks->{$refId}
345 and $toCheckCount == @{ $checks->{$refId} } )
346 {
347 $self->userLogger->notice(
348 "$uid has not accepted notification $reference"
349 );
350 $result = $fileResult = 0;
351 next;
352 }
353 }
354 }
355 else {
356 # Current pending notification has not been found in
357 # request
358 $result = $fileResult = 0;
359 $self->logger->debug(
360 'Current pending notification has not been found');
361 next;
362 }
363  
364 # Register acceptation
365 $self->userLogger->notice(
366 "$uid has accepted notification $reference");
367 $self->p->updatePersistentSession( $req,
368 { "notification_$reference" => time() } );
369 $self->logger->debug(
370 "Notification $reference registered in persistent session");
371 }
372  
373 # Notifications accepted for this file, delete it unless it's a wildcard
374 if ( $fileResult and exists $forUser->{$fileName} ) {
375 $self->logger->debug("Notification file deleted");
376 $self->notifObject->delete($fileName);
377 }
378 }
379 unless ($result) {
380  
381 # One pending notification has been found and not accepted,
382 # restart process to display pending notifications
383 $self->logger->debug(
384 'Pending notification has been found and not accepted');
385 return $self->p->do( $req, [ @{ $self->p->endAuth } ] );
386 }
387  
388 # All pending notifications have been accepted, restore cookies and
389 # launch 'controlUrl' to restore "urldc" using do()
390 $self->logger->debug('All pending notifications have been accepted');
391 $self->p->rebuildCookies($req);
392 return $self->p->do( $req, [ 'controlUrl', @{ $self->p->endAuth } ] );
393 }
394 else {
395 # No notifications checked here, this entry point must not be called.
396 # Redirecting to portal
397 $self->logger->debug('No notifications checked');
398 $req->mustRedirect(1);
399 return $self->p->do( $req, [] );
400 }
401 }
402  
403 sub notificationServer {
404 my ( $self, $req ) = @_;
405 unless ( $self->imported ) {
406 eval {
407 require Lemonldap::NG::Common::PSGI::SOAPServer;
408 require Lemonldap::NG::Common::PSGI::SOAPService;
409 };
410 if ($@) {
411 return $self->p->sendError( $req, $@, 500 );
412 }
413 $self->server( Lemonldap::NG::Common::PSGI::SOAPServer->new );
414 $self->imported(1);
415 }
416 unless ( $req->env->{HTTP_SOAPACTION} ) {
417 return $self->p->sendError( $req, 'SOAP requests only', 400 );
418 }
419 return $self->server->dispatch_to(
420 Lemonldap::NG::Common::PSGI::SOAPService->new(
421 $self, $req, 'newNotification',
422 )
423 )->handle($req);
424 }
425  
426 sub newNotification {
427 my ( $self, $req, $xml ) = @_;
428 return $self->notifObject->newNotification( $xml,
429 $self->conf->{notificationDefaultCond} );
430 }
431  
432 1;