ASP/MediaManager.pm untested

filter: Statementstmt 0.0% 0 / 135 Branchbran 0.0% 0 / 34 Conditioncond 0.0% 0 / 28 MC/DCmcdc 0.0% 0 / 16 Subroutinesub 0.0% 0 / 26 Podpod 0.0% 0 / 21 totaltotal 0.0% 0 / 260 CC 18 SCAR 31.4
CC
18
Cov
0%
run
90.0
delete_file
12.0
upload_start
12.0
CRAP 23.1
1  
2 package Apache2::ASP::MediaManager;
3  
4 use strict;
5 use base 'Apache2::ASP::UploadHandler';
6 use MIME::Types;
7 use IO::File;
8  
9 my $mimetypes = MIME::Types->new();
10  
11  
12 #==============================================================================
13 sub run
14 {
15 my ($s, $context) = @_;
16
17 shift(@_);
18
19 my $mode = $context->request->Form->{mode};
20
21 return unless ( ! $mode ) || ( $mode !~ m/^(create|edit)$/ );
22
23 my $filename = $s->compose_download_file_path( $context );
24 my $file = $s->compose_download_file_name( $context );
25
26 # Find its MIME type and set our 'ContentType' value:
27 my $ext;
28 unless( $mode )
29 {
30 # Find its MIME type and set our 'ContentType' value:
31 ($ext) = $file =~ m/.*?\.([^\.]+)$/;
32 my $type = $ext ? $mimetypes->mimeTypeOf( $ext ) || 'application/octet-stream' : 'application/octet-stream';
33 $context->response->ContentType( $type );
34 }# end unless()
35
36 # Call our extension hooks:
37 if( $mode )
38 {
39 if( $mode eq 'delete' )
40 {
41 $s->before_delete( $context, $filename )
42 or return;
43 $s->delete_file( $context, $filename );
44 return $s->after_delete( $context, $filename );
45 }
46 elsif( defined(my $handler = $s->modes( $mode )) )
47 {
48 return $handler->( $s, $context );
49 }# end if()
50 }# end if()
51
52 # Get the readable filehandle:
53 unless( -f $filename )
54 {
55 $context->response->Status( 404 );
56 return;
57 }# end unless()
58
59 # Call our before- hook:
60 $s->before_download( $context, $filename )
61 or return;
62
63 # Wait until "before_download" has cleared before we open a filehandle:
64 my $ifh = $s->open_file_for_reading( $context, $filename );
65
66 # Send any HTTP headers:
67 $s->send_http_headers($context, $filename, $file, $ext);
68
69 # Print the file out:
70 if( (stat($ifh))[7] < 1024 ** 2 )
71 {
72 # File is < 1M, so just slurp and print:
73 local $/;
74 $context->response->Write( scalar(<$ifh>) );
75 }
76 else
77 {
78 while( my $line = <$ifh> )
79 {
80 $context->response->Write( $line );
81 }# end while()
82 }# end while()
83 $context->response->Flush;
84
85 # Done!
86 $ifh->close;
87
88 # Call our after- hook:
89 $s->after_download( $context, $filename );
90 }# end run()
91  
92  
93 #==============================================================================
94 sub send_http_headers
95 {
96 my ($s, $context, $filename, $file, $ext) = @_;
97
98 # Send the 'content-length' header:
99 $context->r->err_headers_out->{'Content-Length'} = (stat($filename))[7];
100
101 # PDF files should force the "Save file as..." dialog:
102 my $disposition = (lc($ext) eq 'pdf') ? 'attachment' : 'inline';
103 $file =~ s/\s/_/g;
104
105 $context->r->err_headers_out->{'content-disposition'} = "$disposition;filename=" . $file . ';yay=yay';
106 }# end send_http_headers()
107  
108  
109 #==============================================================================
110 sub delete_file
111 {
112 my ($s, $context, $filename) = @_;
113
114 die "'$filename' is a directory, not a file" if -d $filename;
115 return unless -f $filename;
116 unlink( $filename )
117 or die "Cannot delete file '$filename' from disk: $!";
118 }# end delete_file()
119  
120  
121 #==============================================================================
122 sub open_file_for_writing
123 {
124 my ($s, $context, $filename) = @_;
125
126 # Try to open the file for writing:
127 my $ofh = IO::File->new();
128 $ofh->open($filename, '>' )
129 or die "Cannot open file '$filename' for writing: $!";
130 $ofh->binmode;
131 $ofh->autoflush(1);
132
133 return $ofh;
134 }# end open_file_for_writing()
135  
136  
137 #==============================================================================
138 sub open_file_for_reading
139 {
140 my ($s, $context, $filename) = @_;
141
142 # Try to open the file for reading:
143 my $ifh = IO::File->new();
144 $ifh->open($filename, '<' )
145 or die "Cannot open file '$filename' for reading: $!";
146 $ifh->binmode;
147
148 return $ifh;
149 }# end open_file_for_reading()
150  
151  
152 #==============================================================================
153 sub open_file_for_appending
154 {
155 my ($s, $context, $filename) = @_;
156
157 # Try to open the file for appending:
158 my $ofh = IO::File->new();
159 $ofh->open($filename, '>>' )
160 or die "Cannot open file '$filename' for appending: $!";
161 $ofh->binmode;
162 $ofh->autoflush(1);
163
164 return $ofh;
165 }# end open_file_for_appending()
166  
167  
168 #==============================================================================
169 sub compose_download_file_path
170 {
171 my ($s, $context) = @_;
172
173 # Compose the local filename:
174 my $file = $context->request->Form->{file};
175 my $filename = $context->config->web->media_manager_upload_root . '/' . $file;
176
177 return $filename;
178 }# end compose_file_path()
179  
180  
181 #==============================================================================
182 sub compose_download_file_name
183 {
184 my ($s, $context) = @_;
185
186 # Compose the local filename:
187 my $file = $context->request->Form->{file};
188
189 return $file;
190 }# end compose_file_name()
191  
192  
193 #==============================================================================
194 sub compose_upload_file_name
195 {
196 my ($s, $context, $Upload) = @_;
197
198 # my $filename = $Upload;
199 my ($filename) = $Upload->{upload}->{upload_filename} =~ m/.*[\\\/]([^\/\\]+)$/;
200 if( ! $filename )
201 {
202 $filename = $Upload->{upload}->{upload_filename};
203 }# end if()
204
205 return $filename;
206 }# end compose_upload_file_name()
207  
208  
209 #==============================================================================
210 sub compose_upload_file_path
211 {
212 my ($s, $context, $Upload, $filename) = @_;
213
214 unless( defined($filename) && length($filename) )
215 {
216 die "\$filename not provided";
217 }# end unless()
218
219 return $context->config->web->media_manager_upload_root . "/$filename";
220 }# end compose_upload_file_path()
221  
222  
223 #==============================================================================
224 sub upload_start
225 {
226 my ($s, $context, $Upload) = @_;
227
228 shift(@_);
229 $s->SUPER::upload_start( $context, $Upload );
230  
231 my $filename = $s->compose_upload_file_name( @_ );
232
233 # Make sure we can open the file for writing:
234 my $target_file = $s->compose_upload_file_path( $context, $Upload, $filename);
235
236 # Open the file for writing:
237 my $ofh = $s->open_file_for_writing($context, $target_file);
238 print $ofh delete($Upload->{data});
239
240 # Done with the filehandle:
241 $ofh->close;
242
243 # Store some information for later:
244 $ENV{filename} ||= $target_file;
245 $ENV{download_file} ||= $filename;
246
247 # Depending on the 'mode' parameter, we do different things:
248 local $_ = $s->_args('mode');
249 if( /^create$/ )
250 {
251 $s->before_create($context, $Upload);
252 }
253 elsif( /^edit$/ )
254 {
255 $s->before_update($context, $Upload);
256 }
257 else
258 {
259 die "Unknown mode: '$_'";
260 }# end if()
261 }# end upload_start()
262  
263  
264 #==============================================================================
265 sub upload_hook
266 {
267 my ($s, $context, $Upload) = @_;
268
269 shift(@_);
270 $s->SUPER::upload_hook( @_ );
271
272 my $filename = eval {
273 my $name = $ENV{filename}; # $context->r->pnotes( 'filename' );
274 $name;
275 } or return;
276
277 my $ofh = $s->open_file_for_appending($context, $filename);
278 no warnings 'uninitialized';
279 print $ofh delete($Upload->{data});
280 $ofh->close;
281 }# end upload_hook()
282  
283  
284 #==============================================================================
285 sub upload_end
286 {
287 my ($s, $context, $Upload) = @_;
288
289 shift(@_);
290 $s->SUPER::upload_end( @_ );
291
292 # Return information about what we just did:
293 my $info = {
294 new_file => $ENV{filename},
295 filename_only => $ENV{download_file},
296 link_to_file => "/media/" . $ENV{download_file},
297 };
298 $Upload->{$_} = $info->{$_} foreach keys(%$info);
299
300 # Depending on the 'mode' parameter, we do different things:
301 # local $_ = $context->request->Form->{mode};
302 my $form = $context->request->Form;
303 $form = $context->request->Form;
304 if( $form->{mode} =~ /^create$/ )
305 {
306 $s->after_create($context, $Upload);
307 }
308 elsif( $form->{mode} =~ /^edit$/ )
309 {
310 $s->after_update($context, $Upload);
311 }
312 else
313 {
314 die "Unknown mode: '$_'";
315 }# end if()
316 }# end upload_end()
317  
318  
319 #==============================================================================
320 sub before_download
321 {
322 my ($s, $context) = @_;
323
324 }# end before_download()
325  
326  
327 #==============================================================================
328 sub after_download
329 {
330 my ($s, $context) = @_;
331
332 }# end after_download()
333  
334  
335 #==============================================================================
336 sub before_create
337 {
338 my ($s, $context, $Upload) = @_;
339 1;
340 }# end before_create()
341  
342  
343 #==============================================================================
344 sub before_update
345 {
346 my ($s, $context, $Upload) = @_;
347 1;
348 }# end before_update()
349  
350  
351 #==============================================================================
352 sub after_create
353 {
354 my ($s, $context, $Upload) = @_;
355
356 }# end after_create()
357  
358  
359 #==============================================================================
360 sub after_update
361 {
362 my ($s, $context, $Upload) = @_;
363
364 }# end after_update()
365  
366  
367 #==============================================================================
368 sub before_delete
369 {
370 my ($s, $context, $filename) = @_;
371
372 }# end before_delete()
373  
374  
375 #==============================================================================
376 sub after_delete
377 {
378 my ($s, $context, $filename) = @_;
379
380 }# end after_delete()
381  
382 1;# return true:
383  
384  
385 =pod
386  
387 =head1 NAME
388  
389 Apache2::ASP::MediaManager - Instant file management for Apache2::ASP applications
390  
391 =head1 SYNOPSIS
392  
393 Create a file in your C</handlers> folder named C<MM.pm> and add the following:
394  
395 package MM;
396
397 use strict;
398 use warnings 'all';
399 use base 'Apache2::ASP::MediaManager';
400 use vars __PACKAGE__->VARS;
401
402 sub before_download {
403 my ($s, $context, $filename) = @_;
404
405 warn "About to download '$filename'";
406 return 1;
407 }
408
409 sub after_download {
410 my ($s, $context, $filename) = @_;
411
412 warn "Finished download of '$filename'";
413 return 1;
414 }
415
416 sub before_create {
417 my ($s, $context, $Upload) = @_;
418
419 warn "About to create '$Upload->{filename_only}'";
420 return 1;
421 }
422
423 sub after_create {
424 my ($s, $context, $Upload) = @_;
425
426 warn "Just created '$Upload->{filename_only}'";
427 return $Response->Redirect( $ENV{HTTP_REFERER} );
428 }
429
430 sub before_update {
431 my ($s, $context, $Upload) = @_;
432
433 warn "About to update '$Upload->{filename_only}'";
434 return 1;
435 }
436
437 sub after_update {
438 my ($s, $context, $Upload) = @_;
439
440 warn "Just updated '$Upload->{filename_only}'";
441 return $Response->Redirect( $ENV{HTTP_REFERER} );
442 }
443
444 sub after_delete {
445 my ($s, $context, $filename) = @_;
446
447 warn "Just deleted '$filename'";
448 return $Response->Redirect( $ENV{HTTP_REFERER} );
449 }
450
451 1;# return true:
452  
453 Then create a file in your C</htdocs> folder named C<mm-test.asp>:
454  
455 <html>
456 <body>
457 <h1>File Upload Test</h1>
458 <form
459 method="post"
460 enctype="multipart/form-data"
461 action="/handlers/MM?mode=create&uploadID=2kj4hkj234h">
462 <input type="file" name="filename" >
463 <input type="submit" value="Upload File Now">
464 </form>
465
466 <h2>Existing Files (if any)</h2>
467 <p>
468 <%
469 opendir my $dir, $Config->web->media_manager_upload_root;
470 while( my $file = readdir($dir) )
471 {
472 next unless -f $Config->web->media_manager_upload_root . '/' . $file;
473 %>
474 <a href="/handlers/MM?file=<%= $file %>"><%= $file %></a><br>
475 <%
476 }# end while()
477 %>
478 </o>
479 </body>
480 </html>
481  
482 B<REALLY IMPORTANT!>: Notice the C<?mode=create&uploadID=2kj4hkj234h> in the C<action>
483 attribute of the C<form> tag. The C<mode> tells the MediaManager that we are B<creating>
484 a file, and the C<uploadID> will allow us to track the progress of the upload.
485  
486 B<IMPORTANT>: Check your configuration, where you see:
487  
488 <config>
489 ...
490 <web>
491 ...
492 <media_manager_upload_root>@ServerRoot@/MEDIA</media_manager_upload_root>
493 ...
494 </web>
495 ...
496 </config>
497  
498 Make B<*sure*> that your webserver has ownership or read/write access to that folder
499 and all of its contents.
500  
501 When you access http://yoursite.com/mm-test.asp in your browser and submit the form,
502 C<Apache2::ASP::MediaManager> will save it under your C<media_manager_upload_root>
503 folder for you.
504  
505 =head1 DESCRIPTION
506  
507 Handling file uploads can be a real pain. Restricting file uploads and downloads
508 to a select group of users is also problematic.
509  
510 B<And Then...>
511  
512 And then there was C<Apache2::ASP::MediaManager>. Now you can have fully-functional
513 file uploads in seconds.
514  
515 =head1 UPLOAD PROGRESS INDICATORS
516  
517 C<Apache2::ASP::MediaManager> makes it easy to provide upload progress indicators.
518  
519 Remember that C<uploadID> parameter in the C<action> attribute of your form? While
520 the upload is taking place, the C<$Session> object is getting updated with the
521 status of the upload. If you were to make another handler - C</handlers/UploadProgress.pm> -
522 and insert the following code:
523  
524 package UploadProgress;
525
526 use strict;
527 use base 'Apache2::ASP::FormHandler';
528 use vars __PACKAGE__->VARS;
529
530 sub run {
531 my ($s, $context) = @_;
532
533 my $uploadID = $Form->{uploadID};
534
535 $Session->{"upload$uploadID" . "percent_complete"} ||= 0;
536
537 $Response->Expires( -30 );
538 $Response->Write( $Session->{"upload$uploadID" . "percent_complete"} );
539 }# end run()
540
541 1;# return true:
542  
543 And add call out to it via AJAX - you can get real-time upload progress information
544 about the current upload.
545  
546 Example:
547  
548 window.setInterval(function() {
549 httpOb.open("GET", "/handlers/UploadProgress?uploadID=2kj4hkj234h", true);
550 httpOb.onreadystatechange = function() {
551 if( httpOb.readyState == 4 ) {
552 document.getElementById("percent_complete").innerHTML = httpOb.responseText + '%';
553 }// end if()
554 };
555 }, 1000);
556  
557 You should also add an element with an id of "percent_complete" to he form:
558  
559 <div id="percent_complete">0%</div>
560  
561 =head1 PUBLIC PROPERTIES
562  
563 None.
564  
565 =head1 PUBLIC METHODS
566  
567 Nothing you need to worry about.
568  
569 =head1 EVENTS
570  
571 B<About the C<$Upload> argument>:
572  
573 The C<$Upload> argument is an instance of L<Apache2::ASP::UploadHookArgs>.
574  
575 =head2 before_download( $self, $context )
576  
577 Called before allowing a file to be downloaded from the server.
578  
579 B<NOTE>: This method must return true, or the file will not be downloaded.
580  
581 =head2 after_download( $self, $context )
582  
583 Called after allowing a file to be downloaded from the server.
584  
585 =head2 before_create( $self, $context, $Upload )
586  
587 Called before allowing a new file to be uploaded to the server.
588  
589 B<NOTE>: This method must return true, or the file will not be created.
590  
591 =head2 after_create( $self, $context, $Upload )
592  
593 Called after allowing a new file to be uploaded to the server.
594  
595 =head2 before_update( $self, $context, $Upload )
596  
597 Called before allowing a new file to be uploaded to replace an existing file.
598  
599 B<NOTE>: This method must return true, or the file will not be updated.
600  
601 =head2 after_update( $self, $context, $Upload )
602  
603 Called after a new file has been uploaded to replace an existing file.
604  
605 =head2 before_delete( $self, $context, $filename )
606  
607 Called before deleting a file.
608  
609 B<NOTE>: This method must return true, or the file will not be deleted.
610  
611 =head2 after_delete( $self, $context, $filename )
612  
613 Called after deleting a file.
614  
615 =head1 BUGS
616  
617 It's possible that some bugs have found their way into this release.
618  
619 Use RT L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Apache2-ASP> to submit bug reports.
620  
621 =head1 HOMEPAGE
622  
623 Please visit the Apache2::ASP homepage at L<http://www.devstack.com/> to see examples
624 of Apache2::ASP in action.
625  
626 =head1 AUTHOR
627  
628 John Drago L<mailto:jdrago_999@yahoo.com>
629  
630 =head1 COPYRIGHT AND LICENSE
631  
632 Copyright 2007 John Drago, All rights reserved.
633  
634 This software is free software. It may be used and distributed under the
635 same terms as Perl itself.
636  
637 =cut
638