+ # Remove evil characters
+ if ($filename =~ /[^a-zA-Z0-9._-]/) {
+ $filename =~ tr/a-zA-Z0-9.-/_/c;
+ }
+
+ # Get the new ID
+ my $ref = $dbh->selectrow_hashref("SELECT NEXTVAL('imageid_seq') AS id;");
+ my $newid = $ref->{'id'};
+ if (!defined($newid)) {
+ dberror($r, "Couldn't get new ID");
+ }
+
+ # Autorename if we need to
+ {
+ my $ref = $dbh->selectrow_hashref("SELECT COUNT(*) AS numfiles FROM images WHERE vhost=? AND event=? AND filename=?",
+ undef, $r->get_server_name, $event, $filename)
+ or dberror($r, "Couldn't check for existing files");
+ if ($ref->{'numfiles'} > 0) {
+ $r->log->info("Renaming $filename to $newid.jpeg");
+ $filename = "$newid.jpeg";
+ }
+ }
+
+ {
+ # Enable transactions and error raising temporarily
+ local $dbh->{AutoCommit} = 0;
+ local $dbh->{RaiseError} = 1;
+ my $fname;
+
+ # Try to insert this new file
+ eval {
+ $dbh->do('INSERT INTO images (id,vhost,event,uploadedby,takenby,filename) VALUES (?,?,?,?,?,?)',
+ undef, $newid, $r->get_server_name, $event, $user, $takenby, $filename);
+
+ # Now save the file to disk
+ $fname = Sesse::pr0n::Common::get_disk_location($r, $newid);
+ open NEWFILE, ">$fname"
+ or die "$fname: $!";
+
+ my $buf;
+ $file->slurp($buf);
+ print NEWFILE $buf or die "write($fname): $!";
+ close NEWFILE or die "close($fname): $!";
+
+ # Orient stuff correctly
+ system("/usr/bin/exifautotran", $fname) == 0
+ or die "/usr/bin/exifautotran: $!";
+
+ # Make cache while we're at it.
+ Sesse::pr0n::Common::ensure_cached($r, $filename, $newid, undef, undef, 1, 1, 80, 64, 320, 256, -1, -1);
+
+ # OK, we got this far, commit
+ $dbh->commit;
+
+ $r->log->notice("Successfully wrote $event/$filename to $fname");
+ };
+ if ($@) {
+ # Some error occurred, rollback and bomb out
+ $dbh->rollback;
+ error($r, "Transaction aborted because $@");
+ unlink($fname);
+
+ $r->content_type('text/plain; charset="utf-8"');
+ $r->status(500);
+ $r->print("Error: $@");
+ }
+ }
+
+ $r->content_type('text/plain; charset="utf-8"');
+ $r->status(201);
+ $r->print("OK");
+
+ return Apache2::Const::OK;
+ }
+