FileUploadHandler.inc 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. <?php
  2. class FileUploadHandler {
  3. public function saveFileToPost($file, $postId, $userId) {
  4. if (! empty($file) && ! is_null($file)) {
  5. $time = new Time();
  6. $database = new Database();
  7. $logger = new Logger();
  8. $stringToHash = $file['name'] . $time->now() . "doxensalt" . $file['size'];
  9. $fileHash = sha1($stringToHash);
  10. $moveResult = move_uploaded_file($file['tmp_name'], UPLOAD_PATH . $fileHash);
  11. if (! $moveResult) {
  12. $logger->error("File upload-move failed! Check permissions on " . UPLOAD_PATH);
  13. } else {
  14. $sql = sprintf("INSERT INTO files (file_hash, name, size, type) VALUES ('%s','%s','%s','%s')", $fileHash, $file['name'], $file['size'], $file['type']);
  15. $fileId = $database->write($sql);
  16. $sql = sprintf("INSERT INTO post_file_associations (post_id, file_id) VALUES ('%s','%s')", $postId, $fileId);
  17. $database->write($sql);
  18. $sql = sprintf("INSERT INTO user_file_associations (user_id, file_id) VALUES ('%s','%s')", $userId, $fileId);
  19. $database->write($sql);
  20. }
  21. }
  22. }
  23. public function saveFileToComment($file, $commentId, $userId) {
  24. if (! empty($file) && ! is_null($file)) {
  25. $time = new Time();
  26. $database = new Database();
  27. $logger = new Logger();
  28. $stringToHash = $file['name'] . $time->now() . "doxensalt" . $file['size'];
  29. $fileHash = sha1($stringToHash);
  30. $moveResult = move_uploaded_file($file['tmp_name'], UPLOAD_PATH . $fileHash);
  31. if (! $moveResult) {
  32. $logger->error("File upload-move failed! Check permissions on " . UPLOAD_PATH);
  33. } else {
  34. $sql = sprintf("INSERT INTO files (file_hash, name, size, type) VALUES ('%s','%s','%s','%s')", $fileHash, $file['name'], $file['size'], $file['type']);
  35. $fileId = $database->write($sql);
  36. $sql = sprintf("INSERT INTO comment_file_associations (comment_id, file_id) VALUES ('%s','%s')", $commentId, $fileId);
  37. $database->write($sql);
  38. $sql = sprintf("INSERT INTO user_file_associations (user_id, file_id) VALUES ('%s','%s')", $userId, $fileId);
  39. $database->write($sql);
  40. }
  41. }
  42. }
  43. }