-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.php
348 lines (295 loc) · 8.16 KB
/
utils.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
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
<?php
/**
* Opens a connection to the SQLite database and returns this connection.
* The connection is only opened once.
*
* @return PDO SQLite link
*/
function get_db()
{
global $app; // TODO improve (service?)
if (isset($app['db']) && $app['db'] != null)
return $app['db'];
$data_file = $app['config']['data_file'];
$must_init = !is_file($data_file);
$app['db'] = new PDO('sqlite:' . $app['config']['data_file'], null, null);
if ($must_init)
{
$sql = file_get_contents(__DIR__ . '/schema.sql');
$app['db']->exec($sql);
}
return $app['db'];
}
/**
* Retrieves an image in the database from it's storage name.
*
* @return array|boolean The image data or false if not found.
*/
function get_image($storage_name)
{
$db = get_db();
$q = $db->prepare('SELECT * FROM images WHERE storage_name = :name');
$q->execute([':name' => $storage_name]);
$image = $q->fetch(PDO::FETCH_ASSOC);
return $image ? $image : false;
}
/**
* Deletes an image.
*
* @param array $image An array containing the image data.
* @param string $root The storage root directory.
*/
function delete_image($image, $root)
{
@unlink($root . '/' . $image['storage_path']);
@unlink($root . '/' . $image['storage_path_mini']);
$db = get_db();
$q = $db->prepare('UPDATE images SET deleted = 1 WHERE storage_name = :name');
$q->execute([':name' => $image['storage_name']]);
}
/**
* Extracts the name of an image.
*
* @param string $image The image name or URL
* @return The image name.
*/
function extract_image_name($image)
{
if (strpos($image, 'mini_') !== false)
{
$image = str_replace('mini_', '', $image);
}
if (strpos($image, '/') !== false)
{
return array_pop(explode('/', $image));
}
else return $image;
}
/**
* Generates and writes a thumbnail.
*
* @var $original_path string The path to the original file to reduce.
* @var $mini_path string The path to the reduced file to write.
* @var $thumb_size int The thumbnail size wanted.
*
* @return bool Success
*/
function make_thumbnail($original_path, $mini_path, $thumb_size)
{
list($original_width, $original_height, $original_type) = getimagesize($original_path);
if ($original_width < $original_height)
{
$new_height = $thumb_size;
$new_width = intval($original_width * $new_height / $original_height);
}
else
{
$new_width = $thumb_size;
$new_height = intval($original_height * $new_width / $original_width);
}
$dest_x = intval(($thumb_size - $new_width) / 2);
$dest_y = intval(($thumb_size - $new_height) / 2);
$image_save_function = false;
$image_create_function = false;
if ($original_type === 1)
{
$image_save_function = "ImageGIF";
$image_create_function = "ImageCreateFromGIF";
}
elseif ($original_type === 2)
{
$image_save_function = "ImageJPEG";
$image_create_function = "ImageCreateFromJPEG";
}
elseif ($original_type === 3)
{
$image_save_function = "ImagePNG";
$image_create_function = "ImageCreateFromPNG";
}
if ($image_save_function)
{
$old_image = $image_create_function($original_path);
$new_image = imagecreatetruecolor($thumb_size, $thumb_size);
// apply transparent background only if is a png image
if($original_type === 3)
{
imagesavealpha($new_image, true);
$color = imagecolorallocatealpha($new_image, 0, 0, 0, 127);
imagefill($new_image, 0, 0, $color);
}
imagecopyresampled($new_image, $old_image, $dest_x, $dest_y, 0, 0, $new_width, $new_height, $original_width, $original_height);
$image_save_function($new_image, $mini_path);
return true;
}
return false;
}
/**
* Removes the EXIF data from the given image,
* and writes a new image without it at the new
* location.
*
* Thanks http://stackoverflow.com/a/38862429 .
*
* @param string $old Path to the old image.
* @param string $new Path to the new image without EXIF data.
*/
function remove_exif($old, $new)
{
$f1 = fopen($old, 'rb');
$f2 = fopen($new, 'wb');
// Find EXIF marker
while (($s = fread($f1, 2)))
{
$word = unpack('ni', $s)['i'];
if ($word == 0xFFE1)
{
// Read length (includes the word used for the length)
$s = fread($f1, 2);
$len = unpack('ni', $s)['i'];
// Skip the EXIF info
fread($f1, $len - 2);
break;
}
else
{
fwrite($f2, $s, 2);
}
}
// Write the rest of the file
while (($s = fread($f1, 4096)))
{
fwrite($f2, $s, strlen($s));
}
fclose($f1);
fclose($f2);
}
/**
* Fixes the image orientation using EXIF data, if needed.
* Updates the image in place.
*
* @param string $filename The name of the file to be fixed.
*/
function fix_image_orientation($filename)
{
$exif = exif_read_data($filename);
if (!empty($exif['Orientation']))
{
$image = imagecreatefromjpeg($filename);
switch ($exif['Orientation'])
{
case 3:
$image = imagerotate($image, 180, 0);
break;
case 6:
$image = imagerotate($image, 90, 0);
break;
case 8:
$image = imagerotate($image, -90, 0);
break;
}
imagejpeg($image, $filename);
}
}
/**
* Generates and returns a random string of the given length.
*
* @param int $str_length The string length.
* @return string A pseudorandom string.
*/
function random_string($str_length = 10)
{
$keyspace = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$len = strlen($keyspace);
$random_string = '';
for ($i = 0; $i < $str_length; $i++)
{
$random_string .= $keyspace[mt_rand(0, $len - 1)];
}
return $random_string;
}
/**
* A sweet interval formatting, will use the two biggest interval parts.
* On small intervals, you get minutes and seconds.
* On big intervals, you get months and days.
* Only the two biggest parts are used.
*
* @param DateTime $start
* @param DateTime|null $end
* @return string
*/
function format_date_diff($start, $end = null)
{
if(!($start instanceof DateTime))
{
$start = new DateTime($start);
}
if($end === null)
{
$end = new DateTime();
}
if(!($end instanceof DateTime))
{
$end = new DateTime($start);
}
$interval = $end->diff($start);
// adds plurals
$doPlural = function ($nb, $str) {
return $nb > 1 ? $str . 's' : $str;
};
$format = array();
if($interval->y !== 0)
{
$format[] = "%y ".$doPlural($interval->y, "year");
}
if($interval->m !== 0)
{
$format[] = "%m ".$doPlural($interval->m, "month");
}
if($interval->d !== 0)
{
$format[] = "%d ".$doPlural($interval->d, "day");
}
if($interval->h !== 0)
{
$format[] = "%h ".$doPlural($interval->h, "hour");
}
if($interval->i !== 0)
{
$format[] = "%i ".$doPlural($interval->i, "minute");
}
if($interval->s !== 0)
{
if(!count($format))
{
return "less than a minute ago";
}
else
{
$format[] = "%s ".$doPlural($interval->s, "second");
}
}
// We use the two biggest parts
if(count($format) > 1)
{
$format = array_shift($format)." and ".array_shift($format);
}
else
{
$format = array_pop($format);
}
return $interval->format($format);
}
/**
* Returns an human-readable filesize from a bytes cout.
*
* Inspiration from https://php.net/manual/en/function.filesize.php#106569
*
* @param int $bytes The bytes count.
* @param int $decimals The decimals wanted in the final result.
* @return string Human-readable size with unit.
*/
function human_filesize($bytes, $decimals = 2) {
$sz = ['o', 'Kio', 'Mio', 'Gio', 'Tio', 'Pio'];
$factor = floor((strlen($bytes) - 1) / 3);
return sprintf("%.{$decimals}f ", $bytes / pow(1024, $factor)) . @$sz[$factor];
}