ADD script permettant la mise à jour de la BD et le rechargement des modules lors...
[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 Pages.prototype.ajouterPage = function(page)
305 {
306 page.pages = this // la magie des langages dynamiques : le foutoire
307 this.pages[page.nom] = page
308 }
309
310 Pages.prototype.afficherPage = function(nomPage, forcerChargement)
311 {
312 if (forcerChargement == undefined) forcerChargement = false
313
314 var page = this.pages[nomPage]
315 if (page == undefined || (!forcerChargement && page == this.pageCourante)) return
316
317 if (this.pageCourante != null && this.pageCourante.decharger)
318 this.pageCourante.decharger()
319
320 $("#menu li").removeClass("courante")
321 $("#menu li." + nomPage).addClass("courante")
322
323 this.pageCourante = page
324 $("#page").html(this.pageCourante.contenu()).removeClass().addClass(this.pageCourante.nom)
325
326 if (this.pageCourante.charger)
327 this.pageCourante.charger()
328 }
329
330 ///////////////////////////////////////////////////////////////////////////////////////////////////
331
332 /**
333 * Classe permettant de formater du texte par exemple pour la substitution des liens dans les
334 * message par "[url]".
335 * TODO : améliorer l'efficacité des méthods notamment lié au smiles.
336 */
337 function Formateur()
338 {
339 this.smiles = conf.smiles
340 this.protocoles = "http|https|ed2k"
341
342 this.regexUrl = new RegExp("(?:(?:" + this.protocoles + ")://|www\\.)[^ ]*", "gi")
343 this.regexImg = new RegExp("^.*?\\.(gif|jpg|png|jpeg|bmp|tiff)$", "i")
344 this.regexDomaine = new RegExp("^(?:(?:" + this.protocoles + ")://|www\\.).*?([^/.]+\\.[^/.]+)(?:$|/).*$", "i")
345 this.regexTestProtocoleExiste = new RegExp("^(?:" + this.protocoles + ")://.*$", "i")
346 this.regexNomProtocole = new RegExp("^(.*?)://")
347 }
348
349 /**
350 * Formate un pseudo saise par l'utilisateur.
351 * @param pseudo le pseudo brut
352 * @return le pseudo filtré
353 */
354 Formateur.prototype.filtrerInputPseudo = function(pseudo)
355 {
356 return pseudo.replace(/{|}/g, "").trim()
357 }
358
359 Formateur.prototype.getSmilesHTML = function()
360 {
361 var XHTML = ""
362 for (var sNom in this.smiles)
363 {
364 XHTML += "<img class=\"" + sNom + "\" src=\"img/smileys/" + sNom + ".gif\" alt =\"" + sNom + "\" />"
365 }
366 return XHTML
367 }
368
369 /**
370 * Formatage complet d'un texte.
371 * @M le message
372 * @pseudo facultatif, permet de contruire le label des images sous la forme : "<Pseudo> : <Message>"
373 */
374 Formateur.prototype.traitementComplet = function(M, pseudo)
375 {
376 return this.traiterLiensConv(this.traiterSmiles(this.traiterURL(this.traiterWikiSyntaxe(this.remplacerBalisesHTML(M)), pseudo)))
377 }
378
379 /**
380 * Transforme les liens en entités clickables.
381 * Un lien vers une conversation permet d'ouvrire celle ci, elle se marque comme ceci dans un message :
382 * "{5F}" ou 5F est la racine de la conversation.
383 * Ce lien sera transformer en <span class="lienConv">{5F}</span> pouvant être clické pour créer la conv 5F.
384 */
385 Formateur.prototype.traiterLiensConv = function(M)
386 {
387 return M.replace(
388 /\{\w+\}/g,
389 function(lien)
390 {
391 return "<span class=\"lienConv\">" + lien + "</span>"
392 }
393 )
394 }
395
396 /**
397 * FIXME : Cette méthode est attrocement lourde ! A optimiser.
398 * moyenne sur échantillon : 234ms
399 */
400 Formateur.prototype.traiterSmiles = function(M)
401 {
402 for (var sNom in this.smiles)
403 {
404 ss = this.smiles[sNom]
405 for (var i = 0; i < ss.length; i++)
406 M = M.replace(ss[i], "<img src=\"img/smileys/" + sNom + ".gif\" alt =\"" + sNom + "\" />")
407 }
408 return M
409 }
410
411 Formateur.prototype.remplacerBalisesHTML = function(M)
412 {
413 return M.replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;")
414 }
415
416 Formateur.prototype.traiterURL = function(M, pseudo)
417 {
418 thisFormateur = this
419
420 var traitementUrl = function(url)
421 {
422 // si ya pas de protocole on rajoute "http://"
423 if (!thisFormateur.regexTestProtocoleExiste.test(url))
424 url = "http://" + url
425 var extension = thisFormateur.getShort(url)
426 return "<a " + (extension[1] ? "title=\"" + (pseudo == undefined ? "" : thisFormateur.traiterPourFenetreLightBox(pseudo, url) + ": ") + thisFormateur.traiterPourFenetreLightBox(M, url) + "\"" + " rel=\"lightbox\"" : "") + " href=\"" + url + "\" >[" + extension[0] + "]</a>"
427 }
428 return M.replace(this.regexUrl, traitementUrl)
429 }
430
431 /**
432 * Formatage en utilisant un sous-ensemble des règles de mediwiki.
433 * par exemple ''italic'' devient <i>italic</i>
434 */
435 Formateur.prototype.traiterWikiSyntaxe = function(M)
436 {
437 return M.replace(
438 /'''(.*?)'''/g,
439 function(texte, capture)
440 {
441 return "<b>" + capture + "</b>"
442 }
443 ).replace(
444 /''(.*?)''/g,
445 function(texte, capture)
446 {
447 return "<i>" + capture + "</i>"
448 }
449 )
450 }
451
452 /**
453 * Renvoie une version courte de l'url.
454 * par exemple : http://en.wikipedia.org/wiki/Yakov_Smirnoff devient wikipedia.org
455 */
456 Formateur.prototype.getShort = function(url)
457 {
458 var estUneImage = false
459 var versionShort = null
460 var rechercheImg = this.regexImg.exec(url)
461
462 if (rechercheImg != null)
463 {
464 versionShort = rechercheImg[1].toLowerCase()
465 if (versionShort == "jpeg") versionShort = "jpg" // jpeg -> jpg
466 estUneImage = true
467 }
468 else
469 {
470 var rechercheDomaine = this.regexDomaine.exec(url)
471 if (rechercheDomaine != null && rechercheDomaine.length >= 2)
472 versionShort = rechercheDomaine[1]
473 else
474 {
475 var nomProtocole = this.regexNomProtocole.exec(url)
476 if (nomProtocole != null && nomProtocole.length >= 2)
477 versionShort = nomProtocole[1]
478 }
479 }
480
481 return [versionShort == null ? "url" : versionShort, estUneImage]
482 }
483
484 /**
485 * Traite les pseudo et messages à être affiché dans le titre d'une image visualisé avec lightbox.
486 */
487 Formateur.prototype.traiterPourFenetreLightBox = function(M, urlCourante)
488 {
489 thisFormateur = this
490 var traitementUrl = function(url)
491 {
492 return "[" + thisFormateur.getShort(url)[0] + (urlCourante == url ? "*" : "") + "]"
493 }
494
495 return this.remplacerBalisesHTML(M).replace(this.regexUrl, traitementUrl)
496 }
497
498
499 ///////////////////////////////////////////////////////////////////////////////////////////////////
500
501 // les statuts possibes du client
502 var statutType = {
503 // mode enregistré, peut poster des messages et modifier son profile
504 auth_registered : 0,
505 // mode identifié, peut poster des messages mais n'a pas accès au profile
506 auth_not_registered : 1,
507 // mode déconnecté, ne peut pas poster de message
508 deconnected : 2
509 }
510
511 function Client(util)
512 {
513 this.util = util
514
515 this.cookie = null
516 this.regexCookie = new RegExp("^cookie=([^;]*)")
517
518 // données personnels
519 this.resetDonneesPersonnelles()
520
521 this.setStatut(statutType.deconnected)
522
523 // si true alors chaque modification du client est mémorisé sur le serveur
524 this.autoflush = $.browser["opera"]
525 }
526
527 Client.prototype.resetDonneesPersonnelles = function()
528 {
529 this.id = 0
530 this.pseudo = conf.pseudoDefaut
531 this.login = ""
532 this.password = ""
533 this.email = ""
534 this.css = $("link#cssPrincipale").attr("href")
535 this.nickFormat = "nick"
536 this.viewTimes = true
537 this.viewTooltips = true
538 this.cookie = undefined
539
540 this.pagePrincipale = 1
541 this.ekMaster = false
542
543 // les conversations, une conversation est un objet possédant les attributs suivants :
544 // - racine (entier)
545 // - page (entier)
546 this.conversations = new Array()
547 }
548
549 Client.prototype.setCss = function(css)
550 {
551 if (this.css == css || css == "")
552 return
553
554 this.css = css
555 $("link#cssPrincipale").attr("href", this.css)
556 this.majMenu()
557
558 if (this.autoflush) this.flush(true)
559 }
560
561 Client.prototype.pageSuivante = function(numConv)
562 {
563 if (numConv < 0 && this.pagePrincipale > 1)
564 this.pagePrincipale -= 1
565 else if (this.conversations[numConv].page > 1)
566 this.conversations[numConv].page -= 1
567 }
568
569 Client.prototype.pagePrecedente = function(numConv)
570 {
571 if (numConv < 0)
572 this.pagePrincipale += 1
573 else
574 this.conversations[numConv].page += 1
575 }
576
577 /**
578 * Définit la première page pour la conversation donnée.
579 * @return true si la page a changé sinon false
580 */
581 Client.prototype.goPremierePage = function(numConv)
582 {
583 if (numConv < 0)
584 {
585 if (this.pagePrincipale == 1)
586 return false
587 this.pagePrincipale = 1
588 }
589 else
590 {
591 if (this.conversations[numConv].page == 1)
592 return false
593 this.conversations[numConv].page = 1
594 }
595 return true
596 }
597
598 /**
599 * Ajoute une conversation à la vue de l'utilisateur.
600 * Le profile de l'utilisateur est directement sauvegardé sur le serveur.
601 * @param racines la racine de la conversation (integer)
602 * @return true si la conversation a été créée sinon false (par exemple si la conv existe déjà)
603 */
604 Client.prototype.ajouterConversation = function(racine)
605 {
606 // vérification s'il elle n'existe pas déjà
607 for (var i = 0; i < this.conversations.length; i++)
608 if (this.conversations[i].root == racine)
609 return false
610
611 this.conversations.push({root : racine, page : 1})
612
613 if (this.autoflush) this.flush(true)
614
615 return true
616 }
617
618 Client.prototype.supprimerConversation = function(num)
619 {
620 if (num < 0 || num >= this.conversations.length) return
621
622 // décalage TODO : supprimer le dernier élément
623 for (var i = num; i < this.conversations.length - 1; i++)
624 this.conversations[i] = this.conversations[i+1]
625 this.conversations.pop()
626
627 if (this.autoflush) this.flush(true)
628 }
629
630 Client.prototype.getJSONLogin = function(login, password)
631 {
632 return {
633 "action" : "authentification",
634 "login" : login,
635 "password" : password
636 }
637 }
638
639 Client.prototype.getJSONLoginCookie = function()
640 {
641 return {
642 "action" : "authentification",
643 "cookie" : this.cookie
644 }
645 }
646
647 /**
648 * le couple (login, password) est facultatif. S'il n'est pas fournit alors il ne sera pas possible
649 * de s'autentifier avec (login, password).
650 */
651 Client.prototype.getJSONEnregistrement = function(login, password)
652 {
653 var mess = { "action" : "register" }
654
655 if (login != undefined && password != undefined)
656 {
657 mess["login"] = login
658 mess["password"] = password
659 }
660
661 return mess;
662 }
663
664 Client.prototype.getJSONConversations = function()
665 {
666 var conversations = new Array()
667 for (var i = 0; i < this.conversations.length; i++)
668 conversations.push({ "root" : this.conversations[i].root, "page" : this.conversations[i].page})
669 return conversations
670 }
671
672 Client.prototype.getJSONProfile = function()
673 {
674 return {
675 "action" : "set_profile",
676 "cookie" : this.cookie,
677 "login" : this.login,
678 "password" : this.password,
679 "nick" : this.pseudo,
680 "email" : this.email,
681 "css" : this.css,
682 "nick_format" : this.nickFormat,
683 "view_times" : this.viewTimes,
684 "view_tooltips" : this.viewTooltips,
685 "main_page" : this.pagePrincipale < 1 ? 1 : this.pagePrincipale,
686 "conversations" : this.getJSONConversations()
687 }
688 }
689
690 /**
691 * Renvoie null si pas définit.
692 */
693 Client.prototype.getCookie = function()
694 {
695 var cookie = this.regexCookie.exec(document.cookie)
696 if (cookie == null) this.cookie = null
697 else this.cookie = cookie[1]
698 }
699
700 Client.prototype.delCookie = function()
701 {
702 document.cookie = "cookie=; max-age=0"
703 }
704
705 Client.prototype.setCookie = function(cookie)
706 {
707 if (this.cookie == null)
708 return
709
710 document.cookie =
711 "cookie="+this.cookie+
712 "; max-age=" + (60 * 60 * 24 * 365)
713 }
714
715 Client.prototype.authentifie = function()
716 {
717 return this.statut == statutType.auth_registered || this.statut == statutType.auth_not_registered
718 }
719
720 Client.prototype.setStatut = function(statut)
721 {
722 // conversation en "enum" si en "string"
723 if (typeof(statut) == "string")
724 {
725 statut =
726 statut == "auth_registered" ?
727 statutType.auth_registered :
728 (statut == "auth_not_registered" ? statutType.auth_not_registered : statutType.deconnected)
729 }
730
731 if (statut == this.statut) return
732
733 this.statut = statut
734 this.majMenu()
735 }
736
737 /**
738 * Effectue la connexion vers le serveur.
739 * Cette fonction est bloquante tant que la connexion n'a pas été établie.
740 * S'il existe un cookie en local on s'authentifie directement avec lui.
741 * Si il n'est pas possible de s'authentifier alors on affiche un captcha anti-bot.
742 */
743 Client.prototype.connexionCookie = function()
744 {
745 this.getCookie()
746 if (this.cookie == null) return false;
747 return this.connexion(this.getJSONLoginCookie())
748 }
749
750 Client.prototype.connexionLogin = function(login, password)
751 {
752 return this.connexion(this.getJSONLogin(login, password))
753 }
754
755 Client.prototype.enregistrement = function(login, password)
756 {
757 if (this.authentifie())
758 {
759 this.login = login
760 this.password = password
761 if(this.flush())
762 {
763 this.setStatut(statutType.auth_registered)
764 return true
765 }
766 return false
767 }
768 else
769 {
770 return this.connexion(this.getJSONEnregistrement(login, password))
771 }
772 }
773
774 Client.prototype.connexion = function(messageJson)
775 {
776 ;; dumpObj(messageJson)
777 thisClient = this
778 jQuery.ajax(
779 {
780 async: false,
781 type: "POST",
782 url: "request",
783 dataType: "json",
784 data: this.util.jsonVersAction(messageJson),
785 success:
786 function(data)
787 {
788 ;; dumpObj(data)
789 if (data["reply"] == "error")
790 thisClient.util.messageDialogue(data["error_message"])
791 else
792 thisClient.chargerDonnees(data)
793 }
794 }
795 )
796 return this.authentifie()
797 }
798
799 Client.prototype.deconnexion = function()
800 {
801 this.flush(true)
802 this.delCookie()
803 this.resetDonneesPersonnelles()
804 this.setStatut(statutType.deconnected) // deconnexion
805 }
806
807 Client.prototype.chargerDonnees = function(data)
808 {
809 // la modification du statut qui suit met à jour le menu, le menu dépend (page admin)
810 // de l'état ekMaster
811 this.ekMaster = data["ek_master"] != undefined ? data["ek_master"] : false
812
813 this.setStatut(data["status"])
814
815 if (this.authentifie())
816 {
817 this.cookie = data["cookie"]
818 this.setCookie()
819
820 this.id = data["id"]
821 this.login = data["login"]
822 this.pseudo = data["nick"]
823 this.email = data["email"]
824 this.setCss(data["css"])
825 this.nickFormat = data["nick_format"]
826 this.viewTimes = data["view_times"]
827 this.viewTooltips = data["view_tooltips"]
828
829 // la page de la conversation principale
830 this.pagePrincipale = data["main_page"] == undefined ? 1 : data["main_page"]
831
832 // les conversations
833 this.conversations = data["conversations"]
834
835 this.majBulle()
836 }
837 }
838
839 /**
840 * Met à jour les données personne sur serveur.
841 * @param async de manière asynchrone ? défaut = true
842 * @return false si le flush n'a pas pû se faire sinon true
843 */
844 Client.prototype.flush = function(async)
845 {
846 if (async == undefined)
847 async = false
848
849 if (!this.authentifie())
850 return false
851
852 var thisClient = this
853 var ok = true
854
855 ;; dumpObj(this.getJSONProfile())
856 jQuery.ajax(
857 {
858 async: async,
859 type: "POST",
860 url: "request",
861 dataType: "json",
862 data: this.util.jsonVersAction(this.getJSONProfile()),
863 success:
864 function(data)
865 {
866 ;; dumpObj(data)
867 if (data["reply"] == "error")
868 {
869 thisClient.util.messageDialogue(data["error_message"])
870 ok = false
871 }
872 else
873 {
874 thisClient.majBulle()
875 }
876 }
877 }
878 )
879
880 return ok
881 }
882
883 Client.prototype.majMenu = function()
884 {
885 // TODO : à virer : ne plus changer de style de display ... spa beau .. ou trouver une autre méthode
886 // var displayType = this.css == "css/3/euphorik.css" ? "block" : "inline" //this.client
887 displayType = "block"
888
889 $("#menu .admin").css("display", this.ekMaster ? displayType : "none")
890
891 // met à jour le menu
892 if (this.statut == statutType.auth_registered)
893 {
894 $("#menu .profile").css("display", displayType).text("profile")
895 $("#menu .logout").css("display", displayType)
896 $("#menu .register").css("display", "none")
897 }
898 else if (this.statut == statutType.auth_not_registered)
899 {
900 $("#menu .profile").css("display", "none")
901 $("#menu .logout").css("display", displayType)
902 $("#menu .register").css("display", displayType)
903 }
904 else
905 {
906 $("#menu .profile").css("display", displayType).text("login")
907 $("#menu .logout").css("display", "none")
908 $("#menu .register").css("display", displayType)
909 }
910 }
911
912 /**
913 * Met à jour l'affichage des infos bulles en fonction du profile.
914 */
915 Client.prototype.majBulle = function()
916 {
917 this.util.bulleActive = this.viewTooltips
918 }
919
920 Client.prototype.slap = function(userId, raison)
921 {
922 var thisClient = this
923
924 jQuery.ajax({
925 type: "POST",
926 url: "request",
927 dataType: "json",
928 data: this.util.jsonVersAction(
929 {
930 "action" : "slap",
931 "cookie" : thisClient.cookie,
932 "user_id" : userId,
933 "reason" : raison
934 }),
935 success:
936 function(data)
937 {
938 if (data["reply"] == "error")
939 thisClient.util.messageDialogue(data["error_message"])
940 }
941 })
942 }
943
944 Client.prototype.ban = function(userId, raison, minutes)
945 {
946 var thisClient = this
947
948 // par défaut un ban correspond à 3 jours
949 if (typeof(minutes) == "undefined")
950 minutes = conf.tempsBan;
951
952 jQuery.ajax({
953 type: "POST",
954 url: "request",
955 dataType: "json",
956 data: this.util.jsonVersAction(
957 {
958 "action" : "ban",
959 "cookie" : thisClient.cookie,
960 "duration" : minutes,
961 "user_id" : userId,
962 "reason" : raison
963 }),
964 success:
965 function(data)
966 {
967 if (data["reply"] == "error")
968 thisClient.util.messageDialogue(data["error_message"])
969 }
970 })
971 }
972
973 Client.prototype.kick = function(userId, raison)
974 {
975 this.ban(userId, raison, conf.tempsKick)
976 }
977
978 ///////////////////////////////////////////////////////////////////////////////////////////////////
979
980 /**
981 * classe permettant de gérer les événements (push serveur).
982 * @page la page
983 */
984 function PageEvent(page, util)
985 {
986 this.page = page
987 this.util = util
988
989 // l'objet JSONHttpRequest représentant la connexion d'attente
990 this.attenteCourante = null
991
992 // le multhreading du pauvre, merci javascript de m'offrire autant de primitives pour la gestion de la concurrence...
993 this.stop = false
994 }
995
996 /**
997 * Arrête l'attente courante s'il y en a une.
998 */
999 PageEvent.prototype.stopAttenteCourante = function()
1000 {
1001 this.stop = true
1002
1003 if (this.attenteCourante != null)
1004 {
1005 this.attenteCourante.abort()
1006 }
1007 }
1008
1009 /**
1010 * Attend un événement lié à la page.
1011 * @funSend une fonction renvoyant les données json à envoyer
1012 * @funReceive une fonction qui accepte un paramètre correspondant au données reçues
1013 */
1014 PageEvent.prototype.waitEvent = function(funSend, funReceive)
1015 {
1016 this.stopAttenteCourante()
1017
1018 this.stop = false
1019
1020 var thisPageEvent = this
1021
1022 // on doit conserver l'ordre des valeurs de l'objet JSON (le serveur les veut dans l'ordre définit dans le protocole)
1023 // TODO : ya pas mieux ?
1024 var dataToSend =
1025 {
1026 "action" : "wait_event",
1027 "page" : this.page
1028 }
1029 var poulpe = funSend()
1030 for (v in poulpe)
1031 dataToSend[v] = poulpe[v]
1032
1033 ;; dumpObj(dataToSend)
1034
1035 this.attenteCourante = jQuery.ajax({
1036 type: "POST",
1037 url: "request",
1038 dataType: "json",
1039 data: this.util.jsonVersAction(dataToSend),
1040 success:
1041 function(data)
1042 {
1043 ;; dumpObj(data)
1044
1045 funReceive(data)
1046
1047 // rappel de la fonction dans 100 ms
1048 setTimeout(function(){ thisPageEvent.waitEvent2(funSend, funReceive) }, 100)
1049 },
1050 error:
1051 function(XMLHttpRequest, textStatus, errorThrown)
1052 {
1053 setTimeout(function(){ thisPageEvent.waitEvent2(funSend, funReceive) }, 1000)
1054 }
1055 })
1056 }
1057
1058 /**
1059 * Si un stopAttenteCourante survient un peu n'importe quand il faut imédiatement arreter de boucler.
1060 */
1061 PageEvent.prototype.waitEvent2 = function(funSend, funReceive)
1062 {
1063 if (this.stop)
1064 return
1065 this.waitEvent(funSend, funReceive)
1066 }
1067
1068 ///////////////////////////////////////////////////////////////////////////////////////////////////
1069
1070 function initialiserListeStyles(client)
1071 {
1072 $("#menuCss").change(
1073 function()
1074 {
1075 client.setCss("css/" + $("option:selected", this).attr("value") + "/euphorik.css")
1076 }
1077 )
1078 }
1079
1080 // charge dynamiquement le script de debug
1081 ;; jQuery.ajax({async : false, url : "js/debug.js", dataType : "script"})
1082
1083 // le main
1084 $(document).ready(
1085 function()
1086 {
1087 var formateur = new Formateur()
1088 var util = new Util(formateur)
1089 var client = new Client(util)
1090 var pages = new Pages()
1091
1092 // connexion vers le serveur (utilise un cookie qui traine)
1093 client.connexionCookie()
1094
1095 initialiserListeStyles(client)
1096
1097 // FIXME : ne fonctionne pas sous opera
1098 // voir : http://dev.jquery.com/ticket/2892#preview
1099 $(window).unload(function(){client.flush()})
1100
1101 $("#menu .minichat").click(function(){ pages.afficherPage("minichat") })
1102 $("#menu .admin").click(function(){ pages.afficherPage("admin") })
1103 $("#menu .profile").click(function(){ pages.afficherPage("profile") })
1104 $("#menu .logout").click(function(){
1105 util.messageDialogue("Êtes-vous sur de vouloir vous délogger ?", messageType.question,
1106 {"Oui" : function()
1107 {
1108 client.deconnexion();
1109 pages.afficherPage("minichat", true)
1110 },
1111 "Non" : function(){}
1112 }
1113 )
1114 })
1115 $("#menu .register").click(function(){ pages.afficherPage("register") })
1116 $("#menu .about").click(function(){ pages.afficherPage("about") })
1117
1118 pages.ajouterPage(new PageMinichat(client, formateur, util))
1119 pages.ajouterPage(new PageAdmin(client, formateur, util))
1120 pages.ajouterPage(new PageProfile(client, formateur, util))
1121 pages.ajouterPage(new PageRegister(client, formateur, util))
1122 pages.ajouterPage(new PageAbout(client, formateur, util))
1123 pages.afficherPage("minichat")
1124 }
1125 )