/
smush_it.functions.inc
297 lines (268 loc) · 9.5 KB
/
smush_it.functions.inc
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
<?php
/**
* Fake namespacing of the functions (allows for private functions to hide them from the global scope)
*/
class smush_it {
/**
* Load an image from it's file_id (fid)
* @param int $file_id
* @return array
*/
private static function load_file($file_id){
$result = db_query('SELECT * FROM {files} WHERE fid = %d', $file_id);
$file = db_fetch_array($result);
return $file;
}
/**
* Set an image to be ignored by smush_it's cron job
* @param int $file_id
* @return boolean
*/
static function ignore_image($file_id){
$file = self::load_file($file_id);
$smush_it = array(
'space_saved' => 0,
'fid' => $file['fid'],
);
$smush_it_object = (object) $smush_it;
drupal_write_record('smush_it', $smush_it_object);
return true;
}
/**
* Revert an image to it's unsmushed state
* @param int $file_id
* @return boolean
*/
static function revert_image($file_id){
$file = self::load_file($file_id);
$root_path = self::document_root() . '/';
$filepath = $root_path . $file['filepath'];
//don't wipe out files that do not have backups
if(file_exists($filepath.'.old')){
unlink($filepath);
rename($filepath . '.old', $filepath);
}
list($width, $height, $type, $attr) = getimagesize($filepath);
$file['mimetype'] = image_type_to_mime_type($type);
$file['filesize'] = filesize($filepath);
$smush_it = array(
'space_saved' => 0,
$smush_it['fid'] => $file['fid'],
);
$smush_it_object = (object) $smush_it;
$file_object = (object) $file;
db_query('DELETE FROM {smush_it} WHERE fid = %d', $file['fid']);
drupal_write_record('files', $file_object, 'fid');
return true;
}
/**
* Get the total space saved
* @return string
*/
static function _total_saved() {
$result = db_query('SELECT SUM(space_saved) as total FROM {smush_it};');
$result = db_fetch_array($result);
return $result['total'];
}
/**
* Count the total image size
* @return string
*/
static function _image_size() {
$result = db_query("SELECT SUM(filesize) as total FROM {files} WHERE filemime IN ('image/jpeg', 'image/png', 'image/gif');");
$result = db_fetch_array($result);
return $result['total'];
}
/**
* The number of smushed files
* @return string
*/
static function _smushed_count() {
$result = db_query("SELECT COUNT(*) as total FROM {smush_it};");
$result = db_fetch_array($result);
return $result['total'];
}
/**
* The number of images total
* @return string
*/
static function _image_count() {
$result = db_query("SELECT COUNT(*) as total FROM {files} WHERE filemime IN ('image/jpeg', 'image/png', 'image/gif');");
$result = db_fetch_array($result);
return $result['total'];
}
/**
* Get the document root for the current Drupal installation.
* $_SERVER['DOCUMENT_ROOT'] is not reliable across all
* systems, so we need a way to get the correct value.
* @staticvar string $root The value that will be returned
* @return string
*/
static function document_root() {
static $root;
if (!$root) {
//@BUG: there has to be a better way to do this part...
$absolute_dir = dirname(__FILE__);
$relative_dir = drupal_get_path('module', 'smush_it');
$root = substr($absolute_dir, 0, -1 * (1 + strlen($relative_dir)));
}
return $root;
}
/**
* Format a number of bytes nicely for output (B, KB, MB, GB, TB...)
* @param int $bytes Number of bytes
* @param string $unit units you want it back in (default is to choose the biggest one that fits)
* @param int $decimals number of decimal places
* @return string
*/
static function byte_format($bytes, $unit = "", $decimals = 2) {
return _smush_it_byte_format($bytes, $unit, $decimals);
}
/**
* Push an image through the smush.it api
* @global string $base_url
* @staticvar SmushIt $s The smush.it object
* @staticvar bool $smush_it_testing Whether or not we are in test mode
* @staticvar string $smush_it_test_image The image that will be used in test mode
* @param int $file_id The id of the file being processed
* @return boolean Whether or not the smushing was successful
*/
static function smush_image($file_id) {
$file = self::load_file($file_id);
global $base_url;
static $s, $smush_it_testing, $smush_it_test_image;
if (!$s) {
$s = new SmushIt();
$smush_it_testing = variable_get('_smush_it_testing', 0);
$smush_it_test_image = variable_get('_smush_it_test_image', null);
}
$filepath = $file['filepath'];
if (!$smush_it_testing) {
//use the actual file
$file_url = $base_url . DIRECTORY_SEPARATOR . $filepath;
} else {
//use a web accessible file set in the settings section
$file_url = $smush_it_test_image;
}
try {
$q = db_query('SELECT smushid FROM {smush_it} WHERE fid = %d', $file['fid']);
$exists = db_fetch_array($q);
if (!empty($exists['smushid'])) {
throw new Smush_exception('The file has already been smushed', null);
}
$smushed = $s->compress($file_url);
$file = self::save_file($file, $smushed);
//update the mimetype just incase something actually uses it
list($width, $height, $type, $attr) = getimagesize($smushed->src);
$file['filemime'] = image_type_to_mime_type($type);
//drupal_write_record expects an object, not an array
$file_object = (object) $file;
drupal_write_record('files', $file_object, array('fid'));
//store the smushed info in the database as well so the image isn't processed over and over again
$smush_it_object = (object) array(
'fid' => $file['fid'],
'space_saved' => $smushed->src_size - $smushed->dest_size
);
drupal_write_record('smush_it', $smush_it_object);
} catch (Smush_exception $e) {
//no savings means that the file is as small as it can be (not really an error, but returned as one by the api)
if ($e->getMessage() == 'No savings') {
//store the smushed info in the database as well so the image isn't processed over and over again
$smush_it_object = (object) array(
'fid' => $file['fid'],
'space_saved' => 0
);
drupal_write_record('smush_it', $smush_it_object);
} else {
//An actual error! Send it to the user
drupal_set_message($e->getMessage() . ' => ' . $file['filename'], 'error');
return false;
}
}
return true;
}
/**
* Save the smushed file from the smush.it server
* @param file $file
* @param smushed $smushed
* @return file $file
*/
private static function save_file($file, &$smushed) {
$root_path = smush_it::document_root() . '/';
$remote = fopen($smushed->dest, "rb");
$new_file = $root_path . $file['filepath'] . '.new';
$original_file = $root_path . $file['filepath'];
$old_file = $root_path . $file['filepath'] . '.old';
//read the file in bit by bit
$temp = fopen($new_file, 'w+');
while (!feof($remote)) {
fwrite($temp, fread($remote, 8192));
}
fclose($temp);
fclose($remote);
//backup the old file (.old) and replace it with the new file
rename($original_file, $old_file);
rename($new_file, $original_file);
$file['filesize'] = $smushed->dest_size;
return $file;
}
}
if (BC_LOADED) {
/**
* Format a number of bytes nicely for output (B, KB, MB, GB, TB...)
* @param int $bytes Number of bytes
* @param string $unit units you want it back in (default is to choose the biggest one that fits)
* @param int $decimals number of decimal places
* @return string
*/
function _smush_it_byte_format($bytes, $unit = "", $decimals = 2) {
$units = array('B' => 0, 'KB' => 1, 'MB' => 2, 'GB' => 3, 'TB' => 4, 'PB' => 5, 'EB' => 6, 'ZB' => 7, 'YB' => 8);
$value = 0;
if ($bytes > 0) {
// Generate automatic prefix by bytes
// If wrong prefix given
if (!array_key_exists($unit, $units)) {
$pow = floor(log($bytes) / log(1024));
$unit = array_search($pow, $units);
}
// Calculate byte value by prefix
$value = $bytes / pow(1024, floor($units[$unit]));
}
// If decimals is not numeric or decimals is less than 0
// then set default value
if (!is_numeric($decimals) || $decimals < 0) {
$decimals = 2;
}
// Format output
return sprintf('%.' . $decimals . 'f ' . $unit, $value);
}
} else {
/**
* Format a number of bytes nicely for output (B, KB, MB, GB, TB...)
* @param int $bytes Number of bytes
* @param string $unit units you want it back in (default is to choose the biggest one that fits)
* @param int $decimals number of decimal places
* @return string
*/
function _smush_it_byte_format($bytes, $unit = "", $decimals = 2) {
$units = array('B' => 0, 'KB' => 1, 'MB' => 2, 'GB' => 3, 'TB' => 4, 'PB' => 5, 'EB' => 6, 'ZB' => 7, 'YB' => 8);
$value = 0;
if ($bytes > 0) {
// Generate automatic prefix by bytes
// If wrong prefix given
if (!array_key_exists($unit, $units)) {
$pow = floor(bcdiv(log($bytes), log(1024)));
$unit = array_search($pow, $units);
}
// Calculate byte value by prefix
$value = (bcdiv($bytes, bcpow(1024, floor($units[$unit]))));
}
// If decimals is not numeric or decimals is less than 0
// then set default value
if (!is_numeric($decimals) || $decimals < 0) {
$decimals = 2;
}
// Format output
return sprintf('%.' . $decimals . 'f ' . $unit, $value);
}
}