Merge more javascript files.
[platal.git] / htdocs / javascript / xorg.js
1 /***************************************************************************
2 * Copyright (C) 2003-2011 Polytechnique.org *
3 * http://opensource.polytechnique.org/ *
4 * *
5 * This program is free software; you can redistribute it and/or modify *
6 * it under the terms of the GNU General Public License as published by *
7 * the Free Software Foundation; either version 2 of the License, or *
8 * (at your option) any later version. *
9 * *
10 * This program is distributed in the hope that it will be useful, *
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
13 * GNU General Public License for more details. *
14 * *
15 * You should have received a copy of the GNU General Public License *
16 * along with this program; if not, write to the Free Software *
17 * Foundation, Inc., *
18 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *
19 ***************************************************************************/
20
21 var is_IE = $.browser.msie;
22
23 // {{{ function getNow()
24 var days = ['Dimanche', 'Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi'];
25 var months = ['janvier', 'février', 'mars', 'avril', 'mai', 'juin', 'juillet',
26 'août', 'septembre', 'octobre', 'novembre', 'décembre']
27
28 function getNow() {
29 var dt = new Date();
30 var dy = dt.getDay();
31 var mh = dt.getMonth();
32 var wd = dt.getDate();
33 var yr = dt.getYear();
34 if (yr<1000) yr += 1900;
35 var hr = dt.getHours();
36 var mi = dt.getMinutes();
37 if (mi < 10) {
38 mi = '0' + mi;
39 }
40 var se = dt.getSeconds();
41 if (se < 10) {
42 se = '0' + se;
43 }
44
45 $(".date-heure").html(days[dy] + ' ' + wd + ' ' + months[mh] + ' ' + yr + '<br />'
46 + hr + ':' + mi + ':' + se);
47 }
48
49 // }}}
50 // {{{ Search Engine
51
52 function canAddSearchEngine()
53 {
54 if (((typeof window.sidebar == "object") && $.isFunction(window.sidebar.addSearchEngine))
55 || ((typeof window.external == "object") && $.isFunction(window.external.AddSearchProvider))) {
56 return true;
57 }
58 return false;
59 }
60
61 function addSearchEngine()
62 {
63 var searchURI = "http://www.polytechnique.org/xorg.opensearch.xml";
64 if ((typeof window.sidebar == "object") && $.isFunction(window.sidebar.addSearchEngine)) {
65 window.sidebar.addSearchEngine(
66 searchURI,
67 "http://www.polytechnique.org/images/xorg.png",
68 "Annuaire Polytechnique.org",
69 "Academic");
70 } else {
71 try {
72 window.external.AddSearchProvider(searchURI);
73 } catch(e) {
74 alert("Impossible d'installer la barre de recherche");
75 }
76 }
77 }
78
79 // }}}
80
81 /***************************************************************************
82 * POPUP THINGS
83 */
84
85 // {{{ function goodiesPopup()
86
87 var __goodies_active = true;
88
89 var __goodies_ical = {
90 default_title: 'Calendrier iCal',
91 sites: [
92 {'url_prefix': '',
93 'img': 'images/icons/calendar_view_day.gif',
94 'title': 'Calendrier iCal'},
95 {'url_prefix': 'http://www.google.com/calendar/render?cid=',
96 'img': 'images/goodies/add-google-calendar.gif',
97 'title': 'Ajouter à Google Calendar'},
98 {'url_prefix': 'https://www.google.com/calendar/hosted/polytechnique.org/render?cid=',
99 'img': 'images/goodies/add-google-calendar.gif',
100 'title': 'Ajouter à Google Apps / Calendar'}
101 ]
102 };
103
104 var __goodies_rss = {
105 default_title: 'Fils RSS',
106 sites: [
107 {'url_prefix': '',
108 'img': 'images/icons/feed.gif',
109 'title': 'Fil rss'},
110 {'url_prefix': 'http://fusion.google.com/add?feedurl=',
111 'img': 'images/goodies/add-google.gif',
112 'alt': 'Add to Google',
113 'title': 'Ajouter à iGoogle/Google Reader'},
114 {'url_prefix': 'http://www.netvibes.com/subscribe.php?url=',
115 'img': 'images/goodies/add-netvibes.gif',
116 'title': 'Ajouter à Netvibes'},
117 {'url_prefix': 'http://add.my.yahoo.com/content?.intl=fr&url=',
118 'img': 'images/goodies/add-yahoo.gif',
119 'alt': 'Add to My Yahoo!',
120 'title': 'Ajouter à My Yahoo!'}
121 ]
122 };
123
124 function disableGoodiesPopups() {
125 __goodies_active = false;
126 }
127
128 function goodiesPopup(node, goodies) {
129 var text = '<div style="text-align: center; line-height: 2.2">';
130 for (var site in goodies.sites) {
131 var entry = goodies.sites[site];
132 var s_alt = entry["alt"] ? entry["alt"] : "";
133 var s_img = entry["img"];
134 var s_title = entry["title"] ? entry["title"] : "";
135 var s_url = entry["url_prefix"].length > 0 ? entry["url_prefix"] + escape(this.href) : this.href;
136
137 text += '<a href="' + s_url + '"><img src="' + s_img + '" title="' + s_title + '" alt="' + s_alt + '"></a><br />';
138 }
139 text += '<a href="https://www.polytechnique.org/Xorg/Goodies">Plus de bonus</a> ...</div>';
140
141 var title = node.title ? node.title : goodies.default_title;
142
143 $(node)
144 .mouseover(
145 function() {
146 if (__goodies_active) {
147 return overlib(text, CAPTION, title, CLOSETEXT, 'Fermer', DELAY, 800, STICKY, WIDTH, 150);
148 }
149 }
150 )
151 .mouseout(nd);
152 }
153
154 // }}}
155 // {{{ function auto_links()
156
157 function auto_links() {
158 var url = document.URL;
159 var fqdn = url.replace(/^https?:\/\/([^\/]*)\/.*$/,'$1');
160 var light = (url.indexOf('display=light') > url.indexOf('?'));
161 var resource_page = (url.indexOf('rss') > -1 || url.indexOf('ical') > -1);
162
163 $("a,link").each(function(i) {
164 var node = $(this);
165 var href = this.href;
166 if(!href || node.hasClass('xdx')
167 || href.indexOf('mailto:') > -1 || href.indexOf('javascript:') > -1) {
168 return;
169 }
170 if ((href.indexOf(fqdn) < 0 && this.className.indexOf('popup') < 0) || node.hasClass('popup')) {
171 node.click(function () {
172 window.open(href);
173 return false;
174 });
175 }
176 if (href.indexOf(fqdn) > -1 && light) {
177 href = href.replace(/([^\#\?]*)\??([^\#]*)(\#.*)?/, "$1?display=light&$2$3");
178 this.href = href;
179 }
180 var rss = href.indexOf('rss') > -1;
181 var ical = href.indexOf('ical') > -1;
182 if (rss || ical) {
183 if (href.indexOf('http') < 0) {
184 href = 'http://' + fqdn + '/' + href;
185 }
186 }
187 if (this.nodeName.toLowerCase() == 'a' && !resource_page) {
188 if (rss && href.indexOf('prefs/rss') < 0 && (href.indexOf('xml') > -1 || href.indexOf('hash'))) {
189 goodiesPopup(this, __goodies_rss);
190 } else if (ical) {
191 goodiesPopup(this, __goodies_ical);
192 }
193 }
194 if(matches = (/^popup_([0-9]*)x([0-9]*)$/).exec(this.className)) {
195 var w = matches[1], h = matches[2];
196 node.popWin(w, h);
197 }
198 });
199 $('.popup2').popWin(840, 600);
200 $('.popup3').popWin(640, 800);
201 }
202
203
204 // }}}
205
206 /***************************************************************************
207 * Password check
208 */
209
210 // {{{ function checkPassword
211
212 /* {{{ SHA1 Implementation */
213
214 /*
215 * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined
216 * in FIPS PUB 180-1
217 * Version 2.1a Copyright Paul Johnston 2000 - 2002.
218 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
219 * Distributed under the BSD License
220 * See http://pajhome.org.uk/crypt/md5 for details.
221 */
222
223 /*
224 * Configurable variables. You may need to tweak these to be compatible with
225 * the server-side, but the defaults work in most cases.
226 */
227 var hexcase = 0; /* hex output format. 0 - lowercase; 1 - uppercase */
228 var b64pad = ""; /* base-64 pad character. "=" for strict RFC compliance */
229 var chrsz = 8; /* bits per input character. 8 - ASCII; 16 - Unicode */
230
231 /*
232 * These are the functions you'll usually want to call
233 * They take string arguments and return either hex or base-64 encoded strings
234 */
235 function hex_sha1(s){return binb2hex(core_sha1(str2binb(s),s.length * chrsz));}
236 function b64_sha1(s){return binb2b64(core_sha1(str2binb(s),s.length * chrsz));}
237 function str_sha1(s){return binb2str(core_sha1(str2binb(s),s.length * chrsz));}
238 function hex_hmac_sha1(key, data){ return binb2hex(core_hmac_sha1(key, data));}
239 function b64_hmac_sha1(key, data){ return binb2b64(core_hmac_sha1(key, data));}
240 function str_hmac_sha1(key, data){ return binb2str(core_hmac_sha1(key, data));}
241
242 /*
243 * Perform a simple self-test to see if the VM is working
244 */
245 function sha1_vm_test()
246 {
247 return hex_sha1("abc") == "a9993e364706816aba3e25717850c26c9cd0d89d";
248 }
249
250 /*
251 * Calculate the SHA-1 of an array of big-endian words, and a bit length
252 */
253 function core_sha1(x, len)
254 {
255 /* append padding */
256 x[len >> 5] |= 0x80 << (24 - len % 32);
257 x[((len + 64 >> 9) << 4) + 15] = len;
258
259 var w = Array(80);
260 var a = 1732584193;
261 var b = -271733879;
262 var c = -1732584194;
263 var d = 271733878;
264 var e = -1009589776;
265
266 for(var i = 0; i < x.length; i += 16)
267 {
268 var olda = a;
269 var oldb = b;
270 var oldc = c;
271 var oldd = d;
272 var olde = e;
273
274 for(var j = 0; j < 80; j++)
275 {
276 if(j < 16) w[j] = x[i + j];
277 else w[j] = rol(w[j-3] ^ w[j-8] ^ w[j-14] ^ w[j-16], 1);
278 var t = safe_add(safe_add(rol(a, 5), sha1_ft(j, b, c, d)),
279 safe_add(safe_add(e, w[j]), sha1_kt(j)));
280 e = d;
281 d = c;
282 c = rol(b, 30);
283 b = a;
284 a = t;
285 }
286
287 a = safe_add(a, olda);
288 b = safe_add(b, oldb);
289 c = safe_add(c, oldc);
290 d = safe_add(d, oldd);
291 e = safe_add(e, olde);
292 }
293 return Array(a, b, c, d, e);
294
295 }
296
297 /*
298 * Perform the appropriate triplet combination function for the current
299 * iteration
300 */
301 function sha1_ft(t, b, c, d)
302 {
303 if(t < 20) return (b & c) | ((~b) & d);
304 if(t < 40) return b ^ c ^ d;
305 if(t < 60) return (b & c) | (b & d) | (c & d);
306 return b ^ c ^ d;
307 }
308
309 /*
310 * Determine the appropriate additive constant for the current iteration
311 */
312 function sha1_kt(t)
313 {
314 return (t < 20) ? 1518500249 : (t < 40) ? 1859775393 :
315 (t < 60) ? -1894007588 : -899497514;
316 }
317
318 /*
319 * Calculate the HMAC-SHA1 of a key and some data
320 */
321 function core_hmac_sha1(key, data)
322 {
323 var bkey = str2binb(key);
324 if(bkey.length > 16) bkey = core_sha1(bkey, key.length * chrsz);
325
326 var ipad = Array(16), opad = Array(16);
327 for(var i = 0; i < 16; i++)
328 {
329 ipad[i] = bkey[i] ^ 0x36363636;
330 opad[i] = bkey[i] ^ 0x5C5C5C5C;
331 }
332
333 var hash = core_sha1(ipad.concat(str2binb(data)), 512 + data.length * chrsz);
334 return core_sha1(opad.concat(hash), 512 + 160);
335 }
336
337 /*
338 * Add integers, wrapping at 2^32. This uses 16-bit operations internally
339 * to work around bugs in some JS interpreters.
340 */
341 function safe_add(x, y)
342 {
343 var lsw = (x & 0xFFFF) + (y & 0xFFFF);
344 var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
345 return (msw << 16) | (lsw & 0xFFFF);
346 }
347
348 /*
349 * Bitwise rotate a 32-bit number to the left.
350 */
351 function rol(num, cnt)
352 {
353 return (num << cnt) | (num >>> (32 - cnt));
354 }
355
356 /*
357 * Convert an 8-bit or 16-bit string to an array of big-endian words
358 * In 8-bit function, characters >255 have their hi-byte silently ignored.
359 */
360 function str2binb(str)
361 {
362 var bin = Array();
363 var mask = (1 << chrsz) - 1;
364 for(var i = 0; i < str.length * chrsz; i += chrsz)
365 bin[i>>5] |= (str.charCodeAt(i / chrsz) & mask) << (32 - chrsz - i%32);
366 return bin;
367 }
368
369 /*
370 * Convert an array of big-endian words to a string
371 */
372 function binb2str(bin)
373 {
374 var str = "";
375 var mask = (1 << chrsz) - 1;
376 for(var i = 0; i < bin.length * 32; i += chrsz)
377 str += String.fromCharCode((bin[i>>5] >>> (32 - chrsz - i%32)) & mask);
378 return str;
379 }
380
381 /*
382 * Convert an array of big-endian words to a hex string.
383 */
384 function binb2hex(binarray)
385 {
386 var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
387 var str = "";
388 for(var i = 0; i < binarray.length * 4; i++)
389 {
390 str += hex_tab.charAt((binarray[i>>2] >> ((3 - i%4)*8+4)) & 0xF) +
391 hex_tab.charAt((binarray[i>>2] >> ((3 - i%4)*8 )) & 0xF);
392 }
393 return str;
394 }
395
396 /*
397 * Convert an array of big-endian words to a base-64 string
398 */
399 function binb2b64(binarray)
400 {
401 var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
402 var str = "";
403 for(var i = 0; i < binarray.length * 4; i += 3)
404 {
405 var triplet = (((binarray[i >> 2] >> 8 * (3 - i %4)) & 0xFF) << 16)
406 | (((binarray[i+1 >> 2] >> 8 * (3 - (i+1)%4)) & 0xFF) << 8 )
407 | ((binarray[i+2 >> 2] >> 8 * (3 - (i+2)%4)) & 0xFF);
408 for(var j = 0; j < 4; j++)
409 {
410 if(i * 8 + j * 6 > binarray.length * 32) str += b64pad;
411 else str += tab.charAt((triplet >> 6*(3-j)) & 0x3F);
412 }
413 }
414 return str;
415 }
416
417 /* }}} */
418
419 function hash_encrypt(a) {
420 return hex_sha1(a);
421 }
422
423 var hexa_h = "0123456789abcdef";
424
425 function dechex(a) {
426 return hexa_h.charAt(a);
427 }
428
429 function hexdec(a) {
430 return hexa_h.indexOf(a);
431 }
432
433 function hash_xor(a, b) {
434 var c,i,j,k;
435 c = "";
436 i = a.length;
437 j = b.length;
438 if (i < j) {
439 var d;
440 d = a; a = b; b = d;
441 k = i; i = j; j = k;
442 }
443 for (k = 0; k < j; k++)
444 c += dechex(hexdec(a.charAt(k)) ^ hexdec(b.charAt(k)));
445 for (; k < i; k++)
446 c += a.charAt(k);
447 return c;
448 }
449
450
451 function getType(c) {
452 if (c >= 'a' && c <= 'z') {
453 return 1;
454 } else if (c >= 'A' && c <= 'Z') {
455 return 2;
456 } else if (c >= '0' && c <= '9') {
457 return 3;
458 } else {
459 return 4;
460 }
461 }
462
463 function differentTypes(password) {
464 var prev = 0;
465
466 for (i = 0 ; i < password.length ; ++i) {
467 var type = getType(password.charAt(i));
468 if (prev != 0 && prev != type) {
469 return true;
470 }
471 prev = type;
472 }
473 return false;
474 }
475
476 function passwordStrength(password) {
477 var prop = 0;
478 var prev = 0;
479 var firstType = true;
480 var types = Array(0, 0, 0, 0, 0);
481
482 for (i = 0 ; i < password.length ; ++i) {
483 var type = getType(password.charAt(i));
484 if (prev != 0 && prev != type) {
485 prop += 5;
486 firstType = false;
487 }
488 prop += i;
489 if (types[type] == 0 && !firstType) {
490 prop += 15;
491 }
492 types[type]++;
493 prev = type;
494 }
495 if (password.length < 6) {
496 prop *= 0.75;
497 }
498 if (firstType) {
499 prop *= 0.75;
500 }
501 if (prop > 100) {
502 prop = 100;
503 } else if (prop < 0) {
504 prop = 0;
505 }
506
507 return prop;
508 }
509
510 function checkPassword(box, okLabel) {
511 var password = box.value;
512 var prop = passwordStrength(password);
513
514 if (prop >= 60) {
515 color = "#4f4";
516 bgcolor = "#050";
517 ok = true;
518 } else if (prop >= 35) {
519 color = "#ff4";
520 bgcolor = "#750";
521 ok = true;
522 } else {
523 color = "#f20";
524 bgcolor = "#700";
525 ok = false;
526 }
527 $("#passwords_measure")
528 .stop()
529 .animate({ width: prop + "%",
530 backgroundColor: color
531 }, 750)
532 .parent().stop()
533 .animate({ backgroundColor: bgcolor }, 750);
534 var submitButton = $(":submit[name='" + passwordprompt_submit + "']");
535 if (ok && password.length >= 6 && differentTypes(password)) {
536 submitButton.attr("value", okLabel);
537 submitButton.removeAttr("disabled");
538 } else {
539 submitButton.attr("value", "Mot de passe trop faible");
540 submitButton.attr("disabled", "disabled");
541 }
542 }
543
544 function hashResponse(password1, password2, hasConfirmation) {
545 pw1 = $('[name=' + password1 + ']').val();
546
547 if (hasConfirmation) {
548 pw2 = $('[name=' + password2 + ']').val();
549 if (pw1 != pw2) {
550 alert("\nErreur : les deux champs ne sont pas identiques !");
551 return false;
552 }
553 $('[name=' + password2 + ']').val('');
554 } else if (pw1 == '********') {
555 return true;
556 }
557
558 if (pw1.length < 6) {
559 alert("\nErreur : le nouveau mot de passe doit faire au moins 6 caractères !");
560 return false;
561 }
562 if (!differentTypes(pw1)) {
563 alert ("\nErreur : le nouveau mot de passe doit comporter au moins deux types de caractères parmi les suivants : lettres minuscules, lettres majuscules, chiffres, caractères spéciaux.");
564 return false;
565 }
566
567 alert("Le mot de passe que tu as rentré va être chiffré avant de nous parvenir par Internet ! Ainsi il ne circulera pas en clair.");
568 $('[name=' + password1 + ']').val('');
569 $('[name=pwhash]').val(hash_encrypt(pw1));
570 return true;
571 }
572
573 function correctUserName() {
574 var u = document.forms.login.username;
575 // login with no space
576 if (u.value.indexOf(' ') < 0) return true;
577 var mots = u.value.split(' ');
578 // jean paul.du pont -> jean-paul.du-pont
579 if (u.value.indexOf('.') > 0) { u.value = mots.join('-'); return true; }
580 // jean dupont -> jean.dupont
581 if (mots.length == 2) { u.value = mots[0]+"."+mots[1]; return true; }
582 // jean dupont 2001 -> jean.dupont.2001
583 if (mots.length == 3 && mots[2] > 1920 && mots[2] < 3000) { u.value = mots.join('.'); return true; }
584 // jean de la vallee -> jean.de-la-vallee
585 if (mots[1].toUpperCase() == 'DE') { u.value = mots[0]+"."+mots.join('-').substr(mots[0].length+1); return true; }
586 // jean paul dupont -> jean-paul.dupont
587 if (mots.length == 3 && mots[0].toUpperCase() == 'JEAN') { u.value = mots[0]+"-"+mots[1]+"."+mots[2]; return true; }
588
589 alert('Ton email ne doit pas contenir de blanc.\nLe format standard est\n\nprenom.nom.promotion\n\nSi ton nom ou ton prenom est composé,\nsépare les mots par des -');
590
591 return false;
592 }
593
594 function doChallengeResponse() {
595
596 if (!correctUserName()) return false;
597
598 var new_pass = hash_encrypt(document.forms.login.password.value);
599 var old_pass = hash_encrypt(document.forms.login.password.value.substr(0, 10));
600
601 str = document.forms.login.username.value + ":" +
602 new_pass + ":" +
603 document.forms.loginsub.challenge.value;
604
605 document.forms.loginsub.response.value = hash_encrypt(str);
606 if (new_pass != old_pass) {
607 document.forms.loginsub.xorpass.value = hash_xor(new_pass, old_pass);
608 }
609 document.forms.loginsub.username.value = document.forms.login.username.value;
610 document.forms.loginsub.remember.value = document.forms.login.remember.checked;
611 document.forms.loginsub.domain.value = document.forms.login.domain.value;
612 document.forms.login.password.value = "";
613 document.forms.loginsub.submit();
614 }
615
616 function doChallengeResponseLogged() {
617 var new_pass = hash_encrypt(document.forms.login.password.value);
618
619 str = document.forms.loginsub.username.value + ":" +
620 hash_encrypt(document.forms.login.password.value) + ":" +
621 document.forms.loginsub.challenge.value;
622
623 document.forms.loginsub.response.value = hash_encrypt(str);
624 document.forms.loginsub.remember.value = document.forms.login.remember.checked;
625 document.forms.login.password.value = "";
626 document.forms.loginsub.submit();
627 }
628
629 // }}}
630 // {{{ send test email
631
632 function sendTestEmail(token, hruid)
633 {
634 var url = 'emails/test';
635 var msg = "Un email a été envoyé avec succès";
636 if (hruid != null) {
637 url += '/' + hruid;
638 msg += " sur l'adresse de " + hruid + ".";
639 } else {
640 msg += " sur ton addresse.";
641 }
642 $('#mail_sent').successMessage($url + '?token=' + token, msg);
643 return false;
644 }
645
646 // }}}
647
648
649 /***************************************************************************
650 * The real OnLoad
651 */
652
653 $(function() {
654 auto_links();
655 getNow();
656 setInterval(getNow, 1000);
657 $("#quick")
658 .focus(function() {
659 if ($(this).val() === 'Recherche dans l\'annuaire') {
660 $(this).val('');
661 }
662 $("#quick_button").show();
663 })
664 .blur(function() {
665 $("#quick_button").hide();
666 });
667 $("#quick_button").click(function() {
668 if ($("#quick").val() === 'Recherche dans l\'annuaire'
669 || $("#quick").val() === '') {
670 return false;
671 }
672 return true;
673 });
674 });
675
676 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8: