blib/lib/Dancer/Plugin/DirectoryView.pm

filter: Statementstmt 29.9% 50 / 167 Branchbran 5.1% 3 / 58 Conditioncond 3.0% 1 / 33 MC/DCmcdc 0.0% 0 / 18 Subroutinesub 64.7% 11 / 17 Podpod n/a totaltotal 22.1% 65 / 293 CC 42 SCAR 63.8
CC
42
Cov
21%
_serve_files
1056.0
directory_view
56.0
_format_size
30.0
CRAP 592.3
↑ Summary
1 package Dancer::Plugin::DirectoryView;
2  
3 =head1 NAME
4  
5 Dancer::Plugin::DirectoryView - Browse directory contents in Dancer web apps
6  
7 =cut
8  
9 2 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
10  
11 2 ▶use Cwd 'abs_path';
Subroutine BEGIN: called CC=1 SCAR=0.0
12 2 ▶use Dancer ':syntax';
Subroutine BEGIN: called CC=1 SCAR=0.0
13 2 ▶use Dancer::Engine;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 2 ▶use Dancer::MIME;
Subroutine BEGIN: called CC=1 SCAR=0.0
15 2 ▶use Dancer::Plugin;
Subroutine BEGIN: called CC=1 SCAR=0.0
16 2 ▶use DirHandle;
Subroutine BEGIN: called CC=1 SCAR=0.0
17 2 ▶use File::ShareDir;
Subroutine BEGIN: called CC=1 SCAR=0.0
18 2 ▶use File::Spec::Functions qw(catfile);
Subroutine BEGIN: called CC=1 SCAR=0.0
19 2 ▶use HTTP::Date;
Subroutine BEGIN: called CC=1 SCAR=0.0
20 2 ▶use URI::Escape;
Subroutine BEGIN: called CC=1 SCAR=0.0
21  
22 2 our $VERSION = '0.02';
23  
24 # Distribution-level shared data directory
25 2 my $dist_dir = File::ShareDir::dist_dir('Dancer-Plugin-DirectoryView');
26  
27 2 my $settings = plugin_setting;
28 2 ▶my $path_prefix = $settings->{path_prefix} || '/dancer-directory-view';
Condition50%1/2
$settings->{'path_prefix'} || '/dancer-directory-view'
l!l
02
MC/DC0%0/1
$settings->{'path_prefix'} || '/dancer-directory-view'
$settings->{'path_prefix'}
Truth table50%1/2
A
A= $settings->{'path_prefix'}
Aresult
11
00
29 # Need a leading slash
30 2 ▶if ($path_prefix !~ m!^/!) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($path_prefix =~ m[^/]) 0 2 2
31 0 $path_prefix = '/' . $path_prefix;
32 }
33  
34 2 my $mime = Dancer::MIME->instance();
35  
36 2 my $builtin_tpl = {};
37  
38 0 ▶sub directory_view {
Subroutine directory_view: not called CC=7 SCAR=40.3
39 0 my $options;
40
41 0 ▶ if (@_ == 1 || (@_ == 2 && UNIVERSAL::isa($_[1], 'HASH'))) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ == 1 or @_ == 2 and UNIVERSAL::isa($_[1], 'HASH')) { } 0 0 0
Condition0%0/6
@_ == 1 or @_ == 2 and UNIVERSAL::isa($_[1], "HASH")
l!l&&r!l&&!r
000
@_ == 2 and UNIVERSAL::isa($_[1], "HASH")
!ll&&!rl&&r
000
MC/DC0%0/3
@_ == 1 or @_ == 2 and UNIVERSAL::isa($_[1], "HASH")
@_ == 1 @_ == 2 UNIVERSAL::isa($_[1], "HASH")
Truth table0%0/4
A or B and C
A= @_ == 1B= @_ == 2C= UNIVERSAL::isa($_[1], "HASH")
ABCresult
1XX1
0111
00X0
0100
42 #
43 # Called from the application
44 #
45 0 my ($root_url, $options) = @_;
46
47 0 my $root_dir = $options->{root_dir};
48
49 # Public directory
50 0 my $public_dir = abs_path(setting('public'));
51
52 0 ▶ if (defined $root_dir) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $root_dir) { } 0 0 0
53 # Root directory is set explicitly -- is it an absolute path?
54 0 ▶ if (!File::Spec->file_name_is_absolute($root_dir)) {
Branch: 1 branch
BranchTrueFalseTotal
unless ("File::Spec"->file_name_is_absolute($root_dir)) 0 0 0
55 # No -- we assume it's relative to the public directory
56 0 $root_dir = abs_path(catfile($public_dir, $root_dir));
57 }
58 }
59 else {
60 # Root directory not set -- assume it's the same as root URL,
61 # relative to the public directory
62 0 $root_dir = catfile($public_dir, split('/', $root_url));
63 }
64
65 0 $options->{root_dir} = $root_dir;
66
67 0 my $re_root = quotemeta($root_url);
68
69 # Does the root URL have a trailing slash?
70 0 ▶ if ($root_url !~ m!/$!) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($root_url =~ m[/$]) 0 0 0
71 # Add slash
72 0 $root_url =~ s!([^/])$!$1/!;
73
74 # Add a redirection route
75 0 ▶ get qr{$re_root} => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
76 0 redirect $root_url;
77 0 };
78 }
79  
80 0 my $re_path = quotemeta($root_url) . '(.*)';
81
82 0 ▶ get qr{$re_path} => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
83 0 my ($path) = splat;
84
85 0 return directory_view(%$options, path => $path);
86 0 };
87 }
88 else {
89 #
90 # Called from a route handler
91 #
92 0 return _serve_files(@_);
93 }
94 }
95
96 0 ▶sub _serve_files {
Subroutine _serve_files: not called CC=32 SCAR=69.6
97 0 my (%options) = @_;
98
99 # Root directory
100 0 ▶ my $root_dir = $options{root_dir} || '.';
Condition0%0/2
$options{'root_dir'} || '.'
l!l
00
MC/DC0%0/1
$options{'root_dir'} || '.'
$options{'root_dir'}
Truth table0%0/2
A
A= $options{'root_dir'}
Aresult
11
00
101 # Are system paths allowed?
102 0 ▶ my $system_path = $options{system_path} || 0;
Condition0%0/2
$options{'system_path'} || 0
l!l
00
MC/DC0%0/1
$options{'system_path'} || 0
$options{'system_path'}
Truth table0%0/2
A
A= $options{'system_path'}
Aresult
11
00
103 # Template to use (if set to 0, a primitive built-in template is used)
104 0 ▶ my $template = $options{template} || 'basic';
Condition0%0/2
$options{'template'} || 'basic'
l!l
00
MC/DC0%0/1
$options{'template'} || 'basic'
$options{'template'}
Truth table0%0/2
A
A= $options{'template'}
Aresult
11
00
105 # Should hidden files be included in the directory listing?
106 0 ▶ my $show_hidden_files = $options{show_hidden_files} || 0;
Condition0%0/2
$options{'show_hidden_files'} || 0
l!l
00
MC/DC0%0/1
$options{'show_hidden_files'} || 0
$options{'show_hidden_files'}
Truth table0%0/2
A
A= $options{'show_hidden_files'}
Aresult
11
00
107
108 # Current path
109 0 my $path = $options{path};
110
111 # Views directory
112 0 my $views_dir = abs_path(setting('views'));
113
114 # Strip off unwanted leading/trailing slashes
115 0 $root_dir =~ s!/$!!;
116 0 $path =~ s!^/!!;
117
118 # If root_dir is not absolute, assume it is relative to public directory
119 0 ▶ if (!File::Spec->file_name_is_absolute($root_dir)) {
Branch: 1 branch
BranchTrueFalseTotal
unless ("File::Spec"->file_name_is_absolute($root_dir)) 0 0 0
120 0 $root_dir = abs_path(catfile(abs_path(setting('public')), $root_dir));
121 }
122
123 0 my $real_path = abs_path(catfile($root_dir, $path));
124 0 $real_path =~ s!/$!!;
125  
126 0 ▶ if (index($real_path, abs_path(setting('public'))) != 0 && !$system_path) {
Branch: 1 branch
BranchTrueFalseTotal
if (index($real_path, abs_path(setting("public"))) != 0 and not $system_path) 0 0 0
Condition0%0/3
index($real_path, abs_path(setting("public"))) != 0 and not $system_path
!ll&&!rl&&r
000
MC/DC0%0/2
index($real_path, abs_path(setting("public"))) != 0 and not $system_path
index($real_path, abs_path(setting("public"))) != 0 not $system_path
Truth table0%0/3
A and not(B)
A= index($real_path, abs_path(setting("public"))) != 0B= not $system_path
ABresult
0X0
100
111
127 # The requested file/directory lies outside of the public directory, but
128 # system paths are not allowed
129 0 return send_error("Not allowed", 403);
130 }
131
132 # Make sure we're inside root_dir. This shouldn't actually be necessary, as
133 # Dancer takes care of potentially dangerous paths (e.g., containing "..")
134 # and we should be safe at this point, but let's do the check anyway in case
135 # the application is deployed in some weird insecure way or something.
136 0 ▶ if (index($real_path, $root_dir) != 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (index($real_path, $root_dir) != 0) 0 0 0
137 0 return send_error("Not allowed", 403);
138 }
139
140 0 ▶ if (-f $real_path) {
Branch: 2 branches
BranchTrueFalseTotal
if (-f $real_path) { } 0 0 0
elsif (-d $real_path) { } 0 0 0
141 #
142 # Regular file
143 #
144 0 send_file($real_path, system_path => $system_path);
145 }
146 elsif (-d $real_path) {
147 #
148 # Directory -- show contents
149 #
150 0 my @files = ();
151
152 0 ▶ if ($real_path ne $root_dir) {
Branch: 1 branch
BranchTrueFalseTotal
if ($real_path ne $root_dir) 0 0 0
153 0 push(@files, {
154 url => "../",
155 name => "Up to parent directory",
156 size => '',
157 mime_type => '',
158 mtime => '',
159 class => 'parent-directory'
160 });
161 }
162
163 0 my $dh = DirHandle->new($real_path);
164 0 my @entries;
165 0 ▶ while (defined(my $entry = $dh->read)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $entry = $dh->read)) 0 0 0
166 0 ▶ next if $entry eq '.' || $entry eq '..';
Branch: 1 branch
BranchTrueFalseTotal
if $entry eq "." or $entry eq ".." 0 0 0
Condition0%0/3
$entry eq "." or $entry eq ".."
l!l&&r!l&&!r
000
MC/DC0%0/2
$entry eq "." or $entry eq ".."
$entry eq "." $entry eq ".."
Truth table0%0/3
A or B
A= $entry eq "."B= $entry eq ".."
ABresult
1X1
011
000
167 0 ▶ next if $entry =~ /^\./ && !$show_hidden_files;
Branch: 1 branch
BranchTrueFalseTotal
if $entry =~ /^\./ and not $show_hidden_files 0 0 0
Condition0%0/3
$entry =~ /^\./ and not $show_hidden_files
!ll&&!rl&&r
000
MC/DC0%0/2
$entry =~ /^\./ and not $show_hidden_files
$entry =~ /^\./ not $show_hidden_files
Truth table0%0/3
A and not(B)
A= $entry =~ /^\./B= not $show_hidden_files
ABresult
0X0
100
111
168 0 push @entries, $entry;
169 }
170
171 # Mapping of MIME types to CSS class names
172 0 my %classes = (
173 'directory' => 'directory',
174 'application/javascript' => 'file-application-javascript',
175 'application/pdf' => 'file-application-pdf',
176 'application/vnd.ms-excel' => 'file-application-vnd-ms-excel',
177 'application/vnd.oasis.opendocument.spreadsheet' =>
178 'file-application-vnd-oasis-opendocument-spreadsheet',
179 'application/vnd.oasis.opendocument.text' =>
180 'file-application-vnd-oasis-opendocument-text',
181 'application/x-httpd-php' => 'file-application-x-php',
182 'application/x-msword' => 'file-application-msword',
183 'application/x-perl' => 'file-application-x-perl',
184 'application/xml' => 'file-application-xml',
185 'application/zip' => 'file-application-zip',
186 'image/jpeg' => 'file-image-x-generic',
187 'image/png' => 'file-image-x-generic',
188 'text/html' => 'file-text-html',
189 'text/plain' => 'file-text-plain',
190 'text/x-csrc' => 'file-text-x-csrc'
191 );
192
193 0 for my $name (sort { $a cmp $b } @entries) {
194 0 my $file = catfile($real_path, $name);
195 0 my $url = $name;
196 0 $url = join '/', map { uri_escape($_) } split m!/!, $url;
197
198 0 my $is_dir = -d $file;
199 0 my @stat = stat(_);
200
201 0 ▶ if ($is_dir) {
Branch: 1 branch
BranchTrueFalseTotal
if ($is_dir) 0 0 0
202 0 $name .= '/';
203 0 $url .= '/';
204 }
205
206 0 ▶ my $mime_type = $is_dir ? 'directory' : $mime->for_file($name)
Branch: 1 branch
BranchTrueFalseTotal
$is_dir ? : 0 0 0
Condition0%0/2
$mime->for_file($name) or ""
l!l
00
MC/DC0%0/1
$mime->for_file($name) or ""
$mime->for_file($name)
Truth table0%0/2
A
A= $mime->for_file($name)
Aresult
11
00
207 || '';
208
209 push(@files, {
210 url => $url,
211 name => $name,
212 size => $is_dir ? '' : _format_size($stat[7]),
213 mime_type => $mime_type,
214 mtime => HTTP::Date::time2str($stat[9]),
215 0 ▶ class => $classes{$mime_type} || 'file-unknown'
Branch: 1 branch
BranchTrueFalseTotal
$is_dir ? : 0 0 0
Condition0%0/2
$classes{$mime_type} || 'file-unknown'
l!l
00
MC/DC0%0/1
$classes{$mime_type} || 'file-unknown'
$classes{$mime_type}
Truth table0%0/2
A
A= $classes{$mime_type}
Aresult
11
00
216 });
217 }
218  
219 0 ▶ if ($template) {
Branch: 1 branch
BranchTrueFalseTotal
if ($template) { } 0 0 0
220 # Get a new instance of Dancer::Template::Simple
221 0 my $template_simple = Dancer::Engine->build(template => 'simple');
222 0 $template_simple->start_tag('<%');
223 0 $template_simple->stop_tag('%>');
224  
225 0 my $template_dir;
226  
227 # Look for the template files in the application's views directory
228 0 ▶ if (-d catfile($views_dir, $template)) {
Branch: 2 branches
BranchTrueFalseTotal
if (-d catfile($views_dir, $template)) { } 0 0 0
elsif (-d catfile($dist_dir, 'views', $template)) { } 0 0 0
229 0 $template_dir = catfile($views_dir, $template);
230 }
231 # Then, try the plugin's views directory
232 elsif (-d catfile($dist_dir, 'views', $template)) {
233 0 $template_dir = catfile($dist_dir, 'views', $template);
234 }
235 else {
236 # TODO: Template not found -- handle error
237 }
238
239 0 my $file_tpl = catfile($template_dir, 'file.tt');
240 0 my $listing_tpl = catfile($template_dir, 'listing.tt');
241 0 my $layout_tpl = catfile($template_dir, 'layout.tt');
242
243 # Render the list of files
244 0 my $files_html = '';
245 0 for my $file (@files) {
246 0 $files_html .= $template_simple->render($file_tpl,
247 { file => $file });
248 }
249
250 # Insert the rendered list into the listing container
251 0 my $listing_html = $template_simple->render($listing_tpl,
252 { path => '/' . $path, files => $files_html });
253
254 0 ▶ if ($options{layout}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($options{'layout'}) { } 0 0 0
255 # Is there a corresponding layout file in the views directory?
256 0 ▶ if (-f catfile($views_dir, 'layouts',
Branch: 1 branch
BranchTrueFalseTotal
if (-f catfile($views_dir, 'layouts', my $layout_file = $options{'layout'})) { } 0 0 0
257 my $layout_file = $options{layout}))
258 {
259 # Display the directory listing using the specified layout
260 # file
261 0 return $template_simple->apply_layout($listing_html, {}, {
262 layout => $layout_file });
263 }
264 else {
265 # Use the application's default layout
266 0 return $template_simple->apply_layout($listing_html);
267 }
268 }
269 else {
270 # Display the listing in the template's layout
271 0 return $template_simple->render($layout_tpl,
272 { listing => $listing_html, path => '/' . $path,
273 path_prefix => $path_prefix, request => request,
274 template => 'default' });
275 }
276 }
277 else {
278 #
279 # Use a basic built-in template
280 #
281 0 my $files_html = '';
282 0 for my $file (@files) {
283 0 my $file_html = $builtin_tpl->{file};
284 0 $file_html =~ s/\[%\s*file.(\S*)\s*%\]/$file->{$1}/eg;
285 0 $files_html .= $file_html;
286 }
287 0 my $listing_html = $builtin_tpl->{listing};
288 0 $listing_html =~ s/\[%\s*path\s*%\]/"\/".$path/eg;
289 0 $listing_html =~ s/\[%\s*files\s*%\]/$files_html/eg;
290
291 0 ▶ if ($options{layout}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($options{'layout'}) { } 0 0 0
292 # Get the application's template engine
293 0 my $template = engine 'template';
294 0 ▶ if (-f catfile($views_dir, 'layouts',
Branch: 1 branch
BranchTrueFalseTotal
if (-f catfile($views_dir, 'layouts', my $layout_file = $options{'layout'})) { } 0 0 0
295 my $layout_file = $options{layout}))
296 {
297 # Display the directory listing using the specified layout
298 # file
299 0 return $template->apply_layout($listing_html, {},
300 { layout => $layout_file });
301 }
302 else {
303 # Use the default application layout
304 0 return $template->apply_layout($listing_html);
305 }
306 }
307 else {
308 # Use a primitive layout
309 0 (my $html = $builtin_tpl->{layout}) =~
310 0 s/\[%\s*content\s*%\]/$listing_html/eg;
311 0 $html =~ s/\[%\s*path\s*%\]/"\/".$path/eg;
312 0 return $html;
313 }
314 }
315 }
316 };
317  
318 2 my $path_prefix_re = quotemeta($path_prefix);
319  
320 0 ▶get qr{^$path_prefix_re/.*} => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
321 0 (my $path = request->path_info) =~ s!^$path_prefix_re/!!;
322
323 0 send_file(catfile($dist_dir, 'public', split('/', $path)),
324 system_path => 1);
325 2 };
326  
327 2 ▶if (exists $settings->{url}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $settings->{"url"}) 0 2 2
328 0 directory_view $settings->{url} => $settings;
329 }
330  
331 2 ▶if (exists $settings->{directories}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $settings->{"directories"}) 0 2 2
332 0 for my $url (keys %{$settings->{directories}}) {
333 0 ▶ directory_view $url => $settings->{directories}->{$url} || {};
Condition0%0/2
$settings->{'directories'}{$url} || {}
l!l
00
MC/DC0%0/1
$settings->{'directories'}{$url} || {}
$settings->{'directories'}{$url}
Truth table0%0/2
A
A= $settings->{'directories'}{$url}
Aresult
11
00
334 }
335 }
336  
337 2 register 'directory_view' => \&directory_view;
338  
339 2 register_plugin;
340  
341 0 ▶sub _format_size {
Subroutine _format_size: not called CC=5 SCAR=34.0
342 0 my ($size) = @_;
343 0 ▶ $size ||= 0;
Condition0%0/2
$size ||= 0
l!l
00
MC/DC0%0/1
$size ||= 0
$size
Truth table0%0/2
A
A= $size
Aresult
11
00
344
345 0 ▶ if ($size > 1024**3) {
Branch: 3 branches
BranchTrueFalseTotal
if ($size > 1073741824.0) { } 0 0 0
elsif ($size > 1048576.0) { } 0 0 0
elsif ($size > 1024) { } 0 0 0
346 0 return sprintf("%.2f GB", $size / 1024**3);
347 }
348 elsif ($size > 1024**2) {
349 0 return sprintf("%.2f MB", $size / 1024**2);
350 }
351 elsif ($size > 1024) {
352 0 return sprintf("%.0f KB", $size / 1024);
353 }
354 else {
355 0 return sprintf("%d B", $size);
356 }
357 }
358  
359 # This piece of HTML is borrowed from Plack::App::Directory, which admits to
360 # have stolen it from rack/directory.rb. The world of open-source is full of
361 # thieves.
362 2 $builtin_tpl->{layout} = <<END;
363 <html><head>
364 <title>[% path %]</title>
365 <meta http-equiv="content-type" content="text/html; charset=utf-8" />
366 <style type="text/css">
367 table { width: 100%; }
368 .name { text-align:left; }
369 .size, .mtime { text-align:right; }
370 .type { width:11em; }
371 .mtime { width:15em; }
372 </style>
373 </head><body>
374 [% content %]
375 </body></html>
376 END
377 2 $builtin_tpl->{listing} = <<END;
378 <h1>[% path %]</h1>
379 <hr />
380 <table>
381 <tr>
382 <th class="name">Name</th>
383 <th class="size">Size</th>
384 <th class="type">Type</th>
385 <th class="mtime">Last Modified</th>
386 </tr>
387 [% files %]
388 </table>
389 <hr />
390 END
391 2 $builtin_tpl->{file} = <<END;
392 <tr>
393 <td class="name"><a href="[% file.url %]">[% file.name %]</a></td>
394 <td class="size">[% file.size %]</td>
395 <td class="type">[% file.mime_type %]</td>
396 <td class="mtime">[% file.mtime %]</td>
397 </tr>
398 END
399  
400 2 1; # End of Dancer::Plugin::DirectoryView
401 __END__
↑ Summary