scratch – Diff between revs 125 and 126

Subversion Repositories:
Rev:
Only display areas with differencesIgnore whitespace
Rev 125 Rev 126
1 <?php 1 <?php
2   2  
3 ########################################################################### 3 ###########################################################################
4 ## Copyright (C) Wizardry and Steamworks 2017 - License: GNU GPLv3 ## 4 ## Copyright (C) Wizardry and Steamworks 2017 - License: GNU GPLv3 ##
5 ########################################################################### 5 ###########################################################################
6   6  
7 require_once('php/pseudocrypt.php'); 7 require_once('php/pseudocrypt.php');
8 require_once('php/functions.php'); 8 require_once('php/functions.php');
9 require_once('vendor/autoload.php'); 9 require_once('vendor/autoload.php');
10   10  
11 ### Load configuration. 11 ### Load configuration.
12 $config = spyc_load_file('config.yaml'); 12 $config = spyc_load_file('config.yaml');
13   13  
14 #### POST -> upload / GET -> download 14 #### POST -> upload / GET -> download
15 switch ($_SERVER['REQUEST_METHOD']) { 15 switch ($_SERVER['REQUEST_METHOD']) {
16 case 'POST': 16 case 'POST':
17 #### Script restrictions. 17 #### Script restrictions.
18 session_start(); 18 session_start();
19 if (empty($_POST['token']) || !hash_equals($_SESSION['token'], $_POST['token'])) { 19 if (empty($_POST['token']) || !hash_equals($_SESSION['token'], $_POST['token'])) {
20 http_response_code(403); 20 http_response_code(403);
21 die('Forbidden.'); 21 die('Forbidden.');
22 } 22 }
23 #### Retrieve uploaded file. 23 #### Retrieve uploaded file.
24 if (!empty($_FILES['file']) and 24 if (!empty($_FILES['file']) and
25 is_uploaded_file($_FILES['file']['tmp_name'])) { 25 is_uploaded_file($_FILES['file']['tmp_name'])) {
26 if($_FILES['file']['size'] > $config['ALLOWED_ASSET_SIZE'] * 1048576) { 26 if($_FILES['file']['size'] > $config['ALLOWED_ASSET_SIZE'] * 1048576) {
27 http_response_code(403); 27 http_response_code(403);
28 die('File size exceeds '.$config['ALLOWED_ASSET_SIZE'].'MiB.'); 28 die('File size exceeds '.$config['ALLOWED_ASSET_SIZE'].'MiB.');
29 } 29 }
30 # Regular multipart/form-data upload. 30 # Regular multipart/form-data upload.
31 $name = $_FILES['file']['name']; 31 $name = $_FILES['file']['name'];
32 $data = atomized_get_contents($_FILES['file']['tmp_name']); 32 $data = atomized_get_contents($_FILES['file']['tmp_name']);
33 } else { 33 } else {
34 if((int)get_file_size("php://input") > $config['ALLOWED_ASSET_SIZE'] * 1048576) { 34 if((int)get_file_size("php://input") > $config['ALLOWED_ASSET_SIZE'] * 1048576) {
35 http_response_code(403); 35 http_response_code(403);
36 die('File size exceeds '.$config['ALLOWED_ASSET_SIZE'].'MiB.'); 36 die('File size exceeds '.$config['ALLOWED_ASSET_SIZE'].'MiB.');
37 } 37 }
38 # Raw POST data. 38 # Raw POST data.
39 $name = urldecode(@$_SERVER['HTTP_X_FILE_NAME']); 39 $name = urldecode(@$_SERVER['HTTP_X_FILE_NAME']);
40 $data = atomized_get_contents("php://input"); 40 $data = atomized_get_contents("php://input");
41 } 41 }
42   42  
43 #### Grab the file extension. 43 #### Grab the file extension.
44 $fileExtension = pathinfo($name, PATHINFO_EXTENSION); 44 $fileExtension = pathinfo($name, PATHINFO_EXTENSION);
45   45  
46 #### If the extension is not allowed then change it to a text extension. 46 #### If the extension is not allowed then change it to a text extension.
47 if (!isset($fileExtension) || 47 if (!isset($fileExtension) ||
48 !in_array(strtoupper($fileExtension), 48 !in_array(strtoupper($fileExtension),
49 array_map('strtoupper', $config['ALLOWED_FILE_EXTENSIONS']))) { 49 array_map('strtoupper', $config['ALLOWED_FILE_EXTENSIONS']))) {
50 http_response_code(403); 50 http_response_code(403);
51 die('File extension not allowed.'); 51 die('File extension not allowed.');
52 } 52 }
53 53
54 #### Hash filename. 54 #### Hash filename.
55 $file = strtolower( 55 $file = strtolower(
56 PseudoCrypt::hash( 56 PseudoCrypt::hash(
57 preg_replace( 57 preg_replace(
58 '/\D/', 58 '/\D/',
59 '', 59 '',
60 hash( 60 hash(
61 'sha512', 61 'sha512',
62 $data 62 $data
63 ) 63 )
64 ), 64 ),
65 $config['ASSET_HASH_SIZE'] 65 $config['ASSET_HASH_SIZE']
66 ) 66 )
67 ); 67 );
68   68  
69 #### Build the user path. 69 #### Build the user path.
70 $userPath = join( 70 $userPath = join(
71 DIRECTORY_SEPARATOR, 71 DIRECTORY_SEPARATOR,
72 array( 72 array(
73 $config['STORE_FOLDER'], 73 $config['STORE_FOLDER'],
74 $file 74 $file
75 ) 75 )
76 ); 76 );
77   77  
78 #### Check for path traversals. 78 #### Check for path traversals.
79 $pathPart = pathinfo($userPath.'.'.$fileExtension); 79 $pathPart = pathinfo($userPath.'.'.$fileExtension);
80 if (strcasecmp( 80 if (strcasecmp(
81 realpath($pathPart['dirname']), realpath($config['STORE_FOLDER'])) != 0) { 81 realpath($pathPart['dirname']), realpath($config['STORE_FOLDER'])) != 0) {
82 http_response_code(500); 82 http_response_code(500);
83 die('Internal server error.'); 83 die('Internal server error.');
84 } 84 }
85   85  
86 #### Store the file. 86 #### Store the file.
87 $timestamp = atomized_put_contents($userPath.'.'.$fileExtension, $data); 87 $timestamp = atomized_put_contents($userPath.'.'.$fileExtension, $data);
88 88
89 ### Process any sent tags. 89 ### Process any sent tags.
90 if(isset($_POST['tags'])) { 90 if(isset($_POST['tags'])) {
91 $tags = json_decode( 91 $tags = json_decode(
92 stripslashes( 92 stripslashes(
93 $_POST['tags'] 93 $_POST['tags']
94 ) 94 )
95 ); 95 );
96 96
97 ## If we have any tags then insert them into the database. 97 ## If we have any tags then insert them into the database.
98 if(!empty($tags)) { 98 if(!empty($tags)) {
-   99 ## Connect or create the scratch database.
-   100 $db = new PDO('sqlite:db/scratch.sqlite3');
-   101 ## Set the error mode to exceptions.
-   102 $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
99 try { 103 try {
100 ## Connect or create the scratch database. -  
101 $db = new PDO('sqlite:db/scratch.sqlite3'); -  
102 ## Set the error mode to exceptions. -  
103 $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); -  
104 104
105 ## Begin the transaction -  
106 $db->beginTransaction(); 105 $db->beginTransaction();
107 106
108 ## Create the tags table if it does not exist. 107 ## Create tags table if it does not exist.
109 $db->query('CREATE TABLE IF NOT EXISTS "tags" ("hash" text NOT NULL COLLATE NOCASE, "tag" text COLLATE NOCASE)'); 108 $db->query('CREATE TABLE IF NOT EXISTS "tags" ("hash" text NOT NULL COLLATE NOCASE, "tag" text COLLATE NOCASE)');
110 109
111 ## Insert all the tags for the file. 110 ## Now add all the tags.
112 foreach($tags as $tag) { 111 foreach($tags as $tag) {
113 $q = $db->prepare("INSERT INTO tags(hash, tag) VALUES(:hash, :tag)"); 112 $q = $db->prepare('REPLACE INTO "tags" ("hash", "tag") VALUES(:hash, :tag)');
114 $q->execute( -  
115 array( -  
116 ':hash' => $file, 113 $q->bindParam(':hash', $file);
117 ':name' => $tag 114 $q->bindParam(':tag', $tag);
118 ) -  
119 ); 115 $q->execute();
120 } 116 }
121 -  
122 ## Commit the transaction. -  
123 $db->commit(); 117 $db->commit();
124 } catch (Exception $e) { 118 } catch (Exception $e) {
-   119 error_log($e);
125 ## Rollback. 120 ## Rollback.
126 $db->rollback(); 121 $db->rollback();
127 } 122 }
128 } 123 }
129 } 124 }
130   125  
131 ### Hook for various file extensions. 126 ### Hook for various file extensions.
132 $opengraph = FALSE; 127 $opengraph = FALSE;
133 switch(strtoupper($fileExtension)) { 128 switch(strtoupper($fileExtension)) {
134 case 'MP4': 129 case 'MP4':
135 case 'GIF': 130 case 'GIF':
136 $opengraph = TRUE; 131 $opengraph = TRUE;
137 break; 132 break;
138 } 133 }
139 134
140 ### Return the URL to the file. 135 ### Return the URL to the file.
141 header('Content-Type: text/plain; charset=utf-8'); 136 header('Content-Type: text/plain; charset=utf-8');
142 echo json_encode( 137 echo json_encode(
143 array( 138 array(
144 "hash" => $file, 139 "hash" => $file,
145 "timestamp" => $timestamp, 140 "timestamp" => $timestamp,
146 "opengraph" => $opengraph 141 "opengraph" => $opengraph
147 ) 142 )
148 ); 143 );
149 break; 144 break;
150 case 'GET': 145 case 'GET':
151 ### Tell browser not to cache files. 146 ### Tell browser not to cache files.
152 header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); 147 header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
153 header("Cache-Control: post-check=0, pre-check=0", false); 148 header("Cache-Control: post-check=0, pre-check=0", false);
154 header("Pragma: no-cache"); 149 header("Pragma: no-cache");
155 150
156 ### If no file has been specified for download then return. 151 ### If no file has been specified for download then return.
157 if (!isset($_GET['hash']) or empty($_GET['hash'])) { 152 if (!isset($_GET['hash']) or empty($_GET['hash'])) {
158 http_response_code(404); 153 http_response_code(404);
159 die('File not found.'); 154 die('File not found.');
160 } 155 }
161   156  
162 ### Find the requested file. 157 ### Find the requested file.
163 $file = array_shift( 158 $file = array_shift(
164 preg_grep( 159 preg_grep(
165 '/'.$_GET['hash'].'/', 160 '/'.$_GET['hash'].'/',
166 scandir($config['STORE_FOLDER']) 161 scandir($config['STORE_FOLDER'])
167 ) 162 )
168 ); 163 );
169   164  
170 if (!isset($file) or empty($file)) { 165 if (!isset($file) or empty($file)) {
171 http_response_code(404); 166 http_response_code(404);
172 die('File not found.'); 167 die('File not found.');
173 } 168 }
174 169
175 ### Check the path for path traversals. 170 ### Check the path for path traversals.
176 $fileExtension = pathinfo($file, PATHINFO_EXTENSION); 171 $fileExtension = pathinfo($file, PATHINFO_EXTENSION);
177   172  
178 #### If the extension is not allowed then return. 173 #### If the extension is not allowed then return.
179 if (!isset($fileExtension) || 174 if (!isset($fileExtension) ||
180 !in_array(strtoupper($fileExtension), 175 !in_array(strtoupper($fileExtension),
181 array_map('strtoupper', $config['ALLOWED_FILE_EXTENSIONS']))) { 176 array_map('strtoupper', $config['ALLOWED_FILE_EXTENSIONS']))) {
182 http_response_code(403); 177 http_response_code(403);
183 die('File extension not allowed.'); 178 die('File extension not allowed.');
184 } 179 }
185 180
186 #### Build the user path. 181 #### Build the user path.
187 $userPath = join( 182 $userPath = join(
188 DIRECTORY_SEPARATOR, 183 DIRECTORY_SEPARATOR,
189 array( 184 array(
190 $config['STORE_FOLDER'], 185 $config['STORE_FOLDER'],
191 $file 186 $file
192 ) 187 )
193 ); 188 );
194   189  
195 #### Check for path traversals 190 #### Check for path traversals
196 $pathPart = pathinfo($userPath); 191 $pathPart = pathinfo($userPath);
197 if (strcasecmp( 192 if (strcasecmp(
198 realpath($pathPart['dirname']), realpath($config['STORE_FOLDER'])) != 0) { 193 realpath($pathPart['dirname']), realpath($config['STORE_FOLDER'])) != 0) {
199 http_response_code(500); 194 http_response_code(500);
200 die('Internal server error.'); 195 die('Internal server error.');
201 } 196 }
202   197  
203 ### Hook for various file extensions. 198 ### Hook for various file extensions.
204 switch(strtoupper($fileExtension)) { 199 switch(strtoupper($fileExtension)) {
205 case "HTML": 200 case "HTML":
206 case "HTM": 201 case "HTM":
207 header('Content-type: text/html'); 202 header('Content-type: text/html');
208 break; 203 break;
209 break; 204 break;
210 case "URL": 205 case "URL":
211 if(preg_match( 206 if(preg_match(
212 "/URL=(https?:\/\/[\-_\.\+!\*'\(\),a-zA-Z0-9]+:?[0-9]{0,5}\/.*?)\n/", 207 "/URL=(https?:\/\/[\-_\.\+!\*'\(\),a-zA-Z0-9]+:?[0-9]{0,5}\/.*?)\n/",
213 file_get_contents($userPath), $matches)) { 208 file_get_contents($userPath), $matches)) {
214 header('Location: '.$matches[1]); 209 header('Location: '.$matches[1]);
215 return; 210 return;
216 } 211 }
217 break; 212 break;
218 default: 213 default:
219 ### Open MIME info database and send the content type. 214 ### Open MIME info database and send the content type.
220 $finfo = finfo_open(FILEINFO_MIME_TYPE); 215 $finfo = finfo_open(FILEINFO_MIME_TYPE);
221 if (!$finfo) { 216 if (!$finfo) {
222 http_response_code(500); 217 http_response_code(500);
223 die('Internal server error.'); 218 die('Internal server error.');
224 } 219 }
225 header('Content-type: '.finfo_file($finfo, $userPath)); 220 header('Content-type: '.finfo_file($finfo, $userPath));
226 finfo_close($finfo); 221 finfo_close($finfo);
227 break; 222 break;
228 } 223 }
229 224
230 ### Send the file along with the inline content disposition. 225 ### Send the file along with the inline content disposition.
231 header('Content-length: '.(int)get_file_size($userPath)); 226 header('Content-length: '.(int)get_file_size($userPath));
232 header('Content-Disposition: inline; filename="' . basename($userPath) . '"'); 227 header('Content-Disposition: inline; filename="' . basename($userPath) . '"');
233 header('Content-Transfer-Encoding: binary'); 228 header('Content-Transfer-Encoding: binary');
234 header('X-Sendfile: '.$userPath); 229 header('X-Sendfile: '.$userPath);
235 break; 230 break;
236 } 231 }
237   232