root/trunk/Vanilla/templates/vanilla+search+tags/javascript.mtml @ 924

Revision 924, 14.9 kB (checked in by bsmith, 16 months ago)

adding vanilla+search+tags

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 * Handles the action of the "Sign in" link. First clears any existing
184 * user cookie, then directs to the MT comment script to sign the user in.
185 */
186</mt:Ignore>
187function mtSignIn() {
188    var doc_url = document.URL;
189    doc_url = doc_url.replace(/#.+/, '');
190    var url = '<$mt:SignInLink$>';
191    if (is_preview) {
192        if ( document['comments_form'] ) {
193            var entry_id = document['comments_form'].entry_id.value;
194            url += '&entry_id=' + entry_id;
195        } else {
196            url += '&return_url=<$mt:BlogURL encode_url="1"$>';
197        }
198    } else {
199        url += '&return_url=' + encodeURIComponent(doc_url);
200    }
201    mtClearUser();
202    location.href = url;
203}
204
205function mtSignInOnClick(sign_in_element) {
206    var el;
207    if (sign_in_element) {
208        // display throbber
209        el = document.getElementById(sign_in_element);
210        if (!el)  // legacy MT 4.x element id
211            el = document.getElementById('comment-form-external-auth');
212    }
213    if (el)
214        el.innerHTML = '<__trans phrase="Signing in..." escape="js"> <span class="status-indicator">&nbsp;</span>';
215
216    mtClearUser(); // clear any 'anonymous' user cookie to allow sign in
217    mtFetchUser('mtSetUserOrLogin');
218    return false;
219}
220
221function mtSetUserOrLogin(u) {
222    if (u && u.is_authenticated) {
223        mtSetUser(u);
224    } else {
225        // user really isn't logged in; so let's do this!
226        mtSignIn();
227    }
228}
229
230<mt:Ignore>
231/***
232 * Handles sign out from the web site.
233 * First clears any existing user cookie, then direts to the MT comment
234 * script to sign the user out.
235 */
236</mt:Ignore>
237function mtSignOut(entry_id) {
238    mtClearUser();
239    var doc_url = document.URL;
240    doc_url = doc_url.replace(/#.+/, '');
241    var url = '<$mt:SignOutLink$>';
242    if (is_preview) {
243        if ( document['comments_form'] ) {
244            var entry_id = document['comments_form'].entry_id.value;
245            url += '&entry_id=' + entry_id;
246        } else {
247            url += '&return_url=<$mt:BlogURL encode_url="1"$>';
248        }
249    } else {
250        url += '&return_url=' + encodeURIComponent(doc_url);
251    }
252    location.href = url;
253}
254
255<mt:Ignore>
256/***
257 * Handles the action of the "Sign out" link.
258 */
259</mt:Ignore>
260function mtSignOutOnClick() {
261    mtSignOut();
262    return false;
263}
264
265
266
267/* Cookie *****************************************************************/
268
269<mt:Ignore>
270/***
271 * Persists a copy of the current user cookie into the browser cookie stash.
272 */
273</mt:Ignore>
274function mtSaveUser(f) {
275    // We can't reliably store the user cookie during a preview.
276    if (is_preview) return;
277
278    var u = mtGetUser();
279
280    if (f && (!u || u.is_anonymous)) {
281        if ( !u ) {
282            u = {};
283            u.is_authenticated = false;
284            u.can_comment = true;
285            u.is_author = false;
286            u.is_banned = false;
287            u.is_anonymous = true;
288            u.is_trusted = false;
289        }
290        if (f.author != undefined) u.name = f.author.value;
291        if (f.email != undefined) u.email = f.email.value;
292        if (f.url != undefined) u.url = f.url.value;
293    }
294
295    if (!u) return;
296
297    var cache_period = mtCookieTimeout * 1000;
298
299    // cache anonymous user info for a long period if the
300    // user has requested to be remembered
301    if (u.is_anonymous && f && f.bakecookie && f.bakecookie.checked)
302        cache_period = 365 * 24 * 60 * 60 * 1000;
303
304    var now = new Date();
305    mtFixDate(now);
306    now.setTime(now.getTime() + cache_period);
307
308    var cmtcookie = mtBakeUserCookie(u);
309    mtSetCookie(mtCookieName, cmtcookie, now, mtCookiePath, mtCookieDomain,
310        location.protocol == 'https:');
311}
312
313<mt:Ignore>
314/***
315 * Clears the blog-side user cookie.
316 */
317</mt:Ignore>
318function mtClearUser() {
319    user = null;
320    mtDeleteCookie(mtCookieName, mtCookiePath, mtCookieDomain,
321        location.protocol == 'https:');
322}
323
324<mt:Ignore>
325/***
326 * Sets a browser cookie.
327 */
328</mt:Ignore>
329function mtSetCookie(name, value, expires, path, domain, secure) {
330    if (domain && domain.match(/^\.?localhost$/))
331        domain = null;
332    var curCookie = name + "=" + escape(value) +
333        (expires ? "; expires=" + expires.toGMTString() : "") +
334        (path ? "; path=" + path : "") +
335        (domain ? "; domain=" + domain : "") +
336        (secure ? "; secure" : "");
337    document.cookie = curCookie;
338}
339
340<mt:Ignore>
341/***
342 * Retrieves a browser cookie.
343 */
344</mt:Ignore>
345function mtGetCookie(name) {
346    var prefix = name + '=';
347    var c = document.cookie;
348    var cookieStartIndex = c.indexOf(prefix);
349    if (cookieStartIndex == -1)
350        return '';
351    var cookieEndIndex = c.indexOf(";", cookieStartIndex + prefix.length);
352    if (cookieEndIndex == -1)
353        cookieEndIndex = c.length;
354    return unescape(c.substring(cookieStartIndex + prefix.length, cookieEndIndex));
355}
356
357<mt:Ignore>
358/***
359 * Deletes a browser cookie.
360 */
361</mt:Ignore>
362function mtDeleteCookie(name, path, domain, secure) {
363    if (mtGetCookie(name)) {
364        if (domain && domain.match(/^\.?localhost$/))
365            domain = null;
366        document.cookie = name + "=" +
367            (path ? "; path=" + path : "") +
368            (domain ? "; domain=" + domain : "") +
369            (secure ? "; secure" : "") +
370            "; expires=Thu, 01-Jan-70 00:00:01 GMT";
371    }
372}
373
374<mt:Ignore>
375/***
376 * Serializes a user object into a string, suitable for storing as a cookie.
377 */
378</mt:Ignore>
379function mtBakeUserCookie(u) {
380    var str = "";
381    if (u.name) str += "name:'" + mtEscapeJS(u.name) + "';";
382    if (u.url) str += "url:'" + mtEscapeJS(u.url) + "';";
383    if (u.email) str += "email:'" + mtEscapeJS(u.email) + "';";
384    if (u.auth_type) str += "auth_type:'" + u.auth_type + "';";
385    if (u.is_authenticated) str += "is_authenticated:'1';";
386    if (u.profile) str += "profile:'" + mtEscapeJS(u.profile) + "';";
387    if (u.userpic) str += "userpic:'" + mtEscapeJS(u.userpic) + "';";
388    if (u.sid) str += "sid:'" + mtEscapeJS(u.sid) + "';";
389    str += "is_trusted:'" + (u.is_trusted ? "1" : "0") + "';";
390    str += "is_author:'" + (u.is_author ? "1" : "0") + "';";
391    str += "is_banned:'" + (u.is_banned ? "1" : "0") + "';";
392    str += "can_post:'" + (u.can_post ? "1" : "0") + "';";
393    str += "can_comment:'" + (u.can_comment ? "1" : "0") + "';";
394    str = str.replace(/;$/, '');
395    return str;
396}
397
398<mt:Ignore>
399/***
400 * Unserializes a user cookie and returns a user object with the restored
401 * state.
402 */
403</mt:Ignore>
404function mtUnbakeUserCookie(s) {
405    if (!s) return;
406
407    var u = {};
408    var m;
409    while (m = s.match(/^((name|url|email|auth_type|is_authenticated|profile|userpic|sid|is_trusted|is_author|is_banned|can_post|can_comment):'([^']+?)';?)/)) {
410        s = s.substring(m[1].length);
411        if (m[2].match(/^(is|can)_/)) // boolean fields
412            u[m[2]] = m[3] == '1' ? true : false;
413        else
414            u[m[2]] = mtUnescapeJS(m[3]);
415    }
416    if (u.is_authenticated) {
417        u.is_anonymous = false;
418    } else {
419        u.is_anonymous = true;
420        u.can_post = false;
421        u.is_author = false;
422        u.is_banned = false;
423        u.is_trusted = false;
424    }
425    return u;
426}
427
428/* Utility Functions *****************************************************************/
429
430<mt:Ignore>
431/***
432 * Calls the event named, if there are handlers for it.
433 */
434</mt:Ignore>
435function mtFireEvent(eventName,param) {
436    var fn = window['on' + eventName];
437    if (typeof fn == 'function') return fn(param);
438    return;
439}
440
441function mtFixDate(date) {
442    var skew = (new Date(0)).getTime();
443    if (skew > 0)
444        date.setTime(date.getTime() - skew);
445}
446
447<mt:Ignore>
448/***
449 * Simple function that escapes single quote characters for storing
450 * in a cookie.
451 */
452</mt:Ignore>
453function mtEscapeJS(s) {
454    s = s.replace(/'/g, "&apos;");
455    return s;
456}
457
458<mt:Ignore>
459/***
460 * Simple function that unescapes single quote characters that were
461 * stored in a cookie.
462 */
463</mt:Ignore>
464function mtUnescapeJS(s) {
465    s = s.replace(/&apos;/g, "'");
466    return s;
467}
468
469<mt:Ignore>
470/***
471 * A utility function for assigning/adding handlers to window events.
472 */
473</mt:Ignore>
474function mtAttachEvent(eventName,func) {
475    var onEventName = 'on' + eventName;
476    var old = window[onEventName];
477    if( typeof old != 'function' )
478        window[onEventName] = func;
479    else {
480        window[onEventName] = function( evt ) {
481            old( evt );
482            return func( evt );
483        };
484    }
485}
486
487/* section *****************************************************************/
488
489/* Ajax Requests *****************************************************************/
490
491<mt:Ignore>
492/***
493 * Returns a XMLHttpRequest object (for Ajax operations).
494 */
495</mt:Ignore>
496function mtGetXmlHttp() {
497    if ( !window.XMLHttpRequest ) {
498        window.XMLHttpRequest = function() {
499            var types = [
500                "Microsoft.XMLHTTP",
501                "MSXML2.XMLHTTP.5.0",
502                "MSXML2.XMLHTTP.4.0",
503                "MSXML2.XMLHTTP.3.0",
504                "MSXML2.XMLHTTP"
505            ];
506
507            for ( var i = 0; i < types.length; i++ ) {
508                try {
509                    return new ActiveXObject( types[ i ] );
510                } catch( e ) {}
511            }
512
513            return undefined;
514        };
515    }
516    if ( window.XMLHttpRequest )
517        return new XMLHttpRequest();
518}
Note: See TracBrowser for help on using the browser.