| 1 | <?php |
| 2 | |
| 3 | require_once __DIR__ . '/db.php'; |
| 4 | require_once __DIR__ . '/auth.php'; |
| 5 | require_once __DIR__ . '/uuid.php'; |
| 6 | |
| 7 | if ($_SERVER['REQUEST_METHOD'] === 'POST') { |
| 8 | $user = check_auth(); |
| 9 | $db = get_db(); |
| 10 | $db->exec('BEGIN TRANSACTION'); |
| 11 | $post_id = uuid_v4(); |
| 12 | $post_time = time(); |
| 13 | $images = $_FILES['image']; |
| 14 | $num_files = count($images['name']); |
| 15 | for ($i = 0; $i < $num_files; $i++) { |
| 16 | $name = $images['name'][$i]; |
| 17 | $mime_type = $images['type'][$i]; |
| 18 | $tmp_file = $images['tmp_name'][$i]; |
| 19 | $error = $images['error'][$i]; |
| 20 | if($error != '0') { |
| 21 | http_response_code(400); |
| 22 | die('Upload error'); |
| 23 | } |
| 24 | $size = $images['size'][$i]; |
| 25 | // strip EXIF |
| 26 | $img = new Imagick($tmp_file); |
| 27 | // keep ICC for quality |
| 28 | $profiles = $img->getImageProfiles("icc", true); |
| 29 | $img->stripImage(); |
| 30 | if(!empty($profiles)) { |
| 31 | $img->profileImage('icc', $profiles['icc']); |
| 32 | } |
| 33 | |
| 34 | $file_b64 = base64_encode($img->getImageBlob()); |
| 35 | $pic_id = uuid_v4(); |
| 36 | $upload_stmt = $db->prepare('INSERT into pics values (:id, :post_id, :mime_type, :b64_bytes)'); |
| 37 | $upload_stmt->bindValue(':id', $pic_id); |
| 38 | $upload_stmt->bindValue(':post_id', $post_id); |
| 39 | $upload_stmt->bindValue(':mime_type', $mime_type); |
| 40 | $upload_stmt->bindValue(':b64_bytes', $file_b64); |
| 41 | $upload_stmt->execute(); |
| 42 | |
| 43 | echo "<img src='data:{$mime_type};base64,{$file_b64}' alt='$name'/>"; |
| 44 | } |
| 45 | |
| 46 | $post_stmt = $db->prepare('INSERT into posts VALUES(:id, :user, :time)'); |
| 47 | $post_stmt->bindValue(':id', $post_id); |
| 48 | $post_stmt->bindValue(':user', $user); |
| 49 | $post_stmt->bindValue(':time', $post_time); |
| 50 | $post_stmt->execute(); |
| 51 | |
| 52 | $db->exec('COMMIT'); |
| 53 | } else { |
| 54 | echo ' |
| 55 | <html> |
| 56 | <body> |
| 57 | <form enctype="multipart/form-data" method="POST" action="upload.php"> |
| 58 | <label>Pick Images:<input type="file" id="upload" name="image[]" multiple> |
| 59 | </input></label> |
| 60 | <br/> |
| 61 | <textarea id="comment" name="comment" placeholder="Title/comment your post"></textarea> |
| 62 | <br/> |
| 63 | <input type="submit" value="Upload"/> |
| 64 | </form> |
| 65 | </body> |
| 66 | </html> |
| 67 | '; |
| 68 | } |