-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapi.php
250 lines (198 loc) · 7.36 KB
/
api.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
<?php
ini_set('html_errors', false);
ini_set('memory_limit', '512M');
$response = new StdClass();
$response->message = '';
$response->error = false;
try {
session_start();
require_once 'include/functions.php';
require_once 'include/CssSprite.php';
/*
// Debugging
ob_start();
printR($_REQUEST);
print_R($_FILES);
file_put_contents('tmp.log', ob_get_clean());
*/
$token = isset($_REQUEST['token']) ? $_REQUEST['token'] : session_id();
$dir = 'uploads/u-' . $token;
if (isset($_REQUEST['getToken'])) {
$response->token = $token;
} elseif (isset($_REQUEST['upload'])) {
if (preg_match('/[^a-z0-9]|^$/', $token)) {
throw new Exception('Invalid token');
}
if (!is_dir($dir)) {
if (!@mkdir($dir)) {
// It could have been created by another thread
if (!is_dir($dir)) {
throw new Exception('Error creating directory');
}
}
}
receiveUpload($response, $dir);
} elseif (isset($_REQUEST['create'])) {
ini_set('memory_limit', '64M');
if (!is_dir($dir)) {
throw new Exception('Images not found - Either you didn\'t upload any or your session expired');
}
$options = [];
if (!empty($_REQUEST['output_type']) && in_array($_REQUEST['output_type'], ['jpeg', 'gif', 'png'])) {
$options['type'] = $_REQUEST['output_type'];
}
if (isset($_REQUEST['jpeg_quality'])) {
$options['jpeg_quality'] = min(100, max(0, (int)$_REQUEST['jpeg_quality']));
}
if (!empty($_REQUEST['css_prefix'])) {
$options['css_prefix'] = preg_replace('/[^a-z0-9_-]/ui', '', $_REQUEST['css_prefix']);
}
if (isset($_REQUEST['padding'])) {
$options['padding'] = min(max(0, (int)$_REQUEST['padding']), 25);
}
if (!empty($_REQUEST['jpeg_reduce_artefacts']) && ($s->getOutputType() == 'jpeg')) {
$options['jpeg_reduce_artefacts'] = true;
}
$images = [];
foreach (new DirectoryIterator($dir) as $file)
{
if (preg_match('/\.(png|jpe?g|gif)$/ui', $file->getFilename())) {
$images[] = [
'name' => $file->getFilename(),
'file' => $file->getPathname(),
];
}
}
$s = new CssSprite($padding, $reduceArtefacts, $prefix);
$s->run($images);
$filepath = 'uploads/' . $token . '.' . $s->getOutputType();
file_put_contents($filepath, $s->getImage($s->getOutputType(), $options));
$server = $_SERVER['HTTP_HOST'] == 'localhost:96' ? 'dev.justsayplease.co.uk:96' : $_SERVER['HTTP_HOST'];
$response->url = 'http://' . $server . dirname($_SERVER['PHP_SELF']) . '/uploads/' . $token . '.' . $s->getOutputType();
$response->css = $s->getCss();
$response->html = $s->getHtml();
//$s->smush($filepath, $response->url);
$oldSize = 0;
$response->info = [];
foreach ($s->getInfo() as $image) {
$response->info[] = [
'file' => $image['pathInfo']['basename'],
'x' => $image['x'],
'y' => $image['y'],
'width' => $image['width'],
'height' => $image['height'],
'class' => $image['class'],
'selector' => $image['selector'],
'css' => $image['css'],
];
$oldSize += filesize($image['path']);
}
$response->oldSize = $oldSize;
$response->newSize = filesize($filepath);
$info = getimagesize($filepath);
$response->width = $info[0];
$response->height = $info[1];
} elseif (isset($_REQUEST['cleanup'])) {
if (isset($_REQUEST['token'])) {
if (preg_match('/^[a-z0-9]+$/i', $_REQUEST['token'])) {
deleteDir('uploads/u-' . $_REQUEST['token']);
foreach (glob('uploads/u-' . $_REQUEST['token'] . '.*') as $file) {
unlink($file);
}
}
} else {
$cutoff = time() - (0 * 60);
foreach (new DirectoryIterator('uploads') as $f) {
if ($f->isDot() || !$f->isDir() || !preg_match('/^u-(.+)$/', $f->getFilename(), $matches)) {
continue;
}
if ($f->getCTime() < $cutoff) {
deleteDir($f->getPathname());
foreach (glob('uploads/' . $matches[1] . '.*') as $file) {
unlink($file);
}
}
}
}
$response->message = 'Cleanup complete';
} elseif (isset($_REQUEST['help'])) {
print(file_get_contents('include/help.html'));
exit;
}
} catch (Exception $e) {
$response->error = true;
$response->message = $e->getMessage();
}
header('Content-type: application/json');
print(json_encode($response, JSON_PRETTY_PRINT));
/**
* Receive an image or zip of images in $_FILES['img'] and save the image(s) to the specified directory
*
* @param object object to store response messages
* @param string filesystem directory to save image(s) to
*
* @return bool true on success
*/
function receiveUpload($response, $dir)
{
if (empty($_FILES['img'])) {
$response->message = 'No file specified';
$response->error = true;
return false;
}
$errors = [
'Success',
'File too large (exceeds upload_max_filesize in php.ini)',
'File too large (exceeds MAX_FILE_SIZE)',
'Partial file received',
'No file specified',
'No tmp dir',
'Could not write to disk',
];
if ($_FILES['img']['error']) {
$response->message = $errors[$_FILES['img']['error']];
$response->error = true;
return false;
}
$zip = zip_open($_FILES['img']['tmp_name']);
if ($zip && is_resource($zip)) {
$i = 0;
while ($zip_entry = zip_read($zip)) {
$path = zip_entry_name($zip_entry);
$pathInfo = pathinfo($path);
$filename = $pathInfo['basename'];
$dest = $dir . '/' . $filename;
if (empty($pathInfo['extension'])) {
continue;
}
if (!in_array(mb_strtolower($pathInfo['extension']), ['png', 'gif', 'jpg', 'jpeg'])) {
continue;
}
if (zip_entry_open($zip, $zip_entry, 'r')) {
file_put_contents($dest, zip_entry_read($zip_entry, zip_entry_filesize($zip_entry)));
zip_entry_close($zip_entry);
if (!isImage($dest)) {
unlink($dest);
} else {
$i++;
}
}
}
zip_close($zip);
$response->message = 'Unzipped ' . $i . ' images';
return true;
}
// Check the file is OK
if (!isImage($_FILES['img']['tmp_name'])) {
$response->message = 'Invalid image file: Please use PNG, JPEG and GIF files only';
$response->error = true;
return false;
}
if (!move_uploaded_file($_FILES['img']['tmp_name'], $dir . '/' . $_FILES['img']['name'])) {
$response->message = 'Error moving uploaded file';
$response->error = true;
return false;
}
$response->message = 'Uploaded successfully';
return true;
}