MOD cleanage
[euphorik.git] / js / euphorik.js
1 // coding: utf-8
2 // Copyright 2008 Grégory Burri
3 //
4 // This file is part of Euphorik.
5 //
6 // Euphorik is free software: you can redistribute it and/or modify
7 // it under the terms of the GNU General Public License as published by
8 // the Free Software Foundation, either version 3 of the License, or
9 // (at your option) any later version.
10 //
11 // Euphorik is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 // GNU General Public License for more details.
15 //
16 // You should have received a copy of the GNU General Public License
17 // along with Euphorik. If not, see <http://www.gnu.org/licenses/>.
18
19 /**
20 * Contient la base javascript pour le site euphorik.ch.
21 * Chaque page possède son propre fichier js nommé "page<nom de la page>.js".
22 * Auteur : GBurri
23 * Date : 6.11.2007
24 */
25
26
27 /**
28 * La configuration.
29 * Normalement 'const' à la place de 'var' mais non supporté par IE7.
30 */
31 var conf = {
32 nbMessageAffiche : 40, // (par page)
33 pseudoDefaut : "<nick>",
34 tempsAffichageMessageDialogue : 4000, // en ms
35 tempsKick : 15, // en minute
36 tempsBan : 60 * 24 * 3, // en minutes (3jours)
37 smiles : {
38 "smile" : [/:\)/g, /:-\)/g],
39 "bigsmile" : [/:D/g, /:-D/g],
40 "clin" : [/;\)/g, /;-\)/g],
41 "cool" : [/8\)/g, /8-\)/g],
42 "eheheh" : [/:P/g, /:-P/g],
43 "lol" : [/\[-lol\]/g],
44 "spliff" : [/\[-spliff\]/g],
45 "oh" : [/:o/g, /:O/g],
46 "heink" : [/\[-heink\]/g],
47 "hum" : [/\[-hum\]/g],
48 "boh" : [/\[-boh\]/g],
49 "sniff" : [/:\(/g, /:-\(/g],
50 "triste" : [/\[-triste\]/g],
51 "pascontent" : [/>\(/g, /&gt;\(/g],
52 "argn" : [/\[-argn\]/g],
53 "redface" : [/\[-redface\]/g],
54 "bunny" : [/\[-lapin\]/g],
55 "chat" : [/\[-chat\]/g],
56 "renne" : [/\[-renne\]/g],
57 "star" : [/\[-star\]/g],
58 "kirby" : [/\[-kirby\]/g],
59 "slurp" : [/\[-slurp\]/g],
60 "agreed" : [/\[-agreed\]/g],
61 "dodo" : [/\[-dodo\]/g],
62 "bn" : [/\[-bn\]/g]
63 }
64 }
65
66 ///////////////////////////////////////////////////////////////////////////////////////////////////
67
68 String.prototype.trim = function()
69 {
70 return jQuery.trim(this) // anciennement : this.replace(/^\s+|\s+$/g, "");
71 }
72
73 String.prototype.ltrim = function()
74 {
75 return this.replace(/^\s+/, "");
76 }
77
78 String.prototype.rtrim = function()
79 {
80 return this.replace(/\s+$/, "");
81 }
82
83 ///////////////////////////////////////////////////////////////////////////////////////////////////
84
85 /**
86 * Cette classe regroupe des fonctions utilitaires (helpers).
87 * @formateur est permet de formater les messages affichés à l'aide de messageDialogue (facultatif)
88 */
89 function Util(formateur)
90 {
91 $("#info .fermer").click(function(){
92 $("#info").slideUp(50)
93 })
94
95 $("body").append('<div id="flecheBulle"></div>').append('<div id="messageBulle"><p></p></div>')
96
97 this.formateur = formateur
98 this.bulleActive = true
99 }
100
101 var messageType = {informatif: 0, question: 1, erreur: 2}
102
103 /**
104 * Affiche une boite de dialogue avec un message à l'intérieur.
105 * @param message le message (string)
106 * @param type voir 'messageType'. par défaut messageType.informatif
107 * @param les boutons sous la forme d'un objet ou les clefs sont les labels des boutons
108 * et les valeurs les fonctions executées lorsqu'un bouton est activé.
109 * @param formate faut-il formaté le message ? true par défaut
110 */
111 Util.prototype.messageDialogue = function(message, type, boutons, formate)
112 {
113 var thisUtil = this
114
115 if (type == undefined)
116 type = messageType.informatif
117
118 if (formate == undefined)
119 formate = true
120
121 if (this.timeoutMessageDialogue != undefined)
122 clearTimeout(this.timeoutMessageDialogue)
123
124 var fermer = function(){$("#info").slideUp(100)}
125 fermer()
126
127 $("#info .message").html(thisUtil.formateur == undefined || !formate ? message : thisUtil.formateur.traitementComplet(message))
128 switch(type)
129 {
130 case messageType.informatif : $("#info #icone").attr("class", "information"); break
131 case messageType.question : $("#info #icone").attr("class", "interrogation"); break
132 case messageType.erreur : $("#info #icone").attr("class", "exclamation"); break
133 }
134 $("#info .boutons").html("")
135 for (var b in boutons)
136 $("#info .boutons").append("<div>" + b + "</div>").find("div:last").click(boutons[b]).click(fermer)
137
138 $("#info").slideDown(200)
139 this.timeoutMessageDialogue = setTimeout(fermer, conf.tempsAffichageMessageDialogue)
140 }
141
142 /**
143 * Affiche un info bulle lorsque le curseur survole l'élément donné.
144 * FIXME : le width de element ne tient pas compte du padding !?
145 */
146 Util.prototype.infoBulle = function(message, element)
147 {
148 var thisUtil = this
149
150 var cacherBulle = function()
151 {
152 $("#flecheBulle").hide()
153 $("#messageBulle").hide()
154 }
155
156 element.hover(
157 function(e)
158 {
159 if (!thisUtil.bulleActive)
160 return
161
162 var m = $("#messageBulle")
163 var f = $("#flecheBulle")
164
165 $("p", m).html(message)
166
167 var positionFleche = {
168 left : element.offset().left + element.width() / 2 - f.width() / 2,
169 top : element.offset().top - f.height()
170 }
171 var positionMessage = {
172 left : element.offset().left + element.width() / 2 - m.width() / 2,
173 top : element.offset().top - f.height() - m.height()
174 }
175 var depassementDroit = (positionMessage.left + m.width()) - $("body").width()
176 if (depassementDroit > 0)
177 positionMessage.left -= depassementDroit
178 else
179 {
180 if (positionMessage.left < 0)
181 positionMessage.left = 0
182 }
183
184 m.css("top", positionMessage.top).css("left", positionMessage.left).show()
185 f.css("top", positionFleche.top).css("left", positionFleche.left).show()
186 },
187 cacherBulle
188 ).click(cacherBulle)
189 }
190
191 /**
192 * Utilisé pour l'envoie de donnée avec la méthode ajax de jQuery.
193 */
194 Util.prototype.jsonVersAction = function(json)
195 {
196 return {action : JSON.stringify(json) }
197 }
198
199 Util.prototype.md5 = function(chaine)
200 {
201 return hex_md5(chaine)
202 }
203
204 // pompé de http://www.faqts.com/knowledge_base/view.phtml/aid/13562/fid/130
205 Util.prototype.setSelectionRange = function(input, selectionStart, selectionEnd)
206 {
207 if (input.setSelectionRange)
208 {
209 input.focus()
210 input.setSelectionRange(selectionStart, selectionEnd)
211 }
212 else if (input.createTextRange)
213 {
214 var range = input.createTextRange()
215 range.collapse(true)
216 range.moveEnd('character', selectionEnd)
217 range.moveStart('character', selectionStart)
218 range.select()
219 }
220 }
221
222 Util.prototype.setCaretToEnd = function(input)
223 {
224 this.setSelectionRange(input, input.value.length, input.value.length)
225 }
226 Util.prototype.setCaretToBegin = function(input)
227 {
228 this.setSelectionRange(input, 0, 0)
229 }
230 Util.prototype.setCaretToPos = function(input, pos)
231 {
232 this.setSelectionRange(input, pos, pos)
233 }
234 Util.prototype.selectString = function(input, string)
235 {
236 var match = new RegExp(string, "i").exec(input.value)
237 if (match)
238 {
239 this.setSelectionRange (input, match.index, match.index + match[0].length)
240 }
241 }
242 Util.prototype.replaceSelection = function(input, replaceString) {
243 if (input.setSelectionRange)
244 {
245 var selectionStart = input.selectionStart
246 var selectionEnd = input.selectionEnd
247 input.value = input.value.substring(0, selectionStart) + replaceString + input.value.substring(selectionEnd)
248
249 if (selectionStart != selectionEnd) // has there been a selection
250 this.setSelectionRange(input, selectionStart, selectionStart + replaceString.length)
251 else // set caret
252 this.setCaretToPos(input, selectionStart + replaceString.length)
253 }
254 else if (document.selection)
255 {
256 var range = document.selection.createRange();
257 if (range.parentElement() == input)
258 {
259 var isCollapsed = range.text == ''
260 range.text = replaceString
261 if (!isCollapsed)
262 {
263 // there has been a selection
264 // it appears range.select() should select the newly
265 // inserted text but that fails with IE
266 range.moveStart('character', -replaceString.length);
267 range.select();
268 }
269 }
270 }
271 }
272
273 Util.prototype.rot13 = function(chaine)
274 {
275 var ACode = 'A'.charCodeAt(0)
276 var aCode = 'a'.charCodeAt(0)
277 var MCode = 'M'.charCodeAt(0)
278 var mCode = 'm'.charCodeAt(0)
279 var ZCode = 'Z'.charCodeAt(0)
280 var zCode = 'z'.charCodeAt(0)
281
282 var f = function(ch, pos) {
283 if (pos == ch.length)
284 return ""
285
286 var c = ch.charCodeAt(pos);
287 return String.fromCharCode(
288 c +
289 (c >= ACode && c <= MCode || c >= aCode && c <= mCode ? 13 :
290 (c > MCode && c <= ZCode || c > mCode && c <= zCode ? -13 : 0))
291 ) + f(ch, pos + 1)
292 }
293 return f(chaine, 0)
294 }
295
296 ///////////////////////////////////////////////////////////////////////////////////////////////////
297
298 function Pages()
299 {
300 this.pageCourante = null
301 this.pages = {}
302 }
303
304 /**
305 * Accepte soit un objet soit un string.
306 * un string correspond au nom de la page, par exemple : "page" -> "page.html"
307 */
308 Pages.prototype.ajouterPage = function(page)
309 {
310 if (typeof page == "string")
311 {
312 this.pages[page] = page
313 }
314 else
315 {
316 page.pages = this // la magie des langages dynamiques : le foutoire
317 this.pages[page.nom] = page
318 }
319 }
320
321 Pages.prototype.afficherPage = function(nomPage, forcerChargement)
322 {
323 if (forcerChargement == undefined) forcerChargement = false
324
325 var page = this.pages[nomPage]
326 if (page == undefined || (!forcerChargement && page == this.pageCourante)) return
327
328 if (this.pageCourante != null && this.pageCourante.decharger)
329 this.pageCourante.decharger()
330
331 $("#menu li").removeClass("courante")
332 $("#menu li." + nomPage).addClass("courante")
333
334 this.pageCourante = page
335 var contenu = ""
336 if (typeof page == "string")
337 $.ajax({async: false, url: "pages/" + page + ".html", success : function(page) { contenu += page }})
338 else
339 contenu += this.pageCourante.contenu()
340 $("#page").html(contenu).removeClass().addClass(this.pageCourante.nom)
341
342 if (this.pageCourante.charger)
343 this.pageCourante.charger()
344 }
345
346 ///////////////////////////////////////////////////////////////////////////////////////////////////
347
348 /**
349 * Classe permettant de formater du texte par exemple pour la substitution des liens dans les
350 * message par "[url]".
351 * TODO : améliorer l'efficacité des méthods notamment lié au smiles.
352 */
353 function Formateur()
354 {
355 this.smiles = conf.smiles
356 this.protocoles = "http|https|ed2k"
357
358 this.regexUrl = new RegExp("(?:(?:" + this.protocoles + ")://|www\\.)[^ ]*", "gi")
359 this.regexImg = new RegExp("^.*?\\.(gif|jpg|png|jpeg|bmp|tiff)$", "i")
360 this.regexDomaine = new RegExp("^(?:(?:" + this.protocoles + ")://|www\\.).*?([^/.]+\\.[^/.]+)(?:$|/).*$", "i")
361 this.regexTestProtocoleExiste = new RegExp("^(?:" + this.protocoles + ")://.*$", "i")
362 this.regexNomProtocole = new RegExp("^(.*?)://")
363 }
364
365 /**
366 * Formate un pseudo saise par l'utilisateur.
367 * @param pseudo le pseudo brut
368 * @return le pseudo filtré
369 */
370 Formateur.prototype.filtrerInputPseudo = function(pseudo)
371 {
372 return pseudo.replace(/{|}/g, "").trim()
373 }
374
375 Formateur.prototype.getSmilesHTML = function()
376 {
377 var XHTML = ""
378 for (var sNom in this.smiles)
379 {
380 XHTML += "<img class=\"" + sNom + "\" src=\"img/smileys/" + sNom + ".gif\" alt =\"" + sNom + "\" />"
381 }
382 return XHTML
383 }
384
385 /**
386 * Formatage complet d'un texte.
387 * @M le message
388 * @pseudo facultatif, permet de contruire le label des images sous la forme : "<Pseudo> : <Message>"
389 */
390 Formateur.prototype.traitementComplet = function(M, pseudo)
391 {
392 return this.traiterLiensConv(this.traiterSmiles(this.traiterURL(this.traiterWikiSyntaxe(this.remplacerBalisesHTML(M)), pseudo)))
393 }
394
395 /**
396 * Transforme les liens en entités clickables.
397 * Un lien vers une conversation permet d'ouvrire celle ci, elle se marque comme ceci dans un message :
398 * "{5F}" ou 5F est la racine de la conversation.
399 * Ce lien sera transformer en <span class="lienConv">{5F}</span> pouvant être clické pour créer la conv 5F.
400 */
401 Formateur.prototype.traiterLiensConv = function(M)
402 {
403 return M.replace(
404 /\{\w+\}/g,
405 function(lien)
406 {
407 return "<span class=\"lienConv\">" + lien + "</span>"
408 }
409 )
410 }
411
412 /**
413 * FIXME : Cette méthode est attrocement lourde ! A optimiser.
414 * moyenne sur échantillon : 234ms
415 */
416 Formateur.prototype.traiterSmiles = function(M)
417 {
418 for (var sNom in this.smiles)
419 {
420 ss = this.smiles[sNom]
421 for (var i = 0; i < ss.length; i++)
422 M = M.replace(ss[i], "<img src=\"img/smileys/" + sNom + ".gif\" alt =\"" + sNom + "\" />")
423 }
424 return M
425 }
426
427 Formateur.prototype.remplacerBalisesHTML = function(M)
428 {
429 return M.replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;")
430 }
431
432 Formateur.prototype.traiterURL = function(M, pseudo)
433 {
434 thisFormateur = this
435
436 var traitementUrl = function(url)
437 {
438 // si ya pas de protocole on rajoute "http://"
439 if (!thisFormateur.regexTestProtocoleExiste.test(url))
440 url = "http://" + url
441 var extension = thisFormateur.getShort(url)
442 return "<a " + (extension[1] ? "title=\"" + (pseudo == undefined ? "" : thisFormateur.traiterPourFenetreLightBox(pseudo, url) + ": ") + thisFormateur.traiterPourFenetreLightBox(M, url) + "\"" + " rel=\"lightbox\"" : "") + " href=\"" + url + "\" >[" + extension[0] + "]</a>"
443 }
444 return M.replace(this.regexUrl, traitementUrl)
445 }
446
447 /**
448 * Formatage en utilisant un sous-ensemble des règles de mediwiki.
449 * par exemple ''italic'' devient <i>italic</i>
450 */
451 Formateur.prototype.traiterWikiSyntaxe = function(M)
452 {
453 return M.replace(
454 /'''(.*?)'''/g,
455 function(texte, capture)
456 {
457 return "<b>" + capture + "</b>"
458 }
459 ).replace(
460 /''(.*?)''/g,
461 function(texte, capture)
462 {
463 return "<i>" + capture + "</i>"
464 }
465 )
466 }
467
468 /**
469 * Renvoie une version courte de l'url.
470 * par exemple : http://en.wikipedia.org/wiki/Yakov_Smirnoff devient wikipedia.org
471 */
472 Formateur.prototype.getShort = function(url)
473 {
474 var estUneImage = false
475 var versionShort = null
476 var rechercheImg = this.regexImg.exec(url)
477
478 if (rechercheImg != null)
479 {
480 versionShort = rechercheImg[1].toLowerCase()
481 if (versionShort == "jpeg") versionShort = "jpg" // jpeg -> jpg
482 estUneImage = true
483 }
484 else
485 {
486 var rechercheDomaine = this.regexDomaine.exec(url)
487 if (rechercheDomaine != null && rechercheDomaine.length >= 2)
488 versionShort = rechercheDomaine[1]
489 else
490 {
491 var nomProtocole = this.regexNomProtocole.exec(url)
492 if (nomProtocole != null && nomProtocole.length >= 2)
493 versionShort = nomProtocole[1]
494 }
495 }
496
497 return [versionShort == null ? "url" : versionShort, estUneImage]
498 }
499
500 /**
501 * Traite les pseudo et messages à être affiché dans le titre d'une image visualisé avec lightbox.
502 */
503 Formateur.prototype.traiterPourFenetreLightBox = function(M, urlCourante)
504 {
505 thisFormateur = this
506 var traitementUrl = function(url)
507 {
508 return "[" + thisFormateur.getShort(url)[0] + (urlCourante == url ? "*" : "") + "]"
509 }
510
511 return this.remplacerBalisesHTML(M).replace(this.regexUrl, traitementUrl)
512 }
513
514
515 ///////////////////////////////////////////////////////////////////////////////////////////////////
516
517 // les statuts possibes du client
518 var statutType = {
519 // mode enregistré, peut poster des messages et modifier son profile
520 auth_registered : 0,
521 // mode identifié, peut poster des messages mais n'a pas accès au profile
522 auth_not_registered : 1,
523 // mode déconnecté, ne peut pas poster de message
524 deconnected : 2
525 }
526
527 function Client(util)
528 {
529 this.util = util
530
531 this.cookie = null
532 this.regexCookie = new RegExp("^cookie=([^;]*)")
533
534 // données personnels
535 this.resetDonneesPersonnelles()
536
537 this.setStatut(statutType.deconnected)
538
539 // si true alors chaque modification du client est mémorisé sur le serveur
540 this.autoflush = $.browser["opera"]
541 }
542
543 Client.prototype.resetDonneesPersonnelles = function()
544 {
545 this.id = 0
546 this.pseudo = conf.pseudoDefaut
547 this.login = ""
548 this.password = ""
549 this.email = ""
550 this.css = $("link#cssPrincipale").attr("href")
551 this.nickFormat = "nick"
552 this.viewTimes = true
553 this.viewTooltips = true
554 this.cookie = undefined
555
556 this.pagePrincipale = 1
557 this.ekMaster = false
558
559 // les conversations, une conversation est un objet possédant les attributs suivants :
560 // - racine (entier)
561 // - page (entier)
562 this.conversations = new Array()
563 }
564
565 Client.prototype.setCss = function(css)
566 {
567 if (this.css == css || css == "")
568 return
569
570 this.css = css
571 $("link#cssPrincipale").attr("href", this.css)
572 this.majMenu()
573
574 if (this.autoflush) this.flush(true)
575 }
576
577 Client.prototype.pageSuivante = function(numConv)
578 {
579 if (numConv < 0 && this.pagePrincipale > 1)
580 this.pagePrincipale -= 1
581 else if (this.conversations[numConv].page > 1)
582 this.conversations[numConv].page -= 1
583 }
584
585 Client.prototype.pagePrecedente = function(numConv)
586 {
587 if (numConv < 0)
588 this.pagePrincipale += 1
589 else
590 this.conversations[numConv].page += 1
591 }
592
593 /**
594 * Définit la première page pour la conversation donnée.
595 * @return true si la page a changé sinon false
596 */
597 Client.prototype.goPremierePage = function(numConv)
598 {
599 if (numConv < 0)
600 {
601 if (this.pagePrincipale == 1)
602 return false
603 this.pagePrincipale = 1
604 }
605 else
606 {
607 if (this.conversations[numConv].page == 1)
608 return false
609 this.conversations[numConv].page = 1
610 }
611 return true
612 }
613
614 /**
615 * Ajoute une conversation à la vue de l'utilisateur.
616 * Le profile de l'utilisateur est directement sauvegardé sur le serveur.
617 * @param racines la racine de la conversation (integer)
618 * @return true si la conversation a été créée sinon false (par exemple si la conv existe déjà)
619 */
620 Client.prototype.ajouterConversation = function(racine)
621 {
622 // vérification s'il elle n'existe pas déjà
623 for (var i = 0; i < this.conversations.length; i++)
624 if (this.conversations[i].root == racine)
625 return false
626
627 this.conversations.push({root : racine, page : 1})
628
629 if (this.autoflush) this.flush(true)
630
631 return true
632 }
633
634 Client.prototype.supprimerConversation = function(num)
635 {
636 if (num < 0 || num >= this.conversations.length) return
637
638 // décalage TODO : supprimer le dernier élément
639 for (var i = num; i < this.conversations.length - 1; i++)
640 this.conversations[i] = this.conversations[i+1]
641 this.conversations.pop()
642
643 if (this.autoflush) this.flush(true)
644 }
645
646 Client.prototype.getJSONLogin = function(login, password)
647 {
648 return {
649 "action" : "authentification",
650 "login" : login,
651 "password" : password
652 }
653 }
654
655 Client.prototype.getJSONLoginCookie = function()
656 {
657 return {
658 "action" : "authentification",
659 "cookie" : this.cookie
660 }
661 }
662
663 /**
664 * le couple (login, password) est facultatif. S'il n'est pas fournit alors il ne sera pas possible
665 * de s'autentifier avec (login, password).
666 */
667 Client.prototype.getJSONEnregistrement = function(login, password)
668 {
669 var mess = { "action" : "register" }
670
671 if (login != undefined && password != undefined)
672 {
673 mess["login"] = login
674 mess["password"] = password
675 }
676
677 return mess;
678 }
679
680 Client.prototype.getJSONConversations = function()
681 {
682 var conversations = new Array()
683 for (var i = 0; i < this.conversations.length; i++)
684 conversations.push({ "root" : this.conversations[i].root, "page" : this.conversations[i].page})
685 return conversations
686 }
687
688 Client.prototype.getJSONProfile = function()
689 {
690 return {
691 "action" : "set_profile",
692 "cookie" : this.cookie,
693 "login" : this.login,
694 "password" : this.password,
695 "nick" : this.pseudo,
696 "email" : this.email,
697 "css" : this.css,
698 "nick_format" : this.nickFormat,
699 "view_times" : this.viewTimes,
700 "view_tooltips" : this.viewTooltips,
701 "main_page" : this.pagePrincipale < 1 ? 1 : this.pagePrincipale,
702 "conversations" : this.getJSONConversations()
703 }
704 }
705
706 /**
707 * Renvoie null si pas définit.
708 */
709 Client.prototype.getCookie = function()
710 {
711 var cookie = this.regexCookie.exec(document.cookie)
712 if (cookie == null) this.cookie = null
713 else this.cookie = cookie[1]
714 }
715
716 Client.prototype.delCookie = function()
717 {
718 document.cookie = "cookie=; max-age=0"
719 }
720
721 Client.prototype.setCookie = function(cookie)
722 {
723 if (this.cookie == null)
724 return
725
726 document.cookie =
727 "cookie="+this.cookie+
728 "; max-age=" + (60 * 60 * 24 * 365)
729 }
730
731 Client.prototype.authentifie = function()
732 {
733 return this.statut == statutType.auth_registered || this.statut == statutType.auth_not_registered
734 }
735
736 Client.prototype.setStatut = function(statut)
737 {
738 // conversation en "enum" si en "string"
739 if (typeof(statut) == "string")
740 {
741 statut =
742 statut == "auth_registered" ?
743 statutType.auth_registered :
744 (statut == "auth_not_registered" ? statutType.auth_not_registered : statutType.deconnected)
745 }
746
747 if (statut == this.statut) return
748
749 this.statut = statut
750 this.majMenu()
751 }
752
753 /**
754 * Effectue la connexion vers le serveur.
755 * Cette fonction est bloquante tant que la connexion n'a pas été établie.
756 * S'il existe un cookie en local on s'authentifie directement avec lui.
757 * Si il n'est pas possible de s'authentifier alors on affiche un captcha anti-bot.
758 */
759 Client.prototype.connexionCookie = function()
760 {
761 this.getCookie()
762 if (this.cookie == null) return false;
763 return this.connexion(this.getJSONLoginCookie())
764 }
765
766 Client.prototype.connexionLogin = function(login, password)
767 {
768 return this.connexion(this.getJSONLogin(login, password))
769 }
770
771 Client.prototype.enregistrement = function(login, password)
772 {
773 if (this.authentifie())
774 {
775 this.login = login
776 this.password = password
777 if(this.flush())
778 {
779 this.setStatut(statutType.auth_registered)
780 return true
781 }
782 return false
783 }
784 else
785 {
786 return this.connexion(this.getJSONEnregistrement(login, password))
787 }
788 }
789
790 Client.prototype.connexion = function(messageJson)
791 {
792 ;; dumpObj(messageJson)
793 thisClient = this
794 jQuery.ajax(
795 {
796 async: false,
797 type: "POST",
798 url: "request",
799 dataType: "json",
800 data: this.util.jsonVersAction(messageJson),
801 success:
802 function(data)
803 {
804 ;; dumpObj(data)
805 if (data["reply"] == "error")
806 thisClient.util.messageDialogue(data["error_message"])
807 else
808 thisClient.chargerDonnees(data)
809 }
810 }
811 )
812 return this.authentifie()
813 }
814
815 Client.prototype.deconnexion = function()
816 {
817 this.flush(true)
818 this.delCookie()
819 this.resetDonneesPersonnelles()
820 this.setStatut(statutType.deconnected) // deconnexion
821 }
822
823 Client.prototype.chargerDonnees = function(data)
824 {
825 // la modification du statut qui suit met à jour le menu, le menu dépend (page admin)
826 // de l'état ekMaster
827 this.ekMaster = data["ek_master"] != undefined ? data["ek_master"] : false
828
829 this.setStatut(data["status"])
830
831 if (this.authentifie())
832 {
833 this.cookie = data["cookie"]
834 this.setCookie()
835
836 this.id = data["id"]
837 this.login = data["login"]
838 this.pseudo = data["nick"]
839 this.email = data["email"]
840 this.setCss(data["css"])
841 this.nickFormat = data["nick_format"]
842 this.viewTimes = data["view_times"]
843 this.viewTooltips = data["view_tooltips"]
844
845 // la page de la conversation principale
846 this.pagePrincipale = data["main_page"] == undefined ? 1 : data["main_page"]
847
848 // les conversations
849 this.conversations = data["conversations"]
850
851 this.majBulle()
852 }
853 }
854
855 /**
856 * Met à jour les données personne sur serveur.
857 * @param async de manière asynchrone ? défaut = true
858 * @return false si le flush n'a pas pû se faire sinon true
859 */
860 Client.prototype.flush = function(async)
861 {
862 if (async == undefined)
863 async = false
864
865 if (!this.authentifie())
866 return false
867
868 var thisClient = this
869 var ok = true
870
871 ;; dumpObj(this.getJSONProfile())
872 jQuery.ajax(
873 {
874 async: async,
875 type: "POST",
876 url: "request",
877 dataType: "json",
878 data: this.util.jsonVersAction(this.getJSONProfile()),
879 success:
880 function(data)
881 {
882 ;; dumpObj(data)
883 if (data["reply"] == "error")
884 {
885 thisClient.util.messageDialogue(data["error_message"])
886 ok = false
887 }
888 else
889 {
890 thisClient.majBulle()
891 }
892 }
893 }
894 )
895
896 return ok
897 }
898
899 Client.prototype.majMenu = function()
900 {
901 // TODO : à virer : ne plus changer de style de display ... spa beau .. ou trouver une autre méthode
902 // var displayType = this.css == "css/3/euphorik.css" ? "block" : "inline" //this.client
903 displayType = "block"
904
905 $("#menu .admin").css("display", this.ekMaster ? displayType : "none")
906
907 // met à jour le menu
908 if (this.statut == statutType.auth_registered)
909 {
910 $("#menu .profile").css("display", displayType).text("profile")
911 $("#menu .logout").css("display", displayType)
912 $("#menu .register").css("display", "none")
913 }
914 else if (this.statut == statutType.auth_not_registered)
915 {
916 $("#menu .profile").css("display", "none")
917 $("#menu .logout").css("display", displayType)
918 $("#menu .register").css("display", displayType)
919 }
920 else
921 {
922 $("#menu .profile").css("display", displayType).text("login")
923 $("#menu .logout").css("display", "none")
924 $("#menu .register").css("display", displayType)
925 }
926 }
927
928 /**
929 * Met à jour l'affichage des infos bulles en fonction du profile.
930 */
931 Client.prototype.majBulle = function()
932 {
933 this.util.bulleActive = this.viewTooltips
934 }
935
936 Client.prototype.slap = function(userId, raison)
937 {
938 var thisClient = this
939
940 jQuery.ajax({
941 type: "POST",
942 url: "request",
943 dataType: "json",
944 data: this.util.jsonVersAction(
945 {
946 "action" : "slap",
947 "cookie" : thisClient.cookie,
948 "user_id" : userId,
949 "reason" : raison
950 }),
951 success:
952 function(data)
953 {
954 if (data["reply"] == "error")
955 thisClient.util.messageDialogue(data["error_message"])
956 }
957 })
958 }
959
960 Client.prototype.ban = function(userId, raison, minutes)
961 {
962 var thisClient = this
963
964 // par défaut un ban correspond à 3 jours
965 if (typeof(minutes) == "undefined")
966 minutes = conf.tempsBan;
967
968 jQuery.ajax({
969 type: "POST",
970 url: "request",
971 dataType: "json",
972 data: this.util.jsonVersAction(
973 {
974 "action" : "ban",
975 "cookie" : thisClient.cookie,
976 "duration" : minutes,
977 "user_id" : userId,
978 "reason" : raison
979 }),
980 success:
981 function(data)
982 {
983 if (data["reply"] == "error")
984 thisClient.util.messageDialogue(data["error_message"])
985 }
986 })
987 }
988
989 Client.prototype.kick = function(userId, raison)
990 {
991 this.ban(userId, raison, conf.tempsKick)
992 }
993
994 ///////////////////////////////////////////////////////////////////////////////////////////////////
995
996 /**
997 * classe permettant de gérer les événements (push serveur).
998 * @page la page
999 */
1000 function PageEvent(page, util)
1001 {
1002 this.page = page
1003 this.util = util
1004
1005 // l'objet JSONHttpRequest représentant la connexion d'attente
1006 this.attenteCourante = null
1007
1008 // le multhreading du pauvre, merci javascript de m'offrire autant de primitives pour la gestion de la concurrence...
1009 this.stop = false
1010 }
1011
1012 /**
1013 * Arrête l'attente courante s'il y en a une.
1014 */
1015 PageEvent.prototype.stopAttenteCourante = function()
1016 {
1017 this.stop = true
1018
1019 if (this.attenteCourante != null)
1020 {
1021 this.attenteCourante.abort()
1022 }
1023 }
1024
1025 /**
1026 * Attend un événement lié à la page.
1027 * @funSend une fonction renvoyant les données json à envoyer
1028 * @funReceive une fonction qui accepte un paramètre correspondant au données reçues
1029 */
1030 PageEvent.prototype.waitEvent = function(funSend, funReceive)
1031 {
1032 this.stopAttenteCourante()
1033
1034 this.stop = false
1035
1036 var thisPageEvent = this
1037
1038 // on doit conserver l'ordre des valeurs de l'objet JSON (le serveur les veut dans l'ordre définit dans le protocole)
1039 // TODO : ya pas mieux ?
1040 var dataToSend =
1041 {
1042 "action" : "wait_event",
1043 "page" : this.page
1044 }
1045 var poulpe = funSend()
1046 for (v in poulpe)
1047 dataToSend[v] = poulpe[v]
1048
1049 ;; dumpObj(dataToSend)
1050
1051 this.attenteCourante = jQuery.ajax({
1052 type: "POST",
1053 url: "request",
1054 dataType: "json",
1055 data: this.util.jsonVersAction(dataToSend),
1056 success:
1057 function(data)
1058 {
1059 ;; dumpObj(data)
1060
1061 funReceive(data)
1062
1063 // rappel de la fonction dans 100 ms
1064 setTimeout(function(){ thisPageEvent.waitEvent2(funSend, funReceive) }, 100)
1065 },
1066 error:
1067 function(XMLHttpRequest, textStatus, errorThrown)
1068 {
1069 setTimeout(function(){ thisPageEvent.waitEvent2(funSend, funReceive) }, 1000)
1070 }
1071 })
1072 }
1073
1074 /**
1075 * Si un stopAttenteCourante survient un peu n'importe quand il faut imédiatement arreter de boucler.
1076 */
1077 PageEvent.prototype.waitEvent2 = function(funSend, funReceive)
1078 {
1079 if (this.stop)
1080 return
1081 this.waitEvent(funSend, funReceive)
1082 }
1083
1084 ///////////////////////////////////////////////////////////////////////////////////////////////////
1085
1086 function initialiserListeStyles(client)
1087 {
1088 $("#menuCss").change(
1089 function()
1090 {
1091 client.setCss("css/" + $("option:selected", this).attr("value") + "/euphorik.css")
1092 }
1093 )
1094 }
1095
1096 // charge dynamiquement le script de debug
1097 ;; jQuery.ajax({async : false, url : "js/debug.js", dataType : "script"})
1098
1099 // le main
1100 $(document).ready(
1101 function()
1102 {
1103 var formateur = new Formateur()
1104 var util = new Util(formateur)
1105 var client = new Client(util)
1106 var pages = new Pages()
1107
1108 // connexion vers le serveur (utilise un cookie qui traine)
1109 client.connexionCookie()
1110
1111 initialiserListeStyles(client)
1112
1113 // FIXME : ne fonctionne pas sous opera
1114 // voir : http://dev.jquery.com/ticket/2892#preview
1115 $(window).unload(function(){client.flush()})
1116
1117 $("#menu .minichat").click(function(){ pages.afficherPage("minichat") })
1118 $("#menu .admin").click(function(){ pages.afficherPage("admin") })
1119 $("#menu .profile").click(function(){ pages.afficherPage("profile") })
1120 $("#menu .logout").click(function(){
1121 util.messageDialogue("Êtes-vous sur de vouloir vous délogger ?", messageType.question,
1122 {"Oui" : function()
1123 {
1124 client.deconnexion();
1125 pages.afficherPage("minichat", true)
1126 },
1127 "Non" : function(){}
1128 }
1129 )
1130 })
1131 $("#menu .register").click(function(){ pages.afficherPage("register") })
1132 $("#menu .about").click(function(){ pages.afficherPage("about") })
1133
1134 // TODO : simplifier et pouvoir créer des liens par exemple : <span class="lien" href="conditions">Conditions d'utilisation</span>
1135 $("#footer .conditions").click(function(){ pages.afficherPage("conditions_utilisation") })
1136
1137 pages.ajouterPage(new PageMinichat(client, formateur, util))
1138 pages.ajouterPage(new PageAdmin(client, formateur, util))
1139 pages.ajouterPage(new PageProfile(client, formateur, util))
1140 pages.ajouterPage(new PageRegister(client, formateur, util))
1141 pages.ajouterPage(new PageAbout(client, formateur, util))
1142 pages.ajouterPage("conditions_utilisation")
1143
1144 pages.afficherPage("minichat")
1145 }
1146 )