xref: /dokuwiki/lib/scripts/cookie.js (revision 99e7bfd4c733d81cd01dd2d97e10bb4dda62df66)
1/**
2* Handles the cookie used by several JavaScript functions
3*
4* Only a single cookie is written and read. You may only save
5* sime name-value pairs - no complex types!
6*
7* You should only use the getValue and setValue methods
8*
9* @author Andreas Gohr <andi@splitbrain.org>
10* @author Michal Rezler <m.rezler@centrum.cz>
11*/
12DokuCookie = {
13    data: Array(),
14    name: 'DOKU_PREFS',
15
16    /**
17     * Save a value to the cookie
18     *
19     * @author Andreas Gohr <andi@splitbrain.org>
20     */
21    setValue: function(key,val){
22        this.init();
23        this.data[key] = val;
24
25        // prepare expire date
26        var now = new Date();
27        this.fixDate(now);
28        now.setTime(now.getTime() + 365 * 24 * 60 * 60 * 1000); //expire in a year
29
30        //save the whole data array
31        var text = '';
32        for(var key in this.data){
33            if (!this.data.hasOwnProperty(key)) continue;
34            text += '#'+escape(key)+'#'+this.data[key];
35        }
36        this.setCookie(this.name,text.substr(1),now,DOKU_BASE);
37    },
38
39    /**
40     * Get a Value from the Cookie
41     *
42     * @author Andreas Gohr <andi@splitbrain.org>
43     */
44    getValue: function(key){
45        this.init();
46        return this.data[key];
47    },
48
49    /**
50     * Loads the current set cookie
51     *
52     * @author Andreas Gohr <andi@splitbrain.org>
53     */
54    init: function(){
55        if(this.data.length) return;
56        var text = this.getCookie(this.name);
57        if(text){
58            var parts = text.split('#');
59            for(var i=0; i<parts.length; i+=2){
60                this.data[unescape(parts[i])] = unescape(parts[i+1]);
61            }
62        }
63    },
64
65    /**
66     * This sets a cookie by JavaScript
67     *
68     * @link http://www.webreference.com/js/column8/functions.html
69     */
70    setCookie: function(name, value, expires_, path_, domain_, secure_) {
71        var params = {
72            expires: expires_,
73            path: path_,
74            domain: domain_,
75            secure: secure_,
76        };
77
78        jQuery.cookie(name, value, params);
79    },
80
81    /**
82     * This reads a cookie by JavaScript
83     *
84     * @link http://www.webreference.com/js/column8/functions.html
85     */
86    getCookie: function(name) {
87        return unescape(jQuery.cookie(name));
88    },
89
90    /**
91     * This is needed for the cookie functions
92     *
93     * @link http://www.webreference.com/js/column8/functions.html
94     */
95    fixDate: function(date) {
96        var base = new Date(0);
97        var skew = base.getTime();
98        if (skew > 0){
99            date.setTime(date.getTime() - skew);
100        }
101    }
102};
103