ShortPixel Image Optimizer - Version 1.6.4

Version Description

  • API validation URL changed to v1
Download this release

Release Info

Developer ShortPixel
Plugin Icon 128x128 ShortPixel Image Optimizer
Version 1.6.4
Comparing to
See all releases

Code changes from version 1.6.3 to 1.6.4

readme.txt CHANGED
@@ -4,7 +4,7 @@ Contributors: AlexSP
4
  Tags: picture, optimization, image editor, pngout, upload speed, shortpixel, compression, jpegmini, webp, lossless, cwebp, media, tinypng, jpegtran,image, image optimisation, shrink, picture, photo, optimize photos, compress, performance, tinypng, crunch, pngquant, attachment, optimize, pictures,fast, images, image files, image quality, lossy, upload, kraken, resize, seo, smushit, optipng, kraken image optimizer, ewww, photo optimization, gifsicle, image optimizer, images, krakenio, png, gmagick, image optimize
5
  Requires at least: 3.0.0 or higher
6
  Tested up to: 4.0
7
- Stable tag: 1.6.3
8
  License: GPLv2 or later
9
  License URI: http://www.gnu.org/licenses/gpl-2.0.html
10
 
@@ -107,6 +107,10 @@ The ShortPixel team is here to help. <a href="https://shortpixel.com/contact">Co
107
 
108
  == Changelog ==
109
 
 
 
 
 
110
  = 1.6.3 =
111
 
112
  * fallback to http if plugin activation fails for https
4
  Tags: picture, optimization, image editor, pngout, upload speed, shortpixel, compression, jpegmini, webp, lossless, cwebp, media, tinypng, jpegtran,image, image optimisation, shrink, picture, photo, optimize photos, compress, performance, tinypng, crunch, pngquant, attachment, optimize, pictures,fast, images, image files, image quality, lossy, upload, kraken, resize, seo, smushit, optipng, kraken image optimizer, ewww, photo optimization, gifsicle, image optimizer, images, krakenio, png, gmagick, image optimize
5
  Requires at least: 3.0.0 or higher
6
  Tested up to: 4.0
7
+ Stable tag: 1.6.4
8
  License: GPLv2 or later
9
  License URI: http://www.gnu.org/licenses/gpl-2.0.html
10
 
107
 
108
  == Changelog ==
109
 
110
+ = 1.6.4 =
111
+
112
+ * API validation URL changed to v1
113
+
114
  = 1.6.3 =
115
 
116
  * fallback to http if plugin activation fails for https
trunk/JSON/JSON.php ADDED
@@ -0,0 +1,806 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
3
+
4
+ /**
5
+ * Converts to and from JSON format.
6
+ *
7
+ * JSON (JavaScript Object Notation) is a lightweight data-interchange
8
+ * format. It is easy for humans to read and write. It is easy for machines
9
+ * to parse and generate. It is based on a subset of the JavaScript
10
+ * Programming Language, Standard ECMA-262 3rd Edition - December 1999.
11
+ * This feature can also be found in Python. JSON is a text format that is
12
+ * completely language independent but uses conventions that are familiar
13
+ * to programmers of the C-family of languages, including C, C++, C#, Java,
14
+ * JavaScript, Perl, TCL, and many others. These properties make JSON an
15
+ * ideal data-interchange language.
16
+ *
17
+ * This package provides a simple encoder and decoder for JSON notation. It
18
+ * is intended for use with client-side Javascript applications that make
19
+ * use of HTTPRequest to perform server communication functions - data can
20
+ * be encoded into JSON notation for use in a client-side javascript, or
21
+ * decoded from incoming Javascript requests. JSON format is native to
22
+ * Javascript, and can be directly eval()'ed with no further parsing
23
+ * overhead
24
+ *
25
+ * All strings should be in ASCII or UTF-8 format!
26
+ *
27
+ * LICENSE: Redistribution and use in source and binary forms, with or
28
+ * without modification, are permitted provided that the following
29
+ * conditions are met: Redistributions of source code must retain the
30
+ * above copyright notice, this list of conditions and the following
31
+ * disclaimer. Redistributions in binary form must reproduce the above
32
+ * copyright notice, this list of conditions and the following disclaimer
33
+ * in the documentation and/or other materials provided with the
34
+ * distribution.
35
+ *
36
+ * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
37
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
38
+ * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
39
+ * NO EVENT SHALL CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
40
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
41
+ * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
42
+ * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
43
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
44
+ * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
45
+ * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
46
+ * DAMAGE.
47
+ *
48
+ * @category
49
+ * @package Services_JSON
50
+ * @author Michal Migurski <mike-json@teczno.com>
51
+ * @author Matt Knapp <mdknapp[at]gmail[dot]com>
52
+ * @author Brett Stimmerman <brettstimmerman[at]gmail[dot]com>
53
+ * @copyright 2005 Michal Migurski
54
+ * @version CVS: $Id: JSON.php,v 1.31 2006/06/28 05:54:17 migurski Exp $
55
+ * @license http://www.opensource.org/licenses/bsd-license.php
56
+ * @link http://pear.php.net/pepr/pepr-proposal-show.php?id=198
57
+ */
58
+
59
+ /**
60
+ * Marker constant for Services_JSON::decode(), used to flag stack state
61
+ */
62
+ define('SERVICES_JSON_SLICE', 1);
63
+
64
+ /**
65
+ * Marker constant for Services_JSON::decode(), used to flag stack state
66
+ */
67
+ define('SERVICES_JSON_IN_STR', 2);
68
+
69
+ /**
70
+ * Marker constant for Services_JSON::decode(), used to flag stack state
71
+ */
72
+ define('SERVICES_JSON_IN_ARR', 3);
73
+
74
+ /**
75
+ * Marker constant for Services_JSON::decode(), used to flag stack state
76
+ */
77
+ define('SERVICES_JSON_IN_OBJ', 4);
78
+
79
+ /**
80
+ * Marker constant for Services_JSON::decode(), used to flag stack state
81
+ */
82
+ define('SERVICES_JSON_IN_CMT', 5);
83
+
84
+ /**
85
+ * Behavior switch for Services_JSON::decode()
86
+ */
87
+ define('SERVICES_JSON_LOOSE_TYPE', 16);
88
+
89
+ /**
90
+ * Behavior switch for Services_JSON::decode()
91
+ */
92
+ define('SERVICES_JSON_SUPPRESS_ERRORS', 32);
93
+
94
+ /**
95
+ * Converts to and from JSON format.
96
+ *
97
+ * Brief example of use:
98
+ *
99
+ * <code>
100
+ * // create a new instance of Services_JSON
101
+ * $json = new Services_JSON();
102
+ *
103
+ * // convert a complexe value to JSON notation, and send it to the browser
104
+ * $value = array('foo', 'bar', array(1, 2, 'baz'), array(3, array(4)));
105
+ * $output = $json->encode($value);
106
+ *
107
+ * print($output);
108
+ * // prints: ["foo","bar",[1,2,"baz"],[3,[4]]]
109
+ *
110
+ * // accept incoming POST data, assumed to be in JSON notation
111
+ * $input = file_get_contents('php://input', 1000000);
112
+ * $value = $json->decode($input);
113
+ * </code>
114
+ */
115
+ class Services_JSON
116
+ {
117
+ /**
118
+ * constructs a new JSON instance
119
+ *
120
+ * @param int $use object behavior flags; combine with boolean-OR
121
+ *
122
+ * possible values:
123
+ * - SERVICES_JSON_LOOSE_TYPE: loose typing.
124
+ * "{...}" syntax creates associative arrays
125
+ * instead of objects in decode().
126
+ * - SERVICES_JSON_SUPPRESS_ERRORS: error suppression.
127
+ * Values which can't be encoded (e.g. resources)
128
+ * appear as NULL instead of throwing errors.
129
+ * By default, a deeply-nested resource will
130
+ * bubble up with an error, so all return values
131
+ * from encode() should be checked with isError()
132
+ */
133
+ function Services_JSON($use = 0)
134
+ {
135
+ $this->use = $use;
136
+ }
137
+
138
+ /**
139
+ * convert a string from one UTF-16 char to one UTF-8 char
140
+ *
141
+ * Normally should be handled by mb_convert_encoding, but
142
+ * provides a slower PHP-only method for installations
143
+ * that lack the multibye string extension.
144
+ *
145
+ * @param string $utf16 UTF-16 character
146
+ * @return string UTF-8 character
147
+ * @access private
148
+ */
149
+ function utf162utf8($utf16)
150
+ {
151
+ // oh please oh please oh please oh please oh please
152
+ if(function_exists('mb_convert_encoding')) {
153
+ return mb_convert_encoding($utf16, 'UTF-8', 'UTF-16');
154
+ }
155
+
156
+ $bytes = (ord($utf16{0}) << 8) | ord($utf16{1});
157
+
158
+ switch(true) {
159
+ case ((0x7F & $bytes) == $bytes):
160
+ // this case should never be reached, because we are in ASCII range
161
+ // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
162
+ return chr(0x7F & $bytes);
163
+
164
+ case (0x07FF & $bytes) == $bytes:
165
+ // return a 2-byte UTF-8 character
166
+ // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
167
+ return chr(0xC0 | (($bytes >> 6) & 0x1F))
168
+ . chr(0x80 | ($bytes & 0x3F));
169
+
170
+ case (0xFFFF & $bytes) == $bytes:
171
+ // return a 3-byte UTF-8 character
172
+ // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
173
+ return chr(0xE0 | (($bytes >> 12) & 0x0F))
174
+ . chr(0x80 | (($bytes >> 6) & 0x3F))
175
+ . chr(0x80 | ($bytes & 0x3F));
176
+ }
177
+
178
+ // ignoring UTF-32 for now, sorry
179
+ return '';
180
+ }
181
+
182
+ /**
183
+ * convert a string from one UTF-8 char to one UTF-16 char
184
+ *
185
+ * Normally should be handled by mb_convert_encoding, but
186
+ * provides a slower PHP-only method for installations
187
+ * that lack the multibye string extension.
188
+ *
189
+ * @param string $utf8 UTF-8 character
190
+ * @return string UTF-16 character
191
+ * @access private
192
+ */
193
+ function utf82utf16($utf8)
194
+ {
195
+ // oh please oh please oh please oh please oh please
196
+ if(function_exists('mb_convert_encoding')) {
197
+ return mb_convert_encoding($utf8, 'UTF-16', 'UTF-8');
198
+ }
199
+
200
+ switch(strlen($utf8)) {
201
+ case 1:
202
+ // this case should never be reached, because we are in ASCII range
203
+ // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
204
+ return $utf8;
205
+
206
+ case 2:
207
+ // return a UTF-16 character from a 2-byte UTF-8 char
208
+ // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
209
+ return chr(0x07 & (ord($utf8{0}) >> 2))
210
+ . chr((0xC0 & (ord($utf8{0}) << 6))
211
+ | (0x3F & ord($utf8{1})));
212
+
213
+ case 3:
214
+ // return a UTF-16 character from a 3-byte UTF-8 char
215
+ // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
216
+ return chr((0xF0 & (ord($utf8{0}) << 4))
217
+ | (0x0F & (ord($utf8{1}) >> 2)))
218
+ . chr((0xC0 & (ord($utf8{1}) << 6))
219
+ | (0x7F & ord($utf8{2})));
220
+ }
221
+
222
+ // ignoring UTF-32 for now, sorry
223
+ return '';
224
+ }
225
+
226
+ /**
227
+ * encodes an arbitrary variable into JSON format
228
+ *
229
+ * @param mixed $var any number, boolean, string, array, or object to be encoded.
230
+ * see argument 1 to Services_JSON() above for array-parsing behavior.
231
+ * if var is a strng, note that encode() always expects it
232
+ * to be in ASCII or UTF-8 format!
233
+ *
234
+ * @return mixed JSON string representation of input var or an error if a problem occurs
235
+ * @access public
236
+ */
237
+ function encode($var)
238
+ {
239
+ switch (gettype($var)) {
240
+ case 'boolean':
241
+ return $var ? 'true' : 'false';
242
+
243
+ case 'NULL':
244
+ return 'null';
245
+
246
+ case 'integer':
247
+ return (int) $var;
248
+
249
+ case 'double':
250
+ case 'float':
251
+ return (float) $var;
252
+
253
+ case 'string':
254
+ // STRINGS ARE EXPECTED TO BE IN ASCII OR UTF-8 FORMAT
255
+ $ascii = '';
256
+ $strlen_var = strlen($var);
257
+
258
+ /*
259
+ * Iterate over every character in the string,
260
+ * escaping with a slash or encoding to UTF-8 where necessary
261
+ */
262
+ for ($c = 0; $c < $strlen_var; ++$c) {
263
+
264
+ $ord_var_c = ord($var{$c});
265
+
266
+ switch (true) {
267
+ case $ord_var_c == 0x08:
268
+ $ascii .= '\b';
269
+ break;
270
+ case $ord_var_c == 0x09:
271
+ $ascii .= '\t';
272
+ break;
273
+ case $ord_var_c == 0x0A:
274
+ $ascii .= '\n';
275
+ break;
276
+ case $ord_var_c == 0x0C:
277
+ $ascii .= '\f';
278
+ break;
279
+ case $ord_var_c == 0x0D:
280
+ $ascii .= '\r';
281
+ break;
282
+
283
+ case $ord_var_c == 0x22:
284
+ case $ord_var_c == 0x2F:
285
+ case $ord_var_c == 0x5C:
286
+ // double quote, slash, slosh
287
+ $ascii .= '\\'.$var{$c};
288
+ break;
289
+
290
+ case (($ord_var_c >= 0x20) && ($ord_var_c <= 0x7F)):
291
+ // characters U-00000000 - U-0000007F (same as ASCII)
292
+ $ascii .= $var{$c};
293
+ break;
294
+
295
+ case (($ord_var_c & 0xE0) == 0xC0):
296
+ // characters U-00000080 - U-000007FF, mask 110XXXXX
297
+ // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
298
+ $char = pack('C*', $ord_var_c, ord($var{$c + 1}));
299
+ $c += 1;
300
+ $utf16 = $this->utf82utf16($char);
301
+ $ascii .= sprintf('\u%04s', bin2hex($utf16));
302
+ break;
303
+
304
+ case (($ord_var_c & 0xF0) == 0xE0):
305
+ // characters U-00000800 - U-0000FFFF, mask 1110XXXX
306
+ // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
307
+ $char = pack('C*', $ord_var_c,
308
+ ord($var{$c + 1}),
309
+ ord($var{$c + 2}));
310
+ $c += 2;
311
+ $utf16 = $this->utf82utf16($char);
312
+ $ascii .= sprintf('\u%04s', bin2hex($utf16));
313
+ break;
314
+
315
+ case (($ord_var_c & 0xF8) == 0xF0):
316
+ // characters U-00010000 - U-001FFFFF, mask 11110XXX
317
+ // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
318
+ $char = pack('C*', $ord_var_c,
319
+ ord($var{$c + 1}),
320
+ ord($var{$c + 2}),
321
+ ord($var{$c + 3}));
322
+ $c += 3;
323
+ $utf16 = $this->utf82utf16($char);
324
+ $ascii .= sprintf('\u%04s', bin2hex($utf16));
325
+ break;
326
+
327
+ case (($ord_var_c & 0xFC) == 0xF8):
328
+ // characters U-00200000 - U-03FFFFFF, mask 111110XX
329
+ // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
330
+ $char = pack('C*', $ord_var_c,
331
+ ord($var{$c + 1}),
332
+ ord($var{$c + 2}),
333
+ ord($var{$c + 3}),
334
+ ord($var{$c + 4}));
335
+ $c += 4;
336
+ $utf16 = $this->utf82utf16($char);
337
+ $ascii .= sprintf('\u%04s', bin2hex($utf16));
338
+ break;
339
+
340
+ case (($ord_var_c & 0xFE) == 0xFC):
341
+ // characters U-04000000 - U-7FFFFFFF, mask 1111110X
342
+ // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
343
+ $char = pack('C*', $ord_var_c,
344
+ ord($var{$c + 1}),
345
+ ord($var{$c + 2}),
346
+ ord($var{$c + 3}),
347
+ ord($var{$c + 4}),
348
+ ord($var{$c + 5}));
349
+ $c += 5;
350
+ $utf16 = $this->utf82utf16($char);
351
+ $ascii .= sprintf('\u%04s', bin2hex($utf16));
352
+ break;
353
+ }
354
+ }
355
+
356
+ return '"'.$ascii.'"';
357
+
358
+ case 'array':
359
+ /*
360
+ * As per JSON spec if any array key is not an integer
361
+ * we must treat the the whole array as an object. We
362
+ * also try to catch a sparsely populated associative
363
+ * array with numeric keys here because some JS engines
364
+ * will create an array with empty indexes up to
365
+ * max_index which can cause memory issues and because
366
+ * the keys, which may be relevant, will be remapped
367
+ * otherwise.
368
+ *
369
+ * As per the ECMA and JSON specification an object may
370
+ * have any string as a property. Unfortunately due to
371
+ * a hole in the ECMA specification if the key is a
372
+ * ECMA reserved word or starts with a digit the
373
+ * parameter is only accessible using ECMAScript's
374
+ * bracket notation.
375
+ */
376
+
377
+ // treat as a JSON object
378
+ if (is_array($var) && count($var) && (array_keys($var) !== range(0, sizeof($var) - 1))) {
379
+ $properties = array_map(array($this, 'name_value'),
380
+ array_keys($var),
381
+ array_values($var));
382
+
383
+ foreach($properties as $property) {
384
+ if(Services_JSON::isError($property)) {
385
+ return $property;
386
+ }
387
+ }
388
+
389
+ return '{' . join(',', $properties) . '}';
390
+ }
391
+
392
+ // treat it like a regular array
393
+ $elements = array_map(array($this, 'encode'), $var);
394
+
395
+ foreach($elements as $element) {
396
+ if(Services_JSON::isError($element)) {
397
+ return $element;
398
+ }
399
+ }
400
+
401
+ return '[' . join(',', $elements) . ']';
402
+
403
+ case 'object':
404
+ $vars = get_object_vars($var);
405
+
406
+ $properties = array_map(array($this, 'name_value'),
407
+ array_keys($vars),
408
+ array_values($vars));
409
+
410
+ foreach($properties as $property) {
411
+ if(Services_JSON::isError($property)) {
412
+ return $property;
413
+ }
414
+ }
415
+
416
+ return '{' . join(',', $properties) . '}';
417
+
418
+ default:
419
+ return ($this->use & SERVICES_JSON_SUPPRESS_ERRORS)
420
+ ? 'null'
421
+ : new Services_JSON_Error(gettype($var)." can not be encoded as JSON string");
422
+ }
423
+ }
424
+
425
+ /**
426
+ * array-walking function for use in generating JSON-formatted name-value pairs
427
+ *
428
+ * @param string $name name of key to use
429
+ * @param mixed $value reference to an array element to be encoded
430
+ *
431
+ * @return string JSON-formatted name-value pair, like '"name":value'
432
+ * @access private
433
+ */
434
+ function name_value($name, $value)
435
+ {
436
+ $encoded_value = $this->encode($value);
437
+
438
+ if(Services_JSON::isError($encoded_value)) {
439
+ return $encoded_value;
440
+ }
441
+
442
+ return $this->encode(strval($name)) . ':' . $encoded_value;
443
+ }
444
+
445
+ /**
446
+ * reduce a string by removing leading and trailing comments and whitespace
447
+ *
448
+ * @param $str string string value to strip of comments and whitespace
449
+ *
450
+ * @return string string value stripped of comments and whitespace
451
+ * @access private
452
+ */
453
+ function reduce_string($str)
454
+ {
455
+ $str = preg_replace(array(
456
+
457
+ // eliminate single line comments in '// ...' form
458
+ '#^\s*//(.+)$#m',
459
+
460
+ // eliminate multi-line comments in '/* ... */' form, at start of string
461
+ '#^\s*/\*(.+)\*/#Us',
462
+
463
+ // eliminate multi-line comments in '/* ... */' form, at end of string
464
+ '#/\*(.+)\*/\s*$#Us'
465
+
466
+ ), '', $str);
467
+
468
+ // eliminate extraneous space
469
+ return trim($str);
470
+ }
471
+
472
+ /**
473
+ * decodes a JSON string into appropriate variable
474
+ *
475
+ * @param string $str JSON-formatted string
476
+ *
477
+ * @return mixed number, boolean, string, array, or object
478
+ * corresponding to given JSON input string.
479
+ * See argument 1 to Services_JSON() above for object-output behavior.
480
+ * Note that decode() always returns strings
481
+ * in ASCII or UTF-8 format!
482
+ * @access public
483
+ */
484
+ function decode($str)
485
+ {
486
+ $str = $this->reduce_string($str);
487
+
488
+ switch (strtolower($str)) {
489
+ case 'true':
490
+ return true;
491
+
492
+ case 'false':
493
+ return false;
494
+
495
+ case 'null':
496
+ return null;
497
+
498
+ default:
499
+ $m = array();
500
+
501
+ if (is_numeric($str)) {
502
+ // Lookie-loo, it's a number
503
+
504
+ // This would work on its own, but I'm trying to be
505
+ // good about returning integers where appropriate:
506
+ // return (float)$str;
507
+
508
+ // Return float or int, as appropriate
509
+ return ((float)$str == (integer)$str)
510
+ ? (integer)$str
511
+ : (float)$str;
512
+
513
+ } elseif (preg_match('/^("|\').*(\1)$/s', $str, $m) && $m[1] == $m[2]) {
514
+ // STRINGS RETURNED IN UTF-8 FORMAT
515
+ $delim = substr($str, 0, 1);
516
+ $chrs = substr($str, 1, -1);
517
+ $utf8 = '';
518
+ $strlen_chrs = strlen($chrs);
519
+
520
+ for ($c = 0; $c < $strlen_chrs; ++$c) {
521
+
522
+ $substr_chrs_c_2 = substr($chrs, $c, 2);
523
+ $ord_chrs_c = ord($chrs{$c});
524
+
525
+ switch (true) {
526
+ case $substr_chrs_c_2 == '\b':
527
+ $utf8 .= chr(0x08);
528
+ ++$c;
529
+ break;
530
+ case $substr_chrs_c_2 == '\t':
531
+ $utf8 .= chr(0x09);
532
+ ++$c;
533
+ break;
534
+ case $substr_chrs_c_2 == '\n':
535
+ $utf8 .= chr(0x0A);
536
+ ++$c;
537
+ break;
538
+ case $substr_chrs_c_2 == '\f':
539
+ $utf8 .= chr(0x0C);
540
+ ++$c;
541
+ break;
542
+ case $substr_chrs_c_2 == '\r':
543
+ $utf8 .= chr(0x0D);
544
+ ++$c;
545
+ break;
546
+
547
+ case $substr_chrs_c_2 == '\\"':
548
+ case $substr_chrs_c_2 == '\\\'':
549
+ case $substr_chrs_c_2 == '\\\\':
550
+ case $substr_chrs_c_2 == '\\/':
551
+ if (($delim == '"' && $substr_chrs_c_2 != '\\\'') ||
552
+ ($delim == "'" && $substr_chrs_c_2 != '\\"')) {
553
+ $utf8 .= $chrs{++$c};
554
+ }
555
+ break;
556
+
557
+ case preg_match('/\\\u[0-9A-F]{4}/i', substr($chrs, $c, 6)):
558
+ // single, escaped unicode character
559
+ $utf16 = chr(hexdec(substr($chrs, ($c + 2), 2)))
560
+ . chr(hexdec(substr($chrs, ($c + 4), 2)));
561
+ $utf8 .= $this->utf162utf8($utf16);
562
+ $c += 5;
563
+ break;
564
+
565
+ case ($ord_chrs_c >= 0x20) && ($ord_chrs_c <= 0x7F):
566
+ $utf8 .= $chrs{$c};
567
+ break;
568
+
569
+ case ($ord_chrs_c & 0xE0) == 0xC0:
570
+ // characters U-00000080 - U-000007FF, mask 110XXXXX
571
+ //see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
572
+ $utf8 .= substr($chrs, $c, 2);
573
+ ++$c;
574
+ break;
575
+
576
+ case ($ord_chrs_c & 0xF0) == 0xE0:
577
+ // characters U-00000800 - U-0000FFFF, mask 1110XXXX
578
+ // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
579
+ $utf8 .= substr($chrs, $c, 3);
580
+ $c += 2;
581
+ break;
582
+
583
+ case ($ord_chrs_c & 0xF8) == 0xF0:
584
+ // characters U-00010000 - U-001FFFFF, mask 11110XXX
585
+ // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
586
+ $utf8 .= substr($chrs, $c, 4);
587
+ $c += 3;
588
+ break;
589
+
590
+ case ($ord_chrs_c & 0xFC) == 0xF8:
591
+ // characters U-00200000 - U-03FFFFFF, mask 111110XX
592
+ // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
593
+ $utf8 .= substr($chrs, $c, 5);
594
+ $c += 4;
595
+ break;
596
+
597
+ case ($ord_chrs_c & 0xFE) == 0xFC:
598
+ // characters U-04000000 - U-7FFFFFFF, mask 1111110X
599
+ // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
600
+ $utf8 .= substr($chrs, $c, 6);
601
+ $c += 5;
602
+ break;
603
+
604
+ }
605
+
606
+ }
607
+
608
+ return $utf8;
609
+
610
+ } elseif (preg_match('/^\[.*\]$/s', $str) || preg_match('/^\{.*\}$/s', $str)) {
611
+ // array, or object notation
612
+
613
+ if ($str{0} == '[') {
614
+ $stk = array(SERVICES_JSON_IN_ARR);
615
+ $arr = array();
616
+ } else {
617
+ if ($this->use & SERVICES_JSON_LOOSE_TYPE) {
618
+ $stk = array(SERVICES_JSON_IN_OBJ);
619
+ $obj = array();
620
+ } else {
621
+ $stk = array(SERVICES_JSON_IN_OBJ);
622
+ $obj = new stdClass();
623
+ }
624
+ }
625
+
626
+ array_push($stk, array('what' => SERVICES_JSON_SLICE,
627
+ 'where' => 0,
628
+ 'delim' => false));
629
+
630
+ $chrs = substr($str, 1, -1);
631
+ $chrs = $this->reduce_string($chrs);
632
+
633
+ if ($chrs == '') {
634
+ if (reset($stk) == SERVICES_JSON_IN_ARR) {
635
+ return $arr;
636
+
637
+ } else {
638
+ return $obj;
639
+
640
+ }
641
+ }
642
+
643
+ //print("\nparsing {$chrs}\n");
644
+
645
+ $strlen_chrs = strlen($chrs);
646
+
647
+ for ($c = 0; $c <= $strlen_chrs; ++$c) {
648
+
649
+ $top = end($stk);
650
+ $substr_chrs_c_2 = substr($chrs, $c, 2);
651
+
652
+ if (($c == $strlen_chrs) || (($chrs{$c} == ',') && ($top['what'] == SERVICES_JSON_SLICE))) {
653
+ // found a comma that is not inside a string, array, etc.,
654
+ // OR we've reached the end of the character list
655
+ $slice = substr($chrs, $top['where'], ($c - $top['where']));
656
+ array_push($stk, array('what' => SERVICES_JSON_SLICE, 'where' => ($c + 1), 'delim' => false));
657
+ //print("Found split at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n");
658
+
659
+ if (reset($stk) == SERVICES_JSON_IN_ARR) {
660
+ // we are in an array, so just push an element onto the stack
661
+ array_push($arr, $this->decode($slice));
662
+
663
+ } elseif (reset($stk) == SERVICES_JSON_IN_OBJ) {
664
+ // we are in an object, so figure
665
+ // out the property name and set an
666
+ // element in an associative array,
667
+ // for now
668
+ $parts = array();
669
+
670
+ if (preg_match('/^\s*(["\'].*[^\\\]["\'])\s*:\s*(\S.*),?$/Uis', $slice, $parts)) {
671
+ // "name":value pair
672
+ $key = $this->decode($parts[1]);
673
+ $val = $this->decode($parts[2]);
674
+
675
+ if ($this->use & SERVICES_JSON_LOOSE_TYPE) {
676
+ $obj[$key] = $val;
677
+ } else {
678
+ $obj->$key = $val;
679
+ }
680
+ } elseif (preg_match('/^\s*(\w+)\s*:\s*(\S.*),?$/Uis', $slice, $parts)) {
681
+ // name:value pair, where name is unquoted
682
+ $key = $parts[1];
683
+ $val = $this->decode($parts[2]);
684
+
685
+ if ($this->use & SERVICES_JSON_LOOSE_TYPE) {
686
+ $obj[$key] = $val;
687
+ } else {
688
+ $obj->$key = $val;
689
+ }
690
+ }
691
+
692
+ }
693
+
694
+ } elseif ((($chrs{$c} == '"') || ($chrs{$c} == "'")) && ($top['what'] != SERVICES_JSON_IN_STR)) {
695
+ // found a quote, and we are not inside a string
696
+ array_push($stk, array('what' => SERVICES_JSON_IN_STR, 'where' => $c, 'delim' => $chrs{$c}));
697
+ //print("Found start of string at {$c}\n");
698
+
699
+ } elseif (($chrs{$c} == $top['delim']) &&
700
+ ($top['what'] == SERVICES_JSON_IN_STR) &&
701
+ ((strlen(substr($chrs, 0, $c)) - strlen(rtrim(substr($chrs, 0, $c), '\\'))) % 2 != 1)) {
702
+ // found a quote, we're in a string, and it's not escaped
703
+ // we know that it's not escaped becase there is _not_ an
704
+ // odd number of backslashes at the end of the string so far
705
+ array_pop($stk);
706
+ //print("Found end of string at {$c}: ".substr($chrs, $top['where'], (1 + 1 + $c - $top['where']))."\n");
707
+
708
+ } elseif (($chrs{$c} == '[') &&
709
+ in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) {
710
+ // found a left-bracket, and we are in an array, object, or slice
711
+ array_push($stk, array('what' => SERVICES_JSON_IN_ARR, 'where' => $c, 'delim' => false));
712
+ //print("Found start of array at {$c}\n");
713
+
714
+ } elseif (($chrs{$c} == ']') && ($top['what'] == SERVICES_JSON_IN_ARR)) {
715
+ // found a right-bracket, and we're in an array
716
+ array_pop($stk);
717
+ //print("Found end of array at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n");
718
+
719
+ } elseif (($chrs{$c} == '{') &&
720
+ in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) {
721
+ // found a left-brace, and we are in an array, object, or slice
722
+ array_push($stk, array('what' => SERVICES_JSON_IN_OBJ, 'where' => $c, 'delim' => false));
723
+ //print("Found start of object at {$c}\n");
724
+
725
+ } elseif (($chrs{$c} == '}') && ($top['what'] == SERVICES_JSON_IN_OBJ)) {
726
+ // found a right-brace, and we're in an object
727
+ array_pop($stk);
728
+ //print("Found end of object at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n");
729
+
730
+ } elseif (($substr_chrs_c_2 == '/*') &&
731
+ in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) {
732
+ // found a comment start, and we are in an array, object, or slice
733
+ array_push($stk, array('what' => SERVICES_JSON_IN_CMT, 'where' => $c, 'delim' => false));
734
+ $c++;
735
+ //print("Found start of comment at {$c}\n");
736
+
737
+ } elseif (($substr_chrs_c_2 == '*/') && ($top['what'] == SERVICES_JSON_IN_CMT)) {
738
+ // found a comment end, and we're in one now
739
+ array_pop($stk);
740
+ $c++;
741
+
742
+ for ($i = $top['where']; $i <= $c; ++$i)
743
+ $chrs = substr_replace($chrs, ' ', $i, 1);
744
+
745
+ //print("Found end of comment at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n");
746
+
747
+ }
748
+
749
+ }
750
+
751
+ if (reset($stk) == SERVICES_JSON_IN_ARR) {
752
+ return $arr;
753
+
754
+ } elseif (reset($stk) == SERVICES_JSON_IN_OBJ) {
755
+ return $obj;
756
+
757
+ }
758
+
759
+ }
760
+ }
761
+ }
762
+
763
+ /**
764
+ * @todo Ultimately, this should just call PEAR::isError()
765
+ */
766
+ function isError($data, $code = null)
767
+ {
768
+ if (class_exists('pear')) {
769
+ return PEAR::isError($data, $code);
770
+ } elseif (is_object($data) && (get_class($data) == 'services_json_error' ||
771
+ is_subclass_of($data, 'services_json_error'))) {
772
+ return true;
773
+ }
774
+
775
+ return false;
776
+ }
777
+ }
778
+
779
+ if (class_exists('PEAR_Error')) {
780
+
781
+ class Services_JSON_Error extends PEAR_Error
782
+ {
783
+ function Services_JSON_Error($message = 'unknown error', $code = null,
784
+ $mode = null, $options = null, $userinfo = null)
785
+ {
786
+ parent::PEAR_Error($message, $code, $mode, $options, $userinfo);
787
+ }
788
+ }
789
+
790
+ } else {
791
+
792
+ /**
793
+ * @todo Ultimately, this class shall be descended from PEAR_Error
794
+ */
795
+ class Services_JSON_Error
796
+ {
797
+ function Services_JSON_Error($message = 'unknown error', $code = null,
798
+ $mode = null, $options = null, $userinfo = null)
799
+ {
800
+
801
+ }
802
+ }
803
+
804
+ }
805
+
806
+ ?>
trunk/JSON/LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Redistribution and use in source and binary forms, with or without
2
+ modification, are permitted provided that the following conditions are
3
+ met:
4
+
5
+ Redistributions of source code must retain the above copyright notice,
6
+ this list of conditions and the following disclaimer.
7
+
8
+ Redistributions in binary form must reproduce the above copyright
9
+ notice, this list of conditions and the following disclaimer in the
10
+ documentation and/or other materials provided with the distribution.
11
+
12
+ THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
13
+ WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
14
+ MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
15
+ NO EVENT SHALL CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
16
+ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
17
+ NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
18
+ USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
19
+ ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
20
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
21
+ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
trunk/readme.txt ADDED
@@ -0,0 +1,208 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ === ShortPixel Image Optimiser ===
2
+
3
+ Contributors: AlexSP
4
+ Tags: picture, optimization, image editor, pngout, upload speed, shortpixel, compression, jpegmini, webp, lossless, cwebp, media, tinypng, jpegtran,image, image optimisation, shrink, picture, photo, optimize photos, compress, performance, tinypng, crunch, pngquant, attachment, optimize, pictures,fast, images, image files, image quality, lossy, upload, kraken, resize, seo, smushit, optipng, kraken image optimizer, ewww, photo optimization, gifsicle, image optimizer, images, krakenio, png, gmagick, image optimize
5
+ Requires at least: 3.0.0 or higher
6
+ Tested up to: 4.1
7
+ Stable tag: 1.6.5
8
+ License: GPLv2 or later
9
+ License URI: http://www.gnu.org/licenses/gpl-2.0.html
10
+
11
+ The ShortPixel plugin reduces the images' size making your website load faster. Image quality is preserved using advanced compression technology.
12
+
13
+ == Description ==
14
+
15
+ ShortPixel is an image compression tool that helps improve your website performance. The plugin optimises images automatically using both lossy and lossless compression. Resulting, smaller, images are no different in quality from the original.
16
+
17
+ ShortPixel uses powerful algorithms that enable your website to load faster, use less bandwidth and rank better in search.
18
+
19
+ **The ShortPixel package includes:**
20
+
21
+ * **Both lossy and lossless optimisation:** you can choose between the two types of compression. Lossy for photographs. Lossless for technical drawings, clip art and comics.
22
+ * **Up to 90% compression rate:** with lossy compression images that were 3MB can crunch to 307Kb, with no before/after differences.
23
+ * **Supported formats:** JPG, PNG, GIF (including animated): optimisation applies to JPG, PNG and static GIF. NEW UPDATE: we introduced optimisation for animated GIFs.
24
+ * **Backup and restore originals:** if you ever want to return to the original version, images are automatically stored in a backup folder on your hosting servers.
25
+ * **Bulk image optimisation:** Crunch your image gallery, and downsize your website. This feature may take up to several hours, depending on the number and size of existing images.
26
+
27
+ On the https://ShortPixel.com website, we offer free access to the ShrtPixel API which you can use for further image optimisation purposes.
28
+
29
+ == Installation ==
30
+
31
+ Let's get ShortPixel plugin running on your WordPress website:
32
+
33
+
34
+ 1. Sign up using your email at https://shortpixel.com/wp-apikey
35
+ 2. You will receive your personal API key in a confirmation email, to the address you provided.
36
+ 3. Upload the ShortPixel plugin to the /wp-content/plugins/ directory
37
+ 4. Use your unique API key to activate ShortPixel plugin in the 'Plugins' menu in WordPress.
38
+ 5. Uploaded images can be automatically optimised in the Media Library.
39
+ 6. Done!
40
+
41
+
42
+ == Frequently Asked Questions ==
43
+
44
+ = What happens to the existing images, when installing the ShortPixel plugin? =
45
+
46
+ Just installing the plugin won’t start the optimisation process on existing images. To begin optimising the images previously loaded on your website, you should:
47
+
48
+ * Go to **Media Library**, and select which of the existing images you want to optimise.
49
+
50
+ OR
51
+
52
+ * Use the **Bulk ShortPixel** option, to automatically optimise all your previous library.
53
+
54
+ = Should I pick lossy or lossless optimisation? =
55
+
56
+ This depends on your compression needs. **Lossy** has a better compression rate than lossless compression. The resulting image is not 100% identical with the original. Works well for photos taken with your camera.
57
+
58
+ With **lossless** compression, the shrunk image will be indistinguishable from the original, and smaller in size. Use this when you do not want to loose any of the original image's details. Works best for technical drawings, clip art and comics.
59
+
60
+ For more information about the difference read the <a href="http://en.wikipedia.org/wiki/Lossy_compression#Lossy_and_lossless_compression" target="_blank">Wiki article</a> on the lossy/lossless difference.
61
+
62
+ = Why do I need an API key? =
63
+
64
+ ShortPixel Image Optimiser uses automated processes to crunch images. The ShortPixel API integrates in the dashboard of your Wordpress website and processes both old and new images automatically.
65
+ You can also use the API in your own applications, the <a href="https://shortpixel.com/api-docs">Documentation API</a> shows you how.
66
+
67
+ = Where do I get my API key? =
68
+
69
+ To get your API key, you must <a href="https://shortpixel.com/wp-apikey">Sign up to ShortPixel</a>. You will receive your personal API key in a confirmation email to the address you provided. Use your API key to activate ShortPixel plugin in the 'Plugins' menu in WordPress.
70
+
71
+ = Where do I use my API key? =
72
+
73
+ You use the API key in the ShortPixel plugin Settings (don’t forget to click Save Settings). The same API key can be used on multiple websites/blogs.
74
+
75
+ = How does Bulk Optimisation work? =
76
+
77
+ The Bulk option makes ShortPixel optimise all your images at once (not one by one). You can do this in the Media > Bulk ShortPixel section by clicking on the **Compress all your images** button.
78
+
79
+ The batch optimisation may work slower, depending on your existing image gallery. Please be patient and do not close the Wordpress admin while you are rolling the Bulk Processing on your media gallery.
80
+
81
+ = Are my images safe? =
82
+
83
+ Yes, privacy is guaranteed. The ShortPixel encryption process doesn't allow anyone to view your photos.
84
+
85
+ = What happens with my original images after they have been processed with ShortPixel? =
86
+
87
+ Your images are automatically stored in a backup folder, on your hosting server. After optimisation, if you want to switch back to a certain original image, hit **Restore backup** in the Media Library. If you are happy with the ShortPixel optimised images, you can deactivate saving the backups in the plugin Settings.
88
+
89
+ = What types of formats can be optimised? =
90
+
91
+ For now, ShortPixel supports JPEG, PNG and GIF formats. Animated GIFs and thumbnails are also optimised. Additional formats are scheduled for optimisation in the future.
92
+
93
+ = I’m stuck. What do I do? =
94
+
95
+ The ShortPixel team is here to help. <a href="https://shortpixel.com/contact">Contact us</a>!
96
+
97
+
98
+ == Screenshots ==
99
+
100
+ 1. Activate your API key in the plugin Settings. (Settings>ShortPixel)
101
+
102
+ 2. Compress all your past images with one click. (Media>Bulk)
103
+
104
+ 3. Your stats: number of processed files, saved space, average compression, saved bandwidth, remaining images. (Settings>ShortPixel)
105
+
106
+ 4. Restore to original image. (Media>Library)
107
+
108
+ == Changelog ==
109
+
110
+ = 1.6.5 =
111
+
112
+ * plugin tested for WP 4.1
113
+
114
+ = 1.6.4 =
115
+
116
+ * API validation URL changed to v1
117
+
118
+ = 1.6.3 =
119
+
120
+ * fallback to http if plugin activation fails for https
121
+ * added error mesage API Key validation fail
122
+
123
+ = 1.6.2 =
124
+
125
+ * extra check for images that return 3xx/4xx codes to be ignored
126
+ * API Key validation (error) message is returned to user
127
+ * error messages for images are displayed in the "ShortPixel Compression" column
128
+
129
+ = 1.6.1 =
130
+
131
+ * fixed small upload glitch
132
+ * added succes message upon bulk processing completion
133
+ * improved image backup
134
+ * lossy option by default upon plugin installation
135
+
136
+ = 1.6.0 =
137
+
138
+ * images' requests for optimization are sent for all sizes upon image upload in media gallery
139
+ * non-image (e.g. PDF files) are ignored now @ bulk processing
140
+ * bulk optimization improved & some bugs fixed.
141
+ * FAQ/Description small changes
142
+
143
+ = 1.5.1 =
144
+
145
+ * readme changes
146
+
147
+ = 1.5.0 =
148
+
149
+ * pictures are removed from backup as well when deleted
150
+ * restore backup warning/error fixed
151
+ * fixed useless/bad AJAX requests that occured sometimes
152
+ * added user agent to API Key validation for debugging purposes
153
+ * Bulk Processing was freezing for some users, fixed this + added Cancel button
154
+
155
+ = 1.4.1 =
156
+
157
+ * optimize again overwrote the original image, fixed
158
+ * fixed restore errors
159
+ * changes to FAQ/Description texts
160
+
161
+ = 1.4.0 =
162
+
163
+ * Bulk image processing improved so it can optimize all the images in background while admin page is open
164
+ * small changes in readme.txt descrption
165
+
166
+ = 1.3.5 =
167
+
168
+ * fixed broken link in settings page
169
+ * updated FAQ
170
+ * description updated
171
+
172
+ = 1.3.2 =
173
+
174
+ * fixed missing action link @ Bulk Processing
175
+ * added more screenshots
176
+
177
+ = 1.3.1 =
178
+
179
+ * possible fix for API key validation failing
180
+ * added backup and restore for images that are processed with shortpixel
181
+ * optimize now feature on Media Library
182
+
183
+ = 1.0.6 =
184
+
185
+ * bulk processing runs in background now.
186
+
187
+ = 1.0.5 =
188
+
189
+ * extra check for the converted images to be safely copied from ShortPixel
190
+
191
+ = 1.0.4 =
192
+
193
+ * corrections and additions to readme.txt and wp-shortpixel.php
194
+
195
+ = 1.0.3 =
196
+
197
+ * minor bug fixes
198
+
199
+ = 1.0.2 =
200
+
201
+ * Updated Bulk editing to run in background
202
+ * Updated default options
203
+ * Added notifications on activation
204
+
205
+ = 1.0 =
206
+
207
+ * First working version
208
+
trunk/shortpixel_api.php ADDED
@@ -0,0 +1,210 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ if ( !function_exists( 'download_url' ) ) {
3
+ require_once( ABSPATH . 'wp-admin/includes/file.php' );
4
+ }
5
+
6
+ class shortpixel_api {
7
+
8
+ private $_apiKey = '';
9
+ private $_compressionType = '';
10
+ private $_maxAttempts = 10;
11
+ private $_apiEndPoint = 'https://api.shortpixel.com/v1/reducer.php';
12
+
13
+ public function setCompressionType($compressionType)
14
+ {
15
+ $this->_compressionType = $compressionType;
16
+ }
17
+
18
+ public function getCompressionType()
19
+ {
20
+ return $this->_compressionType;
21
+ }
22
+
23
+ public function setApiKey($apiKey)
24
+ {
25
+ $this->_apiKey = $apiKey;
26
+ }
27
+
28
+ public function getApiKey()
29
+ {
30
+ return $this->_apiKey;
31
+ }
32
+
33
+ public function __construct($apiKey, $compressionType) {
34
+ $this->_apiKey = $apiKey;
35
+ $this->setCompressionType($compressionType);
36
+
37
+ add_action('processImageAction', array(&$this, 'processImageAction'), 10, 4);
38
+ }
39
+
40
+ public function processImageAction($url, $filePath, $ID, $time) {
41
+ $this->processImage($url, $filePath, $ID, $time);
42
+ }
43
+
44
+ public function doRequests($url, $filePath, $ID = null) {
45
+ $requestURL = $this->_apiEndPoint . '?key=' . $this->_apiKey . '&lossy=' . $this->_compressionType . '&url=';
46
+ $requestURL = $requestURL . urlencode($url);
47
+
48
+ $args = array('timeout'=> SP_MAX_TIMEOUT, 'sslverify' => false);
49
+ $response = wp_remote_get($requestURL, $args);
50
+
51
+ if(is_object($response) && get_class($response) == 'WP_Error') {
52
+ return false;
53
+ }
54
+
55
+ return $response;
56
+ }
57
+
58
+ public function parseResponse($response) {
59
+ $data = $response['body'];
60
+ $data = str_replace('Warning: Division by zero in /usr/local/important/web/api.shortpixel.com/lib/functions.php on line 33', '', $data);
61
+ $data = $this->parseJSON($data);
62
+ return $data;
63
+ }
64
+
65
+ //handles the processing of the image using the ShortPixel API
66
+ public function processImage($url, $filePath, $ID = null, $startTime = 0) {
67
+ if($startTime == 0) { $startTime = time(); }
68
+ if(time() - $startTime > MAX_EXECUTION_TIME) {
69
+ $meta = wp_get_attachment_metadata($ID);
70
+ $meta['ShortPixelImprovement'] = 'Could not determine compression';
71
+ unset($meta['ShortPixel']['WaitingProcessing']);
72
+ wp_update_attachment_metadata($ID, $meta);
73
+ return 'Could not determine compression';
74
+ }
75
+
76
+ $response = $this->doRequests($url, $filePath, $ID);
77
+
78
+ if(!$response) return $response;
79
+
80
+ if($response['response']['code'] != 200) {
81
+ WPShortPixel::log("Response 200 OK");
82
+ printf('Web service did not respond. Please try again later.');
83
+ return false;
84
+ }
85
+
86
+ $data = $this->parseResponse($response);
87
+
88
+ switch($data->Status->Code) {
89
+ case 1:
90
+ //handle image has been scheduled
91
+ sleep(1);
92
+ return $this->processImage($url, $filePath, $ID, $startTime);
93
+ break;
94
+ case 2:
95
+ //handle image has been processed
96
+ $this->handleSuccess($data, $url, $filePath, $ID);
97
+ break;
98
+ case -16:
99
+ return 'Quota exceeded</br>';
100
+ case -17:
101
+ return 'Wrong API Key</br>';
102
+ default:
103
+ //handle error
104
+ return $data->Status->Message;
105
+ }
106
+
107
+ return $data;
108
+ }
109
+
110
+
111
+ public function handleSuccess($callData, $url, $filePath, $ID) {
112
+
113
+ if($this->_compressionType) {
114
+ //lossy
115
+ $correctFileSize = $callData->LossySize;
116
+ $tempFile = download_url(urldecode($callData->LossyURL));
117
+ if(is_wp_error( $tempFile )) {
118
+ $tempFile = download_url(str_replace('https://', 'http://', urldecode($callData->LossyURL)));
119
+ }
120
+ } else {
121
+ //lossless
122
+ $correctFileSize = $callData->LoselessSize;
123
+ $tempFile = download_url(urldecode($callData->LosslessURL));
124
+ if(is_wp_error( $tempFile )) {
125
+ $tempFile = download_url(str_replace('https://', 'http://', urldecode($callData->LosslessURL)));
126
+ }
127
+ }
128
+
129
+ if ( is_wp_error( $tempFile ) ) {
130
+ @unlink($tempFile);
131
+ return sprintf("Error downloading file (%s)", $tempFile->get_error_message());
132
+ die;
133
+ }
134
+
135
+ //check response so that download is OK
136
+ if(filesize($tempFile) != $correctFileSize) {
137
+ return sprintf("Error downloading file - incorrect file size");
138
+ die;
139
+ }
140
+
141
+ if (!file_exists($tempFile)) {
142
+ return sprintf("Unable to locate downloaded file (%s)", $tempFile);
143
+ die;
144
+ }
145
+
146
+ //if backup is enabled
147
+ if(get_option('wp-short-backup_images')) {
148
+
149
+ if(!file_exists(SP_BACKUP_FOLDER) && !mkdir(SP_BACKUP_FOLDER, 0777, true)) {
150
+ return sprintf("Backup folder does not exist and it could not be created");
151
+ }
152
+
153
+ $source = $filePath;
154
+ $destination = SP_BACKUP_FOLDER . DIRECTORY_SEPARATOR . basename($source);
155
+
156
+ if(is_writable(SP_BACKUP_FOLDER)) {
157
+ if(!file_exists($destination)) {
158
+ @copy($source, $destination);
159
+ }
160
+ } else {
161
+ return sprintf("Backup folder exists but is not writable");
162
+ }
163
+ }
164
+
165
+ @unlink( $filePath );
166
+ $success = @rename( $tempFile, $filePath );
167
+
168
+ if (!$success) {
169
+ $copySuccess = copy($tempFile, $filePath);
170
+ unlink($tempFile);
171
+ }
172
+
173
+ if($success || $copySuccess) {
174
+ //update statistics
175
+ if(isset($callData->LossySize)) {
176
+ $savedSpace = $callData->OriginalSize - $callData->LossySize;
177
+ } else {
178
+ $savedSpace = $callData->OriginalSize - $callData->LoselessSize;
179
+ }
180
+
181
+ update_option(
182
+ 'wp-short-pixel-savedSpace',
183
+ get_option('wp-short-pixel-savedSpace') + $savedSpace
184
+ );
185
+ $averageCompression = get_option('wp-short-pixel-averageCompression') * get_option('wp-short-pixel-fileCount');
186
+ $averageCompression += $callData->PercentImprovement;
187
+ $averageCompression = $averageCompression / (get_option('wp-short-pixel-fileCount') + 1);
188
+ update_option('wp-short-pixel-averageCompression', $averageCompression);
189
+ update_option('wp-short-pixel-fileCount', get_option('wp-short-pixel-fileCount')+1);
190
+
191
+ //update metadata
192
+ if(isset($ID)) {
193
+ $meta = wp_get_attachment_metadata($ID);
194
+ $meta['ShortPixelImprovement'] = $callData->PercentImprovement;
195
+ wp_update_attachment_metadata($ID, $meta);
196
+ }
197
+ }
198
+ }
199
+
200
+ public function parseJSON($data) {
201
+ if ( function_exists('json_decode') ) {
202
+ $data = json_decode( $data );
203
+ } else {
204
+ require_once( 'JSON/JSON.php' );
205
+ $json = new Services_JSON( );
206
+ $data = $json->decode( $data );
207
+ }
208
+ return $data;
209
+ }
210
+ }
trunk/wp-shortpixel.php ADDED
@@ -0,0 +1,818 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * Plugin Name: ShortPixel Image Optimiser
4
+ * Plugin URI: https://shortpixel.com/
5
+ * Description: ShortPixel is an image compression tool that helps improve your website performance. The plugin optimises images automatically using both lossy and lossless compression. Resulting, smaller, images are no different in quality from the original. To install: 1) Click the "Activate" link to the left of this description. 2) <a href="https://shortpixel.com/wp-apikey" target="_blank">Free Sign up</a> for your unique API Key . 3) Check your email for your API key. 4) Use your API key to activate ShortPixel plugin in the 'Plugins' menu in WordPress. 5) Done!
6
+ * Version: 1.6.4
7
+ * Author: ShortPixel
8
+ * Author URI: https://shortpixel.com
9
+ */
10
+
11
+ require_once('shortpixel_api.php');
12
+ require_once( ABSPATH . 'wp-admin/includes/image.php' );
13
+
14
+ define('SP_DEBUG', false);
15
+ define('SP_LOG', false);
16
+ define('SP_MAX_TIMEOUT', 10);
17
+ define('SP_BACKUP_FOLDER', WP_CONTENT_DIR . DIRECTORY_SEPARATOR . 'ShortpixelBackups');
18
+ define('MUST_HAVE_KEY', true);
19
+ define('BATCH_SIZE', 1);
20
+ define('MAX_EXECUTION_TIME', 30); //in seconds
21
+
22
+ class WPShortPixel {
23
+
24
+ private $_apiInterface = null;
25
+ private $_apiKey = '';
26
+ private $_compressionType = 1;
27
+ private $_processThumbnails = 1;
28
+ private $_backupImages = 1;
29
+ private $_verifiedKey = false;
30
+
31
+ public function __construct() {
32
+ $this->populateOptions();
33
+
34
+ $this->_apiInterface = new shortpixel_api($this->_apiKey, $this->_compressionType);
35
+
36
+ //add hook for image upload processing
37
+ add_filter( 'wp_generate_attachment_metadata', array( &$this, 'handleImageUpload' ), 10, 2 );
38
+ add_filter( 'manage_media_columns', array( &$this, 'columns' ) );
39
+ add_filter( 'plugin_action_links_' . plugin_basename(__FILE__), array(&$this, 'generatePluginLinks'));
40
+
41
+ //add_action( 'admin_footer', array(&$this, 'handleImageProcessing'));
42
+ add_action( 'manage_media_custom_column', array( &$this, 'generateCustomColumn' ), 10, 2 );
43
+
44
+ //add settings page
45
+ add_action( 'admin_menu', array( &$this, 'registerSettingsPage' ) );
46
+ add_action( 'admin_menu', array( &$this, 'registerAdminPage' ) );
47
+ add_action( 'delete_attachment', array( &$this, 'handleDeleteAttachmentInBackup' ) );
48
+
49
+ //automatic optimization
50
+ add_action( 'admin_footer', array( &$this, 'my_action_javascript') );
51
+ add_action( 'wp_ajax_my_action', array( &$this, 'handleImageProcessing') );
52
+
53
+ //manual optimization
54
+ add_action('admin_action_shortpixel_manual_optimize', array(&$this, 'handleManualOptimization'));
55
+ //backup restore
56
+ add_action('admin_action_shortpixel_restore_backup', array(&$this, 'handleRestoreBackup'));
57
+
58
+ //bulk processing in media library
59
+ //add_action('load-upload.php', array(&$this, 'wp_load_admin_js'));
60
+ //add_action('admin_enqueue_scripts', array(&$this, 'bulkOptimizeActionHandler'));
61
+ }
62
+
63
+ public function populateOptions() {
64
+
65
+ if(get_option('wp-short-pixel-apiKey') != false) {
66
+ $this->_apiKey = get_option('wp-short-pixel-apiKey');
67
+ } else {
68
+ add_option( 'wp-short-pixel-apiKey', '', '', 'yes' );
69
+ }
70
+
71
+ if(get_option('wp-short-pixel-verifiedKey') != false) {
72
+ $this->_verifiedKey = get_option('wp-short-pixel-verifiedKey');
73
+ }
74
+
75
+ if(get_option('wp-short-pixel-compression') != false) {
76
+ $this->_compressionType = get_option('wp-short-pixel-compression');
77
+ } else {
78
+ add_option('wp-short-pixel-compression', $this->_compressionType, '', 'yes');
79
+ }
80
+
81
+ if(get_option('wp-short-process_thumbnails') != false) {
82
+ $this->_processThumbnails = get_option('wp-short-process_thumbnails');
83
+ } else {
84
+ add_option('wp-short-process_thumbnails', $this->_processThumbnails, '', 'yes' );
85
+ }
86
+
87
+ if(get_option('wp-short-backup_images') != false) {
88
+ $this->_backupImages = get_option('wp-short-backup_images');
89
+ } else {
90
+ add_option('wp-short-backup_images', $this->_backupImages, '', 'yes' );
91
+ }
92
+
93
+ if(get_option('wp-short-pixel-fileCount') === false) {
94
+ add_option( 'wp-short-pixel-fileCount', 0, '', 'yes' );
95
+ }
96
+
97
+ if(get_option('wp-short-pixel-savedSpace') === false) {
98
+ add_option( 'wp-short-pixel-savedSpace', 0, '', 'yes' );
99
+ }
100
+
101
+ if(get_option('wp-short-pixel-averageCompression') === false) {
102
+ add_option( 'wp-short-pixel-averageCompression', 0, '', 'yes' );
103
+ }
104
+ }
105
+
106
+ static function log($message) {
107
+ if(SP_DEBUG) {
108
+ echo "{$message}</br>";
109
+ }
110
+ }
111
+
112
+ function my_action_javascript() { ?>
113
+ <script type="text/javascript" >
114
+ jQuery(document).ready(sendRequest());
115
+ function sendRequest() {
116
+ var data = { 'action': 'my_action' };
117
+ // since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
118
+ jQuery.post(ajaxurl, data, function(response) {
119
+ if(response.search('Empty queue') >= 0 || response.search('Error processing image') >= 0) {
120
+ console.log('Queue is empty');
121
+ } else {
122
+ console.log('Server response: ' + response);
123
+ sendRequest();
124
+ }
125
+ });
126
+ }
127
+ </script> <?php
128
+ }
129
+
130
+ function wp_load_admin_js() {
131
+ add_action('admin_print_footer_scripts', array(&$this, 'add_bulk_actions_via_javascript'));
132
+ }
133
+
134
+ function add_bulk_actions_via_javascript() {
135
+ ?>
136
+ <script type="text/javascript">
137
+ jQuery(document).ready(function($){
138
+ $('select[name^="action"] option:last-child').before('<option value="2">Bulk Optimize</option>');
139
+ });
140
+ </script>
141
+ <?php }
142
+
143
+ //handling older
144
+ public function WPShortPixel() {
145
+ $this->__construct();
146
+ }
147
+
148
+ public function handleImageUpload($meta, $ID = null) {
149
+ if(MUST_HAVE_KEY && $this->_verifiedKey) {
150
+ self::log("Processing image id {$ID}");
151
+ $url = wp_get_attachment_url($ID);
152
+ $path = get_attached_file($ID);
153
+ if(exif_imagetype($path) != false) {
154
+ $this->_apiInterface->doRequests($url, $path, $ID);
155
+
156
+ //send request for thumbs as well
157
+ if($this->_processThumbnails && !empty($meta['sizes'])) {
158
+ foreach($meta['sizes'] as $thumbnailInfo) {
159
+ $thumbURL = str_replace(basename($url), $thumbnailInfo['file'], $url);
160
+ $thumbPath = str_replace(basename($path), $thumbnailInfo['file'], $path);
161
+ $this->_apiInterface->doRequests($thumbURL, $thumbPath);
162
+ }
163
+ }
164
+ } else {
165
+ $meta['ShortPixelImprovement'] = 'File is not an image';
166
+ return $meta;
167
+ }
168
+ } else {
169
+
170
+ }
171
+ $meta['ShortPixel']['WaitingProcessing'] = true;
172
+ return $meta;
173
+ }
174
+
175
+ public function handleImageProcessing($ID = null) {
176
+ if(MUST_HAVE_KEY && $this->_verifiedKey == false) {
177
+ echo "Missing API Key";
178
+ die();
179
+ }
180
+
181
+ //query database for first found entry that needs processing
182
+ global $wpdb;
183
+ $qry = "SELECT * FROM " . $wpdb->prefix . "postmeta
184
+ WHERE meta_value LIKE '%\"WaitingProcessing\";b:1;%'
185
+ OR meta_value LIKE '%\"BulkProcessing\";b:1;%'
186
+ LIMIT " . BATCH_SIZE;
187
+ $idList = $wpdb->get_results($qry);
188
+
189
+ if(empty($idList)) { echo 'Empty queue'; die; }
190
+
191
+ foreach($idList as $post) {
192
+ $ID = $post->post_id;
193
+ $imageURL = wp_get_attachment_url($ID);
194
+ $imagePath = get_attached_file($ID);
195
+ $meta = wp_get_attachment_metadata($ID);
196
+
197
+ //check if image is public
198
+ if(wp_remote_retrieve_response_code($imageURL) > 400) {
199
+ if(isset($meta['ShortPixel']['BulkProcessing'])) { unset($meta['ShortPixel']['BulkProcessing']); }
200
+ if(isset($met['ShortPixel']['WaitingProcessing'])) { unset($meta['ShortPixel']['WaitingProcessing']); }
201
+ wp_update_attachment_metadata($ID, $meta);
202
+ die;
203
+ }
204
+
205
+ $result = $this->_apiInterface->processImage($imageURL, $imagePath, $ID);
206
+
207
+ if(is_string($result)) {
208
+ if(isset($meta['ShortPixel']['BulkProcessing'])) { unset($meta['ShortPixel']['BulkProcessing']); }
209
+ if(isset($meta['ShortPixel']['WaitingProcessing'])) { unset($meta['ShortPixel']['WaitingProcessing']); }
210
+ $meta['ShortPixelImprovement'] = $result;
211
+ wp_update_attachment_metadata($ID, $meta);
212
+ echo "Error processing image: " . $result;
213
+ die;
214
+ }
215
+
216
+ $processThumbnails = get_option('wp-short-process_thumbnails');
217
+
218
+ //handle the rest of the thumbnails generated by WP
219
+ if($processThumbnails && $result && !empty($meta['sizes'])) {
220
+ foreach($meta['sizes'] as $thumbnailInfo) {
221
+ $thumbURL = str_replace(basename($imagePath), $thumbnailInfo['file'], $imageURL);
222
+ $thumbPath = str_replace(basename($imagePath), $thumbnailInfo['file'], $imagePath);
223
+ $this->_apiInterface->processImage($thumbURL, $thumbPath);
224
+ }
225
+ }
226
+
227
+ unset($meta['ShortPixel']['WaitingProcessing']);
228
+
229
+ if(isset($meta['ShortPixel']['BulkProcessing'])) {
230
+ unset($meta['ShortPixel']['BulkProcessing']);
231
+ }
232
+
233
+ $meta['ShortPixelImprovement'] = $result->PercentImprovement;
234
+
235
+ wp_update_attachment_metadata($ID, $meta);
236
+ echo "Processing done succesfully for image #{$ID}";
237
+ }
238
+
239
+ die();
240
+ }
241
+
242
+ public function handleManualOptimization() {
243
+ $attachmentID = intval($_GET['attachment_ID']);
244
+
245
+ $url = wp_get_attachment_url($attachmentID);
246
+ $filePath = get_attached_file($attachmentID);
247
+ $meta = wp_get_attachment_metadata($attachmentID);
248
+
249
+ $result = $this->_apiInterface->processImage($url, $filePath, $attachmentID);
250
+
251
+ $processThumbnails = get_option('wp-short-process_thumbnails');
252
+
253
+ //handle the rest of the thumbnails generated by WP
254
+ if($processThumbnails && $result && !empty($meta['sizes'])) {
255
+ foreach($meta['sizes'] as $thumbnailInfo) {
256
+ $thumbURL = str_replace(basename($filePath), $thumbnailInfo['file'], $filePath);
257
+ $thumbPath = str_replace(basename($filePath), $thumbnailInfo['file'], $filePath);
258
+ $this->_apiInterface->processImage($thumbURL, $thumbPath);
259
+ }
260
+ }
261
+
262
+ // store the referring webpage location
263
+ $sendback = wp_get_referer();
264
+ // sanitize the referring webpage location
265
+ $sendback = preg_replace('|[^a-z0-9-~+_.?#=&;,/:]|i', '', $sendback);
266
+ // send the user back where they came from
267
+ wp_redirect($sendback);
268
+ // we are done,
269
+ }
270
+
271
+ public function handleRestoreBackup() {
272
+ $attachmentID = intval($_GET['attachment_ID']);
273
+
274
+ $uploadFilePath = get_attached_file($attachmentID);
275
+ $meta = wp_get_attachment_metadata($attachmentID);
276
+ $pathInfo = pathinfo($uploadFilePath);
277
+
278
+ try {
279
+ //main file
280
+ @rename(SP_BACKUP_FOLDER . DIRECTORY_SEPARATOR . basename($uploadFilePath), $uploadFilePath);
281
+ //overwriting thumbnails
282
+ if(is_array($meta["sizes"])) {
283
+ foreach($meta["sizes"] as $size => $imageData) {
284
+ $source = SP_BACKUP_FOLDER . DIRECTORY_SEPARATOR . $imageData['file'];
285
+ $destination = $pathInfo['dirname'] . DIRECTORY_SEPARATOR . $imageData['file'];
286
+ @rename($source, $destination);
287
+ }
288
+ }
289
+
290
+ unset($meta["ShortPixelImprovement"]);
291
+ wp_update_attachment_metadata($attachmentID, $meta);
292
+
293
+ } catch(Exception $e) {
294
+ //what to do, what to do?
295
+ }
296
+ // store the referring webpage location
297
+ $sendback = wp_get_referer();
298
+ // sanitize the referring webpage location
299
+ $sendback = preg_replace('|[^a-z0-9-~+_.?#=&;,/:]|i', '', $sendback);
300
+ // send the user back where they came from
301
+ wp_redirect($sendback);
302
+ // we are done
303
+ }
304
+
305
+
306
+ public function handleDeleteAttachmentInBackup($ID) {
307
+ $uploadFilePath = get_attached_file($ID);
308
+ $meta = wp_get_attachment_metadata($ID);
309
+ if(exif_imagetype($uploadFilePath) != false) {
310
+ try {
311
+ //main file
312
+ @unlink(SP_BACKUP_FOLDER . DIRECTORY_SEPARATOR . basename($uploadFilePath));
313
+ //overwriting thumbnails
314
+ foreach($meta["sizes"] as $size => $imageData) {
315
+ @unlink(SP_BACKUP_FOLDER . DIRECTORY_SEPARATOR . $imageData['file']);
316
+ }
317
+ } catch(Exception $e) {
318
+ //what to do, what to do?
319
+ }
320
+ }
321
+ }
322
+
323
+ public function bulkOptimizeActionHandler($hook) {
324
+ if($hook == 'upload.php') {
325
+ if($_GET['action'] == 2) {
326
+ if(!empty($_GET['media'])) {
327
+ $imageLog = array();
328
+ //remove all ShortPixel data from metadata
329
+ foreach($_GET['media'] as $attachmentID) {
330
+ $meta = wp_get_attachment_metadata($attachmentID);
331
+ $meta['ShortPixel']['BulkProcessing'] = true;
332
+ unset($meta['ShortPixelImprovement']);
333
+ wp_update_attachment_metadata($attachmentID, $meta);
334
+ $imageLog[$attachmentID] = false;
335
+ }
336
+ update_option('bulkProcessingLog', $imageLog);
337
+ }
338
+ }
339
+ }
340
+ }
341
+
342
+ public function registerSettingsPage() {
343
+ add_options_page( 'ShortPixel Settings', 'ShortPixel', 'manage_options', 'wp-shortpixel', array($this, 'renderSettingsMenu'));
344
+ }
345
+
346
+ function registerAdminPage( ) {
347
+ add_media_page( 'ShortPixel Bulk Process', 'Bulk ShortPixel', 'edit_others_posts', 'wp-short-pixel-bulk', array( &$this, 'bulkProcesss' ) );
348
+ }
349
+
350
+ public function bulkProcesss() {
351
+ echo '<h1>Bulk Image Optimisation by ShortPixel</h1>';
352
+
353
+ if(MUST_HAVE_KEY && $this->_verifiedKey == false) {
354
+ echo "<p>In order to start processing your images, you need to validate your API key in the ShortPixel Settings. If you don’t have an API Key, you can get one delivered to your inbox.</p>";
355
+ echo "<p>Don’t have an API Key yet? Get it now at <a href=\"https://shortpixel.com/wp-apikey\" target=\"_blank\">www.ShortPixel.com</a>, for free.</p>";
356
+ return;
357
+ }
358
+
359
+ $attachments = null;
360
+ $attachments = get_posts( array(
361
+ 'numberposts' => -1,
362
+ 'post_type' => 'attachment',
363
+ 'post_mime_type' => 'image'
364
+ ));
365
+
366
+ if($_GET['cancel']) {
367
+ foreach($attachments as $attachment) {
368
+ $meta = wp_get_attachment_metadata($attachment->ID);
369
+ if(isset($meta['ShortPixel']['BulkProcessing'])) unset($meta['ShortPixel']['BulkProcessing']);
370
+ wp_update_attachment_metadata($attachment->ID, $meta);
371
+ }
372
+ }
373
+
374
+ if($_POST["bulkProcess"]) {
375
+ //remove all ShortPixel data from metadata
376
+ foreach($attachments as $attachment) {
377
+ if(exif_imagetype(get_attached_file($attachment->ID)) == false) continue;
378
+ $meta = wp_get_attachment_metadata($attachment->ID);
379
+ $meta['ShortPixel']['BulkProcessing'] = true;
380
+ wp_update_attachment_metadata($attachment->ID, $meta);
381
+ }
382
+
383
+ //break this in separate foreach in order to easily comment it out if performance issues
384
+ // foreach($attachments as $attachment) {
385
+ // if(exif_imagetype(get_attached_file($attachment->ID)) == false) continue;
386
+ // $meta = wp_get_attachment_metadata($attachment->ID);
387
+ // $url = wp_get_attachment_url($attachment->ID);
388
+ // $path = get_attached_file($attachment->ID);
389
+ // $this->_apiInterface->doRequests($url, $path, $attachment->ID);
390
+ //
391
+ // if($this->_processThumbnails && !empty($meta['sizes'])) {
392
+ // foreach($meta['sizes'] as $thumbnailInfo) {
393
+ // $thumbURL = str_replace(basename($url), $thumbnailInfo['file'], $url);
394
+ // $thumbPath = str_replace(basename($path), $thumbnailInfo['file'], $path);
395
+ // $this->_apiInterface->doRequests($thumbURL, $thumbPath);
396
+ // }
397
+ // }
398
+ // }
399
+
400
+ update_option('bulkProcessingStatus', 'running');
401
+ }
402
+
403
+ global $wpdb;
404
+ $qry = "SELECT * FROM " . $wpdb->prefix . "postmeta
405
+ WHERE meta_value LIKE '%\"BulkProcessing\";b:1;%'";
406
+ $idList = $wpdb->get_results($qry);
407
+
408
+ if(!empty($idList)) {
409
+ if(is_array($idList)) {
410
+ echo "<p>
411
+ Bulk optimisation has started. It may take a while until we process all your images. <BR>The latest status of the processing will be displayed here every 30 seconds.
412
+ In the meantime, you can continue using the admin as usual.<BR> However, <b>you musn’t close the WordPress admin</b>, or the bulk processing will stop.
413
+ </p>";
414
+ echo '
415
+ <script type="text/javascript" >
416
+ var bulkProcessingRunning = true;
417
+ </script>
418
+ ';
419
+
420
+ $imagesLeft = count($idList);
421
+ $totalImages = count($attachments);
422
+
423
+ echo "<p>{$imagesLeft} out of {$totalImages} images left to process.</p>";
424
+
425
+ echo '
426
+ <a class="button button-secondary" href="' . get_admin_url() . 'upload.php">Media Library</a>
427
+ <a class="button button-secondary" href="' . get_admin_url() . 'upload.php?page=wp-short-pixel-bulk&cancel=1">Cancel Processing</a>
428
+ ';
429
+ }
430
+ } else {
431
+ $bulkProcessingStatus = get_option('bulkProcessingStatus');
432
+ if(isset($bulkProcessingStatus) && $bulkProcessingStatus == 'running') {
433
+ echo "<p>Bulk optimisation was successful. ShortPixel has finished optimising all your images.</p>
434
+ <p>Go to the ShortPixel <a href='" . get_admin_url() . "options-general.php?page=wp-shortpixel#facts'>Facts &amp; Figures</a> and see your website's optimised stats (in Settings > ShortPixel). </p>";
435
+ delete_option('bulkProcessingStatus');
436
+ }
437
+ echo $this->getBulkProcessingForm(count($attachments));
438
+ echo '
439
+ <script type="text/javascript" >
440
+ var bulkProcessingRunning = false;
441
+ </script>
442
+ ';
443
+ }
444
+
445
+ echo '
446
+ <script type="text/javascript" >
447
+ jQuery(document).ready(function() {
448
+ if(bulkProcessingRunning) {
449
+ console.log("Bulk processing running");
450
+ setTimeout(function(){
451
+ window.location = window.location.href;
452
+ }, 30000);
453
+ } else {
454
+ console.log("No bulk processing is currently running");
455
+ }
456
+ });
457
+ </script>
458
+ ';
459
+ }
460
+
461
+ public function renderSettingsMenu() {
462
+ if ( !current_user_can( 'manage_options' ) ) {
463
+ wp_die('You do not have sufficient permissions to access this page.');
464
+ }
465
+ echo '<h1>ShortPixel Image Optimiser Settings</h1>';
466
+ echo '<p>
467
+ <a href="https://shortpixel.com">ShortPixel.com</a> |
468
+ <a href="https://wordpress.org/plugins/shortpixel-image-optimiser/installation/">Installation </a> |
469
+ <a href="https://wordpress.org/support/plugin/shortpixel-image-optimiser">Support </a>
470
+ </p>';
471
+ echo '<p>New images uploaded to the Media Library will be optimized automatically.<br/>If you have existing images you would like to optimize, you can use the <a href="' . get_admin_url() . 'upload.php?page=wp-short-pixel-bulk">Bulk Optimisation Tool</a>.</p>';
472
+
473
+ $noticeHTML = "<br/><div style=\"background-color: #fff; border-left: 4px solid %s; box-shadow: 0 1px 1px 0 rgba(0, 0, 0, 0.1); padding: 1px 12px;\"><p>%s</p></div>";
474
+
475
+ if(isset($_POST['submit']) || isset($_POST['validate'])) {
476
+ //handle API Key - common for submit and validate
477
+ $_POST['key'] = trim($_POST['key']);
478
+ $validityData = $this->getQuotaInformation($_POST['key'], true);
479
+
480
+ $this->_apiKey = $_POST['key'];
481
+ $this->_apiInterface->setApiKey($this->_apiKey);
482
+ update_option('wp-short-pixel-apiKey', $_POST['key']);
483
+ if($validityData['APIKeyValid']) {
484
+ if(isset($_POST['validate'])) {
485
+ //display notification
486
+ printf($noticeHTML, '#7ad03a', 'API Key valid!');
487
+ }
488
+ update_option('wp-short-pixel-verifiedKey', true);
489
+ $this->_verifiedKey = true;
490
+ } else {
491
+ if(isset($_POST['validate'])) {
492
+ //display notification
493
+ printf($noticeHTML, '#dd3d36', $validityData["Message"]);
494
+ }
495
+ update_option('wp-short-pixel-verifiedKey', false);
496
+ $this->_verifiedKey = false;
497
+ }
498
+
499
+ //if save button - we process the rest of the form elements
500
+ if(isset($_POST['submit'])) {
501
+ update_option('wp-short-pixel-compression', $_POST['compressionType']);
502
+ $this->_compressionType = $_POST['compressionType'];
503
+ $this->_apiInterface->setCompressionType($this->_compressionType);
504
+ if(isset($_POST['thumbnails'])) { $this->_processThumbnails = 1; } else { $this->_processThumbnails = 0; }
505
+ if(isset($_POST['backupImages'])) { $this->_backupImages = 1; } else { $this->_backupImages = 0; }
506
+ update_option('wp-short-process_thumbnails', $this->_processThumbnails);
507
+ update_option('wp-short-backup_images', $this->_backupImages);
508
+ }
509
+ }
510
+
511
+ if(isset($_POST['emptyBackup'])) {
512
+ if(file_exists(SP_BACKUP_FOLDER)) {
513
+ $files = scandir(SP_BACKUP_FOLDER);
514
+ $cleanPath = rtrim(SP_BACKUP_FOLDER, '/'). '/';
515
+ foreach($files as $t) {
516
+ if ( $t != "." && $t != "..") {
517
+ unlink(SP_BACKUP_FOLDER . DIRECTORY_SEPARATOR . $t);
518
+ }
519
+ }
520
+ }
521
+ }
522
+
523
+ $checked = '';
524
+ if($this->_processThumbnails) { $checked = 'checked'; }
525
+
526
+ $checkedBackupImages = '';
527
+ if($this->_backupImages) { $checkedBackupImages = 'checked'; }
528
+
529
+ $formHTML = <<< HTML
530
+ <form name='wp_shortpixel_options' action='' method='post' id='wp_shortpixel_options'>
531
+ <table class="form-table">
532
+ <tbody><tr>
533
+ <th scope="row"><label for="key">API Key:</label></th>
534
+ <td><input name="key" type="text" id="key" value="{$this->_apiKey}" class="regular-text">
535
+ <input type="submit" name="validate" id="validate" class="button button-primary" title="Validate the provided API key" value="Validate">
536
+ </td>
537
+ </tr>
538
+ HTML;
539
+
540
+ if(!$this->_verifiedKey) {
541
+ //if invalid key we display the link to the API Key
542
+ $formHTML .= '<tr><td style="padding-left: 0px;" colspan="2">Don’t have an API Key? <a href="https://shortpixel.com/wp-apikey" target="_blank">Sign up, it’s free.</a></td></tr>';
543
+ $formHTML .= '</form>';
544
+ } else {
545
+ //if valid key we display the rest of the options
546
+ $formHTML .= <<< HTML
547
+ <tr><th scope="row">
548
+ <label for="compressionType">Compression type: <span title="
549
+ Lossy compression: lossy has a better compression rate than lossless compression. The resulting image is not 100% identical with the original. Works well for photos taken with your camera.
550
+ Lossless compression: the shrunk image will be identical with the original and smaller in size. Use this when you do not want to loose any of the original image's details. Works best for technical drawings, clip art and comics.
551
+ ">?</span></label>
552
+ </th><td>
553
+ HTML;
554
+
555
+ if($this->_compressionType == 1) {
556
+ $formHTML .= '<input type="radio" name="compressionType" value="1" checked>Lossy</br></br>';
557
+ $formHTML .= '<input type="radio" name="compressionType" value="0" >Lossless';
558
+ } else {
559
+ $formHTML .= '<input type="radio" name="compressionType" value="1">Lossy</br></br>';
560
+ $formHTML .= '<input type="radio" name="compressionType" value="0" checked>Lossless';
561
+ }
562
+
563
+ $formHTML .= <<<HTML
564
+ </td>
565
+ </tr>
566
+ <tr>
567
+ <th scope="row"><label for="thumbnails">Compress also image thumbnails:</label></th>
568
+ <td><input name="thumbnails" type="checkbox" id="thumbnails" {$checked}></td>
569
+ </tr>
570
+ <tr>
571
+ <th scope="row"><label for="backupImages">Back up all images
572
+ <span title="If selected all images will be backed up in the ShortpixelBackups folder located in your wp-content folder">?</span>
573
+ </label></th>
574
+ <td>
575
+ <input name="backupImages" type="checkbox" id="backupImages" {$checkedBackupImages}>
576
+ </td>
577
+ </tr>
578
+ </tbody></table>
579
+ <p class="submit">
580
+ <input type="submit" name="submit" id="submit" class="button button-primary" title="Save Changes" value="Save Changes">
581
+ <a class="button button-primary" title="Process all the images in your Media Library" href="upload.php?page=wp-short-pixel-bulk">Bulk Process</a>
582
+ </p>
583
+ </form>
584
+ <script>
585
+ var rad = document.wp_shortpixel_options.compressionType;
586
+ var prev = null;
587
+ for(var i = 0; i < rad.length; i++) {
588
+ rad[i].onclick = function() {
589
+
590
+ if(this !== prev) {
591
+ prev = this;
592
+ }
593
+ alert('Select Media/Bulk ShortPixel to reprocess all the images');
594
+ };
595
+ }
596
+ </script>
597
+ HTML;
598
+ }
599
+
600
+ echo $formHTML;
601
+
602
+ if($this->_verifiedKey) {
603
+ $fileCount = get_option('wp-short-pixel-fileCount');
604
+ $savedSpace = self::formatBytes(get_option('wp-short-pixel-savedSpace'),2);
605
+ $averageCompression = round(get_option('wp-short-pixel-averageCompression'),2);
606
+ $savedBandwidth = self::formatBytes(get_option('wp-short-pixel-savedSpace') * 1000,2);
607
+ $quotaData = $this->getQuotaInformation();
608
+ $backupFolderSize = self::formatBytes(self::folderSize(SP_BACKUP_FOLDER));
609
+
610
+ $statHTML = <<< HTML
611
+ <a id="facts"></a>
612
+ <h3>ShortPixlel Facts & Figures</h3>
613
+ <table class="form-table">
614
+ <tbody><tr>
615
+ <th scope="row"><label for="totalFiles">Your total number of processed files:</label></th>
616
+ <td>$fileCount</td>
617
+ </tr>
618
+ <tr>
619
+ <th scope="row"><label for="savedSpace">Saved space by ShortPixel</label></th>
620
+ <td>$savedSpace</td>
621
+ </tr>
622
+ <tr>
623
+ <th scope="row"><label for="savedBandwidth">Bandwith* saved with ShortPixel:</label></th>
624
+ <td>$savedBandwidth</td>
625
+ </tr>
626
+ <tr>
627
+ <th scope="row"><label for="apiQuota">Your ShortPixel plan</label></th>
628
+ <td>{$quotaData['APICallsQuota']}</td>
629
+ </tr>
630
+ <tr>
631
+ <th scope="row"><label for="usedQUota">Used Quota:</label></th>
632
+ <td>{$quotaData['APICallsMade']}</td>
633
+ </tr>
634
+ <tr>
635
+ <th scope="row"><label for="averagCompression">Average file size compression:</label></th>
636
+ <td>$averageCompression%</td>
637
+ </tr>
638
+ HTML;
639
+ if($this->_backupImages) {
640
+ $statHTML .= <<< HTML
641
+ <form action="" method="POST">
642
+ <tr>
643
+ <th scope="row"><label for="sizeBackup">Backup folder size:</label></th>
644
+ <td>
645
+ {$backupFolderSize}
646
+ <input type="submit" style="margin-left: 15px; vertical-align: middle;" class="button button-secondary" name="emptyBackup" value="Empty backups"/>
647
+ </td>
648
+ </tr>
649
+ </form>
650
+ HTML;
651
+ }
652
+
653
+ $statHTML .= <<< HTML
654
+ </tbody></table>
655
+ <p>* Saved bandwidth is calculated at 100,000 impressions/image</p>
656
+ HTML;
657
+ echo $statHTML;
658
+ }
659
+ }
660
+
661
+ public function getBulkProcessingForm($imageCount) {
662
+ return <<< HTML
663
+ </br>
664
+ Currently, you have {$imageCount} images in your library. </br>
665
+ </br>
666
+ <form action='' method="POST" >
667
+ <input type="submit" name="bulkProcess" id="bulkProcess" class="button button-primary" value="Compress all your images">
668
+ </form>
669
+ HTML;
670
+ }
671
+
672
+
673
+ public function getQuotaInformation($apiKey = null, $appendUserAgent = false) {
674
+
675
+ if(is_null($apiKey)) { $apiKey = $this->_apiKey; }
676
+
677
+ $requestURL = 'https://api.shortpixel.com/v1/api-status.php?key='.$apiKey;
678
+
679
+ if($appendUserAgent) {
680
+ $requestURL .= '&useragent=' . urlencode($_SERVER['HTTP_USER_AGENT']);
681
+ }
682
+
683
+ $args = array('timeout'=> SP_MAX_TIMEOUT, 'sslverify' => false);
684
+ $response = wp_remote_get($requestURL, $args);
685
+
686
+ if(is_wp_error( $response )) {
687
+ $response = wp_remote_get(str_replace('https://', 'http://', $requestURL), $args);
688
+ }
689
+
690
+ $defaultData = array(
691
+ "APIKeyValid" => false,
692
+ "Message" => 'API Key could not be validated. Could not connect Shortpixel service.',
693
+ "APICallsMade" => 'Information unavailable. Please check your API key.',
694
+ "APICallsQuota" => 'Information unavailable. Please check your API key.');
695
+
696
+ if(is_object($response) && get_class($response) == 'WP_Error') {
697
+ return $defaultData;
698
+ }
699
+
700
+ if($response['response']['code'] != 200) {
701
+ return $defaultData;
702
+ }
703
+
704
+ $data = $response['body'];
705
+ $data = $this->parseJSON($data);
706
+
707
+ if(empty($data)) { return $defaultData; }
708
+
709
+ if($data->Status->Code != 2) {
710
+ $defaultData['Message'] = $data->Status->Message;
711
+ return $defaultData;
712
+ }
713
+
714
+ return array(
715
+ "APIKeyValid" => true,
716
+ "APICallsMade" => number_format($data->APICallsMade) . ' images',
717
+ "APICallsQuota" => number_format($data->APICallsQuota) . ' images'
718
+ );
719
+
720
+
721
+ }
722
+
723
+ public function generateCustomColumn( $column_name, $id ) {
724
+ if( 'wp-shortPixel' == $column_name ) {
725
+ $data = wp_get_attachment_metadata($id);
726
+
727
+ if ( isset( $data['ShortPixelImprovement'] ) ) {
728
+ if(isset($meta['ShortPixel']['BulkProcessing'])) {
729
+ print 'Waiting for bulk processing';
730
+ return;
731
+ }
732
+
733
+ print $data['ShortPixelImprovement'];
734
+ if(is_numeric($data['ShortPixelImprovement'])) {
735
+ print '%';
736
+ print " | <a href=\"admin.php?action=shortpixel_manual_optimize&amp;attachment_ID={$id}\">Optimize now</a>";
737
+ print " | <a href=\"admin.php?action=shortpixel_restore_backup&amp;attachment_ID={$id}\">Restore backup</a>";
738
+ return;
739
+ }
740
+ } elseif(isset($data['ShortPixel']['WaitingProcessing'])) {
741
+ print 'Image waiting to be processed';
742
+ return;
743
+ } else {
744
+ if ( wp_attachment_is_image( $id ) ) {
745
+ print 'Image not processed';
746
+ print " | <a href=\"admin.php?action=shortpixel_manual_optimize&amp;attachment_ID={$id}\">Optimize now</a>";
747
+ return;
748
+ }
749
+ }
750
+ }
751
+ }
752
+
753
+ public function columns( $defaults ) {
754
+ $defaults['wp-shortPixel'] = 'ShortPixel Compression';
755
+ return $defaults;
756
+ }
757
+
758
+ public function generatePluginLinks($links) {
759
+ $in = '<a href="options-general.php?page=wp-shortpixel">Settings</a>';
760
+ array_unshift($links, $in);
761
+ return $links;
762
+ }
763
+
764
+ public function parseJSON($data) {
765
+ if ( function_exists('json_decode') ) {
766
+ $data = json_decode( $data );
767
+ } else {
768
+ require_once( 'JSON/JSON.php' );
769
+ $json = new Services_JSON( );
770
+ $data = $json->decode( $data );
771
+ }
772
+ return $data;
773
+ }
774
+
775
+
776
+ static public function formatBytes($bytes, $precision = 2) {
777
+ $units = array('B', 'KB', 'MB', 'GB', 'TB');
778
+
779
+ $bytes = max($bytes, 0);
780
+ $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
781
+ $pow = min($pow, count($units) - 1);
782
+
783
+ $bytes /= pow(1024, $pow);
784
+
785
+ return round($bytes, $precision) . ' ' . $units[$pow];
786
+ }
787
+
788
+ static public function folderSize($path) {
789
+ $total_size = 0;
790
+ if(file_exists($path)) {
791
+ $files = scandir($path);
792
+ } else {
793
+ return $total_size;
794
+ }
795
+ $cleanPath = rtrim($path, '/'). '/';
796
+ foreach($files as $t) {
797
+ if ($t<>"." && $t<>"..") {
798
+ $currentFile = $cleanPath . $t;
799
+ if (is_dir($currentFile)) {
800
+ $size = foldersize($currentFile);
801
+ $total_size += $size;
802
+ }
803
+ else {
804
+ $size = filesize($currentFile);
805
+ $total_size += $size;
806
+ }
807
+ }
808
+ }
809
+ return $total_size;
810
+ }
811
+
812
+
813
+ }
814
+
815
+ $pluginInstance = new WPShortPixel();
816
+ global $pluginInstance;
817
+
818
+ ?>
wp-shortpixel.php CHANGED
@@ -3,7 +3,7 @@
3
  * Plugin Name: ShortPixel Image Optimiser
4
  * Plugin URI: https://shortpixel.com/
5
  * Description: ShortPixel is an image compression tool that helps improve your website performance. The plugin optimises images automatically using both lossy and lossless compression. Resulting, smaller, images are no different in quality from the original. To install: 1) Click the "Activate" link to the left of this description. 2) <a href="https://shortpixel.com/wp-apikey" target="_blank">Free Sign up</a> for your unique API Key . 3) Check your email for your API key. 4) Use your API key to activate ShortPixel plugin in the 'Plugins' menu in WordPress. 5) Done!
6
- * Version: 1.6.3
7
  * Author: ShortPixel
8
  * Author URI: https://shortpixel.com
9
  */
@@ -674,7 +674,7 @@ HTML;
674
 
675
  if(is_null($apiKey)) { $apiKey = $this->_apiKey; }
676
 
677
- $requestURL = 'https://api.shortpixel.com/api-status.php?key='.$apiKey;
678
 
679
  if($appendUserAgent) {
680
  $requestURL .= '&useragent=' . urlencode($_SERVER['HTTP_USER_AGENT']);
3
  * Plugin Name: ShortPixel Image Optimiser
4
  * Plugin URI: https://shortpixel.com/
5
  * Description: ShortPixel is an image compression tool that helps improve your website performance. The plugin optimises images automatically using both lossy and lossless compression. Resulting, smaller, images are no different in quality from the original. To install: 1) Click the "Activate" link to the left of this description. 2) <a href="https://shortpixel.com/wp-apikey" target="_blank">Free Sign up</a> for your unique API Key . 3) Check your email for your API key. 4) Use your API key to activate ShortPixel plugin in the 'Plugins' menu in WordPress. 5) Done!
6
+ * Version: 1.6.4
7
  * Author: ShortPixel
8
  * Author URI: https://shortpixel.com
9
  */
674
 
675
  if(is_null($apiKey)) { $apiKey = $this->_apiKey; }
676
 
677
+ $requestURL = 'https://api.shortpixel.com/v1/api-status.php?key='.$apiKey;
678
 
679
  if($appendUserAgent) {
680
  $requestURL .= '&useragent=' . urlencode($_SERVER['HTTP_USER_AGENT']);