ASP/MediaManager.pm untested

filter: Statementstmt 0.0% 0 / 135 Branchbran 0.0% 0 / 34 Conditioncond 0.0% 0 / 26 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 26 Podpod 0.0% 0 / 21 totaltotal 0.0% 0 / 242 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->( @_ );
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 or return;
253 }
254 elsif( /^edit$/ )
255 {
256 $s->before_update($context, $Upload)
257 or return;
258 }
259 else
260 {
261 die "Unknown mode: '$_'";
262 }# end if()
263 }# end upload_start()
264  
265  
266 #==============================================================================
267 sub upload_hook
268 {
269 my ($s, $context, $Upload) = @_;
270
271 shift(@_);
272 $s->SUPER::upload_hook( @_ );
273
274 my $filename = eval {
275 my $name = $ENV{filename}; # $context->r->pnotes( 'filename' );
276 $name;
277 } or return;
278
279 my $ofh = $s->open_file_for_appending($context, $filename);
280 no warnings 'uninitialized';
281 print $ofh delete($Upload->{data});
282 $ofh->close;
283 }# end upload_hook()
284  
285  
286 #==============================================================================
287 sub upload_end
288 {
289 my ($s, $context, $Upload) = @_;
290
291 shift(@_);
292 $s->SUPER::upload_end( @_ );
293
294 # Return information about what we just did:
295 my $info = {
296 new_file => $ENV{filename},
297 filename_only => $ENV{download_file},
298 link_to_file => "/media/" . $ENV{download_file},
299 };
300 $Upload->{$_} = $info->{$_} foreach keys(%$info);
301
302 # Depending on the 'mode' parameter, we do different things:
303 # local $_ = $context->request->Form->{mode};
304 my $form = $context->request->Form;
305 $form = $context->request->Form;
306 if( $form->{mode} =~ /^create$/ )
307 {
308 $s->after_create($context, $Upload);
309 }
310 elsif( $form->{mode} =~ /^edit$/ )
311 {
312 $s->after_update($context, $Upload);
313 }
314 else
315 {
316 die "Unknown mode: '$_'";
317 }# end if()
318 }# end upload_end()
319  
320  
321 #==============================================================================
322 sub before_download
323 {
324 my ($s, $context) = @_;
325
326 }# end before_download()
327  
328  
329 #==============================================================================
330 sub after_download
331 {
332 my ($s, $context) = @_;
333
334 }# end after_download()
335  
336  
337 #==============================================================================
338 sub before_create
339 {
340 my ($s, $context, $Upload) = @_;
341 1;
342 }# end before_create()
343  
344  
345 #==============================================================================
346 sub before_update
347 {
348 my ($s, $context, $Upload) = @_;
349 1;
350 }# end before_update()
351  
352  
353 #==============================================================================
354 sub after_create
355 {
356 my ($s, $context, $Upload) = @_;
357
358 }# end after_create()
359  
360  
361 #==============================================================================
362 sub after_update
363 {
364 my ($s, $context, $Upload) = @_;
365
366 }# end after_update()
367  
368  
369 #==============================================================================
370 sub before_delete
371 {
372 my ($s, $context, $filename) = @_;
373
374 }# end before_delete()
375  
376  
377 #==============================================================================
378 sub after_delete
379 {
380 my ($s, $context, $filename) = @_;
381
382 }# end after_delete()
383  
384 1;# return true:
385  
386  
387 =pod
388  
389 =head1 NAME
390  
391 Apache2::ASP::MediaManager - Instant file management for Apache2::ASP applications
392  
393 =head1 SYNOPSIS
394  
395 Create a file in your C</handlers> folder named C<MM.pm> and add the following:
396  
397 package MM;
398
399 use strict;
400 use warnings 'all';
401 use base 'Apache2::ASP::MediaManager';
402 use vars __PACKAGE__->VARS;
403
404 sub before_download {
405 my ($s, $context, $filename) = @_;
406
407 warn "About to download '$filename'";
408 return 1;
409 }
410
411 sub after_download {
412 my ($s, $context, $filename) = @_;
413
414 warn "Finished download of '$filename'";
415 return 1;
416 }
417
418 sub before_create {
419 my ($s, $context, $Upload) = @_;
420
421 warn "About to create '$Upload->{filename_only}'";
422 return 1;
423 }
424
425 sub after_create {
426 my ($s, $context, $Upload) = @_;
427
428 warn "Just created '$Upload->{filename_only}'";
429 return $Response->Redirect( $ENV{HTTP_REFERER} );
430 }
431
432 sub before_update {
433 my ($s, $context, $Upload) = @_;
434
435 warn "About to update '$Upload->{filename_only}'";
436 return 1;
437 }
438
439 sub after_update {
440 my ($s, $context, $Upload) = @_;
441
442 warn "Just updated '$Upload->{filename_only}'";
443 return $Response->Redirect( $ENV{HTTP_REFERER} );
444 }
445
446 sub after_delete {
447 my ($s, $context, $filename) = @_;
448
449 warn "Just deleted '$filename'";
450 return $Response->Redirect( $ENV{HTTP_REFERER} );
451 }
452
453 1;# return true:
454  
455 Then create a file in your C</htdocs> folder named C<mm-test.asp>:
456  
457 <html>
458 <body>
459 <h1>File Upload Test</h1>
460 <form
461 method="post"
462 enctype="multipart/form-data"
463 action="/handlers/MM?mode=create&uploadID=2kj4hkj234h">
464 <input type="file" name="filename" >
465 <input type="submit" value="Upload File Now">
466 </form>
467
468 <h2>Existing Files (if any)</h2>
469 <p>
470 <%
471 opendir my $dir, $Config->web->media_manager_upload_root;
472 while( my $file = readdir($dir) )
473 {
474 next unless -f $Config->web->media_manager_upload_root . '/' . $file;
475 %>
476 <a href="/handlers/MM?file=<%= $file %>"><%= $file %></a><br>
477 <%
478 }# end while()
479 %>
480 </o>
481 </body>
482 </html>
483  
484 B<REALLY IMPORTANT!>: Notice the C<?mode=create&uploadID=2kj4hkj234h> in the C<action>
485 attribute of the C<form> tag. The C<mode> tells the MediaManager that we are B<creating>
486 a file, and the C<uploadID> will allow us to track the progress of the upload.
487  
488 B<IMPORTANT>: Check your configuration, where you see:
489  
490 <config>
491 ...
492 <web>
493 ...
494 <media_manager_upload_root>@ServerRoot@/MEDIA</media_manager_upload_root>
495 ...
496 </web>
497 ...
498 </config>
499  
500 Make B<*sure*> that your webserver has ownership or read/write access to that folder
501 and all of its contents.
502  
503 When you access http://yoursite.com/mm-test.asp in your browser and submit the form,
504 C<Apache2::ASP::MediaManager> will save it under your C<media_manager_upload_root>
505 folder for you.
506  
507 =head1 DESCRIPTION
508  
509 Handling file uploads can be a real pain. Restricting file uploads and downloads
510 to a select group of users is also problematic.
511  
512 B<And Then...>
513  
514 And then there was C<Apache2::ASP::MediaManager>. Now you can have fully-functional
515 file uploads in seconds.
516  
517 =head1 UPLOAD PROGRESS INDICATORS
518  
519 C<Apache2::ASP::MediaManager> makes it easy to provide upload progress indicators.
520  
521 Remember that C<uploadID> parameter in the C<action> attribute of your form? While
522 the upload is taking place, the C<$Session> object is getting updated with the
523 status of the upload. If you were to make another handler - C</handlers/UploadProgress.pm> -
524 and insert the following code:
525  
526 package UploadProgress;
527
528 use strict;
529 use base 'Apache2::ASP::FormHandler';
530 use vars __PACKAGE__->VARS;
531
532 sub run {
533 my ($s, $context) = @_;
534
535 my $uploadID = $Form->{uploadID};
536
537 $Session->{"upload$uploadID" . "percent_complete"} ||= 0;
538
539 $Response->Expires( -30 );
540 $Response->Write( $Session->{"upload$uploadID" . "percent_complete"} );
541 }# end run()
542
543 1;# return true:
544  
545 And add call out to it via AJAX - you can get real-time upload progress information
546 about the current upload.
547  
548 Example:
549  
550 window.setInterval(function() {
551 httpOb.open("GET", "/handlers/UploadProgress?uploadID=2kj4hkj234h", true);
552 httpOb.onreadystatechange = function() {
553 if( httpOb.readyState == 4 ) {
554 document.getElementById("percent_complete").innerHTML = httpOb.responseText + '%';
555 }// end if()
556 };
557 }, 1000);
558  
559 You should also add an element with an id of "percent_complete" to he form:
560  
561 <div id="percent_complete">0%</div>
562  
563 =head1 PUBLIC PROPERTIES
564  
565 None.
566  
567 =head1 PUBLIC METHODS
568  
569 Nothing you need to worry about.
570  
571 =head1 EVENTS
572  
573 B<About the C<$Upload> argument>:
574  
575 The C<$Upload> argument is an instance of L<Apache2::ASP::UploadHookArgs>.
576  
577 =head2 before_download( $self, $context )
578  
579 Called before allowing a file to be downloaded from the server.
580  
581 B<NOTE>: This method must return true, or the file will not be downloaded.
582  
583 =head2 after_download( $self, $context )
584  
585 Called after allowing a file to be downloaded from the server.
586  
587 =head2 before_create( $self, $context, $Upload )
588  
589 Called before allowing a new file to be uploaded to the server.
590  
591 B<NOTE>: This method must return true, or the file will not be created.
592  
593 =head2 after_create( $self, $context, $Upload )
594  
595 Called after allowing a new file to be uploaded to the server.
596  
597 =head2 before_update( $self, $context, $Upload )
598  
599 Called before allowing a new file to be uploaded to replace an existing file.
600  
601 B<NOTE>: This method must return true, or the file will not be updated.
602  
603 =head2 after_update( $self, $context, $Upload )
604  
605 Called after a new file has been uploaded to replace an existing file.
606  
607 =head2 before_delete( $self, $context, $filename )
608  
609 Called before deleting a file.
610  
611 B<NOTE>: This method must return true, or the file will not be deleted.
612  
613 =head2 after_delete( $self, $context, $filename )
614  
615 Called after deleting a file.
616  
617 =head1 BUGS
618  
619 It's possible that some bugs have found their way into this release.
620  
621 Use RT L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Apache2-ASP> to submit bug reports.
622  
623 =head1 HOMEPAGE
624  
625 Please visit the Apache2::ASP homepage at L<http://www.devstack.com/> to see examples
626 of Apache2::ASP in action.
627  
628 =head1 AUTHOR
629  
630 John Drago L<mailto:jdrago_999@yahoo.com>
631  
632 =head1 COPYRIGHT AND LICENSE
633  
634 Copyright 2007 John Drago, All rights reserved.
635  
636 This software is free software. It may be used and distributed under the
637 same terms as Perl itself.
638  
639 =cut
640