root/trunk/SimpleTemplateSets/templates/vanilla+authentication/javascript.mtml @ 891

Revision 891, 13.6 kB (checked in by bsmith, 16 months ago)

committing initial Vanilla sets

Line 
1<$mt:var name="user-auth" value="signin-content"$>
2
3/* section *****************************************************************/
4
5// The cookie name to use for storing the blog-side comment session cookie.
6var mtCookieName = "<$mt:UserSessionCookieName$>";
7var mtCookieDomain = "<$mt:UserSessionCookieDomain$>";
8var mtCookiePath = "<$mt:UserSessionCookiePath$>";
9var mtCookieTimeout = <$mt:UserSessionCookieTimeout$>;
10var is_preview;
11var user;
12
13<mt:Ignore>
14/***
15 * Issues a request to the MT comment script to retrieve the currently
16 * logged-in user (if any).
17 */
18</mt:Ignore>
19var mtFetchedUser = false;
20<mt:IfBlog>
21function mtFetchUser(cb) {
22    if (!cb) cb = 'mtSetUser';
23    if ( ( cb == 'mtSetUser' ) && mtGetUser() ) {
24        var url = document.URL;
25        url = url.replace(/#.+$/, '');
26        url += '#comments-open';
27        location.href = url;
28    } else {
29        // we aren't using AJAX for this, since we may have to request
30        // from a different domain. JSONP to the rescue.
31        mtFetchedUser = true;
32        var script = document.createElement('script');
33        var ts = new Date().getTime();
34        script.src = '<$mt:CGIPath$><$mt:CommentScript$>?__mode=session_js&blog_id=<$mt:BlogID$>&jsonp=' + cb + '&ts=' + ts;
35        (document.getElementsByTagName('head'))[0].appendChild(script);
36    }
37}
38</mt:IfBlog>
39
40<mt:Ignore>
41/***
42 * A routine that displays various phrases based upon users authenticated status
43 */
44</mt:Ignore>
45
46// <a href="#">Signin</a>
47// You are signed in as <a href="#">UserName</a> (<a href="#">Sign out</a>)
48// You do not have permission to sign in to this blog
49
50function mtUpdateSignInWidget(u) {
51    var el = document.getElementById('<$mt:var name="user-auth"$>');
52    var content = '';
53    var doit = 1;
54    if (!el) return;
55    if (u) {
56        if (u && u.is_authenticated) {
57            user = u;
58            mtSaveUser();
59        } else {
60            // user really isn't logged in; so let's do this!
61            return mtSignIn();
62        }
63    } else {
64        u = mtGetUser();
65    }
66    if (u && u.name) {
67        var url;
68        if (u.is_authenticated) {
69            if (u.is_author) {
70                url = '<$mt:CGIPath$><$mt:CommentScript$>?__mode=edit_profile&blog_id=<$mt:BlogID$>';
71                url += '&static=' + encodeURIComponent( location.href );
72            } else {
73                url = u.url;
74            }
75        } else if (u.url) {
76            url = u.url;
77        } else {
78            url = null;
79        }
80        var content = '<__trans phrase="You are signed in as " escape="js">';
81        if (url)
82            content += '<a href="' + url + '">' + u.name + '</a>';
83        else
84            content += u.name;
85        content += '.  (<a href="javascript:void(0)" onclick="return mtSignOutOnClick()"><__trans phrase="sign out" escape="js"></a>)';
86    } else if (u && u.is_banned) {
87        content = '<__trans phrase="You do not have permission to sign in to this blog." escape="js">';
88    } else {
89    //    content = '<a href="javascript:void(0)" onclick="return mtSignInOnClick(\'<$mt:var name="user-auth"$>\')"><__trans phrase="Sign In" escape="js"></a>';
90        doit = 0;
91    }
92    if (doit) {
93        el.innerHTML = content;
94    }
95}
96
97<mt:Ignore>
98/***
99 * Retrieves an object of the currently logged in user's state.
100 * If no user is logged in or cookied, this will return null.
101 */
102</mt:Ignore>
103function mtGetUser() {
104    if (!user) {
105        var cookie = mtGetCookie(mtCookieName);
106        if (!cookie) return;
107        user = mtUnbakeUserCookie(cookie);
108        if (! user) {
109            user = {};
110            user.is_anonymous = true;
111            user.can_post = false;
112            user.is_author = false;
113            user.is_banned = false;
114            user.is_trusted = false;
115        }
116    }
117    return user;
118}
119
120<mt:Ignore>
121/***
122 * Assigns a user object as the actively logged in user; also saves the
123 * user information in a browser cookie.
124 */
125</mt:Ignore>
126function mtSetUser(u) {
127    if (u) {
128        // persist this
129        user = u;
130        mtSaveUser();
131        // sync up user greeting
132        mtFireEvent('usersignin');
133    }
134}
135
136<mt:Ignore>
137/***
138 * Persists a copy of the current user cookie into the browser cookie stash.
139 */
140</mt:Ignore>
141function mtSaveUser(f) {
142    // We can't reliably store the user cookie during a preview.
143    if (is_preview) return;
144
145    var u = mtGetUser();
146
147    if (f && (!u || u.is_anonymous)) {
148        if ( !u ) {
149            u = {};
150            u.is_authenticated = false;
151            u.can_comment = true;
152            u.is_author = false;
153            u.is_banned = false;
154            u.is_anonymous = true;
155            u.is_trusted = false;
156        }
157        if (f.author != undefined) u.name = f.author.value;
158        if (f.email != undefined) u.email = f.email.value;
159        if (f.url != undefined) u.url = f.url.value;
160    }
161
162    if (!u) return;
163
164    var cache_period = mtCookieTimeout * 1000;
165
166    // cache anonymous user info for a long period if the
167    // user has requested to be remembered
168    if (u.is_anonymous && f && f.bakecookie && f.bakecookie.checked)
169        cache_period = 365 * 24 * 60 * 60 * 1000;
170
171    var now = new Date();
172    mtFixDate(now);
173    now.setTime(now.getTime() + cache_period);
174
175    var cmtcookie = mtBakeUserCookie(u);
176    mtSetCookie(mtCookieName, cmtcookie, now, mtCookiePath, mtCookieDomain,
177        location.protocol == 'https:');
178}
179
180<mt:Ignore>
181/***
182 * Handles the action of the "Sign in" link. First clears any existing
183 * user cookie, then directs to the MT comment script to sign the user in.
184 */
185</mt:Ignore>
186function mtSignIn() {
187    var doc_url = document.URL;
188    doc_url = doc_url.replace(/#.+/, '');
189    var url = '<$mt:SignInLink$>';
190    if (is_preview) {
191        if ( document['comments_form'] ) {
192            var entry_id = document['comments_form'].entry_id.value;
193            url += '&entry_id=' + entry_id;
194        } else {
195            url += '&return_url=<$mt:BlogURL encode_url="1"$>';
196        }
197    } else {
198        url += '&return_url=' + encodeURIComponent(doc_url);
199    }
200    mtClearUser();
201    location.href = url;
202}
203
204function mtSignInOnClick(sign_in_element) {
205    var el;
206    if (sign_in_element) {
207        // display throbber
208        el = document.getElementById(sign_in_element);
209        if (!el)  // legacy MT 4.x element id
210            el = document.getElementById('comment-form-external-auth');
211    }
212    if (el)
213        el.innerHTML = '<__trans phrase="Signing in..." escape="js"> <span class="status-indicator">&nbsp;</span>';
214
215    mtClearUser(); // clear any 'anonymous' user cookie to allow sign in
216    mtFetchUser('mtSetUserOrLogin');
217    return false;
218}
219
220function mtSetUserOrLogin(u) {
221    if (u && u.is_authenticated) {
222        mtSetUser(u);
223    } else {
224        // user really isn't logged in; so let's do this!
225        mtSignIn();
226    }
227}
228
229<mt:Ignore>
230/***
231 * Handles sign out from the web site.
232 * First clears any existing user cookie, then direts to the MT comment
233 * script to sign the user out.
234 */
235</mt:Ignore>
236function mtSignOut(entry_id) {
237    mtClearUser();
238    var doc_url = document.URL;
239    doc_url = doc_url.replace(/#.+/, '');
240    var url = '<$mt:SignOutLink$>';
241    if (is_preview) {
242        if ( document['comments_form'] ) {
243            var entry_id = document['comments_form'].entry_id.value;
244            url += '&entry_id=' + entry_id;
245        } else {
246            url += '&return_url=<$mt:BlogURL encode_url="1"$>';
247        }
248    } else {
249        url += '&return_url=' + encodeURIComponent(doc_url);
250    }
251    location.href = url;
252}
253
254<mt:Ignore>
255/***
256 * Handles the action of the "Sign out" link.
257 */
258</mt:Ignore>
259function mtSignOutOnClick() {
260    mtSignOut();
261    return false;
262}
263
264
265
266/* Cookie *****************************************************************/
267
268<mt:Ignore>
269/***
270 * Persists a copy of the current user cookie into the browser cookie stash.
271 */
272</mt:Ignore>
273function mtSaveUser(f) {
274    // We can't reliably store the user cookie during a preview.
275    if (is_preview) return;
276
277    var u = mtGetUser();
278
279    if (f && (!u || u.is_anonymous)) {
280        if ( !u ) {
281            u = {};
282            u.is_authenticated = false;
283            u.can_comment = true;
284            u.is_author = false;
285            u.is_banned = false;
286            u.is_anonymous = true;
287            u.is_trusted = false;
288        }
289        if (f.author != undefined) u.name = f.author.value;
290        if (f.email != undefined) u.email = f.email.value;
291        if (f.url != undefined) u.url = f.url.value;
292    }
293
294    if (!u) return;
295
296    var cache_period = mtCookieTimeout * 1000;
297
298    // cache anonymous user info for a long period if the
299    // user has requested to be remembered
300    if (u.is_anonymous && f && f.bakecookie && f.bakecookie.checked)
301        cache_period = 365 * 24 * 60 * 60 * 1000;
302
303    var now = new Date();
304    mtFixDate(now);
305    now.setTime(now.getTime() + cache_period);
306
307    var cmtcookie = mtBakeUserCookie(u);
308    mtSetCookie(mtCookieName, cmtcookie, now, mtCookiePath, mtCookieDomain,
309        location.protocol == 'https:');
310}
311
312<mt:Ignore>
313/***
314 * Clears the blog-side user cookie.
315 */
316</mt:Ignore>
317function mtClearUser() {
318    user = null;
319    mtDeleteCookie(mtCookieName, mtCookiePath, mtCookieDomain,
320        location.protocol == 'https:');
321}
322
323<mt:Ignore>
324/***
325 * Sets a browser cookie.
326 */
327</mt:Ignore>
328function mtSetCookie(name, value, expires, path, domain, secure) {
329    if (domain && domain.match(/^\.?localhost$/))
330        domain = null;
331    var curCookie = name + "=" + escape(value) +
332        (expires ? "; expires=" + expires.toGMTString() : "") +
333        (path ? "; path=" + path : "") +
334        (domain ? "; domain=" + domain : "") +
335        (secure ? "; secure" : "");
336    document.cookie = curCookie;
337}
338
339<mt:Ignore>
340/***
341 * Retrieves a browser cookie.
342 */
343</mt:Ignore>
344function mtGetCookie(name) {
345    var prefix = name + '=';
346    var c = document.cookie;
347    var cookieStartIndex = c.indexOf(prefix);
348    if (cookieStartIndex == -1)
349        return '';
350    var cookieEndIndex = c.indexOf(";", cookieStartIndex + prefix.length);
351    if (cookieEndIndex == -1)
352        cookieEndIndex = c.length;
353    return unescape(c.substring(cookieStartIndex + prefix.length, cookieEndIndex));
354}
355
356<mt:Ignore>
357/***
358 * Deletes a browser cookie.
359 */
360</mt:Ignore>
361function mtDeleteCookie(name, path, domain, secure) {
362    if (mtGetCookie(name)) {
363        if (domain && domain.match(/^\.?localhost$/))
364            domain = null;
365        document.cookie = name + "=" +
366            (path ? "; path=" + path : "") +
367            (domain ? "; domain=" + domain : "") +
368            (secure ? "; secure" : "") +
369            "; expires=Thu, 01-Jan-70 00:00:01 GMT";
370    }
371}
372
373<mt:Ignore>
374/***
375 * Serializes a user object into a string, suitable for storing as a cookie.
376 */
377</mt:Ignore>
378function mtBakeUserCookie(u) {
379    var str = "";
380    if (u.name) str += "name:'" + mtEscapeJS(u.name) + "';";
381    if (u.url) str += "url:'" + mtEscapeJS(u.url) + "';";
382    if (u.email) str += "email:'" + mtEscapeJS(u.email) + "';";
383    if (u.auth_type) str += "auth_type:'" + u.auth_type + "';";
384    if (u.is_authenticated) str += "is_authenticated:'1';";
385    if (u.profile) str += "profile:'" + mtEscapeJS(u.profile) + "';";
386    if (u.userpic) str += "userpic:'" + mtEscapeJS(u.userpic) + "';";
387    if (u.sid) str += "sid:'" + mtEscapeJS(u.sid) + "';";
388    str += "is_trusted:'" + (u.is_trusted ? "1" : "0") + "';";
389    str += "is_author:'" + (u.is_author ? "1" : "0") + "';";
390    str += "is_banned:'" + (u.is_banned ? "1" : "0") + "';";
391    str += "can_post:'" + (u.can_post ? "1" : "0") + "';";
392    str += "can_comment:'" + (u.can_comment ? "1" : "0") + "';";
393    str = str.replace(/;$/, '');
394    return str;
395}
396
397<mt:Ignore>
398/***
399 * Unserializes a user cookie and returns a user object with the restored
400 * state.
401 */
402</mt:Ignore>
403function mtUnbakeUserCookie(s) {
404    if (!s) return;
405
406    var u = {};
407    var m;
408    while (m = s.match(/^((name|url|email|auth_type|is_authenticated|profile|userpic|sid|is_trusted|is_author|is_banned|can_post|can_comment):'([^']+?)';?)/)) {
409        s = s.substring(m[1].length);
410        if (m[2].match(/^(is|can)_/)) // boolean fields
411            u[m[2]] = m[3] == '1' ? true : false;
412        else
413            u[m[2]] = mtUnescapeJS(m[3]);
414    }
415    if (u.is_authenticated) {
416        u.is_anonymous = false;
417    } else {
418        u.is_anonymous = true;
419        u.can_post = false;
420        u.is_author = false;
421        u.is_banned = false;
422        u.is_trusted = false;
423    }
424    return u;
425}
426
427/* Utility Functions *****************************************************************/
428
429<mt:Ignore>
430/***
431 * Calls the event named, if there are handlers for it.
432 */
433</mt:Ignore>
434function mtFireEvent(eventName,param) {
435    var fn = window['on' + eventName];
436    if (typeof fn == 'function') return fn(param);
437    return;
438}
439
440function mtFixDate(date) {
441    var skew = (new Date(0)).getTime();
442    if (skew > 0)
443        date.setTime(date.getTime() - skew);
444}
445
446<mt:Ignore>
447/***
448 * Simple function that escapes single quote characters for storing
449 * in a cookie.
450 */
451</mt:Ignore>
452function mtEscapeJS(s) {
453    s = s.replace(/'/g, "&apos;");
454    return s;
455}
456
457<mt:Ignore>
458/***
459 * Simple function that unescapes single quote characters that were
460 * stored in a cookie.
461 */
462</mt:Ignore>
463function mtUnescapeJS(s) {
464    s = s.replace(/&apos;/g, "'");
465    return s;
466}
467
468<mt:Ignore>
469/***
470 * A utility function for assigning/adding handlers to window events.
471 */
472</mt:Ignore>
473function mtAttachEvent(eventName,func) {
474    var onEventName = 'on' + eventName;
475    var old = window[onEventName];
476    if( typeof old != 'function' )
477        window[onEventName] = func;
478    else {
479        window[onEventName] = function( evt ) {
480            old( evt );
481            return func( evt );
482        };
483    }
484}
485
486/* section *****************************************************************/
Note: See TracBrowser for help on using the browser.