Uploader.pm

filter: Statementstmt 88.4% 307 / 347 Branchbran 58.8% 60 / 102 Conditioncond 43.5% 27 / 62 MC/DCmcdc 10.8% 4 / 37 Subroutinesub 93.3% 28 / 30 Podpod 100% 19 / 19 totaltotal 74.5% 445 / 597 CC 88 SCAR 27.9
CC
88
Cov
77%
upload_field_names
72.0
upload
42.6
extract_meta
14.8
CRAP 16.3
« Uploader/Transform/ImageMagick.pm ↑ Summary
1 package CGI::Uploader;
2  
3 9 ▶use 5.008;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 9 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 9 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 9 ▶use Params::Validate ':all';
Subroutine BEGIN: called CC=1 SCAR=0.0
7 9 ▶use File::Path;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 9 ▶use File::Spec;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 9 ▶use File::Temp 'tempfile';
Subroutine BEGIN: called CC=1 SCAR=0.0
10 9 ▶use Carp::Assert;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 9 ▶use Image::Size;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 9 require Exporter;
13  
14 9 our $VERSION = '2.18';
15  
16 =head1 NAME
17  
18 CGI::Uploader - Manage CGI uploads using SQL database
19  
20 =head1 Synopsis
21  
22 use CGI::Uploader::Transform::ImageMagick 'gen_thumb';
23  
24 my $u = CGI::Uploader->new(
25 spec => {
26 # Upload one image named from the form field 'img'
27 # and create one thumbnail for it.
28 img_1 => {
29 gen_files => {
30 'img_1_thmb_1' => gen_thumb({ w => 100, h => 100 }),
31 }
32 },
33 },
34  
35 updir_url => 'http://localhost/uploads',
36 updir_path => '/home/user/www/uploads',
37 temp_dir => '/home/user/www/uploads',
38  
39 dbh => $dbh,
40 query => $q, # defaults to CGI->new(),
41 );
42  
43 # ... now do something with $u
44  
45 =head1 Description
46  
47 This module is designed to help with the task of managing files uploaded
48 through a CGI application. The files are stored on the file system, and
49 the file attributes stored in a SQL database.
50  
51 =head1 Introduction and Recipes
52  
53 The L<CGI::Uploader::Cookbook|CGI::Uploader::Cookbook> provides
54 a slightly more in depth introduction and recipes for a basic BREAD web
55 application. (Browse, Read, Edit, Add, Delete).
56  
57 =head1 Constructor
58  
59 =head2 new()
60  
61 my $u = CGI::Uploader->new(
62 spec => {
63 # The first image has 2 different sized thumbnails
64 img_1 => {
65 gen_files => {
66 'img_1_thmb_1' => gen_thumb({ w => 100, h => 100 }),
67 'img_1_thmb_2' => gen_thumb({ w => 50, h => 50 }),
68 }
69 },
70 },
71  
72 # Just upload it
73 img_2 => {},
74 # Downsize the large image to these maximum dimensions if it's larger
75 img_3 => {
76 # Besides generating dependent files
77 # We can also transform the file itself
78 # Here, we shrink the image to be wider than 380
79 transform_method => \&gen_thumb,
80 # demostrating the old-style param passing
81 params => [{ w => 380 }],
82 }
83 },
84  
85 updir_url => 'http://localhost/uploads',
86 updir_path => '/home/user/www/uploads',
87  
88 dbh => $dbh,
89 query => $q, # defaults to CGI->new(),
90  
91 up_table => 'uploads', # defaults to "uploads"
92 up_seq => 'upload_id_seq', # Required for Postgres
93 );
94  
95 =over 4
96  
97 =item spec [required]
98  
99 The specification described the examples above. The keys correspond to form
100 field names for upload fields.
101  
102 The values are hash references. The simplest case is an empty hash reference,
103 which means to just upload the image and apply no transformations.
104  
105 #####
106  
107 Each key in the hash is the corresponds to a file upload field. The values
108 are hash references used provide options for how to transform the file,
109 and possibly generate additional files based on it.
110  
111 Valid keys here are:
112  
113 =item transform_method
114  
115 This is a subroutine reference. This routine can be used to transform the
116 upload before it is stored. The first argument given to the routine will be the
117 CGI::Uploader object. The second will be a full path to a file name containing
118 the upload.
119  
120 Additional arguments can be passed to the subroutine using C<params>, as in the
121 example above. But don't do that, it's ugly. If you need a custom transform
122 method, write a little closure for it like this:
123  
124 sub my_transformer {
125 my %args = @_;
126 return sub {
127 my ($self, $file) = shift;
128 # do something with $file and %args here...
129 return $path_to_new_file_i_made;
130 }
131  
132 Then in the spec you can put:
133  
134 transform_method => my_tranformer(%args),
135  
136 It must return a full path to a transformed file.
137  
138 }
139  
140 =item params (DEPRECATED)
141  
142 B<NOTE:> Using a closure based interface provides a cleaner alternative to
143 using params. See L<CGI::Uploader::Transform::ImageMagick> for an example.
144  
145 Used to pass additional arguments to C<transform_method>. See above.
146  
147 Each method used may have additional documentation about parameters
148 that can be passed to it.
149  
150  
151 =item gen_files
152  
153 A hash reference to describe files generated from a particular upload.
154 The keys are unique identifiers for the generated files. The values
155 are code references (usually closures) that prove a transformation
156 for the file. See L<CGI::Uploader::Transform::ImageMagick> for an
157 an example.
158  
159 An older interface for C<gen_files> is deprecated. For that, the values are
160 hashrefs, containing keys named C<transform_method> and C<params>, which work
161 as described above to generate a transformed version of the file.
162  
163 =item updir_url [required]
164  
165 URL to upload storage directory. Should not include a trailing slash.
166  
167 =item updir_path [required]
168  
169 File system path to upload storage directory. Should not include a trailing
170 slash.
171  
172 =item temp_dir
173  
174 Optional file system path to temporary directory. Default is File::Spec->tmpdir().
175 This temporary directory will also be used by gen_files during image transforms.
176  
177 =item dbh [required]
178  
179 DBI database handle. Required.
180  
181 =item query
182  
183 A CGI.pm-compatible object, used for the C<param> and C<upload> functions.
184 Defaults to CGI->new() if omitted.
185  
186 =item up_table
187  
188 Name of the SQL table where uploads are stored. See example syntax above or one
189 of the creation scripts included in the distribution. Defaults to "uploads" if
190 omitted.
191  
192 =item up_table_map
193  
194 A hash reference which defines a mapping between the column names used in your
195 SQL table, and those that CGI::Uploader uses. The keys are the CGI::Uploader
196 default names. Values are the names that are actually used in your table.
197  
198 This is not required. It simply allows you to use custom column names.
199  
200 upload_id => 'upload_id',
201 mime_type => 'mime_type',
202 extension => 'extension',
203 width => 'width',
204 height => 'height',
205 gen_from_id => 'gen_from_id',
206 file_name => 'file_name',
207  
208 You may also define additional column names with a value of 'undef'. This feature
209 is only useful if you override the C<extract_meta()> method or pass in
210 C<$shared_meta> to store_uploads(). Values for these additional columns will
211 then be stored by C<store_meta()> and retrieved with C<fk_meta()>.
212  
213 =item up_seq
214  
215 For Postgres only, the name of a sequence used to generate the upload_ids.
216 Defaults to C<upload_id_seq> if omitted.
217  
218 =item file_scheme
219  
220 file_scheme => 'md5',
221  
222 C<file_scheme> controls how file files are stored on the file system. The default
223 is C<simple>, which stores all the files in the same directory with names like
224 C<123.jpg>. Depending on your environment, this may be sufficient to store
225 10,000 or more files.
226  
227 As an alternative, you can specify C<md5>, which will create three levels
228 of directories based on the first three letters of the ID's md5 sum. The
229 result may look like this:
230  
231 2/0/2/123.jpg
232  
233 This should scale well to millions of files. If you want even more control,
234 consider overriding the C<build_loc()> method, which is used to return the
235 stored file path.
236  
237 Note that specifying the file storage scheme for the file system is not related
238 to the C<file_name> stored in the database, which is always the original uploaded
239 file name.
240  
241  
242 =back
243  
244 =cut
245  
246 4 ▶sub new {
Subroutine new: called CC=11 SCAR=26.6
Pod documented
247 4 my $proto = shift;
248 4 ▶ my $class = ref($proto) || $proto;
Condition33%1/3
ref $proto || $proto
l!l&&r!l&&!r
040
MC/DC0%0/2
ref $proto || $proto
ref $proto $proto
Truth table33%1/3
A || B
A= ref $protoB= $proto
ABresult
1X1
011
000
249 4 my %in = validate( @_, {
250 updir_url => { type => SCALAR },
251 updir_path => { type => SCALAR },
252 dbh => 1,
253 up_table => {
254 type => SCALAR,
255 default=> 'uploads',
256 },
257 temp_dir => {
258 type => SCALAR,
259 default => File::Spec->tmpdir()
260 },
261 up_table_map => {
262 type => HASHREF,
263 default => {
264 upload_id => 'upload_id',
265 mime_type => 'mime_type',
266 extension => 'extension',
267 width => 'width',
268 height => 'height',
269 gen_from_id => 'gen_from_id',
270 # bytes => 'bytes',
271 }
272 },
273 up_seq => { default => 'upload_id_seq'},
274 spec => { type => HASHREF },
275 query => { optional => 1 } ,
276 file_scheme => {
277 regex => qr/^simple|md5$/,
278 default => 'simple',
279 },
280  
281 });
282 4 $in{db_driver} = $in{dbh}->{Driver}->{Name};
283 # Support PostgreSQL via ODBC
284 4 ▶ $in{db_driver} = 'Pg' if $in{dbh}->get_info(17) eq 'PostgreSQL';
Branch: 1 branch
BranchTrueFalseTotal
if $in{"dbh"}->get_info(17) eq "PostgreSQL" 0 4 4
285 4 ▶ unless (($in{db_driver} eq 'mysql') or ($in{db_driver} eq 'Pg') or ($in{db_driver} eq 'SQLite')) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($in{"db_driver"} eq "mysql" or $in{"db_driver"} eq "Pg" or $in{"db_driver"} eq "SQLite") 0 4 4
Condition33%2/6
$in{"db_driver"} eq "mysql" or $in{"db_driver"} eq "Pg" or $in{"db_driver"} eq "SQLite"
l!l&&r!l&&!r
040
$in{"db_driver"} eq "mysql" or $in{"db_driver"} eq "Pg"
l!l&&r!l&&!r
004
MC/DC0%0/3
$in{"db_driver"} eq "mysql" or $in{"db_driver"} eq "Pg" or $in{"db_driver"} eq "SQLite"
$in{"db_driver"} eq "mysql" $in{"db_driver"} eq "Pg" $in{"db_driver"} eq "SQLite"
Truth table25%1/4
A or B or C
A= $in{"db_driver"} eq "mysql"B= $in{"db_driver"} eq "Pg"C= $in{"db_driver"} eq "SQLite"
ABCresult
1XX1
01X1
0011
0000
286 0 croak "only mysql, Pg and SQLite drivers are supported at this time. You are trying to use $in{db_driver}.";
287 }
288  
289 4 ▶ unless ($in{query}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($in{"query"}) 0 4 4
290 0 require CGI;
291 0 $in{query} = CGI->new;
292 }
293  
294 # Process the spec
295 4 for my $k (keys %{ $in{spec} }) {
296 # If the spec is an arrayref, that's a shorthand for specifying some gen_files.
297 4 ▶ if (ref $in{spec}->{$k} eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $in{"spec"}{$k} eq "ARRAY") 1 3 4
298 $in{spec}->{$k} = {
299 1 gen_files => $in{spec}->{$k},
300 };
301 }
302 }
303  
304 # Fill in missing map values
305 4 for (keys %{ $in{up_table_map} }) {
306 25 ▶ $in{up_table_map}{$_} = $_ unless defined $in{up_table_map}{$_};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $in{"up_table_map"}{$_} 2 23 25
307 }
308  
309 # keep pointer to input hash for easier re-use later
310 4 $in{input} =\%in;
311  
312 4 my $self = \%in;
313 4 bless ($self, $class);
314 4 return $self;
315 }
316  
317 =head1 Basic Methods
318  
319 These basic methods are all you need to know to make effective use of this
320 module.
321  
322 =head2 store_uploads()
323  
324 my $entity = $u->store_uploads($form_data);
325  
326 Stores uploaded files based on the definition given in C<spec>.
327  
328 Specifically, it does the following:
329  
330 =over
331  
332 =item o
333  
334 possibily transforms the original file according to C<transform_method>
335  
336 =item o
337  
338 possibly generates additional files based on those uploaded, according to
339 C<gen_files>.
340  
341 =item o
342  
343 stores all the files on the file system
344  
345 =item o
346  
347 inserts upload details into the database, including upload_id,
348 mime_type and extension. The columns 'width' and 'height' will be
349 populated if that meta data is available.
350  
351 =back
352  
353 As input, a hash reference of form data is expected. The simplest way
354 to get this is like this:
355  
356 use CGI;
357 my $q = new CGI;
358 $form_data = $q->Vars;
359  
360 However, I recommend that you validate your data with a module with
361 L<Data::FormValidator|Data::FormValidator>, and use a hash reference
362 of validated data, instead of directly using the CGI form data.
363  
364 CGI::Uploader is designed to handle uploads that are included as a part
365 of an add/edit form for an entity stored in a database. So, C<$form_data>
366 is expected to contain additional fields for this entity as well
367 as the file upload fields.
368  
369 For this reason, the C<store_uploads> method returns a hash reference of the
370 valid data with some transformations. File upload fields will be removed from
371 the hash, and corresponding "_id" fields will be added.
372  
373 So for a file upload field named 'img_field', the 'img_field' key
374 will be removed from the hash and 'img_field_id' will be added, with
375 the appropriate upload ID as the value.
376  
377 store_uploads takes an optional second argument as well:
378  
379 my $entity = $u->store_uploads($form_data,$shared_meta);
380  
381 This is a hash refeference of additional meta data that you want to store
382 for all of the images you storing. For example, you may wish to store
383 an "uploaded_user_id".
384  
385 The keys should be column names that exist in your C<uploads> table. The values
386 should be appropriate data for the column. Only the key names defined by the
387 C<up_table_map> in C<new()> will be used. Other values in the hash will be
388 ignored.
389  
390 =cut
391  
392 2 ▶sub store_uploads {
Subroutine store_uploads: called CC=3 SCAR=11.0
Pod documented
393 2 validate_pos(@_,1,1,0);
394 2 my $self = shift;
395 2 my $form_data = shift;
396 2 my $shared_meta = shift;
397 2 assert($form_data, 'store_uploads: input hashref missing');
398  
399 2 my $uploads = $self->{spec};
400  
401 2 my %entity_all_extra;
402 2 for my $file_field (keys %$uploads) {
403 # If we have an uploaded file for this
404 2 my ($tmp_filename,$uploaded_mt,$file_name) = $self->upload($file_field);
405 2 ▶ if ($tmp_filename) {
Branch: 1 branch
BranchTrueFalseTotal
if ($tmp_filename) 2 0 2
406 2 my $id_to_update = $form_data->{$file_field.'_id'};
407  
408 2 my %entity_upload_extra = $self->store_upload(
409 file_field => $file_field,
410 src_file => $tmp_filename,
411 uploaded_mt => $uploaded_mt,
412 file_name => $file_name,
413 shared_meta => $shared_meta,
414 id_to_update => $id_to_update,
415 );
416  
417 2 %entity_all_extra = (%entity_all_extra, %entity_upload_extra);
418 }
419 }
420  
421 # Now add and delete as needed
422 2 my $entity = { %$form_data, %entity_all_extra };
423 2 map { delete $entity->{$_} } keys %{ $self->{spec} };
424 # For good measure.
425 2 delete $entity->{''};
426  
427 2 File::Temp::cleanup();
428  
429 2 return $entity;
430 }
431  
432 =head2 delete_checked_uploads()
433  
434 my @fk_col_names = $u->delete_checked_uploads;
435  
436 This method deletes all uploads and any generated files
437 based on form input. Both files and meta data are removed.
438  
439 It looks through all the field names defined in C<spec>. For an upload named
440 I<img_1>, a field named I<img_1_delete> is checked to see if it has a true
441 value.
442  
443 A list of the field names is returned, prepended with '_id', such as:
444  
445 img_1_id
446  
447 The expectation is that you have foreign keys with these names defined in
448 another table. Having the names is format allows you to easily
449 set these fields to NULL in a database update:
450  
451 map { $entity->{$_} = undef } @fk_names;
452  
453 B<NOTE:> This method can not currently be used to delete a generated file by itself.
454  
455 =cut
456  
457 2 ▶sub delete_checked_uploads {
Subroutine delete_checked_uploads: called CC=7 SCAR=19.8
Pod documented
458 2 my $self = shift;
459 2 my $imgs = $self->{spec};
460  
461 2 my $q = $self->{query};
462 2 my $map = $self->{up_table_map};
463  
464 2 ▶ croak "missing gen_from_id in up_table_map" unless $map->{gen_from_id};
Branch: 1 branch
BranchTrueFalseTotal
unless $map->{"gen_from_id"} 0 2 2
465  
466  
467 2 my @to_delete;
468  
469 2 for my $file_field (keys %$imgs) {
470 2 ▶ if ($q->param($file_field.'_delete') ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($q->param($file_field . '_delete')) 2 0 2
471 2 ▶ my $upload_id = $q->param($file_field.'_id') ||
Condition50%1/2
$q->param($file_field . '_id') || croak("$file_field was selected to delete,\n but ID was missing in '${file_field}_id' field")
l!l
20
MC/DC0%0/1
$q->param($file_field . '_id') || croak("$file_field was selected to delete,\n but ID was missing in '${file_field}_id' field")
$q->param($file_field . '_id')
Truth table50%1/2
A
A= $q->param($file_field . '_id')
Aresult
11
00
472 croak "$file_field was selected to delete,
473 but ID was missing in '${file_field}_id' field";
474  
475 2 $self->delete_upload($upload_id);
476  
477 # Delete generated files as well.
478 my $gen_file_ids = $self->{dbh}->selectcol_arrayref(
479 2 ▶ "SELECT $map->{upload_id}
Condition50%1/2
$self->{'dbh'}->selectcol_arrayref("SELECT $map->{'upload_id'}\n FROM $self->{'up_table'}\n WHERE $map->{'gen_from_id'} = ?", {}, $upload_id) || []
l!l
20
MC/DC0%0/1
$self->{'dbh'}->selectcol_arrayref("SELECT $map->{'upload_id'}\n FROM $self->{'up_table'}\n WHERE $map->{'gen_from_id'} = ?", {}, $upload_id) || []
$self->{'dbh'}->selectcol_arrayref("SELECT $map->{'upload_id'}\n FROM $self->{'up_table'}\n WHERE $map->{'gen_from_id'} = ?", {}, $upload_id)
Truth table50%1/2
A
A= $self->{'dbh'}->selectcol_arrayref("SELECT $map->{'upload_id'}\n FROM $self->{'up_table'}\n WHERE $map->{'gen_from_id'} = ?", {}, $upload_id)
Aresult
11
00
480 FROM $self->{up_table}
481 WHERE $map->{gen_from_id} = ?",{},$upload_id) || [];
482  
483 2 for my $gen_file_id (@$gen_file_ids) {
484 2 $self->delete_upload($gen_file_id);
485 }
486  
487 2 push @to_delete, map {$_.'_id'} $self->spec_names($file_field) ;
488 }
489  
490 }
491  
492 2 return @to_delete;
493 }
494  
495  
496 =head2 fk_meta()
497  
498 my $href = $u->fk_meta(
499 table => $table,
500 where => \%where,
501 prefixes => \@prefixes,
502  
503 Returns a hash reference of information about the file, useful for
504 passing to a templating system. Here's an example of what the contents
505 of C<$href> might look like:
506  
507 {
508 file_1_id => 523,
509 file_1_url => 'http://localhost/images/uploads/523.pdf',
510 }
511  
512 If the files happen to be images and have their width and height
513 defined in the database row, template variables will be made
514 for these as well.
515  
516 This is going to fetch the file information from the upload table for using the row
517 where news.item_id = 23 AND news.file_1_id = uploads.upload_id.
518  
519 This is going to fetch the file information from the upload table for using the row
520 where news.item_id = 23 AND news.file_1_id = uploads.upload_id.
521  
522 The C<%where> hash mentioned here is a L<SQL::Abstract|SQL::Abstract> where clause. The
523 complete SQL that used to fetch the data will be built like this:
524  
525 SELECT upload_id as id,width,height,extension
526 FROM uploads, $table
527 WHERE (upload_id = ${prefix}_id AND (%where_clause_expanded here));
528  
529 =cut
530  
531 2 ▶sub fk_meta {
Subroutine fk_meta: called CC=3 SCAR=11.0
Pod documented
532 2 my $self = shift;
533 2 my %p = validate(@_,{
534 table => { type => SCALAR },
535 where => { type => HASHREF },
536 prefixes => { type => ARRAYREF },
537 prevent_browser_caching => { default => 1 }
538 });
539  
540  
541 2 my $table = $p{table};
542 2 my $where = $p{where};
543 2 my @file_fields = @{ $p{prefixes} };
544  
545 2 my $DBH = $self->{dbh};
546 2 my %fields;
547 2 require SQL::Abstract;
548 2 my $sql = SQL::Abstract->new;
549 2 my ($stmt,@bind) = $sql->where($where);
550  
551 # We don't want the 'WHERE' word that SQL::Abstract adds
552 2 $stmt =~ s/^\s?WHERE//;
553  
554 # XXX There is probably a more efficient way to get this data than using N selects
555  
556 # mysql uses non-standard quoting
557 2 ▶ my $qt = ($DBH->{Driver}->{Name} eq 'mysql') ? '`' : '"';
Branch: 1 branch
BranchTrueFalseTotal
$DBH->{'Driver'}{'Name'} eq 'mysql' ? : 0 2 2
558  
559 2 my $map = $self->{up_table_map};
560  
561 2 for my $field (@file_fields) {
562 my $upload = $DBH->selectrow_hashref(qq!
563 SELECT *
564 4 FROM !.$self->{up_table}.qq!, $table AS t
565 WHERE ($self->{up_table}.$map->{upload_id} = t.${qt}${field}_id${qt} and ($stmt) )!,
566 {},@bind);
567  
568 my %upload_fields = $self->transform_meta(
569 meta => $upload,
570 prevent_browser_caching => $p{prevent_browser_caching},
571 4 prefix => $field,
572 );
573 4 %fields = (%fields, %upload_fields);
574  
575 }
576  
577 2 return \%fields;
578 }
579  
580 =head1 Class Methods
581  
582 These are some handy class methods that you can use without the need to first create
583 an object using C<new()>.
584  
585 =head2 upload()
586  
587 # As a class method
588 ($tmp_filename,$uploaded_mt,$file_name) =
589 CGI::Uplooader->upload('file_field',$q);
590  
591 # As an object method
592 ($tmp_filename,$uploaded_mt,$file_name) =
593 $u->upload('file_field');
594  
595 The function is responsible for actually uploading the file.
596  
597 It can be called as a class method or an object method. As a class method, it's
598 necessary to provide a query object as the second argument. As an object
599 method, the query object given the constructor is used.
600  
601 Input:
602 - file field name
603  
604 Output:
605 - temporary file name
606 - Uploaded MIME Type
607 - Name of uploaded file (The value of the file form field)
608  
609 Currently CGI.pm, CGI::Simple and Apache::Request and are supported.
610  
611 =cut
612  
613 2 ▶sub upload {
Subroutine upload: called CC=14 SCAR=37.5
Pod documented
614 2 my $self = shift;
615 2 my $file_field = shift;
616 2 ▶ my $q = shift || $self->{query};
Condition33%1/3
shift() || $self->{'query'}
l!l&&r!l&&!r
020
MC/DC0%0/2
shift() || $self->{'query'}
shift() $self->{'query'}
Truth table33%1/3
A || B
A= shift()B= $self->{'query'}
ABresult
1X1
011
000
617  
618 2 my $fh;
619 2 my $mt = '';
620 2 my $filename = $q->param($file_field);
621  
622 2 ▶ if ($q->isa('CGI::Simple') ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($q->isa('CGI::Simple')) { } 0 2 2
elsif ($q->isa('Apache::Request')) { } 0 2 2
623 0 local $CGI::Simple::DISABLE_UPLOADS = 0; # Having uploads enabled is mandatory for this to work.
624 0 $fh = $q->upload($filename);
625 0 $mt = $q->upload_info($filename, 'mime' );
626  
627 0 ▶ if (!$fh && $q->cgi_error) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $fh and $q->cgi_error) 0 0 0
Condition0%0/3
not $fh and $q->cgi_error
!ll&&!rl&&r
000
MC/DC0%0/2
not $fh and $q->cgi_error
not $fh $q->cgi_error
Truth table0%0/3
not(A) and B
A= not $fhB= $q->cgi_error
ABresult
0X0
100
111
628 0 ▶ warn $q->cgi_error && return undef;
Condition0%0/2
$q->cgi_error && (return undef)
!ll
00
MC/DC0%0/1
$q->cgi_error && (return undef)
$q->cgi_error
Truth table0%0/2
A
A= $q->cgi_error
Aresult
00
11
629 }
630 }
631 elsif ( $q->isa('Apache::Request') ) {
632 0 my $upload = $q->upload($file_field);
633 0 $fh = $upload->fh;
634 0 $mt = $upload->type;
635 }
636 # default to CGI.pm behavior
637 else {
638 2 local $CGI::DISABLE_UPLOADS = 0; # Having uploads enabled is mandatory for this to work.
639 2 $fh = $q->upload($file_field);
640 2 ▶ $mt = $q->uploadInfo($fh)->{'Content-Type'} if $q->uploadInfo($fh);
Branch: 1 branch
BranchTrueFalseTotal
if $q->uploadInfo($fh) 2 0 2
641  
642 2 ▶ if (!$fh && $q->cgi_error) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $fh and $q->cgi_error) 0 2 2
Condition33%1/3
not $fh and $q->cgi_error
!ll&&!rl&&r
200
MC/DC0%0/2
not $fh and $q->cgi_error
not $fh $q->cgi_error
Truth table33%1/3
not(A) and B
A= not $fhB= $q->cgi_error
ABresult
0X0
100
111
643 0 ▶ warn $q->cgi_error && return undef;
Condition0%0/2
$q->cgi_error && (return undef)
!ll
00
MC/DC0%0/1
$q->cgi_error && (return undef)
$q->cgi_error
Truth table0%0/2
A
A= $q->cgi_error
Aresult
00
11
644 }
645 }
646  
647 2 ▶ return undef unless ($fh && $filename);
Branch: 1 branch
BranchTrueFalseTotal
unless $fh and $filename 0 2 2
Condition33%1/3
$fh and $filename
!ll&&!rl&&r
002
MC/DC0%0/2
$fh and $filename
$fh $filename
Truth table33%1/3
A and B
A= $fhB= $filename
ABresult
0X0
100
111
648  
649 2 my ($tmp_fh, $tmp_filename) = tempfile('CGIuploaderXXXXX', UNLINK => 1, DIR => $self->{'temp_dir'} );
650  
651 2 binmode($fh);
652  
653 2 require File::Copy;
654 2 import File::Copy;
655 2 ▶ copy($fh,$tmp_filename) || croak "upload: unable to create tmp file: $!";
Branch: 1 branch
BranchTrueFalseTotal
copy($fh, $tmp_filename) or croak("upload: unable to create tmp file: $!") 2 0 2
656  
657 2 return ($tmp_filename,$mt,$filename);
658 }
659  
660 =head1 Upload Methods
661  
662 These methods are high level methods to manage the file and meta data parts of
663 an upload, as well its generated files. If you are doing something more
664 complex or customized you may want to call or overide one of the below methods.
665  
666 =head2 store_upload()
667  
668 my %entity_upload_extra = $u->store_upload(
669 file_field => $file_field,
670 src_file => $tmp_filename,
671 uploaded_mt => $uploaded_mt,
672 file_name => $file_name,
673 shared_meta => $shared_meta, # optional
674 id_to_update => $id_to_update, # optional
675 );
676  
677 Does all the processing for a single upload, after it has been uploaded
678 to a temp file already.
679  
680 It returns a hash of key/value pairs as described in L</store_uploads()>.
681  
682 =cut
683  
684 4 ▶sub store_upload {
Subroutine store_upload: called CC=4 SCAR=13.9
Pod documented
685 4 my $self = shift;
686 4 my %p = validate(@_, {
687 file_field => { type => SCALAR },
688 src_file => { type => SCALAR },
689 uploaded_mt => { type => SCALAR },
690 file_name => { type => SCALAR | GLOBREF },
691 shared_meta => { type => HASHREF | UNDEF, default => {} },
692 id_to_update => { type => SCALAR | UNDEF, optional => 1 },
693 });
694  
695 my (
696 $file_field,
697 $tmp_filename,
698 $uploaded_mt,
699 $file_name,
700 $shared_meta,
701 $id_to_update,
702 4 ) = ($p{file_field},$p{src_file},$p{uploaded_mt},$p{file_name},$p{shared_meta},$p{id_to_update});
703  
704 # Transform file if needed
705 4 ▶ if (my $meth = $self->{spec}{$file_field}{transform_method}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $meth = $self->{"spec"}{$file_field}{"transform_method"}) 0 4 4
706 $tmp_filename = $meth->( $self,
707 $tmp_filename,
708 $self->{spec}{$file_field}{params},
709 0 );
710 }
711  
712 # XXX The uploaded mime type may have nothing to do with
713 # the current mime-type after it's transformed
714 4 my $meta = $self->extract_meta($tmp_filename,$file_name,$uploaded_mt);
715  
716 4 ▶ $shared_meta ||= {};
Condition100%2/2
$shared_meta ||= {}
l!l
22
MC/DC100%1/1
$shared_meta ||= {}
$shared_meta
Truth table100%2/2
A
A= $shared_meta
Aresult
11
00
717 4 my $all_meta = { %$meta, %$shared_meta };
718  
719 4 my $id;
720 # If it's an update
721 4 ▶ if ($id = $id_to_update) {
Branch: 1 branch
BranchTrueFalseTotal
if ($id = $id_to_update) 1 3 4
722 # delete old generated files before we create new ones
723 1 $self->delete_gen_files($id);
724  
725 # It's necessary to delete the old file when updating, because
726 # the new one may have a new extension.
727 1 $self->delete_file($id);
728 }
729  
730 # insert or update will be performed as appropriate.
731 4 $id = $self->store_meta(
732 $file_field,
733 $all_meta,
734 $id );
735  
736 4 $self->store_file($file_field,$id,$meta->{extension},$tmp_filename);
737  
738 4 my %ids = ();
739 4 %ids = $self->create_store_gen_files(
740 file_field => $file_field,
741 meta => $all_meta,
742 src_file => $tmp_filename,
743 gen_from_id => $id,
744 );
745  
746 4 return (%ids, $file_field.'_id' => $id);
747  
748 }
749  
750 =head2 create_store_gen_files()
751  
752 my %gen_file_ids = $u->create_store_gen_files(
753 file_field => $file_field,
754 meta => $meta_href,
755 src_file => $tmp_filename,
756 gen_from_id => $gen_from_id,
757 );
758  
759 This method is responsible for creating and storing
760 any needed thumbnails.
761  
762 Input:
763 - file_field: file field name
764 - meta: a hash ref of meta data, as C<extract_meta> would produce
765 - src_file: path to temporary file of the file upload
766 - gen_from_id: ID of upload that generated files will be made from
767  
768 =cut
769  
770 4 ▶sub create_store_gen_files {
Subroutine create_store_gen_files: called CC=6 SCAR=18.0
Pod documented
771 4 my $self = shift;
772 4 my %p = validate(@_, {
773 file_field => { type => SCALAR },
774 src_file => { type => SCALAR },
775 meta => { type => HASHREF | UNDEF, default => {} },
776 gen_from_id => { regex => qr/^\d*$/, },
777 });
778 my ($file_field,
779 $meta,
780 $tmp_filename,
781 4 $gen_from_id) = ($p{file_field},$p{meta},$p{src_file},$p{gen_from_id});
782  
783 4 ▶ my $gen_fields_key = $self->{spec}{$file_field}{gen_files} || return undef;
Condition50%1/2
$self->{'spec'}{$file_field}{'gen_files'} || (return undef)
l!l
40
MC/DC0%0/1
$self->{'spec'}{$file_field}{'gen_files'} || (return undef)
$self->{'spec'}{$file_field}{'gen_files'}
Truth table50%1/2
A
A= $self->{'spec'}{$file_field}{'gen_files'}
Aresult
11
00
784 4 my @gen_files = keys %{ $gen_fields_key };
785  
786 4 my $gen_files = $self->{spec}{$file_field}{gen_files};
787 4 my $q = $self->{query};
788 4 my %out;
789  
790 4 my ($w,$h) = ($meta->{width},$meta->{height});
791 4 for my $gen_file (@gen_files) {
792 4 my $gen_tmp_filename;
793  
794 # tranform as needed
795 4 my $gen_file_key = $self->{spec}{$file_field}{gen_files}{$gen_file};
796 # Recommended code ref API
797 4 ▶ if (ref $gen_file_key eq 'CODE') {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $gen_file_key eq 'CODE') { } 2 2 4
elsif (ref $gen_file_key eq 'HASH') { } 2 0 2
798 # It needed any params, they should already have been provided via closure.
799 2 $gen_tmp_filename = $gen_file_key->($self,$tmp_filename);
800 }
801 # Old, yucky hashref API
802 elsif (ref $gen_file_key eq 'HASH') {
803 2 my $meth = $gen_file_key->{transform_method};
804 $gen_tmp_filename = $meth->(
805 $self,
806 $tmp_filename,
807 $gen_file_key->{params},
808 2 );
809 }
810 else {
811 0 croak "$gen_file for $file_field was not a hashref or code ref. Check spec syntax.";
812 }
813  
814 # inherit mime-type and extension from parent
815 # but merge in updated details for this file
816 4 my $meta_from_gen_file = $self->extract_meta($gen_tmp_filename,$gen_file);
817 4 ▶ $meta_from_gen_file ||= {};
Condition50%1/2
$meta_from_gen_file ||= {}
l!l
40
MC/DC0%0/1
$meta_from_gen_file ||= {}
$meta_from_gen_file
Truth table50%1/2
A
A= $meta_from_gen_file
Aresult
11
00
818 4 my %t_info = (%$meta, gen_from_id => $gen_from_id, %$meta_from_gen_file);
819  
820  
821  
822 # Try to get image dimensions (will fail safely for non-images)
823 #($t_info{width}, $t_info{height}) = imgsize($gen_tmp_filename);
824  
825 # Insert
826 4 my $id = $self->store_meta($gen_file, \%t_info );
827  
828 # Add to output hash
829 4 $out{$gen_file.'_id'} = $id;
830  
831 4 $self->store_file($gen_file,$id,$t_info{extension},$gen_tmp_filename);
832 }
833 4 return %out;
834 }
835  
836 =head2 delete_upload()
837  
838 $u->delete_upload($upload_id);
839  
840 This method is used to delete the meta data and file associated with an upload.
841 Usually it's more convenient to use C<delete_checked_uploads> than to call this
842 method directly.
843  
844 This method does not delete generated files for this upload.
845  
846 =cut
847  
848 4 ▶sub delete_upload {
Subroutine delete_upload: called CC=1 SCAR=0.0
Pod documented
849 4 my $self = shift;
850 4 my ($id) = @_;
851  
852 4 $self->delete_file($id);
853 4 $self->delete_meta($id);
854  
855 }
856  
857 =head2 delete_gen_files()
858  
859 $self->delete_gen_files($id);
860  
861 Delete the generated files for a given file ID, from the file system and the database
862  
863 =cut
864  
865 1 ▶sub delete_gen_files {
Subroutine delete_gen_files: called CC=3 SCAR=11.0
Pod documented
866 1 validate_pos(@_,1,1);
867 1 my ($self,$id) = @_;
868  
869 1 my $dbh = $self->{dbh};
870 1 my $map = $self->{up_table_map};
871  
872 my $gen_file_ids_aref = $dbh->selectcol_arrayref(
873 "SELECT $map->{upload_id}
874 1 ▶ FROM ".$self->{up_table}. "
Condition50%1/2
$dbh->selectcol_arrayref("SELECT $map->{'upload_id'}\n FROM " . $self->{'up_table'} . "\n WHERE $map->{'gen_from_id'} = ?", {}, $id) || []
l!l
10
MC/DC0%0/1
$dbh->selectcol_arrayref("SELECT $map->{'upload_id'}\n FROM " . $self->{'up_table'} . "\n WHERE $map->{'gen_from_id'} = ?", {}, $id) || []
$dbh->selectcol_arrayref("SELECT $map->{'upload_id'}\n FROM " . $self->{'up_table'} . "\n WHERE $map->{'gen_from_id'} = ?", {}, $id)
Truth table50%1/2
A
A= $dbh->selectcol_arrayref("SELECT $map->{'upload_id'}\n FROM " . $self->{'up_table'} . "\n WHERE $map->{'gen_from_id'} = ?", {}, $id)
Aresult
11
00
875 WHERE $map->{gen_from_id} = ?",{},$id) || [];
876  
877 1 for my $gen_file_id (@$gen_file_ids_aref) {
878 1 $self->delete_file($gen_file_id);
879 1 $self->delete_meta($gen_file_id);
880 }
881  
882 }
883  
884 =head1 Meta-data Methods
885  
886 =head2 extract_meta()
887  
888 $meta = $self->extract_meta($tmp_filename,$file_name,$uploaded_mt);
889  
890 This method extracts and returns the meta data about a file and returns it.
891  
892 Input:
893  
894 - Path to file to extract meta data from
895 - the name of the file (as sent through the file upload file)
896 - The mime-type of the file, as supplied by the browser
897  
898 Returns: a hash reference of meta data, following this example:
899  
900 {
901 mime_type => 'image/gif',
902 extension => '.gif',
903 bytes => 60234,
904 file_name => 'happy.txt',
905  
906 # only for images
907 width => 50,
908 height => 50,
909 }
910  
911 =cut
912  
913 8 ▶sub extract_meta {
Subroutine extract_meta: called CC=14 SCAR=26.9
Pod documented
914 8 validate_pos(@_,1,1,1,0);
915 8 my $self = shift;
916 8 my $tmp_filename = shift;
917 8 my $file_name = shift;
918 8 ▶ my $uploaded_mt = shift || '';
Condition100%2/2
shift() || ''
l!l
44
MC/DC100%1/1
shift() || ''
shift()
Truth table100%2/2
A
A= shift()
Aresult
11
00
919  
920 # Determine and set the appropriate file system parsing routines for the
921 # uploaded path name based upon the HTTP client header information.
922 9 ▶ use HTTP::BrowserDetect;
Subroutine BEGIN: called CC=1 SCAR=0.0
923 8 my $client_os = $^O;
924 8 my $browser = HTTP::BrowserDetect->new;
925 8 ▶ $client_os = 'MSWin32' if $browser->windows;
Branch: 1 branch
BranchTrueFalseTotal
if $browser->windows 0 8 8
926 8 ▶ $client_os = 'MacOS' if $browser->mac;
Branch: 1 branch
BranchTrueFalseTotal
if $browser->mac 0 8 8
927 8 ▶ $client_os = 'Unix' if $browser->macosx;
Branch: 1 branch
BranchTrueFalseTotal
if $browser->macosx 0 8 8
928 8 require File::Basename;
929 8 File::Basename::fileparse_set_fstype($client_os);
930 8 $file_name = File::Basename::fileparse($file_name,[]);
931  
932  
933 8 require File::MMagic;
934 8 my $mm = File::MMagic->new;
935  
936 # If the uploaded mime_type was not provided calculate one from the file magic number
937 # if that does not exist, fall back on the file name
938 8 my $fm_mt = $mm->checktype_magic($tmp_filename);
939 8 ▶ $fm_mt = $mm->checktype_filename($tmp_filename) if (not defined $fm_mt or not length $fm_mt) ;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $fm_mt and length $fm_mt 8 0 8
Condition33%1/3
defined $fm_mt and length $fm_mt
!ll&&!rl&&r
800
MC/DC0%0/2
defined $fm_mt and length $fm_mt
defined $fm_mt length $fm_mt
Truth table33%1/3
A and B
A= defined $fm_mtB= length $fm_mt
ABresult
0X0
100
111
940  
941 8 ▶ my $mt = ($uploaded_mt || $fm_mt);
Condition66%2/3
$uploaded_mt || $fm_mt
l!l&&r!l&&!r
440
MC/DC0%0/2
$uploaded_mt || $fm_mt
$uploaded_mt $fm_mt
Truth table66%2/3
A || B
A= $uploaded_mtB= $fm_mt
ABresult
1X1
011
000
942 8 assert($mt,'found mime type');
943  
944  
945 9 ▶ use MIME::Types;
Subroutine BEGIN: called CC=1 SCAR=0.0
946 8 my $mimetypes = MIME::Types->new;
947 8 my MIME::Type $t = $mimetypes->type($mt);
948 8 ▶ my @mt_exts = $t ? $t->extensions : undef;
Branch: 1 branch
BranchTrueFalseTotal
$t ? : 7 1 8
949  
950 8 my $ext;
951  
952 # figure out an extension
953 8 my ($uploaded_ext) = ($file_name =~ m/\.([\w\d]*)?$/);
954  
955 # If there is at least one MIME-type found
956 8 ▶ if ($mt_exts[0]) {
Branch: 1 branch
BranchTrueFalseTotal
if ($mt_exts[0]) { } 7 1 8
957 # If the upload extension is one recognized by MIME::Type, use it.
958 7 ▶ if ((defined $uploaded_ext)
Branch: 1 branch
BranchTrueFalseTotal
if (defined $uploaded_ext and grep {/^$uploaded_ext$/;} @mt_exts) { } 3 4 7
Condition66%2/3
defined $uploaded_ext and grep {/^$uploaded_ext$/;} @mt_exts
!ll&&!rl&&r
403
MC/DC50%1/2
defined $uploaded_ext and grep {/^$uploaded_ext$/;} @mt_exts
defined $uploaded_ext grep {/^$uploaded_ext$/;} @mt_exts
Truth table66%2/3
A and B
A= defined $uploaded_extB= grep {/^$uploaded_ext$/;} @mt_exts
ABresult
0X0
100
111
959 23 and (grep {/^$uploaded_ext$/} @mt_exts)) {
960 3 $ext = $uploaded_ext;
961 }
962 # otherwise, use one from MIME::Type, just to be safe
963 else {
964 4 $ext = $mt_exts[0];
965 }
966 }
967 else {
968 # If is a provided extension but no MIME::Type extension, use that.
969 # It's possible that there no extension uploaded or found)
970 1 $ext = $uploaded_ext;
971 }
972  
973 8 ▶ if ($ext) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ext) { } 8 0 8
974 8 ▶ $ext = ".$ext" if $ext;
Branch: 1 branch
BranchTrueFalseTotal
if $ext 8 0 8
975 }
976 else {
977 0 croak "no extension found for file name: $file_name";
978 }
979  
980  
981 # Now get the image dimensions if it's an image
982 8 my ($width,$height) = imgsize($tmp_filename);
983  
984 return {
985 8 file_name => $file_name,
986 mime_type => $mt,
987 extension => $ext,
988 bytes => (stat ($tmp_filename))[7],
989  
990 # only for images
991 width => $width,
992 height => $height,
993 };
994  
995  
996 }
997  
998 =head2 store_meta()
999  
1000 my $id = $self->store_meta($file_field,$meta);
1001  
1002 This function is used to store the meta data of a file upload.
1003  
1004 Input:
1005  
1006 - file field name
1007  
1008 - A hashref of key/value pairs to be stored. Only the key names defined by the
1009 C<up_table_map> in C<new()> will be used. Other values in the hash will be
1010 ignored.
1011  
1012 - Optionally, an upload ID can be passed, causing an 'Update' to happen instead of an 'Insert'
1013  
1014 Output:
1015 - The id of the file stored. The id is generated by store_meta().
1016  
1017 =cut
1018  
1019 8 ▶sub store_meta {
Subroutine store_meta: called CC=12 SCAR=25.3
Pod documented
1020 8 validate_pos(@_,1,1,1,0);
1021 8 my $self = shift;
1022  
1023 # Right now we don't use the the file field name
1024 # It seems like a good idea to have in case you want to sub-class it, though.
1025 8 my $file_field = shift;
1026 8 my $href = shift;
1027 8 my $id = shift;
1028  
1029 8 my $DBH = $self->{dbh};
1030  
1031 8 require SQL::Abstract;
1032 8 my $sql = SQL::Abstract->new;
1033 8 my $map = $self->{up_table_map};
1034 8 my %copy = %$href;
1035  
1036 8 ▶ my $is_update = 1 if $id;
Branch: 1 branch
BranchTrueFalseTotal
if $id 1 7 8
1037  
1038 8 ▶ if (!$is_update && $self->{db_driver} eq 'Pg') {
Branch: 1 branch
BranchTrueFalseTotal
if (not $is_update and $self->{"db_driver"} eq "Pg") 0 8 8
Condition66%2/3
not $is_update and $self->{"db_driver"} eq "Pg"
!ll&&!rl&&r
170
MC/DC0%0/2
not $is_update and $self->{"db_driver"} eq "Pg"
not $is_update $self->{"db_driver"} eq "Pg"
Truth table66%2/3
not(A) and B
A= not $is_updateB= $self->{"db_driver"} eq "Pg"
ABresult
0X0
100
111
1039 0 $id = $DBH->selectrow_array("SELECT NEXTVAL('".$self->{up_seq}."')");
1040 0 $copy{$map->{upload_id} } = $id;
1041 }
1042  
1043 8 my @orig_keys = keys %copy;
1044 8 for (@orig_keys) {
1045 54 ▶ if (exists $map->{$_}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $map->{$_}) 37 17 54
1046 # We're done if the names are the same
1047 37 ▶ next if ($_ eq $map->{$_});
Branch: 1 branch
BranchTrueFalseTotal
if $_ eq $map->{$_} 28 9 37
1048  
1049 # Replace each key name with the mapped name
1050 9 $copy{ $map->{$_} } = $copy{$_};
1051  
1052 }
1053 # The original field is now duplicated in the hash or unknown.
1054 # delete in either case.
1055 26 delete $copy{$_};
1056 }
1057  
1058 8 my ($stmt,@bind);
1059 8 ▶ if ($is_update) {
Branch: 1 branch
BranchTrueFalseTotal
if ($is_update) { } 1 7 8
1060 1 ($stmt,@bind) = $sql->update($self->{up_table},\%copy, { $map->{upload_id} => $id });
1061 }
1062 else {
1063 7 ($stmt,@bind) = $sql->insert($self->{up_table},\%copy);
1064 }
1065  
1066 8 $DBH->do($stmt,{},@bind);
1067 8 ▶ if (!$is_update && $self->{db_driver} eq 'mysql') {
Branch: 1 branch
BranchTrueFalseTotal
if (not $is_update and $self->{"db_driver"} eq "mysql") 0 8 8
Condition66%2/3
not $is_update and $self->{"db_driver"} eq "mysql"
!ll&&!rl&&r
170
MC/DC0%0/2
not $is_update and $self->{"db_driver"} eq "mysql"
not $is_update $self->{"db_driver"} eq "mysql"
Truth table66%2/3
not(A) and B
A= not $is_updateB= $self->{"db_driver"} eq "mysql"
ABresult
0X0
100
111
1068 0 $id = $DBH->{'mysql_insertid'};
1069 }
1070 8 ▶ if (!$is_update && $self->{db_driver} eq 'SQLite') {
Branch: 1 branch
BranchTrueFalseTotal
if (not $is_update and $self->{"db_driver"} eq "SQLite") 7 1 8
Condition66%2/3
not $is_update and $self->{"db_driver"} eq "SQLite"
!ll&&!rl&&r
107
MC/DC50%1/2
not $is_update and $self->{"db_driver"} eq "SQLite"
not $is_update $self->{"db_driver"} eq "SQLite"
Truth table66%2/3
not(A) and B
A= not $is_updateB= $self->{"db_driver"} eq "SQLite"
ABresult
0X0
100
111
1071 7 $id = $DBH->func('last_insert_rowid')
1072 }
1073  
1074 8 return $id;
1075 }
1076  
1077 =head2 delete_meta()
1078  
1079 my $dbi_rv = $self->delete_meta($id);
1080  
1081 Deletes the meta data for a file and returns the DBI return value for this operation.
1082  
1083 =cut
1084  
1085 5 ▶sub delete_meta {
Subroutine delete_meta: called CC=1 SCAR=0.0
Pod documented
1086 5 validate_pos(@_,1,1);
1087 5 my $self = shift;
1088 5 my $id = shift;
1089  
1090 5 my $DBH = $self->{dbh};
1091 5 my $map = $self->{up_table_map};
1092  
1093 5 return $DBH->do("DELETE from ".$self->{up_table}." WHERE $map->{upload_id} = $id");
1094  
1095 }
1096  
1097 =head2 transform_meta()
1098  
1099 my %meta_to_display = $u->transform_meta(
1100 meta => $meta_from_db,
1101 prefix => 'my_field',
1102 prevent_browser_caching => 0,
1103 fields => [qw/id url width height/],
1104 );
1105  
1106 Prepares meta data from the database for display.
1107  
1108  
1109 Input:
1110 - meta: A hashref, as might be returned from "SELECT * FROM uploads WHERE upload_id = ?"
1111  
1112 - prefix: the resulting hashref keys will be prefixed with this,
1113 adding an underscore as well.
1114  
1115 - prevent_browse_caching: If set to true, a random query string
1116 will be added, preventing browsings from caching the image. This is very
1117 useful when displaying an image an 'update' page. Defaults to true.
1118  
1119 - fields: An arrayef of fields to format. The values here must be
1120 keys in the C<up_table_map>. Two field names are special. 'C<id> is
1121 used to denote the upload_id. C<url> combines several fields into
1122 a URL to link to the upload.
1123  
1124 Output:
1125 - A formatted hash.
1126  
1127 See L</fk_meta()> for example output.
1128  
1129 =cut
1130  
1131 5 ▶sub transform_meta {
Subroutine transform_meta: called CC=6 SCAR=18.1
Pod documented
1132 5 my $self = shift;
1133 5 my %p = validate(@_, {
1134 meta => { type => HASHREF },
1135 prefix => { type => SCALAR },
1136 prevent_browser_caching => { default => 1 },
1137 fields => { type => ARRAYREF ,
1138 default => [qw/id url width height/],
1139 },
1140 });
1141 # return undef unless (ref $p{meta} eq 'HASH');
1142  
1143 5 my $map = $self->{up_table_map};
1144  
1145 5 my %result;
1146  
1147 my $qs;
1148 5 ▶ if ($p{prevent_browser_caching}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($p{"prevent_browser_caching"}) 5 0 5
1149 # a random number to defeat image caching. We may want to change this later.
1150 5 my $rand = (int rand 100);
1151 5 $qs = "?$rand";
1152 }
1153  
1154 5 my %fields = map { $_ => 1 } @{ $p{fields} };
1155  
1156 5 ▶ if ($fields{url}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($fields{"url"}) 5 0 5
1157 $result{$p{prefix}.'_url'} = $self->{updir_url}.'/'.
1158 $self->build_loc(
1159 $p{meta}{ $map->{upload_id} }
1160 ,$p{meta}{ $map->{extension} })
1161 5 .$qs ;
1162 5 delete $fields{url};
1163 }
1164  
1165 5 ▶ if (exists $fields{id}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $fields{"id"}) 5 0 5
1166 5 $result{$p{prefix}.'_id'} = $p{meta}->{ $map->{upload_id} };
1167 5 delete $fields{id};
1168 }
1169  
1170 5 for my $k (keys %fields) {
1171 10 my $v = $p{meta}->{ $map->{$k} };
1172 10 ▶ $result{$p{prefix}.'_'.$k} = $v if defined $v;
Branch: 1 branch
BranchTrueFalseTotal
if defined $v 0 10 10
1173 }
1174  
1175 5 return %result;
1176  
1177  
1178 }
1179  
1180 =head2 get_meta()
1181  
1182 my $meta_href = $self->get_meta($id);
1183  
1184 Returns a hashref of data stored in the uploads database table for the requested file id.
1185  
1186 =cut
1187  
1188 0 ▶sub get_meta {
Subroutine get_meta: not called CC=1 SCAR=6.9
Pod documented
1189 0 validate_pos(@_,1,1);
1190 0 my ($self,$id) = @_;
1191  
1192 0 my $map = $self->{up_table_map};
1193 0 return $self->{dbh}->selectrow_hashref("
1194 SELECT * FROM $self->{up_table}
1195 WHERE $map->{upload_id} = ?",{},$id);
1196 }
1197  
1198  
1199  
1200 =head1 File Methods
1201  
1202 =head2 store_file()
1203  
1204 $self->store_file($file_field,$tmp_file,$id,$ext);
1205  
1206 Stores an upload file or dies if there is an error.
1207  
1208 Input:
1209 - file field name
1210 - path to tmp file for uploaded image
1211 - file id, as generated by C<store_meta()>
1212 - file extension, as discovered by L<extract_meta()>
1213  
1214 Output: none
1215  
1216 =cut
1217  
1218 8 ▶sub store_file {
Subroutine store_file: called CC=2 SCAR=6.9
Pod documented
1219 8 validate_pos(@_,1,1,1,1,1);
1220 8 my $self = shift;
1221 8 my ($file_field,$id,$ext,$tmp_file) = @_;
1222 8 assert($ext, 'have extension');
1223 8 assert($id,'have id');
1224 8 assert(-f $tmp_file,'tmp file exists');
1225 8 assert(-d $self->{updir_path},'updir_path is a directory');
1226 8 assert(-w $self->{updir_path},'updir_path is writeable');
1227  
1228 8 require File::Copy;
1229 8 import File::Copy;
1230 8 ▶ copy($tmp_file, File::Spec->catdir($self->{updir_path},$self->build_loc($id,$ext)) )
Branch: 1 branch
BranchTrueFalseTotal
copy($tmp_file, "File::Spec"->catdir($self->{"updir_path"}, $self->build_loc($id, $ext))) or croak("Unexpected error occured when uploading the image: $!") 8 0 8
1231 || croak "Unexpected error occured when uploading the image: $!";
1232  
1233 }
1234  
1235 =head2 delete_file()
1236  
1237 $self->delete_file($id);
1238  
1239 Call from within C<delete_upload>, this routine deletes the actual file.
1240 Dont' delete the the meta data first, you may need it build the path name
1241 of the file to delete.
1242  
1243 =cut
1244  
1245 6 ▶sub delete_file {
Subroutine delete_file: called CC=4 SCAR=14.4
Pod documented
1246 6 validate_pos(@_,1,1);
1247 6 my $self = shift;
1248 6 my $id = shift;
1249  
1250 6 my $map = $self->{up_table_map};
1251 6 my $dbh = $self->{dbh};
1252  
1253 6 my $ext = $dbh->selectrow_array("
1254 SELECT $map->{extension}
1255 FROM $self->{up_table}
1256 WHERE $map->{upload_id} = ?",{},$id);
1257 6 ▶ $ext || croak "found no extension in meta data for ID $id. Deleting file failed.";
Branch: 1 branch
BranchTrueFalseTotal
$ext or croak("found no extension in meta data for ID $id. Deleting file failed.") 6 0 6
1258  
1259  
1260 6 my $file = $self->{updir_path}.'/'.$self->build_loc($id,$ext);
1261  
1262 6 ▶ if (-e $file) {
Branch: 1 branch
BranchTrueFalseTotal
if (-e $file) { } 6 0 6
1263 6 ▶ unlink $file || croak "couldn't delete upload file: $file: $!";
Condition50%1/2
$file || croak("couldn't delete upload file: ${file}: $!")
l!l
60
MC/DC0%0/1
$file || croak("couldn't delete upload file: ${file}: $!")
$file
Truth table50%1/2
A
A= $file
Aresult
11
00
1264 }
1265 else {
1266 0 warn "file to delete not found: $file";
1267 }
1268  
1269 }
1270  
1271 =head1 Utility Methods
1272  
1273 =head2 build_loc()
1274  
1275 my $up_loc = $self->build_loc($id,$ext);
1276  
1277 Builds a path to access a single upload, relative to C<updir_path>.
1278 This is used to both file-system and URL access. Also see the C<file_scheme>
1279 option to C<new()>, which affects it's behavior.
1280  
1281 =cut
1282  
1283 20 ▶sub build_loc {
Subroutine build_loc: called CC=4 SCAR=13.9
Pod documented
1284 20 validate_pos(@_,1,1,0);
1285 20 my ($self,$id,$ext) = @_;
1286  
1287 20 my $scheme = $self->{file_scheme};
1288  
1289 20 my $loc;
1290 20 ▶ if ($scheme eq 'simple') {
Branch: 2 branches
BranchTrueFalseTotal
if ($scheme eq 'simple') { } 19 1 20
elsif ($scheme eq 'md5') { } 1 0 1
1291 19 $loc = "$id$ext";
1292 }
1293 elsif ($scheme eq 'md5') {
1294 1 require Digest::MD5;
1295 1 import Digest::MD5 qw/md5_hex/;
1296 1 my $md5_path = md5_hex($id);
1297 1 $md5_path =~ s|^(.)(.)(.).*|$1/$2/$3|;
1298  
1299 1 my $full_path = $self->{updir_path}.'/'.$md5_path;
1300 1 ▶ unless (-e $full_path) {
Branch: 1 branch
BranchTrueFalseTotal
unless (-e $full_path) 1 0 1
1301 1 mkpath($full_path);
1302 }
1303  
1304  
1305 1 $loc = File::Spec->catdir($md5_path,"$id$ext");
1306 }
1307 }
1308  
1309 =head2 upload_field_names()
1310  
1311 # As a class method
1312 (@file_field_names) = CGI::Uploader->upload_field_names($q);
1313  
1314 # As an object method
1315 (@file_field_names) = $u->upload_field_names();
1316  
1317 Returns the names of all form fields which contain file uploads. Empty
1318 file upload fields may be excluded.
1319  
1320 This can be useful for auto-generating a C<spec>.
1321  
1322 Input:
1323 - A query object is required as input only when called as a class method.
1324  
1325 Output:
1326 - an array of the file upload field names.
1327  
1328 =cut
1329  
1330 0 ▶sub upload_field_names {
Subroutine upload_field_names: not called CC=8 SCAR=42.8
Pod documented
1331 0 my $self = shift;
1332 0 ▶ my $q = shift || $self->{query};
Condition0%0/3
shift() || $self->{'query'}
l!l&&r!l&&!r
000
MC/DC0%0/2
shift() || $self->{'query'}
shift() $self->{'query'}
Truth table0%0/3
A || B
A= shift()B= $self->{'query'}
ABresult
1X1
011
000
1333  
1334 0 my @file_field_names;
1335 0 ▶ if ( $q->isa('CGI::Simple') ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($q->isa('CGI::Simple')) { } 0 0 0
elsif ($q->isa('Apache::Request')) { } 0 0 0
1336 0 my @list_of_files = $q->upload;
1337 0 my @all_field_names = $q->param();
1338 0 for my $field (@all_field_names) {
1339 0 my $potential_file_name = $q->param($field);
1340 0 ▶ push @file_field_names, $field , if grep {m/^$potential_file_name/} @list_of_files;
Branch: 1 branch
BranchTrueFalseTotal
if grep {/^$potential_file_name/;} @list_of_files 0 0 0
1341 }
1342 }
1343 elsif ($q->isa('Apache::Request') ) {
1344 0 @file_field_names = map { $_->name } @{ $q->upload() };
1345 }
1346 # default to CGI.pm behavior
1347 else {
1348 0 my @all_field_names = $q->param();
1349 0 for my $field (@all_field_names) {
1350 0 ▶ push @file_field_names, $field , if $q->upload($field);
Branch: 1 branch
BranchTrueFalseTotal
if $q->upload($field) 0 0 0
1351 }
1352 }
1353  
1354 0 return @file_field_names;
1355  
1356 }
1357  
1358  
1359  
1360  
1361  
1362  
1363 =head2 spec_names()
1364  
1365 $spec_names = $u->spec_names('file_field'):
1366  
1367 With no arguments, returns an array of all the upload names defined in the
1368 spec, including any generated file names.
1369  
1370 With one argument, a file field from the spec, can also be provided. It then returns
1371 that name as well as the names of any related generated files.
1372  
1373 =cut
1374  
1375 3 ▶sub spec_names {
Subroutine spec_names: called CC=2 SCAR=6.9
Pod documented
1376 3 my $self = shift;
1377 3 my $spec_key = shift;
1378  
1379 3 my $all_keys = $self->{spec};
1380  
1381 # only use $spec_key if it was passed in
1382 3 ▶ my @primary_spec_keys_to_use = (defined $spec_key) ? $spec_key : keys %$all_keys;
Branch: 1 branch
BranchTrueFalseTotal
defined $spec_key ? : 2 1 3
1383  
1384 my @gen_files = @primary_spec_keys_to_use,
1385 3 map { keys %{ $all_keys->{$_}{gen_files} } } @primary_spec_keys_to_use;
1386 }
1387  
1388 9 1;
1389 __END__
« Uploader/Transform/ImageMagick.pm ↑ Summary