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