Start tracking comments
[pics.git] / upload.php
CommitLineData
cd757b9e
JC
1<?php
2
3require_once __DIR__ . '/db.php';
4require_once __DIR__ . '/auth.php';
5require_once __DIR__ . '/uuid.php';
6
7if ($_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];
3220d3ad
JC
20 if($error != '0') {
21 http_response_code(400);
22 die('Upload error');
23 }
cd757b9e
JC
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);
cab93e4b
JC
50
51 $comment_stmt = $db->prepare('INSERT into comments VALUES (:id, :post_id, :body)');
52 $comment_stmt->bindValue(':id', uuid_v4());
53 $comment_stmt->bindValue(':post_id', $post_id);
54 $comment_stmt->bindValue(':body', $_POST['comment'] ?? '');
55 $comment_stmt->execute();
cd757b9e
JC
56 $post_stmt->execute();
57
58 $db->exec('COMMIT');
59} else {
60echo '
61 <html>
62 <body>
63 <form enctype="multipart/form-data" method="POST" action="upload.php">
64 <label>Pick Images:<input type="file" id="upload" name="image[]" multiple>
65 </input></label>
66 <br/>
9f2fce35 67 <textarea id="comment" name="comment" placeholder="Title/comment your post"></textarea>
cd757b9e
JC
68 <br/>
69 <input type="submit" value="Upload"/>
70 </form>
71 </body>
72 </html>
73';
74}