1 package Sesse::pr0n::WebDAV;
5 use Sesse::pr0n::Common qw(error dberror);
13 my $dbh = Sesse::pr0n::Common::get_dbh();
15 $r->headers_out->{'DAV'} = "1,2";
17 # We only handle depth=0, depth=1 (cf. the RFC)
18 my $depth = $r->headers_in->{'depth'};
19 $depth = 0 if (!defined($depth));
20 if (defined($depth) && $depth ne "0" && $depth ne "1") {
21 $r->content_type('text/plain; charset="utf-8"');
23 $r->print("Invalid depth setting");
24 return Apache2::Const::OK;
27 my ($user,$takenby) = Sesse::pr0n::Common::check_access($r);
28 if (!defined($user)) {
29 return Apache2::Const::OK;
32 # Just "ping, are you alive and do you speak WebDAV"
33 if ($r->method eq "OPTIONS") {
34 $r->content_type('text/plain; charset="utf-8"');
36 $r->headers_out->{'allow'} = 'OPTIONS,PUT';
37 $r->headers_out->{'ms-author-via'} = 'DAV';
38 return Apache2::Const::OK;
41 # Directory listings et al
42 if ($r->method eq "PROPFIND") {
43 # We ignore the body, but we _must_ consume it fully before
44 # we output anything, or Squid will get seriously confused
45 $r->discard_request_body;
47 $r->content_type('text/xml; charset="utf-8"');
50 if ($r->uri =~ m#^/webdav/?$#) {
51 $r->headers_out->{'content-location'} = "/webdav/";
55 <?xml version="1.0" encoding="utf-8"?>
56 <multistatus xmlns="DAV:">
61 <resourcetype><collection/></resourcetype>
62 <getcontenttype>text/xml</getcontenttype>
64 <status>HTTP/1.1 200 OK</status>
69 # Optionally list the upload/ dir
73 <href>/webdav/upload/</href>
76 <resourcetype><collection/></resourcetype>
77 <getcontenttype>text/xml</getcontenttype>
79 <status>HTTP/1.1 200 OK</status>
84 $r->print("</multistatus>\n");
85 } elsif ($r->uri =~ m#^/webdav/upload/?$#) {
86 $r->headers_out->{'content-location'} = "/webdav/upload/";
88 # Upload root directory
90 <?xml version="1.0" encoding="utf-8"?>
91 <multistatus xmlns="DAV:">
93 <href>/webdav/upload/</href>
96 <resourcetype><collection/></resourcetype>
97 <getcontenttype>text/xml</getcontenttype>
99 <status>HTTP/1.1 200 OK</status>
104 # Optionally list all events
106 my $q = $dbh->prepare('SELECT * FROM events WHERE vhost=?') or
107 dberror($r, "Couldn't list events");
108 $q->execute($r->get_server_name) or
109 dberror($r, "Couldn't get events");
111 while (my $ref = $q->fetchrow_hashref()) {
112 my $id = $ref->{'event'};
113 my $name = $ref->{'name'};
115 $name =~ s/&/\&/g; # hack :-)
118 <href>/webdav/upload/$id/</href>
121 <resourcetype><collection/></resourcetype>
122 <getcontenttype>text/xml</getcontenttype>
123 <displayname>$name</displayname>
125 <status>HTTP/1.1 200 OK</status>
133 $r->print("</multistatus>\n");
134 } elsif ($r->uri =~ m#^/webdav/upload/([a-zA-Z0-9-]+)/?$#) {
137 $r->headers_out->{'content-location'} = "/webdav/upload/$event/";
139 # Check that we do indeed exist
140 my $ref = $dbh->selectrow_hashref('SELECT count(*) AS numev FROM events WHERE vhost=? AND event=?',
141 undef, $r->get_server_name, $event);
142 if ($ref->{'numev'} != 1) {
144 $r->content_type('text/plain; charset=utf-8');
145 $r->print("Couldn't find event in database");
146 return Apache2::Const::OK;
149 # OK, list the directory
151 <?xml version="1.0" encoding="utf-8"?>
152 <multistatus xmlns="DAV:">
154 <href>/webdav/upload/$event/</href>
157 <resourcetype><collection/></resourcetype>
158 <getcontenttype>text/xml</getcontenttype>
160 <status>HTTP/1.1 200 OK</status>
165 # List all the files within too, of course :-)
167 my $q = $dbh->prepare('SELECT * FROM images WHERE vhost=? AND event=?') or
168 dberror($r, "Couldn't list images");
169 $q->execute($r->get_server_name, $event) or
170 dberror($r, "Couldn't get events");
172 while (my $ref = $q->fetchrow_hashref()) {
173 my $id = $ref->{'id'};
174 my $filename = $ref->{'filename'};
175 my $fname = Sesse::pr0n::Common::get_disk_location($r, $id);
176 my (undef, undef, undef, undef, undef, undef, undef, $size, undef, $mtime) = stat($fname)
178 $mtime = POSIX::strftime("%a, %d %b %Y %H:%M:%S GMT", gmtime($mtime));
179 my $mime_type = Sesse::pr0n::Common::get_mimetype_from_filename($filename);
183 <href>/webdav/upload/$event/$filename</href>
187 <getcontenttype>$mime_type</getcontenttype>
188 <getcontentlength>$size</getcontentlength>
189 <getlastmodified>$mtime</getlastmodified>
191 <status>HTTP/1.1 200 OK</status>
198 # And the magical autorename folder
201 <href>/webdav/upload/$event/autorename/</href>
204 <resourcetype><collection/></resourcetype>
205 <getcontenttype>text/xml</getcontenttype>
207 <status>HTTP/1.1 200 OK</status>
213 $r->print("</multistatus>\n");
215 return Apache2::Const::OK;
216 } elsif ($r->uri =~ m#^/webdav/upload/([a-zA-Z0-9-]+)/autorename/?$#) {
217 # The autorename folder is always empty
220 $r->headers_out->{'content-location'} = "/webdav/upload/$event/autorename/";
222 # Check that we do indeed exist
223 my $ref = $dbh->selectrow_hashref('SELECT count(*) AS numev FROM events WHERE vhost=? AND event=?',
224 undef, $r->get_server_name, $event);
225 if ($ref->{'numev'} != 1) {
227 $r->content_type('text/plain; charset=utf-8');
228 $r->print("Couldn't find event in database");
229 return Apache2::Const::OK;
232 # OK, list the (empty) directory
234 <?xml version="1.0" encoding="utf-8"?>
235 <multistatus xmlns="DAV:">
237 <href>/webdav/upload/$event/autorename/</href>
240 <resourcetype><collection/></resourcetype>
241 <getcontenttype>text/xml</getcontenttype>
243 <status>HTTP/1.1 200 OK</status>
249 return Apache2::Const::OK;
250 } elsif ($r->uri =~ m#^/webdav/upload/([a-zA-Z0-9-]+)/([a-zA-Z0-9._()-]+)$#) {
252 my ($event, $filename) = ($1, $2);
253 my ($fname, $size, $mtime);
255 # check if we have a pending fake file for this
256 my $ref = $dbh->selectrow_hashref('SELECT count(*) AS numfiles FROM fake_files WHERE event=? AND vhost=? AND filename=? AND expires_at > now()',
257 undef, $event, $r->get_server_name, $filename);
258 if ($ref->{'numfiles'} == 1) {
259 $fname = "/dev/null";
263 ($fname, $size, $mtime) = Sesse::pr0n::Common::stat_image($r, $event, $filename);
266 if (!defined($fname)) {
268 $r->content_type('text/plain; charset=utf-8');
269 $r->print("Couldn't find file");
270 return Apache2::Const::OK;
272 my $mime_type = Sesse::pr0n::Common::get_mimetype_from_filename($filename);
274 $mtime = POSIX::strftime("%a, %d %b %Y %H:%M:%S GMT", gmtime($mtime));
276 <?xml version="1.0" encoding="utf-8"?>
277 <multistatus xmlns="DAV:">
279 <href>/webdav/upload/$event/$filename</href>
283 <getcontenttype>$mime_type</getcontenttype>
284 <getcontentlength>$size</getcontentlength>
285 <getlastmodified>$mtime</getlastmodified>
287 <status>HTTP/1.1 200 OK</status>
292 return Apache2::Const::OK;
293 } elsif ($r->uri =~ m#^/webdav/upload/([a-zA-Z0-9-]+)/autorename/(.{1,250})$#) {
294 # stat a single file in autorename
295 my ($event, $filename) = ($1, $2);
296 my ($fname, $size, $mtime);
298 # check if we have a pending fake file for this
299 my $ref = $dbh->selectrow_hashref('SELECT count(*) AS numfiles FROM fake_files WHERE event=? AND vhost=? AND filename=? AND expires_at > now()',
300 undef, $event, $r->get_server_name, $filename);
301 if ($ref->{'numfiles'} == 1) {
302 $fname = "/dev/null";
306 # check if we have a "shadow file" for this
307 my $ref = $dbh->selectrow_hashref('SELECT id FROM shadow_files WHERE vhost=? AND event=? AND filename=? AND expires_at > now()',
308 undef, $r->get_server_name, $event, $filename);
310 ($fname, $size, $mtime) = Sesse::pr0n::Common::stat_image_from_id($r, $ref->{'id'});
314 if (!defined($fname)) {
316 $r->content_type('text/plain; charset=utf-8');
317 $r->print("Couldn't find file");
318 return Apache2::Const::OK;
320 my $mime_type = Sesse::pr0n::Common::get_mimetype_from_filename($filename);
322 $mtime = POSIX::strftime("%a, %d %b %Y %H:%M:%S GMT", gmtime($mtime));
324 <?xml version="1.0" encoding="utf-8"?>
325 <multistatus xmlns="DAV:">
327 <href>/webdav/upload/$event/autorename/$filename</href>
331 <getcontenttype>$mime_type</getcontenttype>
332 <getcontentlength>$size</getcontentlength>
333 <getlastmodified>$mtime</getlastmodified>
335 <status>HTTP/1.1 200 OK</status>
342 $r->content_type('text/plain; charset=utf-8');
343 $r->print("Couldn't find file");
345 return Apache2::Const::OK;
348 if ($r->method eq "HEAD" or $r->method eq "GET") {
349 if ($r->uri !~ m#^/webdav/upload/([a-zA-Z0-9-]+)/(autorename/)?(.{1,250})$#) {
351 $r->content_type('text/xml; charset=utf-8');
352 $r->print("<?xml version=\"1.0\"?>\n<p>Couldn't find file</p>");
353 return Apache2::Const::OK;
356 my ($event, $autorename, $filename) = ($1, $2, $3);
358 # Check if this file really exists
359 my ($fname, $size, $mtime);
361 # check if we have a pending fake file for this
362 my $ref = $dbh->selectrow_hashref('SELECT count(*) AS numfiles FROM fake_files WHERE event=? AND vhost=? AND filename=? AND expires_at > now()',
363 undef, $event, $r->get_server_name, $filename);
364 if ($ref->{'numfiles'} == 1) {
365 $fname = "/dev/null";
369 # check if we have a "shadow file" for this
370 if (defined($autorename) && $autorename eq "autorename/") {
371 my $ref = $dbh->selectrow_hashref('SELECT id FROM shadow_files WHERE host=? AND event=? AND filename=? AND expires_at > now()',
372 undef, $r->get_server_name, $event, $filename);
374 ($fname, $size, $mtime) = Sesse::pr0n::Common::stat_image_from_id($r, $ref->{'id'});
376 } elsif (!defined($fname)) {
377 ($fname, $size, $mtime) = Sesse::pr0n::Common::stat_image($r, $event, $filename);
381 if (!defined($fname)) {
383 $r->content_type('text/plain; charset=utf-8');
384 $r->print("Couldn't find file");
385 return Apache2::Const::OK;
389 $r->set_content_length($size);
390 $r->set_last_modified($mtime);
392 if ($r->method eq "GET") {
393 $r->sendfile($fname);
395 return Apache2::Const::OK;
398 if ($r->method eq "PUT") {
399 if ($r->uri !~ m#^/webdav/upload/([a-zA-Z0-9-]+)/(autorename/)?(.{1,250})$#) {
401 $r->content_type('text/plain; charset=utf-8');
402 $r->print("No access");
403 return Apache2::Const::OK;
406 my ($event, $autorename, $filename) = ($1, $2, $3);
407 my $size = $r->headers_in->{'content-length'};
408 my $orig_filename = $filename;
410 # Remove evil characters
411 if ($filename =~ /[^a-zA-Z0-9._()-]/) {
412 if (defined($autorename) && $autorename eq "autorename/") {
413 $filename =~ tr/a-zA-Z0-9.()-/_/c;
416 $r->content_type('text/plain; charset=utf-8');
417 $r->print("Illegal characters in filename");
418 return Apache2::Const::OK;
423 # gnome-vfs and mac os x love to make zero-byte files,
426 if ($r->headers_in->{'content-length'} == 0 || $filename =~ /^\.(_|DS_Store)/) {
427 $dbh->do('DELETE FROM fake_files WHERE expires_at <= now() OR (event=? AND vhost=? AND filename=?);',
428 undef, $event, $r->get_server_name, $filename)
429 or dberror($r, "Couldn't prune fake_files");
430 $dbh->do('INSERT INTO fake_files (vhost,event,filename,expires_at) VALUES (?,?,?,now() + interval \'1 day\');',
431 undef, $r->get_server_name, $event, $filename)
432 or dberror($r, "Couldn't add file");
433 $r->content_type('text/plain; charset="utf-8"');
436 $r->log->info("Fake upload of $event/$filename");
437 return Apache2::Const::OK;
441 my $ref = $dbh->selectrow_hashref("SELECT NEXTVAL('imageid_seq') AS id;");
442 my $newid = $ref->{'id'};
443 if (!defined($newid)) {
444 dberror($r, "Couldn't get new ID");
447 # Autorename if we need to
448 if (defined($autorename) && $autorename eq "autorename/") {
449 my $ref = $dbh->selectrow_hashref("SELECT COUNT(*) AS numfiles FROM images WHERE vhost=? AND event=? AND filename=?",
450 undef, $r->get_server_name, $event, $filename)
451 or dberror($r, "Couldn't check for existing files");
452 if ($ref->{'numfiles'} > 0) {
453 $r->log->info("Renaming $filename to $newid.jpeg");
454 $filename = "$newid.jpeg";
459 # Enable transactions and error raising temporarily
460 local $dbh->{AutoCommit} = 0;
461 local $dbh->{RaiseError} = 1;
464 # Try to insert this new file
466 $dbh->do('DELETE FROM fake_files WHERE vhost=? AND event=? AND filename=?',
467 undef, $r->get_server_name, $event, $filename);
469 $dbh->do('INSERT INTO images (id,vhost,event,uploadedby,takenby,filename) VALUES (?,?,?,?,?,?)',
470 undef, $newid, $r->get_server_name, $event, $user, $takenby, $filename);
471 $dbh->do('UPDATE events SET last_update=CURRENT_TIMESTAMP WHERE vhost=? AND event=?',
472 undef, $r->get_server_name, $event);
474 # Now save the file to disk
475 $fname = Sesse::pr0n::Common::get_disk_location($r, $newid);
476 open NEWFILE, ">$fname"
480 my $content_length = $r->headers_in->{'content-length'};
481 if ($r->read($buf, $content_length)) {
482 print NEWFILE $buf or die "write($fname): $!";
485 close NEWFILE or die "close($fname): $!";
487 # Orient stuff correctly
488 system("/usr/bin/exifautotran", $fname) == 0
489 or die "/usr/bin/exifautotran: $!";
491 # Make cache while we're at it.
492 # Don't do it for the resource forks Mac OS X loves to upload :-(
493 if ($filename !~ /^\.(_|DS_Store)/) {
494 # FIXME: Ideally we'd want to ensure cache of -1x-1 here as well (for NEFs), but that would
495 # preclude mipmapping in its current form.
496 Sesse::pr0n::Common::ensure_cached($r, $filename, $newid, undef, undef, 1, 80, 64, 320, 256);
499 # OK, we got this far, commit
502 $r->log->notice("Successfully wrote $event/$filename to $fname");
505 # Some error occurred, rollback and bomb out
507 error($r, "Transaction aborted because $@");
512 # Insert a `shadow file' we can stat the next day or so
513 if (defined($autorename) && $autorename eq "autorename/") {
514 $dbh->do('DELETE FROM shadow_files WHERE expires_at <= now() OR (vhost=? AND event=? AND filename=?);',
515 undef, $r->get_server_name, $event, $filename)
516 or dberror($r, "Couldn't prune shadow_files");
517 $dbh->do('INSERT INTO shadow_files (vhost,event,filename,id,expires_at) VALUES (?,?,?,?,now() + interval \'1 day\');',
518 undef, $r->get_server_name, $event, $orig_filename, $newid)
519 or dberror($r, "Couldn't add shadow file");
520 $r->log->info("Added shadow entry for $event/$filename");
523 $r->content_type('text/plain; charset="utf-8"');
527 return Apache2::Const::OK;
530 # Used by the XP publishing wizard -- largely the same as the code above
531 # but vastly simplified. Should we refactor?
532 if ($r->method eq "POST") {
533 my $apr = Apache2::Request->new($r);
534 my $client_size = $apr->param('size');
535 my $event = $apr->param('event');
537 my $file = $apr->upload('image');
538 my $filename = $file->filename();
539 if ($client_size != $file->size()) {
540 $r->content_type('text/plain; charset="utf-8"');
542 $r->print("Client-size resizing detected; refusing automatically");
544 $r->log->info("Client-size resized upload of $event/$filename detected");
545 return Apache2::Const::OK;
548 # Ugh, Windows XP seems to be sending this in... something that's not UTF-8, at least
549 my $takenby_given = Sesse::pr0n::Common::guess_charset($apr->param('takenby'));
551 if (defined($takenby_given) && $takenby_given !~ /^\s*$/ && $takenby_given !~ /[<>&]/ && length($takenby_given) <= 100) {
552 $takenby = $takenby_given;
555 my $ne_id = Sesse::pr0n::Common::guess_charset($apr->param('neweventid'));
556 my $ne_date = Sesse::pr0n::Common::guess_charset($apr->param('neweventdate'));
557 my $ne_desc = Sesse::pr0n::Common::guess_charset($apr->param('neweventdesc'));
558 if (defined($ne_id)) {
559 # Trying to add a new event, let's see if it already exists
560 my $q = $dbh->prepare('SELECT COUNT(*) AS cnt FROM events WHERE event=? AND vhost=?')
561 or dberror($r, "Couldn't prepare event count");
562 $q->execute($ne_id, $r->get_server_name)
563 or dberror($r, "Couldn't execute event count");
564 my $ref = $q->fetchrow_hashref;
566 if ($ref->{'cnt'} == 0) {
567 my @errors = Sesse::pr0n::Common::add_new_event($dbh, $ne_id, $ne_date, $ne_desc, $r->get_server_name);
568 if (scalar @errors > 0) {
569 die "Couldn't add new event $ne_id: " . join(', ', @errors);
576 # Remove evil characters
577 if ($filename =~ /[^a-zA-Z0-9._-]/) {
578 $filename =~ tr/a-zA-Z0-9.-/_/c;
582 my $ref = $dbh->selectrow_hashref("SELECT NEXTVAL('imageid_seq') AS id;");
583 my $newid = $ref->{'id'};
584 if (!defined($newid)) {
585 dberror($r, "Couldn't get new ID");
588 # Autorename if we need to
590 my $ref = $dbh->selectrow_hashref("SELECT COUNT(*) AS numfiles FROM images WHERE vhost=? AND event=? AND filename=?",
591 undef, $r->get_server_name, $event, $filename)
592 or dberror($r, "Couldn't check for existing files");
593 if ($ref->{'numfiles'} > 0) {
594 $r->log->info("Renaming $filename to $newid.jpeg");
595 $filename = "$newid.jpeg";
600 # Enable transactions and error raising temporarily
601 local $dbh->{AutoCommit} = 0;
602 local $dbh->{RaiseError} = 1;
605 # Try to insert this new file
607 $dbh->do('INSERT INTO images (id,vhost,event,uploadedby,takenby,filename) VALUES (?,?,?,?,?,?)',
608 undef, $newid, $r->get_server_name, $event, $user, $takenby, $filename);
609 $dbh->do('UPDATE events SET last_update=CURRENT_TIMESTAMP WHERE vhost=? AND event=?',
610 undef, $r->get_server_name, $event);
612 # Now save the file to disk
613 $fname = Sesse::pr0n::Common::get_disk_location($r, $newid);
614 open NEWFILE, ">$fname"
619 print NEWFILE $buf or die "write($fname): $!";
620 close NEWFILE or die "close($fname): $!";
622 # Orient stuff correctly
623 system("/usr/bin/exifautotran", $fname) == 0
624 or die "/usr/bin/exifautotran: $!";
626 # Make cache while we're at it.
627 Sesse::pr0n::Common::ensure_cached($r, $filename, $newid, undef, undef, 1, 80, 64, 320, 256, -1, -1);
629 # OK, we got this far, commit
632 $r->log->notice("Successfully wrote $event/$filename to $fname");
635 # Some error occurred, rollback and bomb out
637 error($r, "Transaction aborted because $@");
640 $r->content_type('text/plain; charset="utf-8"');
642 $r->print("Error: $@");
646 $r->content_type('text/plain; charset="utf-8"');
650 return Apache2::Const::OK;
653 # Yes, we fake locks. :-)
654 if ($r->method eq "LOCK") {
655 if ($r->uri !~ m#^/webdav/upload/([a-zA-Z0-9-]+)/(autorename/)?([a-zA-Z0-9._-]+)$#) {
657 $r->content_type('text/plain; charset=utf-8');
658 $r->print("No access");
659 return Apache2::Const::OK;
662 my ($event, $autorename, $filename) = ($1, $2, $3);
663 $autorename = '' if (!defined($autorename));
664 my $sha1 = Digest::SHA1::sha1_base64("/$event/$autorename$filename");
667 $r->content_type('text/xml; charset=utf-8');
670 <?xml version="1.0" encoding="utf-8"?>
674 <locktype><write/></locktype>
675 <lockscope><exclusive/></lockscope>
678 <href>/webdav/upload/$event/$autorename$filename</href>
680 <timeout>Second-3600</timeout>
682 <href>opaquelocktoken:$sha1</href>
688 return Apache2::Const::OK;
691 if ($r->method eq "UNLOCK") {
692 $r->content_type('text/plain; charset="utf-8"');
696 return Apache2::Const::OK;
699 if ($r->method eq "DELETE") {
700 if ($r->uri !~ m#^/webdav/upload/([a-zA-Z0-9-]+)/(autorename/)?(\._[a-zA-Z0-9._-]+)$#) {
702 $r->content_type('text/plain; charset=utf-8');
703 $r->print("No access");
704 return Apache2::Const::OK;
707 my ($event, $autorename, $filename) = ($1, $2, $3);
708 $dbh->do('DELETE FROM images WHERE vhost=? AND event=? AND filename=?',
709 undef, $r->get_server_name, $event, $filename)
710 or dberror($r, "Couldn't remove file");
711 $dbh->do('UPDATE events SET last_update=CURRENT_TIMESTAMP WHERE vhost=? AND event=?',
712 undef, $r->get_server_name, $event)
713 or dberror($r, "Couldn't invalidate cache");
717 $r->log->info("deleted $event/$filename");
719 return Apache2::Const::OK;
722 if ($r->method eq "MOVE" or
723 $r->method eq "MKCOL" or
724 $r->method eq "RMCOL" or
725 $r->method eq "RENAME" or
726 $r->method eq "COPY") {
727 $r->content_type('text/plain; charset="utf-8"');
729 $r->print("Sorry, you do not have access to that feature.");
730 return Apache2::Const::OK;
733 $r->content_type('text/plain; charset=utf-8');
734 $r->log->error("unknown method " . $r->method);
736 $r->print("Unknown method");
738 return Apache2::Const::OK;