NOBUG: Fixed file access permissions
[moodle.git] / lib / yuilib / 3.13.0 / cookie / cookie-debug.js
blobcf737084c379bde827cc30c343084443279dcf7c
1 /*
2 YUI 3.13.0 (build 508226d)
3 Copyright 2013 Yahoo! Inc. All rights reserved.
4 Licensed under the BSD License.
5 http://yuilibrary.com/license/
6 */
8 YUI.add('cookie', function (Y, NAME) {
10 /**
11  * Utilities for cookie management
12  * @module cookie
13  */
15     //shortcuts
16     var L       = Y.Lang,
17         O       = Y.Object,
18         NULL    = null,
20         //shortcuts to functions
21         isString    = L.isString,
22         isObject    = L.isObject,
23         isUndefined = L.isUndefined,
24         isFunction  = L.isFunction,
25         encode      = encodeURIComponent,
26         decode      = decodeURIComponent,
28         //shortcut to document
29         doc         = Y.config.doc;
31     /*
32      * Throws an error message.
33      */
34     function error(message){
35         throw new TypeError(message);
36     }
38     /*
39      * Checks the validity of a cookie name.
40      */
41     function validateCookieName(name){
42         if (!isString(name) || name === ""){
43             error("Cookie name must be a non-empty string.");
44         }
45     }
47     /*
48      * Checks the validity of a subcookie name.
49      */
50     function validateSubcookieName(subName){
51         if (!isString(subName) || subName === ""){
52             error("Subcookie name must be a non-empty string.");
53         }
54     }
56     /**
57      * Cookie utility.
58      * @class Cookie
59      * @static
60      */
61     Y.Cookie = {
63         //-------------------------------------------------------------------------
64         // Private Methods
65         //-------------------------------------------------------------------------
67         /**
68          * Creates a cookie string that can be assigned into document.cookie.
69          * @param {String} name The name of the cookie.
70          * @param {String} value The value of the cookie.
71          * @param {Boolean} encodeValue True to encode the value, false to leave as-is.
72          * @param {Object} options (Optional) Options for the cookie.
73          * @return {String} The formatted cookie string.
74          * @method _createCookieString
75          * @private
76          * @static
77          */
78         _createCookieString : function (name /*:String*/, value /*:Variant*/, encodeValue /*:Boolean*/, options /*:Object*/) /*:String*/ {
80             options = options || {};
82             var text /*:String*/ = encode(name) + "=" + (encodeValue ? encode(value) : value),
83                 expires = options.expires,
84                 path    = options.path,
85                 domain  = options.domain;
88             if (isObject(options)){
89                 //expiration date
90                 if (expires instanceof Date){
91                     text += "; expires=" + expires.toUTCString();
92                 }
94                 //path
95                 if (isString(path) && path !== ""){
96                     text += "; path=" + path;
97                 }
99                 //domain
100                 if (isString(domain) && domain !== ""){
101                     text += "; domain=" + domain;
102                 }
104                 //secure
105                 if (options.secure === true){
106                     text += "; secure";
107                 }
108             }
110             return text;
111         },
113         /**
114          * Formats a cookie value for an object containing multiple values.
115          * @param {Object} hash An object of key-value pairs to create a string for.
116          * @return {String} A string suitable for use as a cookie value.
117          * @method _createCookieHashString
118          * @private
119          * @static
120          */
121         _createCookieHashString : function (hash /*:Object*/) /*:String*/ {
122             if (!isObject(hash)){
123                 error("Cookie._createCookieHashString(): Argument must be an object.");
124             }
126             var text /*:Array*/ = [];
128             O.each(hash, function(value, key){
129                 if (!isFunction(value) && !isUndefined(value)){
130                     text.push(encode(key) + "=" + encode(String(value)));
131                 }
132             });
134             return text.join("&");
135         },
137         /**
138          * Parses a cookie hash string into an object.
139          * @param {String} text The cookie hash string to parse (format: n1=v1&n2=v2).
140          * @return {Object} An object containing entries for each cookie value.
141          * @method _parseCookieHash
142          * @private
143          * @static
144          */
145         _parseCookieHash : function (text) {
147             var hashParts   = text.split("&"),
148                 hashPart    = NULL,
149                 hash        = {};
151             if (text.length){
152                 for (var i=0, len=hashParts.length; i < len; i++){
153                     hashPart = hashParts[i].split("=");
154                     hash[decode(hashPart[0])] = decode(hashPart[1]);
155                 }
156             }
158             return hash;
159         },
161         /**
162          * Parses a cookie string into an object representing all accessible cookies.
163          * @param {String} text The cookie string to parse.
164          * @param {Boolean} shouldDecode (Optional) Indicates if the cookie values should be decoded or not. Default is true.
165          * @param {Object} options (Optional) Contains settings for loading the cookie.
166          * @return {Object} An object containing entries for each accessible cookie.
167          * @method _parseCookieString
168          * @private
169          * @static
170          */
171         _parseCookieString : function (text /*:String*/, shouldDecode /*:Boolean*/, options /*:Object*/) /*:Object*/ {
173             var cookies /*:Object*/ = {};
175             if (isString(text) && text.length > 0) {
177                 var decodeValue = (shouldDecode === false ? function(s){return s;} : decode),
178                     cookieParts = text.split(/;\s/g),
179                     cookieName  = NULL,
180                     cookieValue = NULL,
181                     cookieNameValue = NULL;
183                 for (var i=0, len=cookieParts.length; i < len; i++){
184                     //check for normally-formatted cookie (name-value)
185                     cookieNameValue = cookieParts[i].match(/([^=]+)=/i);
186                     if (cookieNameValue instanceof Array){
187                         try {
188                             cookieName = decode(cookieNameValue[1]);
189                             cookieValue = decodeValue(cookieParts[i].substring(cookieNameValue[1].length+1));
190                         } catch (ex){
191                             //intentionally ignore the cookie - the encoding is wrong
192                         }
193                     } else {
194                         //means the cookie does not have an "=", so treat it as a boolean flag
195                         cookieName = decode(cookieParts[i]);
196                         cookieValue = "";
197                     }
198                     // don't overwrite an already loaded cookie if set by option
199                     if (!isUndefined(options) && options.reverseCookieLoading) {
200                         if (isUndefined(cookies[cookieName])) {
201                             cookies[cookieName] = cookieValue;
202                         }
203                     } else {
204                         cookies[cookieName] = cookieValue;
205                     }
206                 }
208             }
210             return cookies;
211         },
213         /**
214          * Sets the document object that the cookie utility uses for setting
215          * cookies. This method is necessary to ensure that the cookie utility
216          * unit tests can pass even when run on a domain instead of locally.
217          * This method should not be used otherwise; you should use
218          * <code>Y.config.doc</code> to change the document that the cookie
219          * utility uses for everyday purposes.
220          * @param {Object} newDoc The object to use as the document.
221          * @return {void}
222          * @method _setDoc
223          * @private
224          */
225         _setDoc: function(newDoc){
226             doc = newDoc;
227         },
229         //-------------------------------------------------------------------------
230         // Public Methods
231         //-------------------------------------------------------------------------
233         /**
234          * Determines if the cookie with the given name exists. This is useful for
235          * Boolean cookies (those that do not follow the name=value convention).
236          * @param {String} name The name of the cookie to check.
237          * @return {Boolean} True if the cookie exists, false if not.
238          * @method exists
239          * @static
240          */
241         exists: function(name) {
243             validateCookieName(name);   //throws error
245             var cookies = this._parseCookieString(doc.cookie, true);
247             return cookies.hasOwnProperty(name);
248         },
250         /**
251          * Returns the cookie value for the given name.
252          * @param {String} name The name of the cookie to retrieve.
253          * @param {Function|Object} options (Optional) An object containing one or more
254          *      cookie options: raw (true/false), reverseCookieLoading (true/false)
255          *      and converter (a function).
256          *      The converter function is run on the value before returning it. The
257          *      function is not used if the cookie doesn't exist. The function can be
258          *      passed instead of the options object for backwards compatibility. When
259          *      raw is set to true, the cookie value is not URI decoded.
260          * @return {Variant} If no converter is specified, returns a string or null if
261          *      the cookie doesn't exist. If the converter is specified, returns the value
262          *      returned from the converter or null if the cookie doesn't exist.
263          * @method get
264          * @static
265          */
266         get : function (name, options) {
268             validateCookieName(name);   //throws error
270             var cookies,
271                 cookie,
272                 converter;
274             //if options is a function, then it's the converter
275             if (isFunction(options)) {
276                 converter = options;
277                 options = {};
278             } else if (isObject(options)) {
279                 converter = options.converter;
280             } else {
281                 options = {};
282             }
284             cookies = this._parseCookieString(doc.cookie, !options.raw, options);
285             cookie = cookies[name];
287             //should return null, not undefined if the cookie doesn't exist
288             if (isUndefined(cookie)) {
289                 return NULL;
290             }
292             if (!isFunction(converter)){
293                 return cookie;
294             } else {
295                 return converter(cookie);
296             }
297         },
299         /**
300          * Returns the value of a subcookie.
301          * @param {String} name The name of the cookie to retrieve.
302          * @param {String} subName The name of the subcookie to retrieve.
303          * @param {Function} converter (Optional) A function to run on the value before returning
304          *      it. The function is not used if the cookie doesn't exist.
305          * @param {Object} options (Optional) Containing one or more settings for cookie parsing.
306          * @return {Variant} If the cookie doesn't exist, null is returned. If the subcookie
307          *      doesn't exist, null if also returned. If no converter is specified and the
308          *      subcookie exists, a string is returned. If a converter is specified and the
309          *      subcookie exists, the value returned from the converter is returned.
310          * @method getSub
311          * @static
312          */
313         getSub : function (name /*:String*/, subName /*:String*/, converter /*:Function*/, options /*:Object*/) /*:Variant*/ {
315             var hash /*:Variant*/ = this.getSubs(name, options);
317             if (hash !== NULL) {
319                 validateSubcookieName(subName);   //throws error
321                 if (isUndefined(hash[subName])){
322                     return NULL;
323                 }
325                 if (!isFunction(converter)){
326                     return hash[subName];
327                 } else {
328                     return converter(hash[subName]);
329                 }
330             } else {
331                 return NULL;
332             }
334         },
336         /**
337          * Returns an object containing name-value pairs stored in the cookie with the given name.
338          * @param {String} name The name of the cookie to retrieve.
339          * @param {Object} options (Optional) Containing one or more settings for cookie parsing.
340          * @return {Object} An object of name-value pairs if the cookie with the given name
341          *      exists, null if it does not.
342          * @method getSubs
343          * @static
344          */
345         getSubs : function (name /*:String*/, options /*:Object*/) {
347             validateCookieName(name);   //throws error
349             var cookies = this._parseCookieString(doc.cookie, false, options);
350             if (isString(cookies[name])){
351                 return this._parseCookieHash(cookies[name]);
352             }
353             return NULL;
354         },
356         /**
357          * Removes a cookie from the machine by setting its expiration date to
358          * sometime in the past.
359          * @param {String} name The name of the cookie to remove.
360          * @param {Object} options (Optional) An object containing one or more
361          *      cookie options: path (a string), domain (a string),
362          *      and secure (true/false). The expires option will be overwritten
363          *      by the method.
364          * @return {String} The created cookie string.
365          * @method remove
366          * @static
367          */
368         remove : function (name, options) {
370             validateCookieName(name);   //throws error
372             //set options
373             options = Y.merge(options || {}, {
374                 expires: new Date(0)
375             });
377             //set cookie
378             return this.set(name, "", options);
379         },
381         /**
382          * Removes a sub cookie with a given name.
383          * @param {String} name The name of the cookie in which the subcookie exists.
384          * @param {String} subName The name of the subcookie to remove.
385          * @param {Object} options (Optional) An object containing one or more
386          *      cookie options: path (a string), domain (a string), expires (a Date object),
387          *      removeIfEmpty (true/false), and secure (true/false). This must be the same
388          *      settings as the original subcookie.
389          * @return {String} The created cookie string.
390          * @method removeSub
391          * @static
392          */
393         removeSub : function(name, subName, options) {
395             validateCookieName(name);   //throws error
397             validateSubcookieName(subName);   //throws error
399             options = options || {};
401             //get all subcookies for this cookie
402             var subs = this.getSubs(name);
404             //delete the indicated subcookie
405             if (isObject(subs) && subs.hasOwnProperty(subName)){
406                 delete subs[subName];
408                 if (!options.removeIfEmpty) {
409                     //reset the cookie
411                     return this.setSubs(name, subs, options);
412                 } else {
413                     //reset the cookie if there are subcookies left, else remove
414                     for (var key in subs){
415                         if (subs.hasOwnProperty(key) && !isFunction(subs[key]) && !isUndefined(subs[key])){
416                             return this.setSubs(name, subs, options);
417                         }
418                     }
420                     return this.remove(name, options);
421                 }
422             } else {
423                 return "";
424             }
426         },
428         /**
429          * Sets a cookie with a given name and value.
430          * @param {String} name The name of the cookie to set.
431          * @param {Variant} value The value to set for the cookie.
432          * @param {Object} options (Optional) An object containing one or more
433          *      cookie options: path (a string), domain (a string), expires (a Date object),
434          *      secure (true/false), and raw (true/false). Setting raw to true indicates
435          *      that the cookie should not be URI encoded before being set.
436          * @return {String} The created cookie string.
437          * @method set
438          * @static
439          */
440         set : function (name, value, options) {
442             validateCookieName(name);   //throws error
444             if (isUndefined(value)){
445                 error("Cookie.set(): Value cannot be undefined.");
446             }
448             options = options || {};
450             var text = this._createCookieString(name, value, !options.raw, options);
451             doc.cookie = text;
452             return text;
453         },
455         /**
456          * Sets a sub cookie with a given name to a particular value.
457          * @param {String} name The name of the cookie to set.
458          * @param {String} subName The name of the subcookie to set.
459          * @param {Variant} value The value to set.
460          * @param {Object} options (Optional) An object containing one or more
461          *      cookie options: path (a string), domain (a string), expires (a Date object),
462          *      and secure (true/false).
463          * @return {String} The created cookie string.
464          * @method setSub
465          * @static
466          */
467         setSub : function (name, subName, value, options) {
469             validateCookieName(name);   //throws error
471             validateSubcookieName(subName);   //throws error
473             if (isUndefined(value)){
474                 error("Cookie.setSub(): Subcookie value cannot be undefined.");
475             }
477             var hash = this.getSubs(name);
479             if (!isObject(hash)){
480                 hash = {};
481             }
483             hash[subName] = value;
485             return this.setSubs(name, hash, options);
487         },
489         /**
490          * Sets a cookie with a given name to contain a hash of name-value pairs.
491          * @param {String} name The name of the cookie to set.
492          * @param {Object} value An object containing name-value pairs.
493          * @param {Object} options (Optional) An object containing one or more
494          *      cookie options: path (a string), domain (a string), expires (a Date object),
495          *      and secure (true/false).
496          * @return {String} The created cookie string.
497          * @method setSubs
498          * @static
499          */
500         setSubs : function (name, value, options) {
502             validateCookieName(name);   //throws error
504             if (!isObject(value)){
505                 error("Cookie.setSubs(): Cookie value must be an object.");
506             }
508             var text /*:String*/ = this._createCookieString(name, this._createCookieHashString(value), false, options);
509             doc.cookie = text;
510             return text;
511         }
513     };
516 }, '3.13.0', {"requires": ["yui-base"]});