Version Description
Download this release
Release Info
Developer | ShortPixel |
Plugin | ShortPixel Image Optimizer |
Version | 1.0.2 |
Comparing to | |
See all releases |
Code changes from version 1.0.1 to 1.0.2
- JSON/JSON.php +806 -806
- JSON/LICENSE +21 -21
- readme.txt +12 -4
- trunk/JSON/JSON.php +806 -0
- trunk/JSON/LICENSE +21 -0
- trunk/ShortPixel_options_screenshot.png +0 -0
- trunk/ShortPixel_plugin_screenshot.png +0 -0
- trunk/readme.txt +80 -0
- trunk/shortpixel_api.php +162 -0
- trunk/wp-shortpixel.php +455 -0
- wp-shortpixel.php +137 -40
JSON/JSON.php
CHANGED
@@ -1,806 +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 |
-
?>
|
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 |
+
?>
|
JSON/LICENSE
CHANGED
@@ -1,21 +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.
|
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.
|
readme.txt
CHANGED
@@ -4,7 +4,7 @@ Contributors: AlexSP
|
|
4 |
Tags: image optimisation, compression, lossy, lossless, performance, upload speed, fast, image quality
|
5 |
Requires at least: 3.0.0 or higher
|
6 |
Tested up to: 4.0
|
7 |
-
Stable tag: 1.
|
8 |
License: GPLv2 or later
|
9 |
License URI: http://www.gnu.org/licenses/gpl-2.0.html
|
10 |
|
@@ -30,7 +30,7 @@ Features included:
|
|
30 |
- Better search ranking
|
31 |
- Super fast websites
|
32 |
|
33 |
-
On the ShortPixel.com website, we are offering an API you can also use for image optimisation purposses.
|
34 |
|
35 |
|
36 |
== Installation ==
|
@@ -63,10 +63,18 @@ Yes, privacy is guaranteed. The ShortPixel automated encription process doesn't
|
|
63 |
|
64 |
== Screenshots ==
|
65 |
|
66 |
-
1.
|
67 |
-
2. ShortPixel_plugin_screenshot
|
68 |
|
69 |
== Changelog ==
|
70 |
|
71 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
72 |
|
4 |
Tags: image optimisation, compression, lossy, lossless, performance, upload speed, fast, image quality
|
5 |
Requires at least: 3.0.0 or higher
|
6 |
Tested up to: 4.0
|
7 |
+
Stable tag: 1.1
|
8 |
License: GPLv2 or later
|
9 |
License URI: http://www.gnu.org/licenses/gpl-2.0.html
|
10 |
|
30 |
- Better search ranking
|
31 |
- Super fast websites
|
32 |
|
33 |
+
On the https://ShortPixel.com website, we are offering an API you can also use for image optimisation purposses.
|
34 |
|
35 |
|
36 |
== Installation ==
|
63 |
|
64 |
== Screenshots ==
|
65 |
|
66 |
+
1. Using the personal API key in the plugin Settings.
|
|
|
67 |
|
68 |
== Changelog ==
|
69 |
|
70 |
|
71 |
+
= 1.1 =
|
72 |
+
|
73 |
+
* Updated Bulk editing to run in background
|
74 |
+
* Updated default options
|
75 |
+
* Added notifications on activation
|
76 |
+
|
77 |
+
= 1.0 =
|
78 |
+
|
79 |
+
* First working version
|
80 |
|
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/ShortPixel_options_screenshot.png
ADDED
Binary file
|
trunk/ShortPixel_plugin_screenshot.png
ADDED
Binary file
|
trunk/readme.txt
ADDED
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
=== ShortPixel Image Optimiser ===
|
2 |
+
|
3 |
+
Contributors: AlexSP
|
4 |
+
Tags: image optimisation, compression, lossy, lossless, performance, upload speed, fast, image quality
|
5 |
+
Requires at least: 3.0.0 or higher
|
6 |
+
Tested up to: 4.0
|
7 |
+
Stable tag: 1.1
|
8 |
+
License: GPLv2 or later
|
9 |
+
License URI: http://www.gnu.org/licenses/gpl-2.0.html
|
10 |
+
|
11 |
+
The ShortPixel WordPress plugin optimizes images automaticaly using both lossy and lossless compression, thus improving your website performance.
|
12 |
+
|
13 |
+
== Description ==
|
14 |
+
|
15 |
+
The ShortPixel WordPress plugin optimizes images automaticaly using both lossy and lossless compression, thus improving your website performance.
|
16 |
+
Resulting, smaller, images are no different in quality from the original.
|
17 |
+
|
18 |
+
|
19 |
+
ShortPixel uses advanced compression technology that reduces image size without any before/after differences.
|
20 |
+
|
21 |
+
Features included:
|
22 |
+
- Both lossy and lossless optimisation
|
23 |
+
- Supported formats: JPG, PNG, GIF
|
24 |
+
- Batch image optimisation
|
25 |
+
- Powerful algorithms
|
26 |
+
- Quick backups
|
27 |
+
|
28 |
+
- Less bandwidth usage
|
29 |
+
- Up to 90% compression rate
|
30 |
+
- Better search ranking
|
31 |
+
- Super fast websites
|
32 |
+
|
33 |
+
On the https://ShortPixel.com website, we are offering an API you can also use for image optimisation purposses.
|
34 |
+
|
35 |
+
|
36 |
+
== Installation ==
|
37 |
+
|
38 |
+
Let's get ShortPixel plugin running on your WordPress website:
|
39 |
+
|
40 |
+
|
41 |
+
1. Sign up using your email at http://shortpixel.com/free-sign-up
|
42 |
+
2. You will receive your personal API key in a confirmation email, to the address you provided.
|
43 |
+
3. Upload the ShortPixel plugin to the /wp-content/plugins/ directory
|
44 |
+
4. Use your unique API key to activate ShortPixel plugin in the 'Plugins' menu in WordPress.
|
45 |
+
5. Uploaded images can be automatically optimised in the Media Library.
|
46 |
+
6. Done!
|
47 |
+
|
48 |
+
|
49 |
+
== Frequently Asked Questions ==
|
50 |
+
|
51 |
+
= Should I pick lossy or losssless optimisation =
|
52 |
+
|
53 |
+
This depends on your compression needs. Lossy has a better compression rate than lossless compression.
|
54 |
+
The resulting image is not 100% identical with the original. Works well for photos taken with your camera.
|
55 |
+
|
56 |
+
With lossless compression, the shrunk image will be identical with the original and smaller in size.
|
57 |
+
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.
|
58 |
+
|
59 |
+
|
60 |
+
= Is my privacy ensured, are all my images safe? =
|
61 |
+
|
62 |
+
Yes, privacy is guaranteed. The ShortPixel automated encription process doesn't allow anyone to view your photos.
|
63 |
+
|
64 |
+
== Screenshots ==
|
65 |
+
|
66 |
+
1. Using the personal API key in the plugin Settings.
|
67 |
+
|
68 |
+
== Changelog ==
|
69 |
+
|
70 |
+
|
71 |
+
= 1.1 =
|
72 |
+
|
73 |
+
* Updated Bulk editing to run in background
|
74 |
+
* Updated default options
|
75 |
+
* Added notifications on activation
|
76 |
+
|
77 |
+
= 1.0 =
|
78 |
+
|
79 |
+
* First working version
|
80 |
+
|
trunk/shortpixel_api.php
ADDED
@@ -0,0 +1,162 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
|
12 |
+
public function setCompressionType($compressionType)
|
13 |
+
{
|
14 |
+
if($compressionType == 'lossy') { $this->_compressionType = 1; }
|
15 |
+
else { $this->_compressionType = 0; }
|
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, $time = 0) {
|
45 |
+
$requestURL = 'https://api.shortpixel.com/reducer.php?key='.$this->_apiKey.'&lossy='.$this->_compressionType.'&url=';
|
46 |
+
|
47 |
+
$requestURL = $requestURL . urlencode($url);
|
48 |
+
|
49 |
+
$args = array('timeout'=> SP_MAX_TIMEOUT);
|
50 |
+
|
51 |
+
$response = wp_remote_get($requestURL, $args);
|
52 |
+
|
53 |
+
if(is_object($response) && get_class($response) == 'WP_Error') {
|
54 |
+
return false;
|
55 |
+
}
|
56 |
+
|
57 |
+
return $response;
|
58 |
+
}
|
59 |
+
|
60 |
+
public function parseResponse($response) {
|
61 |
+
$data = $response['body'];
|
62 |
+
$data = str_replace('Warning: Division by zero in /usr/local/important/web/api.shortpixel.com/lib/functions.php on line 33', '', $data);
|
63 |
+
$data = $this->parseJSON($data);
|
64 |
+
return $data;
|
65 |
+
}
|
66 |
+
|
67 |
+
//handles the processing of the image using the ShortPixel API
|
68 |
+
public function processImage($url, $filePath, $ID = null, $time = 0) {
|
69 |
+
|
70 |
+
$response = $this->doRequests($url, $filePath, $ID, $time);
|
71 |
+
|
72 |
+
if(!$response) return $response;
|
73 |
+
|
74 |
+
if($response['response']['code'] != 200) {
|
75 |
+
printf('Web service did not respond. Please try again later.');
|
76 |
+
return false;
|
77 |
+
//error
|
78 |
+
}
|
79 |
+
|
80 |
+
$data = $this->parseResponse($response);
|
81 |
+
|
82 |
+
switch($data->Status->Code) {
|
83 |
+
case 1:
|
84 |
+
//handle image has been scheduled
|
85 |
+
sleep(1);
|
86 |
+
return $this->processImage($url, $filePath, $ID, $time);
|
87 |
+
break;
|
88 |
+
case 2:
|
89 |
+
//handle image has been processed
|
90 |
+
$this->handleSuccess($data, $url, $filePath, $ID);
|
91 |
+
break;
|
92 |
+
case -16:
|
93 |
+
return 'Quota exceeded</br>';
|
94 |
+
case -17:
|
95 |
+
return 'Wrong API Key</br>';
|
96 |
+
default:
|
97 |
+
//handle error
|
98 |
+
return 'An error occurred while processing this image. Please try uploading it again.</br>';
|
99 |
+
}
|
100 |
+
|
101 |
+
return $data;
|
102 |
+
}
|
103 |
+
|
104 |
+
|
105 |
+
public function handleSuccess($callData, $url, $filePath, $ID) {
|
106 |
+
$tempFile = download_url(str_replace('https://','http://',urldecode($callData->DownloadURL)));
|
107 |
+
|
108 |
+
if ( is_wp_error( $tempFile ) ) {
|
109 |
+
@unlink($tempFile);
|
110 |
+
return printf("Error downloading file (%s)", $tempFile->get_error_message());
|
111 |
+
}
|
112 |
+
|
113 |
+
if (!file_exists($tempFile)) {
|
114 |
+
return printf("Unable to locate downloaded file (%s)", $tempFile);
|
115 |
+
}
|
116 |
+
|
117 |
+
@unlink( $filePath );
|
118 |
+
$success = @rename( $tempFile, $filePath );
|
119 |
+
|
120 |
+
if (!$success) {
|
121 |
+
$copySuccess = copy($tempFile, $filePath);
|
122 |
+
unlink($tempFile);
|
123 |
+
}
|
124 |
+
|
125 |
+
if($success || $copySuccess) {
|
126 |
+
//update statistics
|
127 |
+
if(isset($callData->LossySize)) {
|
128 |
+
$savedSpace = $callData->OriginalSize - $callData->LossySize;
|
129 |
+
} else {
|
130 |
+
$savedSpace = $callData->OriginalSize - $callData->SPSize;
|
131 |
+
}
|
132 |
+
|
133 |
+
update_option(
|
134 |
+
'wp-short-pixel-savedSpace',
|
135 |
+
get_option('wp-short-pixel-savedSpace') + $savedSpace
|
136 |
+
);
|
137 |
+
$averageCompression = get_option('wp-short-pixel-averageCompression') * get_option('wp-short-pixel-fileCount');
|
138 |
+
$averageCompression += $callData->PercentImprovement;
|
139 |
+
$averageCompression = $averageCompression / (get_option('wp-short-pixel-fileCount') + 1);
|
140 |
+
update_option('wp-short-pixel-averageCompression', $averageCompression);
|
141 |
+
update_option('wp-short-pixel-fileCount', get_option('wp-short-pixel-fileCount')+1);
|
142 |
+
|
143 |
+
//update metadata
|
144 |
+
if(isset($ID)) {
|
145 |
+
$meta = wp_get_attachment_metadata($ID);
|
146 |
+
$meta['ShortPixelImprovement'] = $callData->PercentImprovement;
|
147 |
+
wp_update_attachment_metadata($ID, $meta);
|
148 |
+
}
|
149 |
+
}
|
150 |
+
}
|
151 |
+
|
152 |
+
public function parseJSON($data) {
|
153 |
+
if ( function_exists('json_decode') ) {
|
154 |
+
$data = json_decode( $data );
|
155 |
+
} else {
|
156 |
+
require_once( 'JSON/JSON.php' );
|
157 |
+
$json = new Services_JSON( );
|
158 |
+
$data = $json->decode( $data );
|
159 |
+
}
|
160 |
+
return $data;
|
161 |
+
}
|
162 |
+
}
|
trunk/wp-shortpixel.php
ADDED
@@ -0,0 +1,455 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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.
|
6 |
+
* Version: 1.1
|
7 |
+
*/
|
8 |
+
|
9 |
+
require_once('shortpixel_api.php');
|
10 |
+
require_once( ABSPATH . 'wp-admin/includes/image.php' );
|
11 |
+
|
12 |
+
class WPShortPixel {
|
13 |
+
|
14 |
+
private $_apiInterface = null;
|
15 |
+
private $_apiKey = '';
|
16 |
+
private $_compressionType = '';
|
17 |
+
private $_processThumbnails = 1;
|
18 |
+
|
19 |
+
public function __construct() {
|
20 |
+
define('SP_DEBUG', false);
|
21 |
+
define('SP_LOG', false);
|
22 |
+
define('SP_MAX_TIMEOUT', 10);
|
23 |
+
|
24 |
+
$this->populateOptions();
|
25 |
+
|
26 |
+
$this->_apiInterface = new shortpixel_api($this->_apiKey, $this->_compressionType);
|
27 |
+
|
28 |
+
//add hook for image upload processing
|
29 |
+
add_filter( 'wp_generate_attachment_metadata', array( &$this, 'handleImageUpload' ), 10, 2 );
|
30 |
+
add_filter( 'manage_media_columns', array( &$this, 'columns' ) );
|
31 |
+
add_filter( 'plugin_action_links_' . plugin_basename(__FILE__), array(&$this, 'generatePluginLinks'));
|
32 |
+
|
33 |
+
add_action( 'manage_media_custom_column', array( &$this, 'generateCustomColumn' ), 10, 2 );
|
34 |
+
add_action( 'handleBulkProcessing', array( &$this, 'handleBulkProcessing' ) );
|
35 |
+
|
36 |
+
|
37 |
+
//add settings page
|
38 |
+
add_action( 'admin_menu', array( &$this, 'registerSettingsPage' ) );
|
39 |
+
add_action( 'admin_menu', array( &$this, 'registerAdminPage' ) );
|
40 |
+
add_action( 'admin_notices', array( &$this, 'displayNotice' ) );
|
41 |
+
|
42 |
+
}
|
43 |
+
|
44 |
+
public function populateOptions() {
|
45 |
+
|
46 |
+
if(get_option('wp-short-pixel-apiKey') != false) {
|
47 |
+
$this->_apiKey = get_option('wp-short-pixel-apiKey');
|
48 |
+
}
|
49 |
+
|
50 |
+
if(get_option('wp-short-pixel-compression') != false) {
|
51 |
+
$this->_compressionType = get_option('wp-short-pixel-compression');
|
52 |
+
}
|
53 |
+
|
54 |
+
if(get_option('wp-short-process_thumbnails') != false) {
|
55 |
+
$this->_processThumbnails = get_option('wp-short-process_thumbnails');
|
56 |
+
} else {
|
57 |
+
add_option('wp-short-process_thumbnails', $this->_processThumbnails, '', 'yes' );
|
58 |
+
}
|
59 |
+
|
60 |
+
if(get_option('wp-short-pixel-fileCount') === false) {
|
61 |
+
add_option( 'wp-short-pixel-fileCount', 0, '', 'yes' );
|
62 |
+
}
|
63 |
+
|
64 |
+
if(get_option('wp-short-pixel-savedSpace') === false) {
|
65 |
+
add_option( 'wp-short-pixel-savedSpace', 0, '', 'yes' );
|
66 |
+
}
|
67 |
+
|
68 |
+
if(get_option('wp-short-pixel-averageCompression') === false) {
|
69 |
+
add_option( 'wp-short-pixel-averageCompression', 0, '', 'yes' );
|
70 |
+
}
|
71 |
+
}
|
72 |
+
|
73 |
+
//handling older
|
74 |
+
public function WPShortPixel() {
|
75 |
+
$this->__construct();
|
76 |
+
}
|
77 |
+
|
78 |
+
public function handleImageUpload($meta, $ID = null) {
|
79 |
+
$imageURL = wp_get_attachment_url($ID);
|
80 |
+
$imagePath = get_attached_file($ID);
|
81 |
+
|
82 |
+
$result = $this->_apiInterface->processImage($imageURL, $imagePath, $ID);
|
83 |
+
|
84 |
+
if(is_string($result)) {
|
85 |
+
$meta['ShortPixelImprovement'] = $result;
|
86 |
+
return $meta;
|
87 |
+
} else {
|
88 |
+
$processThumbnails = get_option('wp-short-process_thumbnails');
|
89 |
+
|
90 |
+
//handle the rest of the thumbnails generated by WP
|
91 |
+
if($processThumbnails && $result && !empty($meta['sizes'])) {
|
92 |
+
foreach($meta['sizes'] as $thumbnailInfo) {
|
93 |
+
$thumbURL = str_replace(basename($imagePath), $thumbnailInfo['file'], $imageURL);
|
94 |
+
$thumbPath = str_replace(basename($imagePath), $thumbnailInfo['file'], $imagePath);
|
95 |
+
$this->_apiInterface->processImage($thumbURL, $thumbPath);
|
96 |
+
}
|
97 |
+
}
|
98 |
+
}
|
99 |
+
|
100 |
+
$meta['ShortPixelImprovement'] = $result->PercentImprovement;
|
101 |
+
|
102 |
+
return $meta;
|
103 |
+
}
|
104 |
+
|
105 |
+
public function registerSettingsPage() {
|
106 |
+
add_options_page( 'ShortPixel Settings', 'ShortPixel', 'manage_options', 'wp-shortpixel', array($this, 'renderSettingsMenu'));
|
107 |
+
}
|
108 |
+
|
109 |
+
function registerAdminPage( ) {
|
110 |
+
add_media_page( 'ShortPixel Bulk Process', 'Bulk ShortPixel', 'edit_others_posts', 'wp-short-pixel-bulk', array( &$this, 'bulkProcesss' ) );
|
111 |
+
}
|
112 |
+
|
113 |
+
public function bulkProcesss() {
|
114 |
+
echo '<h1>ShortPixel Bulk Processing</h1>';
|
115 |
+
|
116 |
+
if ( function_exists( 'apache_setenv' ) ) {
|
117 |
+
@apache_setenv('no-gzip', 1);
|
118 |
+
}
|
119 |
+
@ini_set('output_buffering','on');
|
120 |
+
@ini_set('zlib.output_compression', 0);
|
121 |
+
@ini_set('implicit_flush', 1);
|
122 |
+
|
123 |
+
$attachments = null;
|
124 |
+
$attachments = get_posts( array(
|
125 |
+
'numberposts' => -1,
|
126 |
+
'post_type' => 'attachment',
|
127 |
+
'post_mime_type' => 'image'
|
128 |
+
));
|
129 |
+
|
130 |
+
$bulkProcessingLog = get_option('bulkProcessingLog');
|
131 |
+
$bulkProcessingRunning = false;
|
132 |
+
|
133 |
+
if(
|
134 |
+
is_null($bulkProcessingLog['endDate']) &&
|
135 |
+
( $bulkProcessingLog['lastUpdate'] < $bulkProcessingLog['lastUpdate'] + 60 ) &&
|
136 |
+
( $bulkProcessingLog['startTime'] < $bulkProcessingLog['startTime'] + (60 * 15))
|
137 |
+
) {
|
138 |
+
$bulkProcessingRunning = true;
|
139 |
+
}
|
140 |
+
|
141 |
+
if(isset($_POST['bulkProcess'])) {
|
142 |
+
|
143 |
+
$scheduleResult = wp_schedule_single_event(time()+1, 'handleBulkProcessing');
|
144 |
+
if(is_null($scheduleResult)) {
|
145 |
+
$bulkProcessingLog = array(
|
146 |
+
'startTime' => time(),
|
147 |
+
'totalImageCount' => count($attachments),
|
148 |
+
'doneCount' => 0,
|
149 |
+
'log' => '',
|
150 |
+
'lastUpdate' => time(),
|
151 |
+
'endDate' => null
|
152 |
+
);
|
153 |
+
update_option('bulkProcessingLog', $bulkProcessingLog);
|
154 |
+
echo "Bulk processing started. Please visite the Bulk processing page to view the status. </br>";
|
155 |
+
}
|
156 |
+
|
157 |
+
if($scheduleResult === false) {
|
158 |
+
echo "There was a problem scheduling the bulk processing. Please try again later.";
|
159 |
+
}
|
160 |
+
|
161 |
+
} else {
|
162 |
+
|
163 |
+
if ($bulkProcessingRunning) {
|
164 |
+
echo "{$bulkProcessingLog['doneCount']}/{$bulkProcessingLog['totalImageCount']} images processed</br></br>Processing log:</br>";
|
165 |
+
echo $bulkProcessingLog['log'];
|
166 |
+
} else {
|
167 |
+
|
168 |
+
if(count($attachments)) {
|
169 |
+
if($bulkProcessingLog) { echo "Last succesful bulk processing done on {$bulkProcessingLog['totalImageCount']} images (" . date("d-m-Y H:i:s", $bulkProcessingLog['endDate']) . ").</br>"; }
|
170 |
+
echo $this->getBulkProcessingForm(count($attachments));
|
171 |
+
} else {
|
172 |
+
echo "It appear that you have no images uploaded yet.</br>";
|
173 |
+
}
|
174 |
+
}
|
175 |
+
}
|
176 |
+
|
177 |
+
}
|
178 |
+
|
179 |
+
public function handleBulkProcessing() {
|
180 |
+
//get all images
|
181 |
+
$attachments = null;
|
182 |
+
$attachments = get_posts( array(
|
183 |
+
'numberposts' => -1,
|
184 |
+
'post_type' => 'attachment',
|
185 |
+
'post_mime_type' => 'image'
|
186 |
+
));
|
187 |
+
//set up logging in db
|
188 |
+
$bulkProcessingLog = get_option('bulkProcessingLog');
|
189 |
+
//for each image
|
190 |
+
foreach( $attachments as $attachment ) {
|
191 |
+
//handle image processing
|
192 |
+
$imageURL = wp_get_attachment_url($attachment->ID);
|
193 |
+
$imagePath = get_attached_file($attachment->ID);
|
194 |
+
|
195 |
+
$processingResult = $this->_apiInterface->processImage($imageURL, $imagePath, $attachment->ID);
|
196 |
+
|
197 |
+
if(!is_object($processingResult)) {
|
198 |
+
$bulkProcessingLog['log'] .= "Error! Image " . basename($imagePath) . " could not be processed<br/>";
|
199 |
+
}
|
200 |
+
|
201 |
+
if($processingResult->Status->Code == 1) {
|
202 |
+
$bulkProcessingLog['log'] .= "Image " . basename($imagePath) . " scheduled for processing.<br/>";
|
203 |
+
} elseif($processingResult->Status->Code == 2) {
|
204 |
+
$bulkProcessingLog['log'] .= "Image " . basename($imagePath) . " processed succesfully.<br/>";
|
205 |
+
} else {
|
206 |
+
$bulkProcessingLog['log'] .= "Error! Image " . basename($imagePath) . " could not be processed<br/>";
|
207 |
+
}
|
208 |
+
|
209 |
+
$bulkProcessingLog['doneCount'] = $bulkProcessingLog['doneCount'] + 1;
|
210 |
+
$bulkProcessingLog['lastUpdate'] = time();
|
211 |
+
update_option('bulkProcessingLog', $bulkProcessingLog);
|
212 |
+
|
213 |
+
}
|
214 |
+
|
215 |
+
$bulkProcessingLog['endDate'] = time();
|
216 |
+
|
217 |
+
update_option('bulkProcessingLog', $bulkProcessingLog);
|
218 |
+
|
219 |
+
}
|
220 |
+
|
221 |
+
public function renderSettingsMenu() {
|
222 |
+
if ( !current_user_can( 'manage_options' ) ) {
|
223 |
+
wp_die('You do not have sufficient permissions to access this page.');
|
224 |
+
}
|
225 |
+
|
226 |
+
if(isset($_POST['submit'])) {
|
227 |
+
//handle save options
|
228 |
+
update_option('wp-short-pixel-apiKey', $_POST['key']);
|
229 |
+
$this->_apiKey = $_POST['key'];
|
230 |
+
$this->_apiInterface->setApiKey($this->_apiKey);
|
231 |
+
update_option('wp-short-pixel-compression', $_POST['compressionType']);
|
232 |
+
$this->_compressionType = $_POST['compressionType'];
|
233 |
+
$this->_apiInterface->setCompressionType($this->_compressionType);
|
234 |
+
if(isset($_POST['thumbnails'])) { $this->_processThumbnails = 1; } else { $this->_processThumbnails = 0; }
|
235 |
+
update_option('wp-short-process_thumbnails', $this->_processThumbnails);
|
236 |
+
}
|
237 |
+
|
238 |
+
$checked = '';
|
239 |
+
if($this->_processThumbnails) { $checked = 'checked'; }
|
240 |
+
|
241 |
+
echo '<h1>ShortPixel Image Optimiser Settings</h1>';
|
242 |
+
echo '<p>ShortPixel improves website performance by reducing the images’ size.<BR>Configure ShortPixel plugin to compress both past and new past images and optimise your website.</p>';
|
243 |
+
|
244 |
+
$formHTML = <<< HTML
|
245 |
+
<form name='wp_shortpixel_options' action='' method='post' id='wp_shortpixel_options'>
|
246 |
+
<table class="form-table">
|
247 |
+
<tbody><tr>
|
248 |
+
<th scope="row"><label for="key">API Key:</label></th>
|
249 |
+
<td><input name="key" type="text" id="key" value="{$this->_apiKey}" class="regular-text"></td>
|
250 |
+
</tr>
|
251 |
+
<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>
|
252 |
+
<tr><th scope="row">
|
253 |
+
<label for="compressionType">Compression type: <span title="
|
254 |
+
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.
|
255 |
+
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.
|
256 |
+
">?</span></label>
|
257 |
+
</th><td>
|
258 |
+
HTML;
|
259 |
+
if($this->_compressionType == 'lossless') {
|
260 |
+
$formHTML .= '<input type="radio" name="compressionType" value="lossy" >Lossy</br></br>';
|
261 |
+
$formHTML .= '<input type="radio" name="compressionType" value="lossless" checked>Lossless';
|
262 |
+
} else {
|
263 |
+
$formHTML .= '<input type="radio" name="compressionType" value="lossy" checked>Lossy</br></br>';
|
264 |
+
$formHTML .= '<input type="radio" name="compressionType" value="lossless" >Lossless';
|
265 |
+
}
|
266 |
+
|
267 |
+
$formHTML .= <<<HTML
|
268 |
+
</td>
|
269 |
+
</tr>
|
270 |
+
<tr>
|
271 |
+
<th scope="row"><label for="thumbnails">Compress also image thumbnails</label></th>
|
272 |
+
<td><input name="thumbnails" type="checkbox" id="thumbnails" {$checked}></td>
|
273 |
+
</tr>
|
274 |
+
</tbody></table>
|
275 |
+
<p class="submit"><input type="submit" name="submit" id="submit" class="button button-primary" value="Save Changes"></p>
|
276 |
+
</form>
|
277 |
+
<script>
|
278 |
+
var rad = document.wp_shortpixel_options.compressionType;
|
279 |
+
var prev = null;
|
280 |
+
for(var i = 0; i < rad.length; i++) {
|
281 |
+
rad[i].onclick = function() {
|
282 |
+
|
283 |
+
if(this !== prev) {
|
284 |
+
prev = this;
|
285 |
+
}
|
286 |
+
alert('Select Media/Bulk Short Pixel to reprocess all the images');
|
287 |
+
};
|
288 |
+
}
|
289 |
+
</script>
|
290 |
+
HTML;
|
291 |
+
echo $formHTML;
|
292 |
+
|
293 |
+
$fileCount = get_option('wp-short-pixel-fileCount');
|
294 |
+
$savedSpace = self::formatBytes(get_option('wp-short-pixel-savedSpace'),2);
|
295 |
+
$averageCompression = round(get_option('wp-short-pixel-averageCompression'),2);
|
296 |
+
$savedBandwidth = self::formatBytes(get_option('wp-short-pixel-savedSpace') * 1000,2);
|
297 |
+
|
298 |
+
$quotaData = $this->getQuotaInformation();
|
299 |
+
|
300 |
+
$statHTML = <<< HTML
|
301 |
+
<h3>ShortPixlel Facts & Figures</h3>
|
302 |
+
<table class="form-table">
|
303 |
+
<tbody><tr>
|
304 |
+
<th scope="row"><label for="totalFiles">Your total number of processed files:</label></th>
|
305 |
+
<td>$fileCount</td>
|
306 |
+
</tr>
|
307 |
+
<tr>
|
308 |
+
<th scope="row"><label for="savedSpace">Saved space by ShortPixel</label></th>
|
309 |
+
<td>$savedSpace</td>
|
310 |
+
</tr>
|
311 |
+
<tr>
|
312 |
+
<th scope="row"><label for="savedBandwidth">Bandwith* saved with ShortPixel:</label></th>
|
313 |
+
<td>$savedBandwidth</td>
|
314 |
+
</tr>
|
315 |
+
<tr>
|
316 |
+
<th scope="row"><label for="apiQuota">Your ShortPixel plan</label></th>
|
317 |
+
<td>{$quotaData['APICallsQuota']}</td>
|
318 |
+
</tr>
|
319 |
+
<tr>
|
320 |
+
<th scope="row"><label for="usedQUota">Used Quota:</label></th>
|
321 |
+
<td>{$quotaData['APICallsMade']}</td>
|
322 |
+
</tr>
|
323 |
+
<tr>
|
324 |
+
<th scope="row"><label for="averagCompression">Average file size compression:</label></th>
|
325 |
+
<td>$averageCompression%</td>
|
326 |
+
</tr>
|
327 |
+
</tbody></table>
|
328 |
+
<p>* Saved bandwidth is calculated at 100,000 impressions/image</p>
|
329 |
+
HTML;
|
330 |
+
echo $statHTML;
|
331 |
+
}
|
332 |
+
|
333 |
+
public function getBulkProcessingForm($imageCount) {
|
334 |
+
return <<< HTML
|
335 |
+
</br>
|
336 |
+
Currently, you have {$imageCount} images in your library. </br>
|
337 |
+
</br>
|
338 |
+
<form action='' method="POST" >
|
339 |
+
<input type="submit" name="bulkProcess" id="bulkProcess" class="button button-primary" value="Compress all your images">
|
340 |
+
</form>
|
341 |
+
HTML;
|
342 |
+
}
|
343 |
+
|
344 |
+
public function displayNotice() {
|
345 |
+
global $hook_suffix;
|
346 |
+
|
347 |
+
$divHeader = '<div class="updated">';
|
348 |
+
$divWarningHeader = '<div class="update-nag">';
|
349 |
+
$divFooter = '</div>';
|
350 |
+
|
351 |
+
$noticeActivationContent = 'ShortPixel plugin activated! Get an API key <a href="https://shortpixel.com/wp-apikey" target="_blank">here</a>. Sign up, it’s free.';
|
352 |
+
$noticeWrongAPIKeyContent = 'API Key invalid!';
|
353 |
+
$noticeCorrectAPIKeyContent = 'API Key valid!';
|
354 |
+
|
355 |
+
if($hook_suffix == 'settings_page_wp-shortpixel' && !empty($_POST)) {
|
356 |
+
$keyCheckData = $this->getQuotaInformation($_POST['key']);
|
357 |
+
if($keyCheckData['APIKeyValid']) {
|
358 |
+
echo $divHeader . $noticeCorrectAPIKeyContent . $divFooter;
|
359 |
+
} else {
|
360 |
+
echo $divWarningHeader . $noticeWrongAPIKeyContent . $divFooter;
|
361 |
+
}
|
362 |
+
}
|
363 |
+
if($hook_suffix == 'plugins.php' && $_GET['activate']) { echo $divHeader . $noticeActivationContent . $divFooter; }
|
364 |
+
}
|
365 |
+
|
366 |
+
static public function formatBytes($bytes, $precision = 2) {
|
367 |
+
$units = array('B', 'KB', 'MB', 'GB', 'TB');
|
368 |
+
|
369 |
+
$bytes = max($bytes, 0);
|
370 |
+
$pow = floor(($bytes ? log($bytes) : 0) / log(1024));
|
371 |
+
$pow = min($pow, count($units) - 1);
|
372 |
+
|
373 |
+
$bytes /= pow(1024, $pow);
|
374 |
+
|
375 |
+
return round($bytes, $precision) . ' ' . $units[$pow];
|
376 |
+
}
|
377 |
+
|
378 |
+
public function getQuotaInformation($apiKey = null) {
|
379 |
+
|
380 |
+
if(is_null($apiKey)) { $apiKey = $this->_apiKey; }
|
381 |
+
|
382 |
+
$requestURL = 'https://api.shortpixel.com/api-status.php?key='.$apiKey;
|
383 |
+
$args = array('timeout'=> SP_MAX_TIMEOUT);
|
384 |
+
$response = wp_remote_get($requestURL, $args);
|
385 |
+
|
386 |
+
$defaultData = array(
|
387 |
+
"APIKeyValid" => false,
|
388 |
+
"APICallsMade" => 'Information unavailable. Please check your API key.',
|
389 |
+
"APICallsQuota" => 'Information unavailable. Please check your API key.');
|
390 |
+
|
391 |
+
if(is_object($response) && get_class($response) == 'WP_Error') {
|
392 |
+
return $defaultData;
|
393 |
+
}
|
394 |
+
|
395 |
+
if($response['response']['code'] != 200) {
|
396 |
+
return $defaultData;
|
397 |
+
}
|
398 |
+
|
399 |
+
$data = $response['body'];
|
400 |
+
$data = $this->parseJSON($data);
|
401 |
+
|
402 |
+
if(empty($data)) { return $defaultData; }
|
403 |
+
|
404 |
+
if($data->Status->Code == '-401') { return $defaultData; }
|
405 |
+
|
406 |
+
return array(
|
407 |
+
"APIKeyValid" => true,
|
408 |
+
"APICallsMade" => number_format($data->APICallsMade) . ' images',
|
409 |
+
"APICallsQuota" => number_format($data->APICallsQuota) . ' images'
|
410 |
+
);
|
411 |
+
|
412 |
+
|
413 |
+
}
|
414 |
+
|
415 |
+
public function generateCustomColumn( $column_name, $id ) {
|
416 |
+
if( 'wp-shortPixel' == $column_name ) {
|
417 |
+
$data = wp_get_attachment_metadata($id);
|
418 |
+
if ( isset( $data['ShortPixelImprovement'] ) ) {
|
419 |
+
print $data['ShortPixelImprovement'];
|
420 |
+
if(is_numeric($data['ShortPixelImprovement'])) print '%';
|
421 |
+
} else {
|
422 |
+
if ( wp_attachment_is_image( $id ) ) {
|
423 |
+
print 'Image not processed';
|
424 |
+
}
|
425 |
+
}
|
426 |
+
}
|
427 |
+
}
|
428 |
+
|
429 |
+
public function columns( $defaults ) {
|
430 |
+
$defaults['wp-shortPixel'] = 'Short Pixel Compression';
|
431 |
+
return $defaults;
|
432 |
+
}
|
433 |
+
|
434 |
+
public function generatePluginLinks($links) {
|
435 |
+
$in = '<a href="options-general.php?page=wp-shortpixel">Settings</a>';
|
436 |
+
array_unshift($links, $in);
|
437 |
+
return $links;
|
438 |
+
}
|
439 |
+
|
440 |
+
public function parseJSON($data) {
|
441 |
+
if ( function_exists('json_decode') ) {
|
442 |
+
$data = json_decode( $data );
|
443 |
+
} else {
|
444 |
+
require_once( 'JSON/JSON.php' );
|
445 |
+
$json = new Services_JSON( );
|
446 |
+
$data = $json->decode( $data );
|
447 |
+
}
|
448 |
+
return $data;
|
449 |
+
}
|
450 |
+
}
|
451 |
+
|
452 |
+
$pluginInstance = new WPShortPixel();
|
453 |
+
global $pluginInstance;
|
454 |
+
|
455 |
+
?>
|
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.
|
6 |
-
* Version: 1.
|
7 |
*/
|
8 |
|
9 |
require_once('shortpixel_api.php');
|
@@ -14,7 +14,7 @@ class WPShortPixel {
|
|
14 |
private $_apiInterface = null;
|
15 |
private $_apiKey = '';
|
16 |
private $_compressionType = '';
|
17 |
-
private $_processThumbnails =
|
18 |
|
19 |
public function __construct() {
|
20 |
define('SP_DEBUG', false);
|
@@ -28,13 +28,16 @@ class WPShortPixel {
|
|
28 |
//add hook for image upload processing
|
29 |
add_filter( 'wp_generate_attachment_metadata', array( &$this, 'handleImageUpload' ), 10, 2 );
|
30 |
add_filter( 'manage_media_columns', array( &$this, 'columns' ) );
|
31 |
-
|
32 |
|
|
|
|
|
33 |
|
34 |
|
35 |
//add settings page
|
36 |
add_action( 'admin_menu', array( &$this, 'registerSettingsPage' ) );
|
37 |
add_action( 'admin_menu', array( &$this, 'registerAdminPage' ) );
|
|
|
38 |
|
39 |
}
|
40 |
|
@@ -50,6 +53,8 @@ class WPShortPixel {
|
|
50 |
|
51 |
if(get_option('wp-short-process_thumbnails') != false) {
|
52 |
$this->_processThumbnails = get_option('wp-short-process_thumbnails');
|
|
|
|
|
53 |
}
|
54 |
|
55 |
if(get_option('wp-short-pixel-fileCount') === false) {
|
@@ -106,7 +111,7 @@ class WPShortPixel {
|
|
106 |
}
|
107 |
|
108 |
public function bulkProcesss() {
|
109 |
-
echo '<h1>ShortPixel
|
110 |
|
111 |
if ( function_exists( 'apache_setenv' ) ) {
|
112 |
@apache_setenv('no-gzip', 1);
|
@@ -122,44 +127,95 @@ class WPShortPixel {
|
|
122 |
'post_mime_type' => 'image'
|
123 |
));
|
124 |
|
125 |
-
|
|
|
126 |
|
127 |
-
|
128 |
-
|
|
|
|
|
|
|
|
|
|
|
129 |
|
130 |
-
|
131 |
|
132 |
-
|
133 |
-
|
134 |
-
$
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
135 |
|
136 |
-
|
|
|
|
|
137 |
|
138 |
-
|
139 |
-
|
140 |
-
|
|
|
|
|
|
|
141 |
|
142 |
-
if($
|
143 |
-
echo "
|
144 |
-
|
145 |
-
echo "Image " . basename($imagePath) . " processed succesfully.<br/>";
|
146 |
} else {
|
147 |
-
echo "
|
148 |
}
|
149 |
-
sleep(1);
|
150 |
}
|
|
|
151 |
|
152 |
-
|
153 |
-
flush();
|
154 |
|
155 |
-
|
156 |
-
|
157 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
158 |
} else {
|
159 |
-
|
160 |
}
|
|
|
|
|
|
|
|
|
|
|
161 |
}
|
162 |
|
|
|
|
|
|
|
|
|
163 |
}
|
164 |
|
165 |
public function renderSettingsMenu() {
|
@@ -182,7 +238,7 @@ class WPShortPixel {
|
|
182 |
$checked = '';
|
183 |
if($this->_processThumbnails) { $checked = 'checked'; }
|
184 |
|
185 |
-
echo '<h1>ShortPixel
|
186 |
echo '<p>ShortPixel improves website performance by reducing the images’ size.<BR>Configure ShortPixel plugin to compress both past and new past images and optimise your website.</p>';
|
187 |
|
188 |
$formHTML = <<< HTML
|
@@ -194,9 +250,10 @@ class WPShortPixel {
|
|
194 |
</tr>
|
195 |
<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>
|
196 |
<tr><th scope="row">
|
197 |
-
<label for="compressionType">Compression type: <span title="
|
198 |
-
|
199 |
-
|
|
|
200 |
</th><td>
|
201 |
HTML;
|
202 |
if($this->_compressionType == 'lossless') {
|
@@ -257,11 +314,11 @@ HTML;
|
|
257 |
</tr>
|
258 |
<tr>
|
259 |
<th scope="row"><label for="apiQuota">Your ShortPixel plan</label></th>
|
260 |
-
<td>{$quotaData['APICallsQuota']}
|
261 |
</tr>
|
262 |
<tr>
|
263 |
<th scope="row"><label for="usedQUota">Used Quota:</label></th>
|
264 |
-
<td>{$quotaData['APICallsMade']}
|
265 |
</tr>
|
266 |
<tr>
|
267 |
<th scope="row"><label for="averagCompression">Average file size compression:</label></th>
|
@@ -275,15 +332,37 @@ HTML;
|
|
275 |
|
276 |
public function getBulkProcessingForm($imageCount) {
|
277 |
return <<< HTML
|
278 |
-
|
|
|
279 |
</br>
|
280 |
<form action='' method="POST" >
|
281 |
<input type="submit" name="bulkProcess" id="bulkProcess" class="button button-primary" value="Compress all your images">
|
282 |
</form>
|
283 |
-
|
284 |
HTML;
|
285 |
}
|
286 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
287 |
static public function formatBytes($bytes, $precision = 2) {
|
288 |
$units = array('B', 'KB', 'MB', 'GB', 'TB');
|
289 |
|
@@ -296,13 +375,18 @@ HTML;
|
|
296 |
return round($bytes, $precision) . ' ' . $units[$pow];
|
297 |
}
|
298 |
|
299 |
-
public function getQuotaInformation() {
|
300 |
-
|
|
|
|
|
|
|
301 |
$args = array('timeout'=> SP_MAX_TIMEOUT);
|
302 |
$response = wp_remote_get($requestURL, $args);
|
303 |
|
304 |
-
$defaultData = array(
|
305 |
-
|
|
|
|
|
306 |
|
307 |
if(is_object($response) && get_class($response) == 'WP_Error') {
|
308 |
return $defaultData;
|
@@ -317,7 +401,13 @@ HTML;
|
|
317 |
|
318 |
if(empty($data)) { return $defaultData; }
|
319 |
|
320 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
321 |
|
322 |
|
323 |
}
|
@@ -340,6 +430,13 @@ HTML;
|
|
340 |
$defaults['wp-shortPixel'] = 'Short Pixel Compression';
|
341 |
return $defaults;
|
342 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
343 |
public function parseJSON($data) {
|
344 |
if ( function_exists('json_decode') ) {
|
345 |
$data = json_decode( $data );
|
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.
|
6 |
+
* Version: 1.1
|
7 |
*/
|
8 |
|
9 |
require_once('shortpixel_api.php');
|
14 |
private $_apiInterface = null;
|
15 |
private $_apiKey = '';
|
16 |
private $_compressionType = '';
|
17 |
+
private $_processThumbnails = 1;
|
18 |
|
19 |
public function __construct() {
|
20 |
define('SP_DEBUG', false);
|
28 |
//add hook for image upload processing
|
29 |
add_filter( 'wp_generate_attachment_metadata', array( &$this, 'handleImageUpload' ), 10, 2 );
|
30 |
add_filter( 'manage_media_columns', array( &$this, 'columns' ) );
|
31 |
+
add_filter( 'plugin_action_links_' . plugin_basename(__FILE__), array(&$this, 'generatePluginLinks'));
|
32 |
|
33 |
+
add_action( 'manage_media_custom_column', array( &$this, 'generateCustomColumn' ), 10, 2 );
|
34 |
+
add_action( 'handleBulkProcessing', array( &$this, 'handleBulkProcessing' ) );
|
35 |
|
36 |
|
37 |
//add settings page
|
38 |
add_action( 'admin_menu', array( &$this, 'registerSettingsPage' ) );
|
39 |
add_action( 'admin_menu', array( &$this, 'registerAdminPage' ) );
|
40 |
+
add_action( 'admin_notices', array( &$this, 'displayNotice' ) );
|
41 |
|
42 |
}
|
43 |
|
53 |
|
54 |
if(get_option('wp-short-process_thumbnails') != false) {
|
55 |
$this->_processThumbnails = get_option('wp-short-process_thumbnails');
|
56 |
+
} else {
|
57 |
+
add_option('wp-short-process_thumbnails', $this->_processThumbnails, '', 'yes' );
|
58 |
}
|
59 |
|
60 |
if(get_option('wp-short-pixel-fileCount') === false) {
|
111 |
}
|
112 |
|
113 |
public function bulkProcesss() {
|
114 |
+
echo '<h1>ShortPixel Bulk Processing</h1>';
|
115 |
|
116 |
if ( function_exists( 'apache_setenv' ) ) {
|
117 |
@apache_setenv('no-gzip', 1);
|
127 |
'post_mime_type' => 'image'
|
128 |
));
|
129 |
|
130 |
+
$bulkProcessingLog = get_option('bulkProcessingLog');
|
131 |
+
$bulkProcessingRunning = false;
|
132 |
|
133 |
+
if(
|
134 |
+
is_null($bulkProcessingLog['endDate']) &&
|
135 |
+
( $bulkProcessingLog['lastUpdate'] < $bulkProcessingLog['lastUpdate'] + 60 ) &&
|
136 |
+
( $bulkProcessingLog['startTime'] < $bulkProcessingLog['startTime'] + (60 * 15))
|
137 |
+
) {
|
138 |
+
$bulkProcessingRunning = true;
|
139 |
+
}
|
140 |
|
141 |
+
if(isset($_POST['bulkProcess'])) {
|
142 |
|
143 |
+
$scheduleResult = wp_schedule_single_event(time()+1, 'handleBulkProcessing');
|
144 |
+
if(is_null($scheduleResult)) {
|
145 |
+
$bulkProcessingLog = array(
|
146 |
+
'startTime' => time(),
|
147 |
+
'totalImageCount' => count($attachments),
|
148 |
+
'doneCount' => 0,
|
149 |
+
'log' => '',
|
150 |
+
'lastUpdate' => time(),
|
151 |
+
'endDate' => null
|
152 |
+
);
|
153 |
+
update_option('bulkProcessingLog', $bulkProcessingLog);
|
154 |
+
echo "Bulk processing started. Please visite the Bulk processing page to view the status. </br>";
|
155 |
+
}
|
156 |
|
157 |
+
if($scheduleResult === false) {
|
158 |
+
echo "There was a problem scheduling the bulk processing. Please try again later.";
|
159 |
+
}
|
160 |
|
161 |
+
} else {
|
162 |
+
|
163 |
+
if ($bulkProcessingRunning) {
|
164 |
+
echo "{$bulkProcessingLog['doneCount']}/{$bulkProcessingLog['totalImageCount']} images processed</br></br>Processing log:</br>";
|
165 |
+
echo $bulkProcessingLog['log'];
|
166 |
+
} else {
|
167 |
|
168 |
+
if(count($attachments)) {
|
169 |
+
if($bulkProcessingLog) { echo "Last succesful bulk processing done on {$bulkProcessingLog['totalImageCount']} images (" . date("d-m-Y H:i:s", $bulkProcessingLog['endDate']) . ").</br>"; }
|
170 |
+
echo $this->getBulkProcessingForm(count($attachments));
|
|
|
171 |
} else {
|
172 |
+
echo "It appear that you have no images uploaded yet.</br>";
|
173 |
}
|
|
|
174 |
}
|
175 |
+
}
|
176 |
|
177 |
+
}
|
|
|
178 |
|
179 |
+
public function handleBulkProcessing() {
|
180 |
+
//get all images
|
181 |
+
$attachments = null;
|
182 |
+
$attachments = get_posts( array(
|
183 |
+
'numberposts' => -1,
|
184 |
+
'post_type' => 'attachment',
|
185 |
+
'post_mime_type' => 'image'
|
186 |
+
));
|
187 |
+
//set up logging in db
|
188 |
+
$bulkProcessingLog = get_option('bulkProcessingLog');
|
189 |
+
//for each image
|
190 |
+
foreach( $attachments as $attachment ) {
|
191 |
+
//handle image processing
|
192 |
+
$imageURL = wp_get_attachment_url($attachment->ID);
|
193 |
+
$imagePath = get_attached_file($attachment->ID);
|
194 |
+
|
195 |
+
$processingResult = $this->_apiInterface->processImage($imageURL, $imagePath, $attachment->ID);
|
196 |
+
|
197 |
+
if(!is_object($processingResult)) {
|
198 |
+
$bulkProcessingLog['log'] .= "Error! Image " . basename($imagePath) . " could not be processed<br/>";
|
199 |
+
}
|
200 |
+
|
201 |
+
if($processingResult->Status->Code == 1) {
|
202 |
+
$bulkProcessingLog['log'] .= "Image " . basename($imagePath) . " scheduled for processing.<br/>";
|
203 |
+
} elseif($processingResult->Status->Code == 2) {
|
204 |
+
$bulkProcessingLog['log'] .= "Image " . basename($imagePath) . " processed succesfully.<br/>";
|
205 |
} else {
|
206 |
+
$bulkProcessingLog['log'] .= "Error! Image " . basename($imagePath) . " could not be processed<br/>";
|
207 |
}
|
208 |
+
|
209 |
+
$bulkProcessingLog['doneCount'] = $bulkProcessingLog['doneCount'] + 1;
|
210 |
+
$bulkProcessingLog['lastUpdate'] = time();
|
211 |
+
update_option('bulkProcessingLog', $bulkProcessingLog);
|
212 |
+
|
213 |
}
|
214 |
|
215 |
+
$bulkProcessingLog['endDate'] = time();
|
216 |
+
|
217 |
+
update_option('bulkProcessingLog', $bulkProcessingLog);
|
218 |
+
|
219 |
}
|
220 |
|
221 |
public function renderSettingsMenu() {
|
238 |
$checked = '';
|
239 |
if($this->_processThumbnails) { $checked = 'checked'; }
|
240 |
|
241 |
+
echo '<h1>ShortPixel Image Optimiser Settings</h1>';
|
242 |
echo '<p>ShortPixel improves website performance by reducing the images’ size.<BR>Configure ShortPixel plugin to compress both past and new past images and optimise your website.</p>';
|
243 |
|
244 |
$formHTML = <<< HTML
|
250 |
</tr>
|
251 |
<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>
|
252 |
<tr><th scope="row">
|
253 |
+
<label for="compressionType">Compression type: <span title="
|
254 |
+
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.
|
255 |
+
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.
|
256 |
+
">?</span></label>
|
257 |
</th><td>
|
258 |
HTML;
|
259 |
if($this->_compressionType == 'lossless') {
|
314 |
</tr>
|
315 |
<tr>
|
316 |
<th scope="row"><label for="apiQuota">Your ShortPixel plan</label></th>
|
317 |
+
<td>{$quotaData['APICallsQuota']}</td>
|
318 |
</tr>
|
319 |
<tr>
|
320 |
<th scope="row"><label for="usedQUota">Used Quota:</label></th>
|
321 |
+
<td>{$quotaData['APICallsMade']}</td>
|
322 |
</tr>
|
323 |
<tr>
|
324 |
<th scope="row"><label for="averagCompression">Average file size compression:</label></th>
|
332 |
|
333 |
public function getBulkProcessingForm($imageCount) {
|
334 |
return <<< HTML
|
335 |
+
</br>
|
336 |
+
Currently, you have {$imageCount} images in your library. </br>
|
337 |
</br>
|
338 |
<form action='' method="POST" >
|
339 |
<input type="submit" name="bulkProcess" id="bulkProcess" class="button button-primary" value="Compress all your images">
|
340 |
</form>
|
|
|
341 |
HTML;
|
342 |
}
|
343 |
|
344 |
+
public function displayNotice() {
|
345 |
+
global $hook_suffix;
|
346 |
+
|
347 |
+
$divHeader = '<div class="updated">';
|
348 |
+
$divWarningHeader = '<div class="update-nag">';
|
349 |
+
$divFooter = '</div>';
|
350 |
+
|
351 |
+
$noticeActivationContent = 'ShortPixel plugin activated! Get an API key <a href="https://shortpixel.com/wp-apikey" target="_blank">here</a>. Sign up, it’s free.';
|
352 |
+
$noticeWrongAPIKeyContent = 'API Key invalid!';
|
353 |
+
$noticeCorrectAPIKeyContent = 'API Key valid!';
|
354 |
+
|
355 |
+
if($hook_suffix == 'settings_page_wp-shortpixel' && !empty($_POST)) {
|
356 |
+
$keyCheckData = $this->getQuotaInformation($_POST['key']);
|
357 |
+
if($keyCheckData['APIKeyValid']) {
|
358 |
+
echo $divHeader . $noticeCorrectAPIKeyContent . $divFooter;
|
359 |
+
} else {
|
360 |
+
echo $divWarningHeader . $noticeWrongAPIKeyContent . $divFooter;
|
361 |
+
}
|
362 |
+
}
|
363 |
+
if($hook_suffix == 'plugins.php' && $_GET['activate']) { echo $divHeader . $noticeActivationContent . $divFooter; }
|
364 |
+
}
|
365 |
+
|
366 |
static public function formatBytes($bytes, $precision = 2) {
|
367 |
$units = array('B', 'KB', 'MB', 'GB', 'TB');
|
368 |
|
375 |
return round($bytes, $precision) . ' ' . $units[$pow];
|
376 |
}
|
377 |
|
378 |
+
public function getQuotaInformation($apiKey = null) {
|
379 |
+
|
380 |
+
if(is_null($apiKey)) { $apiKey = $this->_apiKey; }
|
381 |
+
|
382 |
+
$requestURL = 'https://api.shortpixel.com/api-status.php?key='.$apiKey;
|
383 |
$args = array('timeout'=> SP_MAX_TIMEOUT);
|
384 |
$response = wp_remote_get($requestURL, $args);
|
385 |
|
386 |
+
$defaultData = array(
|
387 |
+
"APIKeyValid" => false,
|
388 |
+
"APICallsMade" => 'Information unavailable. Please check your API key.',
|
389 |
+
"APICallsQuota" => 'Information unavailable. Please check your API key.');
|
390 |
|
391 |
if(is_object($response) && get_class($response) == 'WP_Error') {
|
392 |
return $defaultData;
|
401 |
|
402 |
if(empty($data)) { return $defaultData; }
|
403 |
|
404 |
+
if($data->Status->Code == '-401') { return $defaultData; }
|
405 |
+
|
406 |
+
return array(
|
407 |
+
"APIKeyValid" => true,
|
408 |
+
"APICallsMade" => number_format($data->APICallsMade) . ' images',
|
409 |
+
"APICallsQuota" => number_format($data->APICallsQuota) . ' images'
|
410 |
+
);
|
411 |
|
412 |
|
413 |
}
|
430 |
$defaults['wp-shortPixel'] = 'Short Pixel Compression';
|
431 |
return $defaults;
|
432 |
}
|
433 |
+
|
434 |
+
public function generatePluginLinks($links) {
|
435 |
+
$in = '<a href="options-general.php?page=wp-shortpixel">Settings</a>';
|
436 |
+
array_unshift($links, $in);
|
437 |
+
return $links;
|
438 |
+
}
|
439 |
+
|
440 |
public function parseJSON($data) {
|
441 |
if ( function_exists('json_decode') ) {
|
442 |
$data = json_decode( $data );
|