]> git.sesse.net Git - pr0n/blob - perl/Sesse/pr0n/WebDAV.pm
Workarounds for OS X 10.5's WebDAV client, which doesn't send Content-Length.
[pr0n] / perl / Sesse / pr0n / WebDAV.pm
1 package Sesse::pr0n::WebDAV;
2 use strict;
3 use warnings;
4
5 use Sesse::pr0n::Common qw(error dberror);
6 use Digest::SHA1;
7 use MIME::Base64;
8 use Apache2::Request;
9 use Apache2::Upload;
10
11 sub handler {
12         my $r = shift;
13         my $dbh = Sesse::pr0n::Common::get_dbh();
14                         
15         $r->headers_out->{'DAV'} = "1,2";
16
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"');
22                 $r->status(403);
23                 $r->print("Invalid depth setting");
24                 return Apache2::Const::OK;
25         }
26
27         my ($user,$takenby) = Sesse::pr0n::Common::check_access($r);
28         if (!defined($user)) {
29                 return Apache2::Const::OK;
30         }
31
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"');
35                 $r->status(200);
36                 $r->headers_out->{'allow'} = 'OPTIONS,PUT';
37                 $r->headers_out->{'ms-author-via'} = 'DAV';
38                 return Apache2::Const::OK;
39         }
40         
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;
46
47                 $r->content_type('text/xml; charset="utf-8"');
48                 $r->status(207);
49
50                 if ($r->uri =~ m#^/webdav/?$#) {
51                         $r->headers_out->{'content-location'} = "/webdav/";
52                 
53                         # Root directory
54                         $r->print(<<"EOF");
55 <?xml version="1.0" encoding="utf-8"?>
56 <multistatus xmlns="DAV:">
57   <response>
58      <href>/webdav/</href>
59      <propstat>
60         <prop>
61           <resourcetype><collection/></resourcetype>
62           <getcontenttype>text/xml</getcontenttype>
63         </prop>
64         <status>HTTP/1.1 200 OK</status>
65      </propstat>
66   </response>
67 EOF
68
69                         # Optionally list the upload/ dir
70                         if ($depth >= 1) {
71                                 $r->print(<<"EOF");
72   <response>
73      <href>/webdav/upload/</href>
74      <propstat>
75         <prop>
76           <resourcetype><collection/></resourcetype>
77           <getcontenttype>text/xml</getcontenttype>
78         </prop>
79         <status>HTTP/1.1 200 OK</status>
80      </propstat>
81   </response>
82 EOF
83                         }
84                         $r->print("</multistatus>\n");
85                  } elsif ($r->uri =~ m#^/webdav/upload/?$#) {
86                         $r->headers_out->{'content-location'} = "/webdav/upload/";
87                         
88                         # Upload root directory
89                         $r->print(<<"EOF");
90 <?xml version="1.0" encoding="utf-8"?>
91 <multistatus xmlns="DAV:">
92   <response>
93      <href>/webdav/upload/</href>
94      <propstat>
95         <prop>
96           <resourcetype><collection/></resourcetype>
97           <getcontenttype>text/xml</getcontenttype>
98         </prop>
99         <status>HTTP/1.1 200 OK</status>
100      </propstat>
101   </response>
102 EOF
103
104                         # Optionally list all events
105                         if ($depth >= 1) {
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");
110                 
111                                 while (my $ref = $q->fetchrow_hashref()) {
112                                         my $id = $ref->{'event'};
113                                         my $name = $ref->{'name'};
114                                 
115                                         $name =~ s/&/\&amp;/g;  # hack :-)
116                                         $r->print(<<"EOF");
117   <response>
118      <href>/webdav/upload/$id/</href>
119      <propstat>
120         <prop>
121           <resourcetype><collection/></resourcetype>
122           <getcontenttype>text/xml</getcontenttype>
123           <displayname>$name</displayname> 
124         </prop>
125         <status>HTTP/1.1 200 OK</status>
126      </propstat>
127   </response>
128 EOF
129                                 }
130                                 $q->finish;
131                         }
132
133                         $r->print("</multistatus>\n");
134                 } elsif ($r->uri =~ m#^/webdav/upload/([a-zA-Z0-9-]+)/?$#) {
135                         my $event = $1;
136                         
137                         $r->headers_out->{'content-location'} = "/webdav/upload/$event/";
138                         
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) {
143                                 $r->status(404);
144                                 $r->content_type('text/plain; charset=utf-8');
145                                 $r->print("Couldn't find event in database");
146                                 return Apache2::Const::OK;
147                         }
148                         
149                         # OK, list the directory
150                         $r->print(<<"EOF");
151 <?xml version="1.0" encoding="utf-8"?>
152 <multistatus xmlns="DAV:">
153   <response>
154      <href>/webdav/upload/$event/</href>
155      <propstat>
156         <prop>
157           <resourcetype><collection/></resourcetype>
158           <getcontenttype>text/xml</getcontenttype>
159         </prop>
160         <status>HTTP/1.1 200 OK</status>
161      </propstat>
162   </response>
163 EOF
164
165                         # List all the files within too, of course :-)
166                         if ($depth >= 1) {
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");
171                 
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)
177                                                 or next;
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);
180
181                                         $r->print(<<"EOF");
182   <response>
183      <href>/webdav/upload/$event/$filename</href>
184      <propstat>
185         <prop>
186           <resourcetype/>
187           <getcontenttype>$mime_type</getcontenttype>
188           <getcontentlength>$size</getcontentlength>
189           <getlastmodified>$mtime</getlastmodified>
190         </prop>
191         <status>HTTP/1.1 200 OK</status>
192      </propstat>
193   </response>
194 EOF
195                                 }
196                                 $q->finish;
197
198                                 # And the magical autorename folder
199                                 $r->print(<<"EOF");
200   <response>
201      <href>/webdav/upload/$event/autorename/</href>
202      <propstat>
203         <prop>
204           <resourcetype><collection/></resourcetype>
205           <getcontenttype>text/xml</getcontenttype>
206         </prop>
207         <status>HTTP/1.1 200 OK</status>
208      </propstat>
209   </response>
210 EOF
211                         }
212
213                         $r->print("</multistatus>\n");
214
215                         return Apache2::Const::OK;
216                 } elsif ($r->uri =~ m#^/webdav/upload/([a-zA-Z0-9-]+)/autorename/?$#) {
217                         # The autorename folder is always empty
218                         my $event = $1;
219                         
220                         $r->headers_out->{'content-location'} = "/webdav/upload/$event/autorename/";
221                         
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) {
226                                 $r->status(404);
227                                 $r->content_type('text/plain; charset=utf-8');
228                                 $r->print("Couldn't find event in database");
229                                 return Apache2::Const::OK;
230                         }
231                         
232                         # OK, list the (empty) directory
233                         $r->print(<<"EOF");
234 <?xml version="1.0" encoding="utf-8"?>
235 <multistatus xmlns="DAV:">
236   <response>
237      <href>/webdav/upload/$event/autorename/</href>
238      <propstat>
239         <prop>
240           <resourcetype><collection/></resourcetype>
241           <getcontenttype>text/xml</getcontenttype>
242         </prop>
243         <status>HTTP/1.1 200 OK</status>
244      </propstat>
245   </response>
246 </multistatus>
247 EOF
248         
249                         return Apache2::Const::OK;
250                 } elsif ($r->uri =~ m#^/webdav/upload/([a-zA-Z0-9-]+)/([a-zA-Z0-9._()-]+)$#) {
251                         # stat a single file
252                         my ($event, $filename) = ($1, $2);
253                         my ($fname, $size, $mtime);
254                         
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";
260                                 $size = 0;
261                                 $mtime = time;
262                         } else {
263                                 ($fname, $size, $mtime) = Sesse::pr0n::Common::stat_image($r, $event, $filename);
264                         }
265                         
266                         if (!defined($fname)) {
267                                 $r->status(404);
268                                 $r->content_type('text/plain; charset=utf-8');
269                                 $r->print("Couldn't find file");
270                                 return Apache2::Const::OK;
271                         }
272                         my $mime_type = Sesse::pr0n::Common::get_mimetype_from_filename($filename);
273                         
274                         $mtime = POSIX::strftime("%a, %d %b %Y %H:%M:%S GMT", gmtime($mtime));
275                         $r->print(<<"EOF");
276 <?xml version="1.0" encoding="utf-8"?>
277 <multistatus xmlns="DAV:">
278   <response>
279     <href>/webdav/upload/$event/$filename</href>
280     <propstat>
281       <prop>
282         <resourcetype/>
283         <getcontenttype>$mime_type</getcontenttype>
284         <getcontentlength>$size</getcontentlength>
285         <getlastmodified>$mtime</getlastmodified>
286       </prop>
287       <status>HTTP/1.1 200 OK</status>
288     </propstat>
289   </response>
290 </multistatus>
291 EOF
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);
297                         
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";
303                                 $size = 0;
304                                 $mtime = time;
305                         } else {
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);
309                                 if (defined($ref)) {
310                                         ($fname, $size, $mtime) = Sesse::pr0n::Common::stat_image_from_id($r, $ref->{'id'});
311                                 }
312                         }
313                         
314                         if (!defined($fname)) {
315                                 $r->status(404);
316                                 $r->content_type('text/plain; charset=utf-8');
317                                 $r->print("Couldn't find file");
318                                 return Apache2::Const::OK;
319                         }
320                         my $mime_type = Sesse::pr0n::Common::get_mimetype_from_filename($filename);
321                         
322                         $mtime = POSIX::strftime("%a, %d %b %Y %H:%M:%S GMT", gmtime($mtime));
323                         $r->print(<<"EOF");
324 <?xml version="1.0" encoding="utf-8"?>
325 <multistatus xmlns="DAV:">
326   <response>
327     <href>/webdav/upload/$event/autorename/$filename</href>
328     <propstat>
329       <prop>
330         <resourcetype/>
331         <getcontenttype>$mime_type</getcontenttype>
332         <getcontentlength>$size</getcontentlength>
333         <getlastmodified>$mtime</getlastmodified>
334       </prop>
335       <status>HTTP/1.1 200 OK</status>
336     </propstat>
337   </response>
338 </multistatus>
339 EOF
340                 } else {
341                         $r->status(404);
342                         $r->content_type('text/plain; charset=utf-8');
343                         $r->print("Couldn't find file");
344                 }
345                 return Apache2::Const::OK;
346         }
347         
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})$#) {
350                         $r->status(404);
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;
354                 }
355
356                 my ($event, $autorename, $filename) = ($1, $2, $3);
357                 
358                 # Check if this file really exists
359                 my ($fname, $size, $mtime);
360
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";
366                         $size = 0;
367                         $mtime = time;
368                 } else {
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);
373                                 if (defined($ref)) {
374                                         ($fname, $size, $mtime) = Sesse::pr0n::Common::stat_image_from_id($r, $ref->{'id'});
375                                 }
376                         } elsif (!defined($fname)) {
377                                 ($fname, $size, $mtime) = Sesse::pr0n::Common::stat_image($r, $event, $filename);
378                         }
379                 }
380                 
381                 if (!defined($fname)) {
382                         $r->status(404);
383                         $r->content_type('text/plain; charset=utf-8');
384                         $r->print("Couldn't find file");
385                         return Apache2::Const::OK;
386                 }
387                 
388                 $r->status(200);
389                 $r->set_content_length($size);
390                 $r->set_last_modified($mtime);
391         
392                 if ($r->method eq "GET") {
393                         $r->sendfile($fname);
394                 }
395                 return Apache2::Const::OK;
396         }
397         
398         if ($r->method eq "PUT") {
399                 if ($r->uri !~ m#^/webdav/upload/([a-zA-Z0-9-]+)/(autorename/)?(.{1,250})$#) {
400                         $r->status(403);
401                         $r->content_type('text/plain; charset=utf-8');
402                         $r->print("No access");
403                         return Apache2::Const::OK;
404                 }
405                 
406                 my ($event, $autorename, $filename) = ($1, $2, $3);
407                 my $size = $r->headers_in->{'content-length'};
408                 if (!defined($size)) {
409                         $size = $r->headers_in->{'x-expected-entity-length'};
410                 }
411                 $r->log->info("sz=$size");
412                 my $orig_filename = $filename;
413
414                 # Remove evil characters
415                 if ($filename =~ /[^a-zA-Z0-9._()-]/) {
416                         if (defined($autorename) && $autorename eq "autorename/") {
417                                 $filename =~ tr/a-zA-Z0-9.()-/_/c;
418                         } else {
419                                 $r->status(403);
420                                 $r->content_type('text/plain; charset=utf-8');
421                                 $r->print("Illegal characters in filename");
422                                 return Apache2::Const::OK;
423                         }
424                 }
425                 
426                 #
427                 # gnome-vfs and mac os x love to make zero-byte files,
428                 # make them happy
429                 # 
430                 if ($size == 0 || $filename =~ /^\.(_|DS_Store)/) {
431                         $dbh->do('DELETE FROM fake_files WHERE expires_at <= now() OR (event=? AND vhost=? AND filename=?);',
432                                 undef, $event, $r->get_server_name, $filename)
433                                 or dberror($r, "Couldn't prune fake_files");
434                         $dbh->do('INSERT INTO fake_files (vhost,event,filename,expires_at) VALUES (?,?,?,now() + interval \'1 day\');',
435                                 undef, $r->get_server_name, $event, $filename)
436                                 or dberror($r, "Couldn't add file");
437                         $r->content_type('text/plain; charset="utf-8"');
438                         $r->status(201);
439                         $r->print("OK");
440                         $r->log->info("Fake upload of $event/$filename");
441                         return Apache2::Const::OK;
442                 }
443                         
444                 # Get the new ID
445                 my $ref = $dbh->selectrow_hashref("SELECT NEXTVAL('imageid_seq') AS id;");
446                 my $newid = $ref->{'id'};
447                 if (!defined($newid)) {
448                         dberror($r, "Couldn't get new ID");
449                 }
450                 
451                 # Autorename if we need to
452                 if (defined($autorename) && $autorename eq "autorename/") {
453                         my $ref = $dbh->selectrow_hashref("SELECT COUNT(*) AS numfiles FROM images WHERE vhost=? AND event=? AND filename=?",
454                                 undef, $r->get_server_name, $event, $filename)
455                                 or dberror($r, "Couldn't check for existing files");
456                         if ($ref->{'numfiles'} > 0) {
457                                 $r->log->info("Renaming $filename to $newid.jpeg");
458                                 $filename = "$newid.jpeg";
459                         }
460                 }
461                 
462                 {
463                         # Enable transactions and error raising temporarily
464                         local $dbh->{AutoCommit} = 0;
465                         local $dbh->{RaiseError} = 1;
466                         my $fname;
467
468                         # Try to insert this new file
469                         eval {
470                                 $dbh->do('DELETE FROM fake_files WHERE vhost=? AND event=? AND filename=?',
471                                         undef, $r->get_server_name, $event, $filename);
472                                         
473                                 $dbh->do('INSERT INTO images (id,vhost,event,uploadedby,takenby,filename) VALUES (?,?,?,?,?,?)',
474                                         undef, $newid, $r->get_server_name, $event, $user, $takenby, $filename);
475                                 $dbh->do('UPDATE last_picture_cache SET last_update=CURRENT_TIMESTAMP WHERE vhost=? AND event=?',
476                                         undef, $r->get_server_name, $event);
477                                 Sesse::pr0n::Common::purge_cache($r, "/$event/");
478
479                                 # Now save the file to disk
480                                 $fname = Sesse::pr0n::Common::get_disk_location($r, $newid);
481                                 open NEWFILE, ">$fname"
482                                         or die "$fname: $!";
483
484                                 my $buf;
485                                 if ($r->read($buf, $size)) {
486                                         print NEWFILE $buf or die "write($fname): $!";
487                                 }
488
489                                 close NEWFILE or die "close($fname): $!";
490                                 
491                                 # Orient stuff correctly
492                                 system("/usr/bin/exifautotran", $fname) == 0
493                                         or die "/usr/bin/exifautotran: $!";
494
495                                 # Make cache while we're at it.
496                                 # Don't do it for the resource forks Mac OS X loves to upload :-(
497                                 if ($filename !~ /^\.(_|DS_Store)/) {
498                                         # FIXME: Ideally we'd want to ensure cache of -1x-1 here as well (for NEFs), but that would
499                                         # preclude mipmapping in its current form.
500                                         Sesse::pr0n::Common::ensure_cached($r, $filename, $newid, undef, undef, "nobox", 80, 64, 320, 256);
501                                 }
502                                 
503                                 # OK, we got this far, commit
504                                 $dbh->commit;
505
506                                 $r->log->notice("Successfully wrote $event/$filename to $fname");
507                         };
508                         if ($@) {
509                                 # Some error occurred, rollback and bomb out
510                                 $dbh->rollback;
511                                 error($r, "Transaction aborted because $@");
512                                 unlink($fname);
513                         }
514                 }
515
516                 # Insert a `shadow file' we can stat the next day or so
517                 if (defined($autorename) && $autorename eq "autorename/") {
518                         $dbh->do('DELETE FROM shadow_files WHERE expires_at <= now() OR (vhost=? AND event=? AND filename=?);',
519                                 undef, $r->get_server_name, $event, $filename)
520                                 or dberror($r, "Couldn't prune shadow_files");
521                         $dbh->do('INSERT INTO shadow_files (vhost,event,filename,id,expires_at) VALUES (?,?,?,?,now() + interval \'1 day\');',
522                                 undef, $r->get_server_name, $event, $orig_filename, $newid)
523                                 or dberror($r, "Couldn't add shadow file");
524                         $r->log->info("Added shadow entry for $event/$filename");
525                 }
526
527                 $r->content_type('text/plain; charset="utf-8"');
528                 $r->status(201);
529                 $r->print("OK");
530
531                 return Apache2::Const::OK;
532         }
533         
534         # Used by the XP publishing wizard -- largely the same as the code above
535         # but vastly simplified. Should we refactor?
536         if ($r->method eq "POST") {
537                 my $apr = Apache2::Request->new($r);
538                 my $client_size = $apr->param('size');
539                 my $event = $apr->param('event');
540                                 
541                 my $file = $apr->upload('image');
542                 my $filename = $file->filename();
543                 if ($client_size != $file->size()) {
544                         $r->content_type('text/plain; charset="utf-8"');
545                         $r->status(403);
546                         $r->print("Client-size resizing detected; refusing automatically");
547
548                         $r->log->info("Client-size resized upload of $event/$filename detected");
549                         return Apache2::Const::OK;
550                 }
551                 
552                 # Ugh, Windows XP seems to be sending this in... something that's not UTF-8, at least
553                 my $takenby_given = Sesse::pr0n::Common::guess_charset($apr->param('takenby'));
554
555                 if (defined($takenby_given) && $takenby_given !~ /^\s*$/ && $takenby_given !~ /[<>&]/ && length($takenby_given) <= 100) {
556                         $takenby = $takenby_given;
557                 }
558                 
559                 my $ne_id = Sesse::pr0n::Common::guess_charset($apr->param('neweventid'));
560                 my $ne_date = Sesse::pr0n::Common::guess_charset($apr->param('neweventdate'));
561                 my $ne_desc = Sesse::pr0n::Common::guess_charset($apr->param('neweventdesc'));
562                 if (defined($ne_id)) {
563                         # Trying to add a new event, let's see if it already exists
564                         my $q = $dbh->prepare('SELECT COUNT(*) AS cnt FROM events WHERE event=? AND vhost=?')
565                                 or dberror($r, "Couldn't prepare event count");
566                         $q->execute($ne_id, $r->get_server_name)
567                                 or dberror($r, "Couldn't execute event count");
568                         my $ref = $q->fetchrow_hashref;
569
570                         if ($ref->{'cnt'} == 0) {
571                                 my @errors = Sesse::pr0n::Common::add_new_event($r, $dbh, $ne_id, $ne_date, $ne_desc);
572                                 if (scalar @errors > 0) {
573                                         die "Couldn't add new event $ne_id: " . join(', ', @errors);
574                                 }
575                         }
576
577                         $event = $ne_id;
578                 }
579
580                 # Remove evil characters
581                 if ($filename =~ /[^a-zA-Z0-9._-]/) {
582                         $filename =~ tr/a-zA-Z0-9.-/_/c;
583                 }
584                 
585                 # Get the new ID
586                 my $ref = $dbh->selectrow_hashref("SELECT NEXTVAL('imageid_seq') AS id;");
587                 my $newid = $ref->{'id'};
588                 if (!defined($newid)) {
589                         dberror($r, "Couldn't get new ID");
590                 }
591                 
592                 # Autorename if we need to
593                 {
594                         my $ref = $dbh->selectrow_hashref("SELECT COUNT(*) AS numfiles FROM images WHERE vhost=? AND event=? AND filename=?",
595                                 undef, $r->get_server_name, $event, $filename)
596                                 or dberror($r, "Couldn't check for existing files");
597                         if ($ref->{'numfiles'} > 0) {
598                                 $r->log->info("Renaming $filename to $newid.jpeg");
599                                 $filename = "$newid.jpeg";
600                         }
601                 }
602                 
603                 {
604                         # Enable transactions and error raising temporarily
605                         local $dbh->{AutoCommit} = 0;
606                         local $dbh->{RaiseError} = 1;
607                         my $fname;
608
609                         # Try to insert this new file
610                         eval {
611                                 $dbh->do('INSERT INTO images (id,vhost,event,uploadedby,takenby,filename) VALUES (?,?,?,?,?,?)',
612                                         undef, $newid, $r->get_server_name, $event, $user, $takenby, $filename);
613                                 $dbh->do('UPDATE last_picture_cache SET last_update=CURRENT_TIMESTAMP WHERE vhost=? AND event=?',
614                                         undef, $r->get_server_name, $event);
615
616                                 # Now save the file to disk
617                                 $fname = Sesse::pr0n::Common::get_disk_location($r, $newid);
618                                 open NEWFILE, ">$fname"
619                                         or die "$fname: $!";
620
621                                 my $buf;
622                                 $file->slurp($buf);
623                                 print NEWFILE $buf or die "write($fname): $!";
624                                 close NEWFILE or die "close($fname): $!";
625                                 
626                                 # Orient stuff correctly
627                                 system("/usr/bin/exifautotran", $fname) == 0
628                                         or die "/usr/bin/exifautotran: $!";
629
630                                 # Make cache while we're at it.
631                                 Sesse::pr0n::Common::ensure_cached($r, $filename, $newid, undef, undef, 1, 80, 64, 320, 256, -1, -1);
632                                 
633                                 # OK, we got this far, commit
634                                 $dbh->commit;
635
636                                 $r->log->notice("Successfully wrote $event/$filename to $fname");
637                         };
638                         if ($@) {
639                                 # Some error occurred, rollback and bomb out
640                                 $dbh->rollback;
641                                 error($r, "Transaction aborted because $@");
642                                 unlink($fname);
643                 
644                                 $r->content_type('text/plain; charset="utf-8"');
645                                 $r->status(500);
646                                 $r->print("Error: $@");
647                         }
648                 }
649
650                 $r->content_type('text/plain; charset="utf-8"');
651                 $r->status(201);
652                 $r->print("OK");
653
654                 return Apache2::Const::OK;
655         }
656         
657         # Yes, we fake locks. :-)
658         if ($r->method eq "LOCK") {
659                 if ($r->uri !~ m#^/webdav/upload/([a-zA-Z0-9-]+)/(autorename/)?([a-zA-Z0-9._-]+)$#) {
660                         $r->status(403);
661                         $r->content_type('text/plain; charset=utf-8');
662                         $r->print("No access");
663                         return Apache2::Const::OK;
664                 }
665
666                 my ($event, $autorename, $filename) = ($1, $2, $3);
667                 $autorename = '' if (!defined($autorename));
668                 my $sha1 = Digest::SHA1::sha1_base64("/$event/$autorename$filename");
669
670                 $r->status(200);
671                 $r->content_type('text/xml; charset=utf-8');
672
673                 $r->print(<<"EOF");
674 <?xml version="1.0" encoding="utf-8"?>
675 <prop xmlns="DAV:">
676   <lockdiscovery>
677     <activelock>
678       <locktype><write/></locktype>
679       <lockscope><exclusive/></lockscope>
680       <depth>0</depth>
681       <owner>
682         <href>/webdav/upload/$event/$autorename$filename</href>
683       </owner>
684       <timeout>Second-3600</timeout>
685       <locktoken>
686         <href>opaquelocktoken:$sha1</href>
687       </locktoken>
688     </activelock>
689   </lockdiscovery>
690 </prop>
691 EOF
692                 return Apache2::Const::OK;
693         }
694         
695         if ($r->method eq "UNLOCK") {
696                 $r->content_type('text/plain; charset="utf-8"');
697                 $r->status(200);
698                 $r->print("OK");
699
700                 return Apache2::Const::OK;
701         }
702
703         if ($r->method eq "DELETE") {
704                 if ($r->uri !~ m#^/webdav/upload/([a-zA-Z0-9-]+)/(autorename/)?(\._[a-zA-Z0-9._-]+)$#) {
705                         $r->status(403);
706                         $r->content_type('text/plain; charset=utf-8');
707                         $r->print("No access");
708                         return Apache2::Const::OK;
709                 }
710                 
711                 my ($event, $autorename, $filename) = ($1, $2, $3);
712                 $dbh->do('DELETE FROM images WHERE vhost=? AND event=? AND filename=?',
713                         undef, $r->get_server_name, $event, $filename)
714                         or dberror($r, "Couldn't remove file");
715                 $dbh->do('UPDATE last_picture_cache SET last_update=CURRENT_TIMESTAMP WHERE vhost=? AND event=?',
716                         undef, $r->get_server_name, $event)
717                         or dberror($r, "Couldn't invalidate cache");
718                 $r->status(200);
719                 $r->print("OK");
720
721                 $r->log->info("deleted $event/$filename");
722                 
723                 return Apache2::Const::OK;
724         }
725         
726         if ($r->method eq "MOVE" or
727             $r->method eq "MKCOL" or
728             $r->method eq "RMCOL" or
729             $r->method eq "RENAME" or
730             $r->method eq "COPY") {
731                 $r->content_type('text/plain; charset="utf-8"');
732                 $r->status(403);
733                 $r->print("Sorry, you do not have access to that feature.");
734                 return Apache2::Const::OK;
735         }
736
737         $r->content_type('text/plain; charset=utf-8');
738         $r->log->error("unknown method " . $r->method);
739         $r->status(500);
740         $r->print("Unknown method");
741         
742         return Apache2::Const::OK;
743 }
744
745 1;
746
747