root/trunk/Vanilla/templates/vanilla+authentication+userpics/javascript.mtml @ 915

Revision 915, 15.3 kB (checked in by bsmith, 16 months ago)

Adding js to check for #_login & #_logout

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