1 /*
  2  * ***** BEGIN LICENSE BLOCK *****
  3  * Zimbra Collaboration Suite Web Client
  4  * Copyright (C) 2011, 2012, 2013, 2014, 2016 Synacor, Inc.
  5  *
  6  * The contents of this file are subject to the Common Public Attribution License Version 1.0 (the "License");
  7  * you may not use this file except in compliance with the License.
  8  * You may obtain a copy of the License at: https://www.zimbra.com/license
  9  * The License is based on the Mozilla Public License Version 1.1 but Sections 14 and 15
 10  * have been added to cover use of software over a computer network and provide for limited attribution
 11  * for the Original Developer. In addition, Exhibit A has been modified to be consistent with Exhibit B.
 12  *
 13  * Software distributed under the License is distributed on an "AS IS" basis,
 14  * WITHOUT WARRANTY OF ANY KIND, either express or implied.
 15  * See the License for the specific language governing rights and limitations under the License.
 16  * The Original Code is Zimbra Open Source Web Client.
 17  * The Initial Developer of the Original Code is Zimbra, Inc.  All rights to the Original Code were
 18  * transferred by Zimbra, Inc. to Synacor, Inc. on September 14, 2015.
 19  *
 20  * All portions of the code are Copyright (C) 2011, 2012, 2013, 2014, 2016 Synacor, Inc. All Rights Reserved.
 21  * ***** END LICENSE BLOCK *****
 22  */
 23 /*
 24     http://www.JSON.org/json2.js
 25     2011-02-23
 26 
 27     Public Domain.
 28 
 29     NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
 30 
 31     See http://www.JSON.org/js.html
 32 
 33 
 34     This code should be minified before deployment.
 35     See http://javascript.crockford.com/jsmin.html
 36 
 37     USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
 38     NOT CONTROL.
 39 
 40 
 41     This file creates a global JSON object containing two methods: stringify
 42     and parse.
 43 
 44         JSON.stringify(value, replacer, space)
 45             value       any JavaScript value, usually an object or array.
 46 
 47             replacer    an optional parameter that determines how object
 48                         values are stringified for objects. It can be a
 49                         function or an array of strings.
 50 
 51             space       an optional parameter that specifies the indentation
 52                         of nested structures. If it is omitted, the text will
 53                         be packed without extra whitespace. If it is a number,
 54                         it will specify the number of spaces to indent at each
 55                         level. If it is a string (such as '\t' or ' '),
 56                         it contains the characters used to indent at each level.
 57 
 58             This method produces a JSON text from a JavaScript value.
 59 
 60             When an object value is found, if the object contains a toJSON
 61             method, its toJSON method will be called and the result will be
 62             stringified. A toJSON method does not serialize: it returns the
 63             value represented by the name/value pair that should be serialized,
 64             or undefined if nothing should be serialized. The toJSON method
 65             will be passed the key associated with the value, and this will be
 66             bound to the value
 67 
 68             For example, this would serialize Dates as ISO strings.
 69 
 70                 Date.prototype.toJSON = function (key) {
 71                     function f(n) {
 72                         // Format integers to have at least two digits.
 73                         return n < 10 ? '0' + n : n;
 74                     }
 75 
 76                     return this.getUTCFullYear()   + '-' +
 77                          f(this.getUTCMonth() + 1) + '-' +
 78                          f(this.getUTCDate())      + 'T' +
 79                          f(this.getUTCHours())     + ':' +
 80                          f(this.getUTCMinutes())   + ':' +
 81                          f(this.getUTCSeconds())   + 'Z';
 82                 };
 83 
 84             You can provide an optional replacer method. It will be passed the
 85             key and value of each member, with this bound to the containing
 86             object. The value that is returned from your method will be
 87             serialized. If your method returns undefined, then the member will
 88             be excluded from the serialization.
 89 
 90             If the replacer parameter is an array of strings, then it will be
 91             used to select the members to be serialized. It filters the results
 92             such that only members with keys listed in the replacer array are
 93             stringified.
 94 
 95             Values that do not have JSON representations, such as undefined or
 96             functions, will not be serialized. Such values in objects will be
 97             dropped; in arrays they will be replaced with null. You can use
 98             a replacer function to replace those with JSON values.
 99             JSON.stringify(undefined) returns undefined.
100 
101             The optional space parameter produces a stringification of the
102             value that is filled with line breaks and indentation to make it
103             easier to read.
104 
105             If the space parameter is a non-empty string, then that string will
106             be used for indentation. If the space parameter is a number, then
107             the indentation will be that many spaces.
108 
109             Example:
110 
111             text = JSON.stringify(['e', {pluribus: 'unum'}]);
112             // text is '["e",{"pluribus":"unum"}]'
113 
114 
115             text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
116             // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'
117 
118             text = JSON.stringify([new Date()], function (key, value) {
119                 return this[key] instanceof Date ?
120                     'Date(' + this[key] + ')' : value;
121             });
122             // text is '["Date(---current time---)"]'
123 
124 
125         JSON.parse(text, reviver)
126             This method parses a JSON text to produce an object or array.
127             It can throw a SyntaxError exception.
128 
129             The optional reviver parameter is a function that can filter and
130             transform the results. It receives each of the keys and values,
131             and its return value is used instead of the original value.
132             If it returns what it received, then the structure is not modified.
133             If it returns undefined then the member is deleted.
134 
135             Example:
136 
137             // Parse the text. Values that look like ISO date strings will
138             // be converted to Date objects.
139 
140             myData = JSON.parse(text, function (key, value) {
141                 var a;
142                 if (typeof value === 'string') {
143                     a =
144 /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
145                     if (a) {
146                         return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
147                             +a[5], +a[6]));
148                     }
149                 }
150                 return value;
151             });
152 
153             myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
154                 var d;
155                 if (typeof value === 'string' &&
156                         value.slice(0, 5) === 'Date(' &&
157                         value.slice(-1) === ')') {
158                     d = new Date(value.slice(5, -1));
159                     if (d) {
160                         return d;
161                     }
162                 }
163                 return value;
164             });
165 
166 
167     This is a reference implementation. You are free to copy, modify, or
168     redistribute.
169 */
170 
171 /*jslint evil: true, strict: false, regexp: false */
172 
173 /*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
174     call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
175     getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
176     lastIndex, length, parse, prototype, push, replace, slice, stringify,
177     test, toJSON, toString, valueOf
178 */
179 
180 
181 // Create a JSON object only if one does not already exist. We create the
182 // methods in a closure to avoid creating global variables.
183 
184 var JSON;
185 if (!JSON) {
186     JSON = {};
187 }
188 
189 (function () {
190     "use strict";
191 
192     function f(n) {
193         // Format integers to have at least two digits.
194         return n < 10 ? '0' + n : n;
195     }
196 
197     if (typeof Date.prototype.toJSON !== 'function') {
198 
199         Date.prototype.toJSON = function (key) {
200 
201             return isFinite(this.valueOf()) ?
202                 this.getUTCFullYear()     + '-' +
203                 f(this.getUTCMonth() + 1) + '-' +
204                 f(this.getUTCDate())      + 'T' +
205                 f(this.getUTCHours())     + ':' +
206                 f(this.getUTCMinutes())   + ':' +
207                 f(this.getUTCSeconds())   + 'Z' : null;
208         };
209 
210         String.prototype.toJSON      =
211             Number.prototype.toJSON  =
212             Boolean.prototype.toJSON = function (key) {
213                 return this.valueOf();
214             };
215     }
216 
217     var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
218         escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
219         gap,
220         indent,
221         meta = {    // table of character substitutions
222             '\b': '\\b',
223             '\t': '\\t',
224             '\n': '\\n',
225             '\f': '\\f',
226             '\r': '\\r',
227             '"' : '\\"',
228             '\\': '\\\\'
229         },
230         rep;
231 
232 
233     function quote(string) {
234 
235 // If the string contains no control characters, no quote characters, and no
236 // backslash characters, then we can safely slap some quotes around it.
237 // Otherwise we must also replace the offending characters with safe escape
238 // sequences.
239 
240         escapable.lastIndex = 0;
241         return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
242             var c = meta[a];
243             return typeof c === 'string' ? c :
244                 '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
245         }) + '"' : '"' + string + '"';
246     }
247 
248 
249     function str(key, holder) {
250 
251 // Produce a string from holder[key].
252 
253         var i,          // The loop counter.
254             k,          // The member key.
255             v,          // The member value.
256             length,
257             mind = gap,
258             partial,
259             value = holder[key];
260 
261 // If the value has a toJSON method, call it to obtain a replacement value.
262 
263         if (value && typeof value === 'object' &&
264                 typeof value.toJSON === 'function') {
265             value = value.toJSON(key);
266         }
267 
268 // If we were called with a replacer function, then call the replacer to
269 // obtain a replacement value.
270 
271         if (typeof rep === 'function') {
272             value = rep.call(holder, key, value);
273         }
274 
275 // What happens next depends on the value's type.
276 
277         switch (typeof value) {
278         case 'string':
279             return quote(value);
280 
281         case 'number':
282 
283 // JSON numbers must be finite. Encode non-finite numbers as null.
284 
285             return isFinite(value) ? String(value) : 'null';
286 
287         case 'boolean':
288         case 'null':
289 
290 // If the value is a boolean or null, convert it to a string. Note:
291 // typeof null does not produce 'null'. The case is included here in
292 // the remote chance that this gets fixed someday.
293 
294             return String(value);
295 
296 // If the type is 'object', we might be dealing with an object or an array or
297 // null.
298 
299         case 'object':
300 
301 // Due to a specification blunder in ECMAScript, typeof null is 'object',
302 // so watch out for that case.
303 
304             if (!value) {
305                 return 'null';
306             }
307 
308 // Make an array to hold the partial results of stringifying this object value.
309 
310             gap += indent;
311             partial = [];
312 
313 // Is the value an array? Use check that doesn't rely on type info, which IE loses across windows
314 
315 			if (AjxUtil.isArray1(value)) {
316 
317 // The value is an array. Stringify every element. Use null as a placeholder
318 // for non-JSON values.
319 
320                 length = value.length;
321                 for (i = 0; i < length; i += 1) {
322                     partial[i] = str(i, value) || 'null';
323                 }
324 
325 // Join all of the elements together, separated with commas, and wrap them in
326 // brackets.
327 
328                 v = partial.length === 0 ? '[]' : gap ?
329                     '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' :
330                     '[' + partial.join(',') + ']';
331                 gap = mind;
332                 return v;
333             }
334 
335 // If the replacer is an array, use it to select the members to be stringified.
336 
337             if (rep && typeof rep === 'object') {
338                 length = rep.length;
339                 for (i = 0; i < length; i += 1) {
340                     if (typeof rep[i] === 'string') {
341                         k = rep[i];
342                         v = str(k, value);
343                         if (v) {
344                             partial.push(quote(k) + (gap ? ': ' : ':') + v);
345                         }
346                     }
347                 }
348             } else {
349 
350 // Otherwise, iterate through all of the keys in the object.
351 
352                 for (k in value) {
353                     if (Object.prototype.hasOwnProperty.call(value, k)) {
354                         v = str(k, value);
355                         if (v) {
356                             partial.push(quote(k) + (gap ? ': ' : ':') + v);
357                         }
358                     }
359                 }
360             }
361 
362 // Join all of the member texts together, separated with commas,
363 // and wrap them in braces.
364 
365             v = partial.length === 0 ? '{}' : gap ?
366                 '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' :
367                 '{' + partial.join(',') + '}';
368             gap = mind;
369             return v;
370         }
371     }
372 
373 
374 // Create a version of stringify that doesn't rely on type information, which IE can lose
375 // for arrays when going across windows.
376          JSON.stringify1 = function (value, replacer, space) {
377 
378 // The stringify method takes a value and an optional replacer, and an optional
379 // space parameter, and returns a JSON text. The replacer can be a function
380 // that can replace values, or an array of strings that will select the keys.
381 // A default replacer method can be provided. Use of the space parameter can
382 // produce text that is more easily readable.
383 
384             var i;
385             gap = '';
386             indent = '';
387 
388 // If the space parameter is a number, make an indent string containing that
389 // many spaces.
390 
391             if (typeof space === 'number') {
392                 for (i = 0; i < space; i += 1) {
393                     indent += ' ';
394                 }
395 
396 // If the space parameter is a string, it will be used as the indent string.
397 
398             } else if (typeof space === 'string') {
399                 indent = space;
400             }
401 
402 // If there is a replacer, it must be a function or an array.
403 // Otherwise, throw an error.
404 
405             rep = replacer;
406             if (replacer && typeof replacer !== 'function' &&
407                     (typeof replacer !== 'object' ||
408                     typeof replacer.length !== 'number')) {
409                 throw new Error('JSON.stringify');
410             }
411 
412 // Make a fake root object containing our value under the key of ''.
413 // Return the result of stringifying the value.
414 
415             return str('', {'': value});
416         };
417 
418 // If the JSON object does not yet have a stringify method, add ours.
419     if (typeof JSON.stringify !== 'function') {
420 		JSON.stringify = JSON.stringify1;
421 	}
422 
423 // If the JSON object does not yet have a parse method, give it one.
424 
425     if (typeof JSON.parse !== 'function') {
426         JSON.parse = function (text, reviver) {
427 
428 // The parse method takes a text and an optional reviver function, and returns
429 // a JavaScript value if the text is a valid JSON text.
430 
431             var j;
432 
433             function walk(holder, key) {
434 
435 // The walk method is used to recursively walk the resulting structure so
436 // that modifications can be made.
437 
438                 var k, v, value = holder[key];
439                 if (value && typeof value === 'object') {
440                     for (k in value) {
441                         if (Object.prototype.hasOwnProperty.call(value, k)) {
442                             v = walk(value, k);
443                             if (v !== undefined) {
444                                 value[k] = v;
445                             } else {
446                                 delete value[k];
447                             }
448                         }
449                     }
450                 }
451                 return reviver.call(holder, key, value);
452             }
453 
454 
455 // Parsing happens in four stages. In the first stage, we replace certain
456 // Unicode characters with escape sequences. JavaScript handles many characters
457 // incorrectly, either silently deleting them, or treating them as line endings.
458 
459             text = String(text);
460             cx.lastIndex = 0;
461             if (cx.test(text)) {
462                 text = text.replace(cx, function (a) {
463                     return '\\u' +
464                         ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
465                 });
466             }
467 
468 // In the second stage, we run the text against regular expressions that look
469 // for non-JSON patterns. We are especially concerned with '()' and 'new'
470 // because they can cause invocation, and '=' because it can cause mutation.
471 // But just to be safe, we want to reject all unexpected forms.
472 
473 // We split the second stage into 4 regexp operations in order to work around
474 // crippling inefficiencies in IE's and Safari's regexp engines. First we
475 // replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
476 // replace all simple value tokens with ']' characters. Third, we delete all
477 // open brackets that follow a colon or comma or that begin the text. Finally,
478 // we look to see that the remaining characters are only whitespace or ']' or
479 // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
480 
481             if (/^[\],:{}\s]*$/
482                     .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
483                         .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
484                         .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
485 
486 // In the third stage we use the eval function to compile the text into a
487 // JavaScript structure. The '{' operator is subject to a syntactic ambiguity
488 // in JavaScript: it can begin a block or an object literal. We wrap the text
489 // in parens to eliminate the ambiguity.
490 
491                 j = eval('(' + text + ')');
492 
493 // In the optional fourth stage, we recursively walk the new structure, passing
494 // each name/value pair to a reviver function for possible transformation.
495 
496                 return typeof reviver === 'function' ?
497                     walk({'': j}, '') : j;
498             }
499 
500 // If the text is not JSON parseable, then a SyntaxError is thrown.
501 
502             throw new SyntaxError('JSON.parse');
503         };
504     }
505 }());
506