oiiiiii
Autor: vitor | Publicado: 2012-07-28T17:11:00-07:00

import random
import socket, asyncore, asynchat
import thread, threading
import time
import types
import re
import base64, binascii, hashlib
import logging
from array import array
import json
import sqlite3
import os
#import psutil

from SimpleXMLRPCServer import SimpleXMLRPCServer, SimpleXMLRPCRequestHandler

logging.basicConfig(filename='Logs/server.log',level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")

        
dbcon = sqlite3.connect("dbfile.sqlite")
dbcon.isolation_level = None
dbcur = dbcon.cursor()
dbcon.row_factory = sqlite3.Row

dbcon2 = sqlite3.connect("dbfile.sqlite")
dbcon2.isolation_level = None
dbcur2 = dbcon2.cursor()
dbcon2.row_factory = sqlite3.Row
LANGUAGE = "EN"
VERBOSE = False
VERSION = "0.126"
str_game_version = "0.126"
str_server_version = "1.016"
MJ = True

LEVEL_LIST = range(0, 114+1) + [1006, 1007, 1015, 1027, 1040, 1062, 1067, 1087, 1088, 1092, 888]
RADOMPS_LIST = range(5000, 200000)
#101 to 107 are conjuration
#108 and 109 are catch the cheese
#110 to 114 are catch the cheese with shaman
#
#1087 (Shaman only on nightmode)
#1088 (Shaman only on nightmode)
#1092 (Shaman only on nightmode)
#888 Special Map, temporary

class TransformiceServer(asyncore.dispatcher):
    def __init__(self, HOST='192.168.254.1', PORT=1111):

        self.HOST = HOST
        self.PORT = PORT

        asyncore.dispatcher.__init__(self)
        self.create_socket(socket.AF_INET, socket.SOCK_STREAM)

        # try to re-use a server port if possible
        self.set_reuse_addr()
        self.bind((self.HOST, self.PORT))
        self.listen(5)

        logging.info("Running")
        print '################################# By ~ Seven ~ #################################'
        print '[~Mice Server V3~] Servidor Online'
        #self.clients = []

        self.rooms = {}
        self.recruitTribe = ""
    def handle_accept(self):
        socket, addr = self.accept()

        TransformiceClientHandler(self, socket, addr)

    def authenticate(self, username, passwordHash):
        dbcur.execute('select * from users where name = ?', [username])
        rrf = dbcur.fetchone()
        if rrf is None:
            return -1
        else:
            name = rrf[0]
            password = rrf[1]
            privlevel = rrf[3]
            if passwordHash != password:
                return -1
            else:
                return privlevel

    def setPlayerFur(self, name, fur):
        for room in self.rooms.values():
            for playerCode, client in room.clients.items():
                if client.privilegeLevel>=5:
                    pass
                elif client.username == name.title():
                    if fur.lower().strip() == "normal": fur = "78583a"
                    client.fur = fur
                    
    def getPlayerID(self, username):
        if username.startswith("*"):
            return "1"
        else:
            dbcur.execute('select playerid from users where name = ?', [username])
            rrf = dbcur.fetchone()
            if rrf is None:
                return -1
            else:
                return rrf[0]

    def getServerSetting(self, setting):
        dbcur.execute('select value from settings where setting = ?', [setting])
        rrf = dbcur.fetchone()
        if rrf is None:
            return False
        else:
            return rrf[0]
        
    def getSavesCount(self, username):
        if username.startswith("*"):
            return 0
        else:
            dbcur.execute('select saves from users where name = ?', [username])
            rrf = dbcur.fetchone()
            if rrf is None:
                return -1
            else:
                return rrf[0]

    def getFurColor(self, username):
        try:
            dbcur.execute('select fur from users where name = ?', [username])
            rrf = dbcur.fetchone()
            if rrf is None:
                return -1
            else:
                if rrf[0] == "None":
                    return '78583a'
                else:
                    return rrf[0]
        except:
            return '78583a'
        
    def getShamanCheeseCount(self, username):
        if username.startswith("*"):
            return 0
        else:
            dbcur.execute('select shamcheese from users where name = ?', [username])
            rrf = dbcur.fetchone()
            if rrf is None:
                return -1
            else:
                return rrf[0]

    def getFirstCount(self, username):
        if username.startswith("*"):
            return 0
        else:
            dbcur.execute('select first from users where name = ?', [username])
            rrf = dbcur.fetchone()
            if rrf is None:
                return -1
            else:
                return rrf[0]

    def getCheeseCount(self, username):
        if username.startswith("*"):
            return 0
        else:
            dbcur.execute('select cheese from users where name = ?', [username])
            rrf = dbcur.fetchone()
            if rrf is None:
                return -1
            else:
                return rrf[0]

    def getRoundsCount(self, username):
        if username.startswith("*"):
            return 0
        else:
            dbcur.execute('select rounds from users where name = ?', [username])
            rrf = dbcur.fetchone()
            if rrf is None:
                return -1
            else:
                return rrf[0]

    def getTitleList(self, username):
        if username.startswith("*"):
            return "[]"
        else:
            dbcur.execute('select titlelist from users where name = ?', [username])
            rrf = dbcur.fetchone()
            if rrf is None:
                return -1
            else:
                return rrf[0]
    def getTribeRank(self, username):
        if username.startswith("*"):
            return ""
        else:
            dbcur.execute('select triberank from users where name = ?', [username])
            rrf = dbcur.fetchone()
            if rrf is None:
                return -1
            else:
                return rrf[0]
    def getDrawer(self, username):
        if username.startswith("*"):
                return ""
        else:
            dbcur.execute('select isdrawer from users where name = ?', [username])
            rrf = dbcur.fetchone()
            if rrf is None:
                return -1
            else:
                return rrf[0]
    def getTribeUsers(self, tribe):
        username = tribe
        if username.startswith("*"):
            return ""
        else:
            dbcur.execute('select users from tribes where name = ?', [tribe])
            rrf = dbcur.fetchone()
            if rrf is None:
                return -1
            else:
                return rrf[0]
    def getTribeName(self, username):
        if username.startswith("*"):
            return ""
        else:
            dbcur.execute('select tribe from users where name = ?', [username])
            rrf = dbcur.fetchone()
            
            if rrf is None:
                return -1
            else:
                return rrf[0]
    #self.tribe = self.server.getTribeName(username)
                #self.tribeName = self.server.getTribeName(username)
                #self.tribeGreeting = self.server.getTribeGreeting(self.tribeName)
                #self.tribeSettings = self.server.getTribeSettings(self.tribeName)
                #self.tribeRank = self.server.getTribeRank(username)
    def getTribeGreeting(self, tribe):
        username = tribe
        if username.startswith("*"):
            return ""
        else:
            dbcur.execute('select greeting from tribes where name = ?', [tribe])
            rrf = dbcur.fetchone()
            
            if rrf is None:
                return -1
            else:
                return rrf[0]
    def getTribeSettings(self, tribe):
        username = tribe
        if username.startswith("*"):
            return ""
        else:
            dbcur.execute('select options from tribes where name = ?', [tribe])
            rrf = dbcur.fetchone()
            
            if rrf is None:
                return -1
            else:
                return rrf[0]
    def getCurrentTitle(self, username):
        if username.startswith("*"):
            return 0
        else:
            dbcur.execute('select currenttitle from users where name = ?', [username])
            rrf = dbcur.fetchone()
            if rrf is None:
                return -1
            else:
                return rrf[0]

    def getUserShop(self, username):
        if username.startswith("*"):
            return ""
        else:
            dbcur.execute('select shop from users where name = ?', [username])
            rrf = dbcur.fetchone()
            if rrf is None:
                return -1
            else:
                return rrf[0]

    def getUserFriends(self, username):
        if username.startswith("*"):
            return ""
        else:
            dbcur.execute('select friends from users where name = ?', [username])
            rrf = dbcur.fetchone()
            if rrf is None:
                return -1
            else:
                return rrf[0]

    def getUserLook(self, username):
        if username.startswith("*"):
            return "0,0,0,0,0"
        else:
            dbcur.execute('select look from users where name = ?', [username])
            rrf = dbcur.fetchone()
            if rrf is None:
                return -1
            else:
                return rrf[0]
    def getShopCheese(self, username):
        if username.startswith("*"):
            return 0
        else:
            dbcur.execute('select shopcheese from users where name = ?', [username])
            rrf = dbcur.fetchone()
            if rrf is None:
                return -1
            else:
                return rrf[0]

    def checkExistingUsers(self, username):
        dbcur.execute('select name from users where name = ?', [username])
        rrf = dbcur.fetchone()
        if rrf is None:
            return 0
        else:
            return 1

    def createAccount(self, username, passwordHash):
        name = username
        password = passwordHash
        playerid = "1"
        privlevel = 1
        saves = 0
        shamcheese = 0
        first = 0
        cheese = 0
        rounds = 0
        titlelist = ["0"]
        titlelist = json.dumps(titlelist)
        tribe = ""
        currenttitle = 0
        shop = ""
        friends = ""
        look = "0,0,0,0,0"
        shopcheese = 5000
        isdrawer = 0
        dbcur.execute("insert into users (name, password, id, privlevel, saves, shamcheese, first, cheese, rounds, titlelist, tribe, currenttitle, shop, friends, look, shopcheese, isdrawer) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
        (name, password, playerid, privlevel, saves, shamcheese, first, cheese, rounds, titlelist, tribe, currenttitle, shop, friends, look, shopcheese, isdrawer))

    def getMapName(self, code):
        try:
            dbcur.execute('select name from mapeditor where code = ?', [code])
            rrf = dbcur.fetchone()
            if rrf is None:
                return -1
            else:
                return rrf[0]
        except:
            dbcur2.execute('select name from mapeditor where code = ?', [code])
            rrf = dbcur2.fetchone()
            if rrf is None:
                return -1
            else:
                return rrf[0]
    def getMapXML(self, code):
        try:
            dbcur.execute('select mapxml from mapeditor where code = ?', [code])
            rrf = dbcur.fetchone()
            if rrf is None:
                return -1
            else:
                return rrf[0]
        except:
            dbcur2.execute('select mapxml from mapeditor where code = ?', [code])
            rrf = dbcur2.fetchone()
            if rrf is None:
                return -1
            else:
                return rrf[0]
    def getMapYesVotes(self, code):
        dbcur.execute('select yesvotes from mapeditor where code = ?', [code])
        rrf = dbcur.fetchone()
        if rrf is None:
            return -1
        else:
            return rrf[0]
    def getMapNoVotes(self, code):
        dbcur.execute('select novotes from mapeditor where code = ?', [code])
        rrf = dbcur.fetchone()
        if rrf is None:
            return -1
        else:
            return rrf[0]
    def getMapPerma(self, code):
        dbcur.execute('select perma from mapeditor where code = ?', [code])
        rrf = dbcur.fetchone()
        if rrf is None:
            return -1
        else:
            return rrf[0]
    def getMapDel(self, code):
        dbcur.execute('select deleted from mapeditor where code = ?', [code])
        rrf = dbcur.fetchone()
        if rrf is None:
            return -1
        else:
            return rrf[0]
    def getProfileTitle(self, username):
        found = False
        for room in self.rooms.itervalues():
            for player in room.clients.itervalues():
                if player.username == username:
                    found = player.titleNumber
        return found

    def getProfileTribe(self, username):
        found = False
        for room in self.rooms.itervalues():
            for player in room.clients.itervalues():
                if player.username == username:
                    found = player.tribe
        return found

    def getProfileSaves(self, username):
        found = False
        for room in self.rooms.itervalues():
            for player in room.clients.itervalues():
                if player.username == username:
                    found = player.micesaves
        return found

    def getProfileShamanCheese(self, username):
        found = False
        for room in self.rooms.itervalues():
            for player in room.clients.itervalues():
                if player.username == username:
                    found = player.shamancheese
        return found

    def getProfileFirstCount(self, username):
        found = False
        for room in self.rooms.itervalues():
            for player in room.clients.itervalues():
                if player.username == username:
                    found = player.firstcount
        return found

    def getProfileCheeseCount(self, username):
        found = False
        for room in self.rooms.itervalues():
            for player in room.clients.itervalues():
                if player.username == username:
                    found = player.cheesecount
        return found

    def getProfileTitleList(self, username):
        found = False
        for room in self.rooms.itervalues():
            for player in room.clients.itervalues():
                if player.username == username:
                    titlelist = player.titleList
                    titlelist = json.dumps(titlelist)
                    titlelist = titlelist.replace("[","")
                    titlelist = titlelist.replace("]","")
                    titlelist = titlelist.replace("\"","")
                    titlelist = titlelist.replace(" ","")
                    return titlelist
        return found

    def sendPrivMsg(self, fromUsername, toUsername, message):
        found = False
        for room in self.rooms.itervalues():
            for player in room.clients.itervalues():
                if player.username.lower() == toUsername.lower():
                    player.sendRecievePrivMsg(fromUsername, message)
                    found = True
        return found

    def disconnectPlayer(self, username):
        found = False
        for room in self.rooms.itervalues():
            for player in room.clients.itervalues():
                if player.username == username:
                    room.informAll(TransformiceClientHandler.sendPlayerDisconnect, [player.playerCode])
                    room.removeClient(player)
                    player.close()
                    found = True
                    print '%s disconnected' % (player.username)
                    break
        return found

    def banPlayer(self, username, time, reason, modname):
        found = False
        time = int(time)
        for room in self.rooms.itervalues():
            for playerCode, client in room.clients.iteritems():
                if client.username == username:
                    client.sendPlayerBan(time, reason)
                    if time >= 25:
                        clientaddr = client.address[0]
                        dbcur.execute("insert into ippermaban (ip, bannedby, reason) values (?, ?, ?)", (clientaddr, modname, reason))
                        dbcur.execute("insert into userpermaban (name, bannedby, reason) values (?, ?, ?)", (username, modname, reason))
                    #player.close()
                    found = True
                    break
        return found

    def getIPaddress(self, username):
        found = False
        for room in self.rooms.itervalues():
            for playerCode, client in room.clients.iteritems():
                if client.username == username:
                    found = client.address[0]
                    break
        return found
    
    def restartServer(self):
        logging.info("Restarting")
        found = False
        for room in self.rooms.itervalues():
            for player in room.clients.itervalues():
                #room.informAll(TransformiceClientHandler.sendPlayerDiscnnect, [player.playerCode])
                room.updatesqlserver()
        #os.system("restart.bat")
    def updateit(self):
        room.updatesqlserver()
    def stopServer(self):
        logging.info("Stopping")
        found = False
        for room in self.rooms.itervalues():
            for player in room.clients.itervalues():
                #room.informAll(TransformiceClientHandler.sendPlayerDiscnnect, [player.playerCode])
                room.updatesqlserver()
        os.system("stop.bat")

    def checkAlreadyExistingGuest(self, nusername):
        count = 0
        for room in self.rooms.itervalues():
            for player in room.clients.itervalues():
                playername = player.username
                count = count+1
                if player.username == nusername:
                    nusername = nusername+"_"+str(count)
        return nusername

    def checkAlreadyConnectedAccount(self, username):
        found = False
        for room in self.rooms.itervalues():
            for player in room.clients.itervalues():
                if player.username == username:
                    found = True
        return found
    def findUser(self, username):
        found = False
        for player in room.clients.intervalues():
            if player.username == username:
                found = self.room
        return found

    def addClientToRoom(self, client, roomName):
        roomName = str(roomName)
        if self.rooms.has_key(roomName):
            self.rooms[roomName].addClient(client)
        else:
            self.rooms[roomName] = TransformiceRoomHandler(self, roomName)
            self.rooms[roomName].addClient(client)
        #return self.rooms[roomName]

    def closeRoom(self, room):
        if self.rooms.has_key(room.name):
            room.close()
            del self.rooms[room.name]

    def getConnectedPlayerCount(self):
        count = 0
        for room in self.rooms.itervalues():
            for player in room.clients.itervalues():
                count = count+1
        return count
        #return 1
    def findPlayer(self, username):
        found = "Offline"
        for room in self.rooms.itervalues():
            for player in room.clients.itervalues():
                if player.username == username:
                    found = room.name
        return found
    def setShaman(self, roomz, usernamez):
        found = False
        for room in self.rooms.itervalues():
            if room.name == roomz:
                for player in room.clients.itervalues():
                    if player.username == usernamez:
                        found = player.playerCode
        return found
    def getConnectedRooms(self):
        rooms = ""
        for room in self.rooms.itervalues():
            old = rooms
            new = "%s\n%s" % (old, room.name)
            rooms = new
            roomz = new
        return roomz
    def getConnectedPlayers(self):
        players = ""
        for room in self.rooms.itervalues():
            for player in room.clients.itervalues():
                #self.room.sendData("\x1A" + "\x04", ["[Serveur] %s -> %s" % (player.username, room.name)])
                #playerfound = "%s -> %s" % (player.username, room.name)
                old = players
                new = "%s\n%s -> %s" % (old, player.username, room.name)
                players = new
                playerfound = new
        return playerfound
    def generatePlayerCode(self):
        return random.randrange(1, 10000000)

    def recommendRoom(self):
        return 1
        #return min(self.rooms.itervalues(), key=lambda room: abs(len(room.clients) - 20)).name

class TransformiceStateRecorder(object):
    def __init__(self, room):
        self.room = room

        self.reset()

    def reset(self):
        self.sateLog = []

        self.lastPhysicsStateEvent = None
        self.anchors = []

    def log(self, eventTokens, values):
        self.sateLog.append((eventTokens, values))
    def logMessage(self, messageFunction, args):
        self.sateLog.append((messageFunction, args))

    def setPhyscisState(self, eventTokens, values):
        self.lastPhysicsStateEvent = (eventTokens, values)
    def addAnchor(self, values):
        self.anchors.extend(values)

    def sendToClient(self, client):
        if self.lastPhysicsStateEvent:
            eventTokens, value = self.lastPhysicsStateEvent
            client.sendData(eventTokens, value)

        for sendThing, value in self.sateLog:
            if type(sendThing) == types.FunctionType:
                sendThing(client, *value)
            else:
                client.sendData(sendThing, value)

        if len(self.anchors) > 0:
            client.sendSetAnchors(self.anchors)

class TransformiceRoomHandler(object):
    def __init__(self, server, name):
        self.server = server
        self.name = name.strip()

        self.clients = {}

        #self.stateRecorder = TransformiceStateRecorder(self)

        self.currentShamanCode = None
        self.currentSyncroniserCode = None

        self.isSandbox = False
        self.isCustom = False
        self.customMap = None
        self.isEditeur = False
        self.editeurMap = ""
        self.isTesting = False
        self.customShaman = None
        self.isCustomsh = False
        self.isPlay = False
        self.racing = False
        self.isBootcamp = False
        self.specificMap = False
        self.isSnowing = False
        self.properNoShamanMaps = True
        self.isCatchTheCheeseMap = False
        self.currentTime = 0
        self.alreadySet = False
        self.currentlyDrawing = False
        self.currentDrawer = None

        #               Code[0], Name[1], XML[2], YesVotes[3], NoVotes[4], Perma[5], Deleted[6]
        self.ISCMdata = [0, "Invalid", "", 0, 0, 0, 0]
        self.ISCM = 0
        self.ISCMstatus = 0

        #                Code[0], Name[1], XML[2], YesVotes[3], NoVotes[4], Perma[5], Deleted[6], Validated[7]
        self.ISCMVdata =[0, "Invalid", "null", 0, 0, 0, 0, 0]
        self.ISCMV = 0
        self.ISCMVloaded = 0

        self.snowStormStartTimer = threading.Timer(random.randrange(900, 1500), self.startSnowStorm)
        self.snowStormStartTimer.start()

        #self.currentWorld = random.choice(LEVEL_LIST)
        runthismap = random.choice(LEVEL_LIST)
        self.currentWorld = runthismap
        if self.name == "repeat":
            self.specificMap = True
            self.isPlay = True
            self.currentWorld = "0"
        if self.name == "sandbox":
            self.specificMap = True
            self.isSandbox = True
            self.currentWorld = "444"
        if self.name == "801":
            self.specificMap = True
            self.isSandbox = True
            self.currentWorld = "801"
        if self.name == "racing":
            self.specificMap = True
            self.racing = True
            self.maps = ["@16","@22", "@29", "@42", "@18", "@93", "@94", "@95", "@96", "@97", "@98" , "@99", "@100" ]
        if self.name.startswith("bootcamp"):
            self.countStats = False
            self.currentWorld = "@122429"
            #self.specificMap = True
            self.isBootcamp = True
            self.autoRespawn = True
            self.roundTime = 360
            self.never20secTimer = True

        if self.name.startswith("\x03"+"[Editeur] "):
            self.countStats = False
            self.currentWorld = 0
            #self.specificMap = True
            self.isEditeur = True
            self.roundTime = 120
            self.never20secTimer = True


        self.everybodyIsShaman = self.isSandbox
        self.nobodyIsShaman = self.isBootcamp


        self.worldChangeTimer = None
        self.bootcampRespawnt = None
        self.killAfkTimer= None
        if not self.isSandbox:
                if self.currentWorld==888:
                    self.worldChangeTimer = threading.Timer(60, self.worldChange)
                elif self.isBootcamp:
                    self.worldChangeTimer = threading.Timer(360, self.worldChange)
                    self.bootcampRespawnt = threading.Timer(15, self.bootcampRespawn)
                else:
                    self.worldChangeTimer = threading.Timer(120, self.worldChange)
                self.worldChangeTimer.start()
                try: self.bootcampRespawnt.start()
                except: pass
                self.killAfkTimer = threading.Timer(30, self.killAfk)
                self.killAfkTimer.start()
                #self.world20 = threading.Timer(20, self.worldChange)
        self.gameStartTime = time.time()
        self.numCompleted = 0
        self.numGotCheese = 0

    def close(self):
        if self.worldChangeTimer:
            self.worldChangeTimer.cancel()
        if self.killAfkTimer:
            self.killAfkTimer.cancel()
        if self.snowStormStartTimer:
            self.snowStormStartTimer.cancel()
    def worldChange(self):
        #self.stateRecorder.reset()
        try: self.worldChangeTimerz.cancel()
        except: pass
        self.alreadySet = False
        self.currentSyncroniserCode = None

        for playerCode, client in self.clients.iteritems():
            client.isAfk=True

        for playerCode, client in self.clients.iteritems():
            if client.playerCode == self.currentShamanCode:
                client.score = 0

        if self.clients.has_key(self.currentShamanCode):
            currentShaman = self.clients[self.currentShamanCode]
            for playerCode, client in self.clients.iteritems():
                try:
                    if self.isCatchTheCheeseMap==True:
                        self.isCatchTheCheeseMap=False
                    else:
                        numCompleted = self.numCompleted-1
                        if numCompleted < 0:
                            numCompleted = 0
                        client.sendShamanPerformance(currentShaman.username, numCompleted)
                except:
                    pass
            currentShamanCode = None

        for playerCode, client in self.clients.iteritems():
            client.resetPlay()

        if not self.specificMap:
            runthismap = random.choice(LEVEL_LIST)
            if runthismap == self.currentWorld:
                runthismap = random.choice(LEVEL_LIST)
            self.currentWorld = runthismap
        print self.currentWorld, self.specificMap

        for playerCode, client in self.clients.iteritems():
            client.startPlay()

        if self.currentWorld==888:
            self.worldChangeTimer = threading.Timer(60, self.worldChange)
        elif self.isBootcamp:
            self.worldChangeTimer = threading.Timer(360, self.worldChange)
            self.bootcampRespawnt = threading.Timer(15, self.bootcampRespawn)
            self.bootcampRespawnt.start()
        else:
            self.worldChangeTimer = threading.Timer(120, self.worldChange)
        #self.worldChangeTimer = threading.Timer(120, self.worldChange)
        self.worldChangeTimer.start()
        self.killAfkTimer = threading.Timer(30, self.killAfk)
        self.killAfkTimer.start()
        if self.isSandbox:
            self.worldChangeTimer.cancel()
            self.killAfkTimer.cancel()
        self.gameStartTime = time.time()
        self.numCompleted = 0
        self.numGotCheese = 0
    def worldChangeSpecific(self, mapnumber):
        self.alreadySet = False
        try: self.worldChangeTimerz.cancel()
        except: pass
        mapnumber = int(mapnumber)
        if self.worldChangeTimer:
            self.worldChangeTimer.cancel()
        if self.killAfkTimer:
            self.killAfkTimer.cancel()
        #self.stateRecorder.reset()
        self.currentSyncroniserCode = None
        for playerCode, client in self.clients.iteritems():
            client.isAfk=True
        if self.clients.has_key(self.currentShamanCode):
            currentShaman = self.clients[self.currentShamanCode]
            for playerCode, client in self.clients.iteritems():
                try:
                    if self.isCatchTheCheeseMap==True:
                        self.isCatchTheCheeseMap=False
                    else:
                        client.sendShamanPerformance(currentShaman.username, self.numCompleted)
                except:
                    pass
            currentShaman.micesaves = self.numCompleted + currentShaman.micesaves
        self.currentShamanCode = None
        for playerCode, client in self.clients.iteritems():
            client.resetPlay()
        self.currentWorld = mapnumber
        for playerCode, client in self.clients.iteritems():
            client.startPlay()
        if self.currentWorld==888:
            self.worldChangeTimer = threading.Timer(60, self.worldChange)
        elif self.racing:
            self.worldChangeTimer = threading.Timer(60, self.worldChange)
            self.Timerz = threading.Timer(58, self.changingMap1)
            self.Timerz2 = threading.Timer(59, self.changingMap1)
            self.Timerz.start()
            self.Timerz2.start()
        else:
            self.worldChangeTimer = threading.Timer(120, self.worldChange)
        self.worldChangeTimer.start()
        self.killAfkTimer = threading.Timer(30, self.killAfk)
        self.killAfkTimer.start()
        if self.isSandbox:
            self.worldChangeTimer.cancel()
            self.killAfkTimer.cancel()
        self.gameStartTime = time.time()
        self.numCompleted = 0
        self.numGotCheese = 0

    def checkShouldChangeWorld(self):
        if not self.isSandbox:
            if not self.isBootcamp:
                if all(client.isDead for client in self.clients.itervalues()):
                    self.worldChangeTimer.cancel()
                    self.killAfkTimer.cancel()
                    self.worldChange()

    def checkIfShamanCanGoIn(self):
        allgone=1
        #if all(client.isDead for client in self.clients.itervalues()):
        for playerCode, client in self.clients.iteritems():
            if client.playerCode != self.currentShamanCode:
                if client.isDead:
                    pass
                else:
                    allgone=0
        if allgone==1:
            return 1
        else:
            return 0
    def setTimer(self):
        print 'setTimer() called(alreadySet: %s)'%(str(self.alreadySet))
        if self.alreadySet:
            pass
        else:
            print 'changing Timer...'
            try: self.worldChangeTimer.cancel()
            except: pass
            try: self.worldChangeTimerz.cancel()
            except: pass
            self.worldChangeTimerz = threading.Timer(20, self.worldChange)
            self.worldChangeTimerz.start()
            print ':20 Set'
            self.alreadySet = True
    def resetSandbox(self):
        if self.isSandbox:
            for playerCode, client in self.clients.iteritems():
                resetpscore=0
                self.informAll(TransformiceClientHandler.sendPlayerDied, [playerCode, resetpscore])
                client.isDead=True
            if all(client.isDead for client in self.clients.itervalues()):
                #self.worldChangeTimer.cancel()
                #self.worldChange()
                for playerCode, client in self.clients.iteritems():
                    client.resetPlay()
                self.currentWorld = self.currentWorld
                for playerCode, client in self.clients.iteritems():
                    client.startPlay()
        else:
            pass

    def addClient(self, newClient):

        self.clients[newClient.playerCode] = newClient

        self.informAllOthers(newClient, TransformiceClientHandler.sendNewPlayer, [newClient.getPlayerData()])

        newClient.room = self

        newClient.startPlay()
        #self.stateRecorder.sendToClient(newClient)

    def updatesqlserver(self):
        for playerCode, client in self.clients.iteritems():
            if client.username.startswith("*"):
                pass
            else:
                dbcur.execute('UPDATE users SET rounds = ? WHERE name = ?', [client.roundCount, client.username])
                dbcur.execute('UPDATE users SET saves = ? WHERE name = ?', [client.micesaves, client.username])
                dbcur.execute('UPDATE users SET shamcheese = ? WHERE name = ?', [client.shamancheese, client.username])
                dbcur.execute('UPDATE users SET first = ? WHERE name = ?', [client.firstcount, client.username])
                dbcur.execute('UPDATE users SET cheese = ? WHERE name = ?', [client.cheesecount, client.username])
                dbcur.execute('UPDATE users SET shopcheese = ? WHERE name = ?', [client.shopcheese, client.username])
                dbcur.execute('UPDATE users SET shop = ? WHERE name = ?', [client.shopitems, client.username])
                dbcur.execute('UPDATE users SET look = ? WHERE name = ?', [client.look, client.username])
                dbcur.execute('UPDATE users SET lastroom = ? WHERE name = ?', [client.room, client.username])


    def removeClient(self, removeClient):
        if self.clients.has_key(removeClient.playerCode):

            for playerCode, client in self.clients.iteritems():
                if playerCode == removeClient.playerCode:
                    if client.username.startswith("*"):
                        pass
                    else:
                        dbcur.execute('UPDATE users SET rounds = ? WHERE name = ?', [client.roundCount, client.username])
                        dbcur.execute('UPDATE users SET lastroom = ? WHERE name = ?', ["Offline", client.username])
                        dbcur.execute('UPDATE users SET saves = ? WHERE name = ?', [client.micesaves, client.username])
                        dbcur.execute('UPDATE users SET shamcheese = ? WHERE name = ?', [client.shamancheese, client.username])
                        dbcur.execute('UPDATE users SET first = ? WHERE name = ?', [client.firstcount, client.username])
                        dbcur.execute('UPDATE users SET cheese = ? WHERE name = ?', [client.cheesecount, client.username])
                        dbcur.execute('UPDATE users SET shopcheese = ? WHERE name = ?', [client.shopcheese, client.username])
                        dbcur.execute('UPDATE users SET shop = ? WHERE name = ?', [client.shopitems, client.username])
                        dbcur.execute('UPDATE users SET look = ? WHERE name = ?', [client.look, client.username])

            del self.clients[removeClient.playerCode]

            if self.getPlayerCount() == 0:
                self.server.closeRoom(self)
                return

            self.informAll(TransformiceClientHandler.sendPlayerDisconnect, [removeClient.playerCode])
            if self.currentSyncroniserCode == removeClient.playerCode:
                newSyncroniser = random.choice(self.clients.values())
                newSyncroniser.isSyncroniser = True

                self.currentSyncroniserCode = newSyncroniser.playerCode
                self.informAll(TransformiceClientHandler.sendSynchroniser, [newSyncroniser.playerCode])

        self.checkShouldChangeWorld()

    def changeSyncroniserRandom(self):
        newSyncroniser = random.choice(self.clients.values())
        newSyncroniser.isSyncroniser = True
        self.currentSyncroniserCode = newSyncroniser.playerCode
        self.informAll(TransformiceClientHandler.sendSynchroniser, [newSyncroniser.playerCode])
    def getPlayerName(self, code):
        for room in self.server.rooms.itervalues():
            for playerCode, client in room.clients.iteritems():
                if client.playerCode == code:
                    return client.username
    def getPlayerCode(self, name):
        for room in self.server.rooms.itervalues():
            for playerCode, client in room.clients.iteritems():
                if client.username == name:
                    return client.playerCode
    def changeSyncroniserSpecific(self, username):
        for room in self.server.rooms.itervalues():
            for playerCode, client in room.clients.iteritems():
                if client.username == username:
                    newSyncroniser = client
                    break
        newSyncroniser.isSyncroniser = True
        self.currentSyncroniserCode = newSyncroniser.playerCode
        self.informAll(TransformiceClientHandler.sendSynchroniser, [newSyncroniser.playerCode])

    def playMusic(self, path):
        self.informAll(TransformiceClientHandler.sendPlayMusic, [path])

    def changeScore(self, playerCode, score):
        for playerCode, client in self.clients.iteritems():
            if client.playerCode == playerCode:
                client.score = score

    def startSnowStorm(self):
        self.sendAllOthersAndSelf(self, "\x05" + "\x17", ["0"])
        self.isSnowing=True
        self.endSnowStormTimer = threading.Timer(300, self.endSnowStorm)
        self.endSnowStormTimer.start()

    def endSnowStorm(self):
        self.sendAllOthersAndSelf(self, "\x05" + "\x17", [])
        self.isSnowing=False
        self.snowStormStartTimer = threading.Timer(random.randrange(900, 1500), self.startSnowStorm)
        self.snowStormStartTimer.start()

    def informAll(self, clientFunction, args):
        for playerCode, client in self.clients.iteritems():
            lol = "%r"%(clientFunction)
            if "TransformiceClientHandler.sendPlayMusic" in lol:
                if client.musicOff:
                    pass
                else:
                    clientFunction(client, *args)
            else:
                clientFunction(client, *args)

    def informAllOthers(self, senderClient, clientFunction, args):
        for playerCode, client in self.clients.iteritems():
            if playerCode != senderClient.playerCode:
                clientFunction(client, *args)

    def sendAll(self, eventTokens, data = None):
        for playerCode, client in self.clients.iteritems():
            client.sendData(eventTokens, data)
    def sendAllOthers(self, senderClient, eventTokens, data):
        for playerCode, client in self.clients.iteritems():
            if client.playerCode != senderClient.playerCode:
                client.sendData(eventTokens, data)
    def sendAllOthersAndSelf(self, senderClient, eventTokens, data):
        for playerCode, client in self.clients.iteritems():
            client.sendData(eventTokens, data)

    def sendWholeServer(self, senderClient, eventTokens, data):
        for room in self.server.rooms.itervalues():
            for playerCode, client in room.clients.iteritems():
                client.sendData(eventTokens, data)
    def sendTribeMsg(self, sendClient, eventTokens, data):
        for room in self.server.rooms.itervalues():
            for playerCode, client in room.clients.iteritems():
                #self.room.sendTribeMsg(self, "\x10\x14", ['6', self.username, self.tribeName])
                #print data
                if client.tribeName == data[0]:
                    lol = data
                    if lol[1] == "6":
                        lol = data
                        #[self.username, tribe, user])
                        data2 = [lol[1], lol[2], lol[3]]
                    elif lol[1] == '12':
                        #self.room.sendTribeMsg(self, "\x10\x04", ['12', name, rank])
                        lol = data
                        data2 = [lol[1], lol[2], lol[3]]
                        #print 'Sent: '+str(data2)
                    elif lol[1] == '13':
                        #[str(self.tribeName), '13', '1', name])
                        lol = data
                        data2 = [lol[1], lol[2], lol[3]]
                    elif lol[1] == '11':
                        #[str(self.tribeName), '11', player])
                        lol = data
                        data2 = [lol[1], lol[2]]
                        if lol[2] == client.username:
                            client.tribeName = ""
                    else:
                        lol = data
                        data2 = [lol[1], lol[2]]
                    client.sendData(eventTokens, data2)
    def sendTribeChat(self, senderClient, eventTokens, data):
        for room in self.server.rooms.itervalues():
            for playerCode, client in room.clients.iteritems():
                try:
                    #[tmessage, self.username, self.tribeName)
                    tribe = data[2]
                    lol = [data[1], data[0]]
                    if client.tribeName == tribe:
                        if client.tribeMuted:
                            pass
                        else:
                            client.sendData(eventTokens, lol)
                except:
                    pass
    def sendRecruit(self, senderClient, eventTokens, data):
        for room in self.server.rooms.itervalues():
            for playerCode, client in room.clients.iteritems():
                #[self.username, tribe, user])
                try:
                    if client.username == data[2]:
                        lol = data
                        data = [2, lol[0], lol[1]]
                        client.sendData(eventTokens, data)
                except:
                    print '[ERROR] Recruit: %s'%(str(data))
    def sendAdminChat(self, senderClient, eventTokens, data):
        for room in self.server.rooms.itervalues():
            for playerCode, client in room.clients.iteritems():
                if client.privilegeLevel>=3 and not client.isDrawer:
                    client.sendData(eventTokens, data)
    def sendServeur(self, senderClient, eventTokens, data):
        for room in self.server.rooms.itervalues():
            for playerCode, client in room.clients.iteritems():
                if client.privilegeLevel>=5 and not client.isDrawer:
                    client.sendData(eventTokens, data)
    def sendFriend(self, senderClient, eventTokens, data):
        for room in self.server.rooms.itervalues():
            for playerCode, client in room.clients.iteritems():
                friendList = self.server.getUserFriends(client.username).split(",")
                user = str(data).replace("['", "").replace("']", "")
                if user in friendList:
                    client.sendData(eventTokens, data)
    def sendTribes(self, senderClient, eventTokens, data):
        for room in self.server.rooms.itervalues():
            for playerCode, client in room.clients.iteritems():
                users = self.server.getTribeUsers(data[1]).split(",")
                if client.username in users:
                    data[5] = client.tribeRank
                    #print 'Data: '+str(data)
                    client.sendData(eventTokens, data)
                else:
                    pass
    def sendModChat(self, senderClient, eventTokens, data):
        for room in self.server.rooms.itervalues():
            for playerCode, client in room.clients.iteritems():
                if client.privilegeLevel>=5 and not client.isDrawer:
                    client.sendData(eventTokens, data)
    def killAfk(self):
        for playerCode, client in self.clients.iteritems():
            if client.isAfk == True:
                client.isDead = True
                client.score -= 1
                if client.score < 0:
                    client.score = 0
                self.informAll(TransformiceClientHandler.sendPlayerDied, [playerCode, client.score])
                self.checkShouldChangeWorld()
            else:
                pass

    def killAll(self):
        for playerCode, client in self.clients.iteritems():
            resetpscore=client.score+1
            self.informAll(TransformiceClientHandler.sendPlayerDied, [playerCode, resetpscore])
            client.isDead=True
        self.checkShouldChangeWorld()

    def killShaman(self):
        for playerCode, client in self.clients.iteritems():
            if client.playerCode == self.currentShamanCode:
                client.score -= 1
                if client.score < 0:
                    client.score = 0
                self.informAll(TransformiceClientHandler.sendPlayerDied, [playerCode, client.score])
                client.isDead=True
        self.checkShouldChangeWorld()

    def getPlayerCount(self):
        return len(self.clients)

    def getPlayerList(self):
        for playerCode, client in self.clients.iteritems():
            yield client.getPlayerData()

    def getHighestShaman(self):
        clientscores = []
        clientcode = 0
        for playerCode, client in self.clients.iteritems():
            clientscores.append(client.score)
        for playerCode, client in self.clients.iteritems():
            if client.score==max(clientscores):
                clientcode=playerCode
                clientname=client.username
        return clientcode
    def getHighestShamanTwo(self):
        clientscores = []
        clientcode = 0
        for playerCode, client in self.clients.iteritems():
            clientscores.append(client.score)
        for playerCode, client in self.clients.iteritems():
            if client.score==max(clientscores):
                clientcode=playerCode
                clientname=client.username
                clientscores.remove(client.score)
                #print 'client scores 2: '+str(clientscores)
        for playerCode, client in self.clients.iteritems():
           # print 'Client Scores: '+str(clientscores)
            try:
               # print 'before max'
                if client.score==max(clientscores):
                    clientcode=playerCode
                    #print 'clientcode: '+str(clientcode)
                    clientname=client.username
            except:
                print 'Error o0'
                clientcode = 0
        return clientcode
    def getDoubleShamanCode(self, number):
        if number == 1:
            shamanOne = self.getHighestShaman()
            return shamanOne
        if number == 2:
            shamanTwo = self.getHighestShamanTwo()
            return shamanTwo
    def getShamanCode(self):
        if self.currentShamanCode is None:
            if self.currentWorld in [7, 8, 54, 55, 57, 70, 77, 78, 87, 88, 89, 92, 99, 1007, 888]:
                self.currentShamanCode = 0
            else:
                #self.currentShamanCode = random.choice(self.clients.keys())
                if self.isCustomsh:
                    self.currentShamanCode = self.customShaman
                    self.isCustomsh = False
                else:
                    self.currentShamanCode = self.getHighestShaman()
        return self.currentShamanCode

    def getSyncroniserCode(self):
        if self.currentSyncroniserCode is None:
            self.currentSyncroniserCode = random.choice(self.clients.keys())
        return self.currentSyncroniserCode

class TransformiceClientHandler(asynchat.async_chat):
    def __init__(self, server, sock, address):
        self.server = server
        self.address = address

        asynchat.async_chat.__init__(self, sock=sock)
        self.buffer = ""
        self.set_terminator("\x00")
        self.validatingVersion = True


        self.username = ""
        self.playerCode = -1
        self.privilegeLevel = 0
            #0 - Guest
            #1 - Normal player
            #3 - Arb
            #5 - Mod
            #6 - Super Mod
            #8 - Mega Mod
            #10 - Admin
        self.room = None

        self.isShaman = False
        self.isDead = False
        self.isAfk = True
        self.isSyncroniser = False
        self.score = 0
        self.fur = '78583a'
        self.busy = False
        self.lastmessage = ""
        self.isDrawer = False
        #Tribes
        self.haveTribe = False
        self.tribeName = ""
        self.musicOff = False
        self.tribeMuted = False
        self.tribeGreeting = ""
        self.tribeSettings = ""
        self.tribeRank = ""
        #
        self.isinit = True
        self.sentinelle = False

        self.wrongPasswordAttempts=0

        self.giftCount = 0
        self.gotGift = 0

        self.titleNumber = 0

        self.Tellfirsttime = 0

        self.shoplist = "0,3,20;0,5,100;0,2,200;0,4,200;0,1,500;0,6,500;1,1,200;1,2,200;0,7,200;0,8,5000;0,9,500;0,10,100;0,11,500;1,4,200;0,12,200;0,13,500;0,14,0;1,3,200;1,5,300;0,15,200;3,1,999;3,2,25;3,3,150;3,4,400;0,16,300;0,17,200;0,18,300;0,19,300;0,20,500;0,21,200;2,1,100;3,5,300;0,22,300;0,23,400;0,24,50;0,25,250;0,26,300;0,27,800;0,28,300;0,29,500;4,1,200;4,2,200;0,30,200;0,31,300;0,32,800;0,33,150;0,34,400;0,35,5000;0,36,500;0,37,200;0,38,800;1,6,800;2,2,50;0,39,200;0,40,500;0,41,800;0,42,500;4,3,200;2,3,20;0,43,200;0,44,250;0,45,300;0,46,100;0,47,1500;1,7,50;2,4,20;3,6,300;3,7,300;4,4,50"

        self.cheeseTitleCheckList = [5, 20, 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000, 1100, 1200, 1300, 1400, 1500, 1600, 1700, 1800, 2000, 2300, 2700, 3200, 3800, 4600, 6000, 7000, 8000, 9001, 10000, 14000, 18000, 22000, 26000, 30000, 34000, 38000, 42000, 46000, 50000, 55000, 60000, 65000, 70000, 75000, 80000]
        self.cheeseTitleDictionary = {5:5, 20:6, 100:7, 200:8, 300:35, 400:36, 500:37, 600:26, 700:27, 800:28, 900:29, 1000:30, 1100:31, 1200:32, 1300:33, 1400:34, 1500:38, 1600:39, 1700:40, 1800:41, 2000:72, 2300:73, 2700:74, 3200:75, 3800:76, 4600:77, 6000:78, 7000:79, 8000:80, 9001:81, 10000:82, 14000:83, 18000:84, 22000:85, 26000:86, 30000:87, 34000:88, 38000:89, 42000:90, 46000:91, 50000:92, 55000:234, 60000:235, 65000:236, 70000:237, 75000:238, 80000:93}
        self.firstTitleCheckList = [1, 10, 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000, 1100, 1200, 1400, 1600, 1800, 2000, 2200, 2400, 2600, 2800, 3000, 3200, 3400, 3600, 3800, 4000, 4500, 5000, 5500, 6000, 7000, 8000, 9000, 10000, 12000, 14000, 16000, 18000, 20000, 25000, 30000, 35000, 40000]
        self.firstTitleDictionary = {1:9, 10:10, 100:11, 200:12, 300:42, 400:43, 500:44, 600:45, 700:46, 800:47, 900:48, 1000:49, 1100:50, 1200:51, 1400:52, 1600:53, 1800:54, 2000:55, 2200:56, 2400:57, 2600:58, 2800:59, 3000:60, 3200:61, 3400:62, 3600:63, 3800:64, 4000:65, 4500:66, 5000:67, 5500:68, 6000:69, 7000:231, 8000:232, 9000:233, 10000:70, 12000:224, 14000:225, 16000:226, 18000:227, 20000:202, 25000:228, 30000:229, 35000:230, 40000:71}
        self.shamanTitleCheckList = [10, 100, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000, 11000, 12000, 13000, 14000, 15000, 16000, 18000, 20000, 22000, 24000, 26000, 28000, 30000, 35000, 40000, 45000, 50000, 55000, 60000, 65000, 70000, 75000, 80000, 85000, 90000, 100000, 140000]
        self.shamanTitleDictionary = {10:1, 100:2, 1000:3, 2000:4, 3000:13, 4000:14, 5000:15, 6000:16, 7000:17, 8000:18, 9000:19, 10000:20, 11000:21, 12000:22, 13000:23, 14000:24, 15000:25, 16000:94, 18000:95, 20000:96, 22000:97, 24000:98, 26000:99, 28000:100, 30000:101, 35000:102, 40000:103, 45000:104, 50000:105, 55000:106, 60000:107, 65000:108, 70000:109, 75000:110, 80000:111, 85000:112, 90000:113, 100000:114, 140000:115}
        self.shopTitleCheckList = [1, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22]
        self.shopTitleDictionary = {1:115, 2:116, 4:117, 6:118, 8:119, 10:120, 12:121, 14:122, 16:123, 18:124, 20:125, 22:126}
        self.noelGiftTitleCheckList = [5, 10, 40, 60]
        self.noelGiftTitleDictionary = {5:127, 10:128, 40:129, 60:130}

    def collect_incoming_data(self, data):
        self.buffer += data

    def found_terminator(self):
        #print self.buffer
        if self.buffer == "SuperBelette":
            self.isinit = False
            self.sentinelle = True
            usedram=psutil.avail_phymem()
            totalram=psutil.TOTAL_PHYMEM
            usedram = usedram / 1048576
            usedram = '%.1f' % usedram
            totalram = totalram / 1048576
            totalram = '%.1f' % totalram
            self.sendData("\x05", [
            "0", "0", "0", "0", "0", "0", "0", "0", "0", "0",
            "0", "0", "0", "0", "0", "0", "0", "0", "0", "0",
            "0", "0", "0", "0", "0", "0", "0", "0", "0", "0",
            "0", "0", "0", "0", "0", "0", "0", "0", "0", "0",
            "0", "0", "0", "0", "0", "0", "0", "0", "0", "0",
            "0", "0", "0", "0", "0", "0", "0", "0", "0", "0",
            "0", "0", "0", "0", "0", "0", "0", "0", "0", "0",
            "0", "0", "0", "0", "0", "0", "0", "0", "0", "0",
            "0", "0", "0", "0", "0", "0", "0", "0", "0", "0",
            "0", "0", "0", "0", "0", "0", "0", "0", "0", "0",
            "0", "0", "0", "0", "0", "0", "0", "0", "0", "0",
            "0", "0", "0", "0", "0", "0", "0", "0", "0", "0",
            "0", "0", "0", "0", "0", "0", "0", "0", "0", "0",
            "0", "0", "0", "0", "0", "0", "0", "0", "0", "0",
            "0", "0", "0", "0", "0", "0", "0", "0", "0", "0",
            "0", "0", "0", "0", "0", "0", "0", "0", "0", "0",
            "0", "0", "0", "0", "0", "0", "0", "0", "0", "0",
            "0", "0", "0", "0", "0", "0", "0", "0", "0", "0",
            "0", "0", "0", "0", "0", "0", "0", "0", "0", "0",
            "0", "0", "0", "0", "0", "0", "0", "0", "0", "0",
            "\x00\x04", str(usedram)+"/"+str(totalram), "* - 0.126", str(self.server.getConnectedPlayerCount()),
            "\x00\x06", str(random.randrange(0, 10))])
        #logging.warning("BUFFER: %s" % self.buffer)
        if self.validatingVersion:
            if self.buffer == "":
                dbcur.execute('select * from ippermaban where ip = ?', [self.address[0]])
                rrf = dbcur.fetchone()
                if rrf is None:
                    pass
                else:
                    self.close()

                if VERBOSE:
                    logging.debug("Policy file request")
                self.push(r"""""" % (self.server.PORT) + "\x00")
                self.close_when_done()

            else:
                #version, bytesLoaded1, bytesLoaded2 = self.buffer.split("\x01")
                version = self.buffer
                if self.isinit:
                    #self.sendData("\x1A" + "\x16",["Q1dTCikUAAB4nKVXW3PbxhXGEiRBkBJNUTJsS7ZFS7Rky5QIUBJtMbJsmhQVOZYli/IlF0VckQsSMQkwAEhJSdO06SVtk7ZJp+Pp9MntUzx+yUxfOtOZJh3/ATkduzN970N/QJ/dswBISrKTSVMOdvecg3Pbb3cPlhUm/CXDRhgmiphsz1GGYd7vdXsYZlYvyanVbC6yXauqRgq4i0MV06yn4vGtra2JrckJTS/HpZmZmbiYiCcS46AxbuyoJt4eV43hobmI5SFLjKKu1E1FUyOUx5taw7w4NOS43a7V225VYwKXtE0yUdRq8W1cj0sTYpz6AaVURifY1PQ1TavOpalWJFfFRiWSyU9FVnRNJoYBIXB1Nn5Qe489yUKbS4iSOC6eH5fOryXE1FQyJU6dExMpUdxja2vapkvExCVs4o6xlBgXk9RYnE5NS+dEqW28T9cx10qKvPOtjDuakdn4AfS+HZ6lYhvOekOvWmtUKsZJldSIahoAqWRBWiqmZE2vYXMO1+tVpYipw/j2uFHRine3cJOMyxTe2XhH8bumBDNbWvrmRa7V4i1tw1wl8jdrG2s7dRJfJYbW0IsE1IedTbK0lFpUDROrRbKYnQPBhKKUUpkLyUlpano+mRaleVGSZuanE/PzSVHKzqST01MZC/v9pi1vWa3YoLg53kr/g7c9pi1vy7pSVmCLvsBrdjpzPi1dEbPijJTNSVI6k8ukpUQyCaLJzORUy+sLXLRzJbrSJKWcrtWsVahj3SAUqYtDLagoTBa+KeV5mBI5SYR408nk103sOdOWt9J3mdBzpi1v2v8D09e6iLQXpoPTi7d03Cl8cxEm44Jy+MXhQ9AjJv/owdsNAjOPSCDs+zJIhfALMRN0+A1i3E1NKfGvKHc1bQOOT9cSVtQ1pUaqikq6rfMEszDqVbzDL2lNhWSqSl1oq6f2qrP/+uhD7/LmW6Ro+oHcgAZPm/zT590dKTyhfRw8vQcF8AgvkMHj3sQG6c7aidkh0U1v3tQVtey6mWAhmBcaHWQd14jkW9LUEkkmk6ecU9o5oun8ZDwhisn4ZkOpmooasF81TKVq9NoI4GKR1upNpaqYOy1UiHHX1OpdNkd0XdONFtOkdSvoMNsm0WFdHTMZYhDd8NtcmWg1J0a5qm3iqvKOVdUCtqxGSgrmbVolZnebmijpNcd/HeYMWZfbrAYhiO7oGrhW38MR1eikaewYJqk5mZiQZ7BDTsCa9uxhiQqbk/hsSUNx8rMwcvKDUnhk335JtfdL3355HlI2SXS/cN9aZjT4JEM8fXC/0qIK2OGiCYfBVhz4BifH9y5Gap4O9D02ixWi+2leV7UGaeiBl3HDnFczUG4MV3SKjUqSKyoF51U4GWQjT/QmKIUyWolYe8jR5KkDS8A1FdgaVRLMgx8aQVMp672Fq2DYswh+7E+VY+le2chnPbRL+KnJxqPPNh498FAy4V3QNcMgvjIx6anSe9dIrW4ccPzvh7+Djc3CsruXsFnx6lgtabUuGapDpoJ1mim7ks8HoGqoCtGptW+lsmMoUApCtQ16VLF+i1S1IuxmtOO93qhtEp2bmpBEUZTcRaJUvbfxXXKz7ltKX92g9izEdC2tnMw+emBiwI8WqI0ruFrV1I0OksElrdG03mXJZsMMrWiGQiee09QiHV150deie63sHn2mk1uPHlipPHrgykte+ASAvb+q4RLRF1VZY+FK4IHyXSb+zR2TGGuaiasBi7xGlUq+PCk2dDqVsQDNaCur1WDzuOlB5xRYoO1lOWQCSAa9FChF69QH72pqWSdluLdYbIk0FQybTjctViVbZV1rqCWDsuywFHHTU9WVwXVsVQGFGH661YhOP1f+PHxeSmlAg7DDiQhvZ39z9Zp7WBIj3pVqo7yo9sw7lcDaxTIuEh43sVLFsKbs8GTktNywoTlz9l2dmA1djai4qZTppXACbjzXoY699J67CHPk0tYZuMMOT0fY4WTEW4R1T5touOsW1BZwQfEvdzvmZE2DVPzQVglsAcMc3HMnPghMnKhxz4ZBqvKAvc9e2B/9uneeeVoI0XwQl+BzBRnnra/UoQPHr+e5kyy8uAB47WJxRkACK3iOckdYD+NhfMeEfmFAOC6cEE4Kg0JEOCUMCcNCVDgtjAijwhnhrDAmnBNiwrgwIcQFsZ/rl/oT/ZP9U/3T/cl+3jXqRZzL4+P9AbarO3go1BPu7TssHDl6rH/g+ImTg+7IqaHh6OmR0Tc55OJcbo71csjHIZ5Dfg4FONTFoW4OBTl0iEMhju3hUJhDvRzq49BhDgmc58gA4s8j/gLiZxCfQvxLiJ9F/CXEX0Z8GvFXEJ9BfBbx84jPIX4BcSdf5hcRfxVx6BUOXePQEue7zi8jfgUkaxy6xd9A/G3E30H8q4h/HfFvIH4d8W8ifgPxq4jPI76AeAzKm3wR8SUgCIeKHJI5VOZlxJcRd6zCobc4VOJ8Ve6YwSGT30Jc8B0Ovcuh7/MfIMT/GCGu9yfQfop4H+IFxP8cpL8AKfoI2sfQfom47l8hjv01tE+gfYq89CZhXSusqwXjYlo/5GJ9bsbd7WZgzSw1jnY+2vG089MuQLsuhulm4HZyCK4m0PUgBoUR4+pFDAt+PMjlRuABkvGzu+ICFbH+wN+A3pXdsaNyX3iZYYCUD8tCzzmLpNwR2h29T/tj96OoQyz3I0t7BAvUwUW57/TvPb1+yzA2J/eN4oEFqnBcPtEcC0PWZyl38l74GrLCDIYzNhGRT4Qv2OSpPZpDzfAQchIaDgsMsx7NRS3+9B+ipS4AaiEU3i9NWFJgxp7II58+ffwVHvG5fFaax0fxCRgjeNAKaXOj+BT0hUPro4UzubNMtPTH3CjKjSF8DsSWYxyzEojdkPtiq9DyhTPr47GbuXGUm0Cf4D47vfiyaCc6sixZ0RJjT2KvyX2P08xZK/woHoJ+edLSmgoPWCCN4ikretQNIWHww+Cg2hFyVAgjTcvCfqQF/DTtkvg8rKTL6/YH/oN2xTNPHMTvdXAcBJp36Mi+N6fuhf/aWvK4fEGeaVjmqSgTvG/LU4+DH1tU9BlOtTE5bQUZsSAcsSAcseYHaZJ9UN5vY+m56mEc6G07+fBoG6unFKuvKFYuunZPYe3+8dXfYe1YS2DP9CV8PuS1cnmMUx0KZs962EDon55d8fbYE3F33VOYlWdzHlRx71K7i/JcxQuUt8LtFi7Jl+V0xWcTVyq8o5Gp+B0qWwkU5mPKcg7tUjeVrtCXcM525a4eOIChP9OoXfLlZgtRoOWFZvi3IHeYSnBXDsbu5l5GUaYvT/WDsRrlnj0cC3dZRsGYelCgHRTUbUG4GzzE3obs71e8oRlI4ayTgrwQ0+0gRximsChfjTV6LeWmo9zl5ETnMPvsmTO/VyohW/nhvVaw0MH8QgfzCx3ML9TOj6cht+2QHccUHIvbeXgvPAX5XZOXeqzsvudkN0iFsfdy11EP/SsFBWtXfCy+xow9HRPP1dAJn+vF3vZw74NvWm1iP0B74u88HOvxdVTCYSe6pflDRxP6KJNbRrEfoYed47ByLwx5rN9YX419iK6uotjP0PINJ48+rwUnR23dcn7saZSBLUvptbCPLgn3QchNR+8HlkIUyX1wXH3393L8Ps6/jwvcTyN7/8uJXTmMbzpUD761gD5n/8J+wd6+w7hZ5A+EoGIvMuuv0rLXu/yqC46AxwVlfXRXJEzBIxZeEwvdYuF1sfCGWFgXCyw8d5gT9q9C1S/1Djifmva/0Im9/0KZy/Dqvzy6H0s="])
                    self.sendData("\x1A" + "\x16", ["Q1dTCjQQAAB4nKVWzVcbyRGf1kgatQQChD182VgGGWwM0owAgbQYGySEsS1DLNa7+WBRI/WgWUszysyIj1xyzCE5bC5+eTmRHPLWL5e8l3s+HsdcsPPs/AV7yB+Qc1I9M0jIZjebjd5Md1V1VXX1r6prVOUif+H4KMfFEJfrG+Q47qf9Xh/HLRkVJfMsl48e1WuamQHu3ljVshqZROLw8DB+OBvXjf2EnE6nE1IykUzOgMaMeaxZ5GhGM8fHlqO2hxw1y4basFRdizKe7OlN697YmOv2qN5oudXMOKnoezRe1uuJI9JIyHEpwfyAUiZrUGLpxrau15ZXmFY0XyNmNZotzkW3DF2hpglbkNpS4n3tC/Y0B+9yUpKlGWlhRl7YTkqZuVRGmrsrJTOSdMHW0XRMC9QiFWKRtrGcnJHT27KckVMZOX1XklvGHbquuV5RleNvZdzWjC4l3kPv2+FZKbfgbDSNmp2jSjlBa7RONcsESGUb0ko5o+hGnVjLpNGoqWXCHCaOZsyqXn5xSA7ojMLgXUq0Fb9rSHCyQuGbk1yvJ861TesZVb5Z29w+btDEM2rqTaNMQX3cLZJCIbOhmRbRynQjtwyCuKpWMsmVOTmblubm09LqmiTLi7mFtZX5uYVFKbeYXk2lbOw7Tc+95fRyk+Hmeqv8D94umJ572zTUfRVK9BKvufnswoq8KuWktJzLy/JKNp9dkZOpFIhms7Nz514vcdGKlRrqAa3kDb1uZ6FBDJMypO6NnUPFYLLxzaiXwJT+bwf7wPTcW+W7HOgD03Nv+v8D09e6iLYS08bp8pJOuI1vOcplPdAO/3y1B0bEFU9f/bhJ4eRRGYRX/hZkQvj1cnE2aZz3QFcr+LH6Qtd34fZ0FYiqbat1WlM12m1fJziE2aiRY1zQD1SarakNsaWeuajOf/Xzn/k39z6nZSsI5C688HS3SXh6Ozh4+t8XwCNeIoOH/+qPf/DDyybFIHUqBwq6VqGpVOqme/Xa926lOJtISlIqsddUa5aqhZylpqXWzH7nXKRcZg14T62p1vH5Wan5wtIbXQ5HDUM3zHPmgDWjsMscWdSAZLlmCuxBDTPocPtUr7t77Nf0PVJTf2K3qpAjq9OKSrBDa9TqblHxilF3/TcMVYOo91usDltQw9U1Sb1xgaOa2Q7TPDYtWncjsSDOcJuMQ6b6LrBUg4qjAUfSVN34bIzc+KC/DXRUQaZVBVc65UUI2aKxTmHOmZ2iyOrwnYX9jBudShsaYEfKFlS4ozjyDU6uXUxGZo1NbJ1Y5So1giyuR3qTNo3QQ9K01rQs9BDTE5vjY7LsicnhNQ3qne4WqXEASr1ZvULtGnI1MXNgC4QDFUqjRsNF8MN20DXG+p+TGhj2bYAf5/vjWnq3dos5HxuSQWaye/rl7ukrHyOT/nVDN00a2KcWuytG/zatN8z3HP/z979ihV20IPP7PGTfWyBW1W8QraLXuxS4+dkqMVjA/FaxGIKOoKnUYE4CW9VjU4Vr3lvfZfeQGM9pTS9DUaNj/9NmfY8awlxcliRJ9papWvN/Ql7QjxuBwsqjXWbPw9aewtZo7vSVRQBG1nx2V0mtpmu7bUDDBb15YK/l6F7T6t3STZWdP69rZTZ7ilLgnO63ozv90qDPT1/ZoZy+8hRlP7R3sA/WdFKhxoam6Dx87n3QmvdpcO/Youa2bpFayCafMKVKoEjLTYMdZSrEIjrM6XWooREHrUvHwa9bC5MKdFDoG0W7cfa8VzzdHXXW90FVipcXs98p/NsiEnnRNygM8D7OxwX6xSviVVEUB8RBcUgcFkfEa+J1cVS8IUbFm+KYOC7GxFvihDgp3hbviFPDwvDd4enhmeH4cGJYGsaeST8SPL4ADob4ru5wT29fpP/KVXFgcGh45Nr10Rve6M2x8diticnHAvIIHq/A+wUUEBAWUFBAIQF1CahbQGEB9QioV/D1jSAsI5xEeBbhOYTnEU4hnEY4g/BHCC8hfA/hZYTvI/wA4RUkjK7iLMI5JKA1AeUFtC6gh0JgAz9C+DEINwX0PfwE4WcIFxHeRvg5wp8g/CnC30f4BwgXEH6K8A8R/hEo7+DPEN4FoiSgzwREBLSHCcJ7SBgqC4jiAMIKwvugUBW6VYH/XOBfCHxN4Ot+9pGyv1j2V+vCD3n4gJfzYi8HaNtqAhsCbMBsCLIhhDjUhThPN+J4sPEhjxeBNkI4yJ9J60zEB0N/BfpM8U5HlHBkk+OAVHqU3r67Nsm4PjZETtjYfxJDbWLzCrK1J0gvc7CghG/92tcftA2nF5XwJLm6zhREZeBgKgIR3mHc4MvIE2RvMxTJOsSwMhBZdMiRC5rXDiJjyA3oekTkuJ3R/KjN3/hNrAIn49Z7I53SpC0FZuqtEv3lu9dvSDTgCdhhipNkAOYoGbK3dLhJMgJj6ebOWGk8H+Nild/mx1D+FiITILYdk0k7gOknSni6AO/T0vjO7emt/G2Uv4O+IGEnvKnNu06gE5vT9m4zU2+nP1bCr1e4O/b2k+QajJtxWysRGbFBmiQJe/eYF7aEKQiTi2pbKDAhzCwsG/voOfAsbYpMkpBJj98bDP0LnUm337qIv2zjOAQ0dunhjpWRl5E/nad8SplV5pq2+XyMC5848vnX4V/YVOzfZL6FyQ17kwkbwgkbwgn7fBAm7YDypIWl75GPc6F37JSeyRZW7xhWbxhWHpa7d5C7f7z5O+SOtwXOSVMk2eu3Y3lN5tsUnJ73eYKh38Hpz3Z8pQVlIe9DVe8Zs1lU0lX/WSmjfKQsVQWHuFcNuGvLVexS96vB0oPpyuaKHdDq1NsYB8k7U/w2G0NKGKAXTi5ygQ4Od3DBkxXk5F2ZOVO6SNalQiQH4Xp5FAz1QrQb3M5aDI7RvbnmAbnPA1dz8kyiXMknlfJSaV0qPZRKG1LpkVTi4fmUu+78qkz9fv+I2xpa/0jjF/+Rcg9g6T8g+fg0"])
                    self.isinit = False
                if version == VERSION:
                    self.sendCorrectVersion()
                else:
                    self.close_when_done()
                self.validatingVersion = False
        else:
            if re.match("http://", self.buffer):
                self.buffer=""
            #elif self.buffer=="\x04":
            #    self.buffer==""
            #elif self.buffer=="\x05":
            #    self.buffer==""
            else:
                self.parseData(self.buffer)

        self.buffer = ""

    def startRestart(self, time):
        self.timer1 = threading.Timer(1, self.restartMin2)
        self.timer1.start()
        #self.sendServerMessage("Server is restarting in 5...")
    def restartMin2(self):
        try: self.timer1.cancel()
        except: pass
        self.sendRestartMessage("O servidor irá reiniciar em 2 minutos")
        self.timer1 = threading.Timer(60, self.restartMin1)
        self.timer1.start()
    def restartMin1(self):
        try: self.timer1.cancel()
        except: pass
        self.sendRestartMessage("O servidor irá reiniciar em 1 minuto")
        self.timer1 = threading.Timer(30, self.restartMin30)
        self.timer1.start()
    def restartMin30(self):
        try: self.timer1.cancel()
        except: pass
        self.sendRestartMessage("O servidor irá reiniciar em 30 segundos")
        self.timer1 = threading.Timer(15, self.restartMin15)
        self.timer1.start()
    def restartMin15(self):
        try: self.timer1.cancel()
        except: pass
        self.sendRestartMessage("O servidor irá reinicar em 15 segundos")
        self.timer1 = threading.Timer(5, self.restart10)
        self.timer1.start()
    def restart10(self):
        try: self.timer1.cancel()
        except: pass
        self.sendRestartMessage("O servidor irá reiniciar em 10 segundos")
        self.timer1 = threading.Timer(1, self.restart9)
        self.timer1.start()
    def restart9(self):
        try: self.timer1.cancel()
        except: pass
        self.sendRestartMessage("O servidor irá reinicar em in 9 segundos")
        self.timer1 = threading.Timer(1, self.restart8)
        self.timer1.start()
    def restart8(self):
        try: self.timer1.cancel()
        except: pass
        self.sendRestartMessage("O servidor irá reinicar em 8 segundos")
        self.timer1 = threading.Timer(1, self.restart7)
        self.timer1.start()
    def restart7(self):
        try: self.timer1.cancel()
        except: pass
        self.sendRestartMessage("O servidor irá reinicar em 7 segundos")
        self.timer1 = threading.Timer(1, self.restart6)
        self.timer1.start()
    def restart6(self):
        try: self.timer1.cancel()
        except: pass
        self.sendRestartMessage("O servidor irá reinicar em 6 segundos")
        self.timer1 = threading.Timer(1, self.restart5)
        self.timer1.start()
    def restart5(self):
        try: self.timer1.cancel()
        except: pass
        self.sendRestartMessage("O servidor irá reinicar em 5 segundos")
        self.timer1 = threading.Timer(1, self.restart4)
        self.timer1.start()
    def restart4(self):
        try: self.timer1.cancel()
        except: pass
        self.sendRestartMessage("O servidor irá reinicar em 4 segundos")
        self.timer1 = threading.Timer(1, self.restart3)
        self.timer1.start()
    def restart3(self):
        try: self.timer1.cancel()
        except: pass
        self.sendRestartMessage("O servidor irá reinicar em 3 segundos")
        self.timer1 = threading.Timer(1, self.restart2)
        self.timer1.start()
    def restart2(self):
        try: self.timer1.cancel()
        except: pass
        self.sendRestartMessage("O servidor irá reinicar em 2 segundos")
        for room in self.server.rooms.itervalues():
            for player in room.clients.itervalues():
                try:room.updatesqlserver()
                except: pass
                self.server.disconnectPlayer(player)
    def rested(self, time):
        self.restartTimer(time)
    def parseData(self, data):
        MDT_stuff = data[:4]
        data = data[4:]
        #print data
        values = data.split("\x01")
        #print repr(MDT_stuff), values

        #logging.warning("DATA: %s" % data)
        #logging.warning("DATAD: %s" % repr(MDT_stuff))
        #logging.warning("DATAV: %s" % values)

        eventTokens = values.pop(0)
        eventToken1, eventToken2 = eventTokens

        if eventToken1 == "\x1A":
            if eventToken2 == "\x02":
                #awake timer
                unknownTime, = values
                unknownTime = int(unknownTime)

            elif eventToken2 == "\x03":
                #create account
                username, passwordHash = values

                username = username.replace("<","")

                if self.server.checkExistingUsers(username):
                    self.sendData("\x1A" + "\x03", ) #Nickname Already Taken message
                else:
                    passwordHash=hashlib.sha512(passwordHash).hexdigest()
                    self.server.createAccount(username, passwordHash)
                    self.login(username, passwordHash, "1")

            elif eventToken2 == "\x0E":
                    #Sent Change Password
                    if self.privilegeLevel!=0:
                        utfLength=struct.unpack('!h', data[:2])[0]
                        PassHash=data[2:utfLength+2]
                        data=data[utfLength+2:]
                        utfLength=struct.unpack('!h', data[:2])[0]
                        ForumPassHash=data[2:utfLength+2]
                        data=data[utfLength+2:]
                        utfLength=struct.unpack('!h', data[:2])[0]
                        ForumSalt=data[2:utfLength+2]
                        if self.ValidatedPassChange:
                            self.ValidatedPassChange=False
                            passwordHash=hashlib.sha512(PassHash).hexdigest()
                            dbcur.execute('UPDATE users SET password = ? WHERE name = ?', [passwordHash, self.username])
                            
            elif eventToken2 == "\x04":
                #login
                username, passwordHash, startRoom = values

                if passwordHash != "":
                    passwordHash=hashlib.sha512(passwordHash).hexdigest()
                username = username.replace("<","")

                self.login(username, passwordHash, startRoom)

            else:
                logging.warning("Unimplemented %r" % eventTokens)
                #raise NotImplementedError, eventTokens
        elif eventToken1 == "\x04":

            if eventToken2 == "\x03":
                #print 'values: '+str(values)
                #world physics update
                #CodePartieEnCours = values.pop(0)
                #for objectData in values:
                #    if objectData == 'x':
                #        continue
                #    objectType, x, y, dx, dy, rotation, angularVelocity, isSolid, valuea = objectData.split(',')

                if self.isSyncroniser:
                    self.room.sendAllOthersAndSelf(self, eventTokens, values)
                    #self.room.stateRecorder.setPhyscisState(eventTokens, values)

            elif eventToken2 == "\x04":
                #position update
                #isMovingRight, isMovingLeft, x, y, dx, dy, isJumping, jumpAnimation = values
                #self.room.sendAllOthers(self, eventTokens, values + [self.playerCode])
                self.room.sendAll(eventTokens, values + [self.playerCode])

            elif eventToken2 == "\x05":
                #player went out of bounds
                self.isDead = True

                #score
                #self.score = self.score-1
                #if self.score < 0:
                #    self.score = 0
                #end
                self.score -= 1
                if self.score < 0:
                    self.score = 0
                self.room.informAll(TransformiceClientHandler.sendPlayerDied, [self.playerCode, self.score])

                self.room.checkShouldChangeWorld()
            elif eventToken2 == "\x06":
                # "Demande_Giclage"
                #objectCode, = values
                self.room.sendAll(eventTokens, values)


            elif eventToken2 == "\x08":
                #direction, = values
                #direction = int(direction)
                self.room.sendAllOthersAndSelf(self, eventTokens, [self.playerCode] + values)

            elif eventToken2 == "\n":
                #unknown, happens on first move on current map
                self.isAfk=False
                #pass
            elif eventToken2 == "\x0C":
                #unknown, happens on start conjuration
                self.isAfk=False
                #pass
            elif eventToken2 == "\r":
                #unknown, happens on end conjuration
                pass
            elif eventToken2 == "\x07":
                #unknown, happens on jumping.
                pass
            elif eventToken2 == "\x0E":
                #conjuration
                x, y = values
                self.DestroyConjurationTimer = threading.Timer(10, self.sendDestroyConjuration, args=[x, y])
                self.DestroyConjurationTimer.start()
                #print values
                self.room.sendAllOthersAndSelf(self, eventTokens, values)

            elif eventToken2 == "\x10":
                #snowball
                if self.room.isSnowing==True:
                    x, y, direction = values
                    if direction == "1":
                        self.room.sendAllOthers(self, "\x05" + "\x14", [self.playerCode, 34, x, y, 0, 10, -4, 1])
                    if direction == "0":
                        self.room.sendAllOthers(self, "\x05" + "\x14", [self.playerCode, 34, x, y, 0, -10, -4, 1])
                if self.room.isSnowing==False:
                    self.room.informAll(TransformiceClientHandler.sendPlayerDisconnect, [self.playerCode])
                    self.room.removeClient(self)
                    hmessage = "["+self.address[0]+" - "+self.username+"] Snowball when not snowing."
                    self.sendAdminMessageChannel("Hack Detect", hmessage)
                    self.close()


            elif eventToken2 == "\x09":
                #begin/end crouch
                crouching, = values
                crouching = bool(int(crouching))
                if crouching:
                    self.room.sendAllOthersAndSelf(self, eventTokens, [self.playerCode] + values)
                else:
                    self.room.sendAllOthersAndSelf(self, eventTokens, [self.playerCode])
            elif eventToken2 == "\x12":
                x, y = values
                self.room.sendAllOthersAndSelf(self, eventTokens, [self.playerCode] + values)
                #pass
            elif eventToken2 == "\x13":
                self.room.sendAllOthersAndSelf(self, eventTokens, [self.playerCode])
                #pass

            elif eventToken2 == "\x14":
                print 'x14'

            else:
                logging.warning("Unimplemented %r" % eventTokens)
                #raise NotImplementedError, eventTokens
        elif eventToken1 == "\x06":
            if eventToken2 == "\x06":
                #sent chat message
                message, = values

                message = message.replace("<","")
                #print 'Message: '+str(message)
                #if "shit" in str(message).lower():
                #    print 'Shit detected'
                #    message = message.replace("shit", "shyte")

                hackdetect = 0
                if self.privilegeLevel == 0:
                    self.room.informAll(TransformiceClientHandler.sendPlayerDisconnect, [self.playerCode])
                    self.room.removeClient(self)
                    hmessage = "["+self.address[0]+" - "+self.username+"] Guest tried to send chat message."
                    self.sendAdminMessageChannel("Hack Detect", hmessage)
                    self.close()
                    hackdetect = 1


                logging.info("(%s) %s: %r" % (self.room.name, self.username, message))
                print '(%s) %s: %r' % (self.room.name, self.username, message)
                if message.strip()==self.lastmessage:
                    pass
                elif hackdetect==1:
                    pass
                else:
                    self.lastmessage=message.strip()
                    self.room.sendAll(eventTokens, [self.playerCode, self.username, message.strip()])
            elif eventToken2 == "\x1A":
                #sent command

                event, = values
                event_raw = event.strip()
                event = event_raw.lower()

                EVENTRAWSPLIT = event_raw.split(" ")
                EVENTCOUNT = len(EVENTRAWSPLIT)

                logging.info("(%s) [c] %s: %r" % (self.room.name, self.username, event))
                print '(%s) [c] %s: %r' % (self.room.name, self.username, event)
                if len(event) == 1:
                    event = "INVALID"

                if EVENTCOUNT == 1:
                    if event in ("dance", "danse"):
                        self.room.informAll(TransformiceClientHandler.sendPlayerAction, [self.playerCode, 1])
                    elif event in ("laugh", "rire"):
                        self.room.informAll(TransformiceClientHandler.sendPlayerAction, [self.playerCode, 2])
                    elif event in ("cry", "pleurer"):
                        self.room.informAll(TransformiceClientHandler.sendPlayerAction, [self.playerCode, 3])
                    elif event in ("kiss", "bisou"):
                        self.room.informAll(TransformiceClientHandler.sendPlayerAction, [self.playerCode, 4])
                    elif event == "disconnect":
                        self.room.informAll(TransformiceClientHandler.sendPlayerDisconnect, [self.playerCode])
                        self.room.removeClient(self)
                        self.close()
                    elif event == "titlepls":
                        playerCode = self.room.getPlayerCode(self.username)
                        titlenum = '440'
                        self.sendUnlockedTitle(playerCode, titlenum)
                        titleList = self.server.getTitleList(self.username)
                        print titleList
                        lol = array('c', titleList)
                        print lol
                        lol.append('440')
                        print lol
                    elif event == "back":
                        self.sendData("\x0E" + "\x0E",[self.room.editeurMap])
                    elif event == "lsmodo":
                        #"\x1A\x05", [name, message])
                        for room in self.server.rooms.itervalues():
                            for player in room.clients.itervalues():
                                if player.privilegeLevel>=5:
                                    if player.privilegeLevel==5:
                                        priv = "Modo"
                                    elif player.privilegeLevel==6:
                                        priv = "SuperModo"
                                    elif player.privilegeLevel==8:
                                        priv = "MegaModo"
                                    elif player.privilegeLevel==10 and not player.isDrawer:
                                        priv = "Admin"
                                    elif player.privilegeLevel==10 and player.isDrawer:
                                        priv = "Drawer"
                                    else:
                                        priv = "Unknown"
                                    self.sendData("\x1A" + "\x05", ["Serveur", "%s[%s] : %s"%(player.username, priv, room.name)])
                    elif event == "clear":
                        self.sendData("\x1A" + "\x04", [""])
                    elif event == "hide":
                        if self.privilegeLevel == 10 and not self.isDrawer:
                            self.room.informAll(TransformiceClientHandler.sendPlayerDisconnect, [self.playerCode])
                            #self.sendData("\x1A" + "\x04", ["[Serveur] You are now hiding, Remember that after this round you won't be hidden anymore"])
                            self.sendData("\x06" + "\x14", ["Você está agora escondido/invisivel.Lembre-se que após esta rodada não vai ser escondido mais"])
                    elif event == "teste":
                        if self.privilegeLevel == 10 and not self.isDrawer:
                            self.sendServeurMessage("Teste Complete, Proness ^_^")
                    elif event == "stop":
                        if self.privilegeLevel == 10 and not self.isDrawer:
                            musicmessage = "stop"
                            self.room.informAll(TransformiceClientHandler.sendPlayMusic, [musicmessage])
                    elif event == "vanilla":
                        self.enterRoom("vanilla1")
                    elif event == "bootcamp":
                        self.enterRoom("bootcamp1")
                    elif event == "playercount":
                        count = 0
                        for room in self.room.itervalues():
                            for player in room.clients.itervalues():
                                count = count+1
                        self.sendAdminMessageChannel("PlayerCount", count)
                    elif event == "ranking":
                        if self.privilegeLevel==1:
                            self.sendData("\x1A" + "\x04", ["""Ranking:
Rank em Construção, Aguardem ^.^!!
Shaman (Mice saved)
Em Construção!

Mouse (Cheese gathered)
Em Construção!

Mouse (First places)
Em Construção!"""])
                    elif event == "ranking1":
                        if self.privilegeLevel==10:
                            self.sendData("\x1A" + "\x04", ["""Ranking:
Rank em Construção, Aguardem ^.^!!
Shaman (Mice saved)
Em Construção!

Mouse (Cheese gathered)
Em Construção!

Mouse (First places)
Em Construção!"""])
                    elif event == "ranking2":
                        if self.privilegeLevel==8:
                            self.sendData("\x1A" + "\x04", ["""Ranking:
Rank em Construção, Aguardem ^.^!!
Shaman (Mice saved)
Em Construção!

Mouse (Cheese gathered)
Em Construção!

Mouse (First places)
Em Construção!"""])
                    elif event == "ranking3":
                        if self.privilegeLevel==6:
                            self.sendData("\x1A" + "\x04", ["""Ranking:
Rank em Construção, Aguardem ^.^!!
Shaman (Mice saved)
Em Construção!

Mouse (Cheese gathered)
Em Construção!

Mouse (First places)
Em Construção!"""])
                    elif event == "ranking4":
                        if self.privilegeLevel==5:
                            self.sendData("\x1A" + "\x04", ["""Ranking:
Rank em Construção, Aguardem ^.^!!
Shaman (Mice saved)
Em Construção!

Mouse (Cheese gathered)
Em Construção!

Mouse (First places)
Em Construção!"""])
                    elif event == "ranking5":
                        if self.privilegeLevel==3:
                            self.sendData("\x1A" + "\x04", ["""Ranking:
Rank em Construção, Aguardem ^.^!!
Shaman (Mice saved)
Em Construção!

Mouse (Cheese gathered)
Em Construção!

Mouse (First places)
Em Construção!"""])        
                    elif event == "ajuda":
                        if self.privilegeLevel==10 and not self.isDrawer:
                            str_help = """List of Commands:
/a message - Chat Arbitro
/m message - Mod Chat
/lsplayers - Mostra os usuários online e seus devidos quartos
/players - Mostra o total de usuários online
/startsnow - Inicia a neve
/stopsnow - Para a neve
/music musiclink.mp3 - Reproduz uma musica na sala
/ch Username - Escolhe o shaman da próxima rodada
/party - Todos os usuários irão dançar na sala
/delavatar Username - Chuta um usuário do servidor sem que ele perceba
/ban username hours reason - Bane o usuário. Bans de menos de 24 horas o usuário poderá cumpri com o prazo. Ban acima de 24 horas= ban perma
/clear - Limpa o chat
/csr - Sync Aleatório
/sy? - Mostra o usuário com melhor conexão da sala. ( Nasa )
/map map - Coloca um mapa na sala, coloque o @.
/map - Mata todo mundo colocando outro mapa
/cheese user amount - Dá queijos à alguem
/snpc name clothing x y - Coloca npcs na sala
/npcspam - Spams noobs
/ranking1 - Aparece o Ranking"""
                        elif self.privilegeLevel==10 and self.isDrawer:
                            str_help = "Você é apenas um desenhista :p"
                        elif self.privilegeLevel==8:
                            str_help = """List of Commands:
/ranking2 - Aparece o Ranking"""
                        elif self.privilegeLevel==6:
                            str_help = """List of Commands:
/a message - Chat Arbitro
/m message - Mod Chat
/music musiclink.mp3 - Reproduz uma musica na sala
/ch Username - Escolhe o shaman da próxima rodada
/delavatar Username - Chuta um usuário do servidor sem que ele perceba
/ban username hours reason - Bane o usuário. Bans de menos de 24 horas o usuário poderá cumpri com o prazo. Ban acima de 24 horas= ban perma
/clear - Limpa o chat
/sy? - Mostra o usuário com melhor conexão da sala. ( Nasa )
/map map - Coloca um mapa na sala, coloque o @.
/map - Mata todo mundo colocando outro mapa
/ls user - Procura o usuário e sua sala
/ranking3 - Aparece o Ranking"""
                        elif self.privilegeLevel==5:
                            str_help = """List of Commands:
/a message - Chat Arbitro
/m message - Mod Chat
/music musiclink.mp3 - Plays music in room
/ch Username - Escolhe o shaman da próxima rodada
/delavatar Username - Chuta um usuário do servidor sem que ele perceba
/ban username hours reason - Bane o usuário. Bans de menos de 24 horas o usuário poderá cumpri com o prazo. Ban acima de 24 horas= ban perma
/clear - Limpa o chat
/sy? - Mostra o usuário com melhor conexão da sala. ( Nasa )
/map map - Coloca um mapa na sala, coloque o @.
/map - Mata todo mundo colocando outro mapa
/ls user - Procura o usuário e sua sala
/ranking4 - Aparece o Ranking""" 
                        elif self.privilegeLevel==3:
                            str_help = """List of Commands:
/a message - Arb Chat
/ch Username - Escolhe o shaman da próxima rodada
/ban username hours reason - Bane um usuário pelo tempo determinado. Arbitros só podem dar ban de no máximo 2 horas.
/clear - Limpa o chat
/map map - Coloca um mapa na sala, coloque o @.
/map - Mata todo mundo colocando outro mapa
/ls user - Procura o usuário e sua sala
/ranking5 - Aparece o Ranking"""  
                        else:
                            str_help == "Unsupported!"
                        self.sendData("\x06" + "\x14", [str_help])
                    elif event == "editeur":
                        if self.username.startswith("*"):
                            pass
                        else:
                            self.enterRoom("\x03"+"[Editeur] "+self.username)
                            self.sendData("\x0E" + "\x0E",[])
                    elif event in ("kill", "suicide", "bubbles", "die"):
                        self.isDead = True
                        self.score -= 1
                        if self.score < 0:
                            self.score = 0
                        self.room.informAll(TransformiceClientHandler.sendPlayerDied, [self.playerCode, self.score])
                        self.room.checkShouldChangeWorld()
                    elif event == "info":
                        if self.privilegeLevel>=5 and not self.isDrawer:
                            name = self.server.getMapName(self.room.customMap)
                            yes = int(self.server.getMapYesVotes(self.room.customMap))
                            no = int(self.server.getMapNoVotes(self.room.customMap))
                            perma = int(self.server.getMapPerma(self.room.customMap))
                            if yes > no:
                                percent = round(float(no)/float(yes), 0)
                            elif yes < no:
                                percent = round(float(yes)/float(no), 0)
                            else:
                                percent = 0
                            total = yes+no
                            if perma == 0:
                                perm = "P0"
                            elif perma == 1:
                                perm = "P1"
                            #Arkanlol - @215938 - 2389 - 52% - P0
                            self.sendData("\x1A" + "\x04", ["[Serveur] "+name+" - "+self.room.customMap+" - "+str(total)+" - "+str(percent)+"% - "+str(perm)])
                    elif event == "del":
                        if self.privilegeLevel >= 5 and not self.isDrawer:
                            if self.room.isCustom:
                                dbcur.execute('UPDATE mapeditor set deleted = ? WHERE code = ?', ["1", str(self.room.customMap)])
                                self.sendServeurMessage("[%s] %s is now deleted."%(self.username,str(self.room.customMap)))
                    elif event == "p1":
                        if self.privilegeLevel >= 5 and not self.isDrawer:
                            if self.room.isCustom:
                                print '%s is now perm'%(self.room.customMap)
                                self.room.informAll(TransformiceClientHandler.sendMapPerm, [])
                                dbcur.execute('UPDATE mapeditor set perma = ? WHERE code = ?', ["1", str(self.room.customMap)])
                                self.sendServeurMessage("[%s] O mapa %s agora é permanente."%(self.username,str(self.room.customMap)))
                    elif event == "p0":
                        if self.privilegeLevel >= 5 and not self.isDrawer:
                            if self.room.isCustom:
                                print '%s is now perm'%(self.room.customMap)
                                self.room.informAll(TransformiceClientHandler.sendMapPerm, [])
                                dbcur.execute('UPDATE mapeditor set perma = ? WHERE code = ?', ["0", str(self.room.customMap)])
                                self.sendServeurMessage("[%s] O mapa %s não é mais permanente."%(self.username,str(self.room.customMap)))
                    #elif event == "killall":
                        #if self.privilegeLevel==10:
                            #self.room.killAll()
                    elif event == "np" or event == "map":
                        if self.privilegeLevel>=3 and not self.isDrawer:
                            self.room.killAll()
                    elif event == "sy?":
                        if self.privilegeLevel>=5 and not self.isDrawer:
                            player = self.room.getPlayerName(self.room.currentSyncroniserCode)
                            self.sendData("\x1A" + "\x04", ["[Serveur] Sync in cours: %s"%(player)])
                    elif event == "csr":
                        if self.privilegeLevel==10 and not self.isDrawer:
                            self.room.changeSyncroniserRandom()
                    elif event == "log":
                        if self.privilegeLevel>=5 and not self.isDrawer:
                            #user, ip, who, hours, reason
                            self.sendData("\x1A" + "\x17", ["Log em Construção!"])
                    elif event in ("vote"):
                        if self.privilegeLevel==10 and not self.isDrawer:
                            self.sendVoteBox("Oly", 50, 0)
                        else:
                            pass
                    elif event in ("greetingz"):
                        if self.privilegeLevel==10 and not self.isDrawer:
                            self.sendChangeGreeting()
                        else:
                            pass
                    elif event in ("conjuration"):
                        self.sendDestroyConjurationz()
                    elif event in ("players", "ls"):
                        if self.privilegeLevel>=5 and not self.isDrawer:
                            #self.sendAdminMessageChannel("Server", "There are %s users online" % (self.server.getConnectedPlayerCount()))
                            self.sendData("\x1A" + "\x04", ["[Serveur] Players online: %s" % (self.server.getConnectedPlayerCount())])
                    elif event in ("lsplayers"):
                        if self.privilegeLevel>=5 and not self.isDrawer:
                            self.sendData("\x1A" + "\x04", ["[Serveur] "+self.server.getConnectedPlayers()])
                    elif event in ("lsrooms"):
                        if self.privilegeLevel>=5 and not self.isDrawer:
                            self.sendData("\x1A" + "\x04", ["[Serveur] "+self.server.getConnectedRooms()])
                    elif event in ("startsnow"):
                        if self.privilegeLevel==10 and not self.isDrawer:
                            self.room.isSnowing=True
                            self.sendStartSnowStorm()
                            self.sendData("\x1A" + "\x04", ["Snow has started. To stop snow use /stopsnow."])
                            self.sendServeurMessage("[%s] Started snow (%s)" % (self.username, self.room.name))
                            print '%s started snow' % (self.username)
                    elif event in ("new"):
                        self.sendData("\x1A" + "\x04", ["- Fixed map rotation, everything should work normally. - /cmap mapcode has been added for custom maps - It will tell you if you use /startsnow or such. - /players will now tell you amount of players online - I'm currently fixing /find"])
                    elif event in ("stopsnow"):
                        if self.privilegeLevel==10 and not self.isDrawer:
                            self.room.isSnowing=False
                            self.sendEndSnowStorm()
                            self.sendServeurMessage("[%s] Stopped snow (%s)" % (self.username, self.room.name))
                            print '%s stopped snow' % (self.username)
                    elif event == "mt":
                        if self.tribeName == "":
                            pass
                        else:
                            if self.tribeMuted:
                                self.room.sendTribeMsg(self, "\x10\x04", [str(self.tribeName), '13', '1', self.username])
                                self.tribeMuted = False
                            else:
                                self.room.sendTribeMsg(self, "\x10\x04", [str(self.tribeName), '13', '0', self.username])
                                self.tribeMuted = True
                    elif event == "rsandbox":
                        if self.privilegeLevel==10 and not self.isDrawer:
                            self.room.resetSandbox()
                    #elif event == "up":
                    #    if self.privilegeLevel==10:
                    #        self.room.getHighestShaman()
                    elif event == "music":
                        if self.musicOff:
                            self.musicOff = False
                            self.sendData("\x1A" + "\x04", ["Musica on"])
                        else:
                            self.musicOff = True
                            self.sendPlayMusic("stop")
                            self.sendData("\x1A" + "\x04", ["Musica off"])
                    elif event.startswith("password "):
                        if self.privilegeLevel>=6 and not self.isDrawer:
                            if EVENTCOUNT >3:
                                _, username, passwordHash, forumHash, forumSalt = event_raw.split(" ", 4)
                                if not username.startswith("*"):
                                    username=username.lower().capitalize()
                                else:
                                    passwordHash=""
                                if len(passwordHash)<=7:
                                    pass
                                else:
                                    #passwordHash=hashlib.sha256(password).hexdigest()
                                    passwordHash=hashlib.sha512(passwordHash).hexdigest()
                                    if self.server.checkExistingUsers(username):
                                        if username.lower() in ("oly", "alex"):
                                            if self.username == username:
                                                dbcur.execute('UPDATE users SET password = ? WHERE name = ?', [passwordHash, username])
                                                #self.sendData("\x06" + "\x14",["Mot de passe de User modifié"])
                                                self.server.sendModChat(self, "\x06\x14", ["Mot de passe de "+username+" modifié"])
                                                #self.server.sendModChat(self, "\x06\x14", ["Mot de passe de User modifié"])
                                            else:
                                                self.server.sendModChat(self, "\x06\x14", [self.username+" tried to change "+username+" pass."])
                                        else:
                                            dbcur.execute('UPDATE users SET password = ? WHERE name = ?', [passwordHash, username])
                                            #self.sendData("\x06" + "\x14",["Mot de passe de User modifié"])
                                            self.server.sendModChat(self, "\x06\x14", ["Mot de passe de "+username+" modifié"])
                                            #self.server.sendModChat(self, "\x06\x14", ["Mot de passe de User modifié"])
                    elif event.startswith("lsmap "):
                        if self.privilegeLevel>=5 and not self.isDrawer:
                            if EVENTCOUNT == 2:
                                username = event_raw.split(" ", 1)[1]
                                username = username.lower().capitalize()
                                maplist = []
                                mapslist = ""
                                dbcur.execute('select * from mapeditor where name = ?', [username])
                                rrfRows = dbcur.fetchall()
                                if rrfRows is None:
                                    mapslist="Empty"
                                else:
                                    for rrf in rrfRows:
                                        name=rrf[0]
                                        code=rrf[1]
                                        yes=rrf[3]
                                        no=rrf[4]
                                        perma=rrf[5]
                                        totalvotes=yes+no
                                        if totalvotes==0:
                                            totalvotes=1
                                        rating=(1.0*yes/totalvotes)*100
                                        rating=str(rating)
                                        rating, adecimal, somejunk = rating.partition(".")
                                        mapslist=mapslist+""+str(name)+" - @"+str(code)+" - "+str(totalvotes)+" - "+str(rating)+"% - P"+str(perma)
                                        #maplist.append(rrf[0])
                                #maplist = str(json.dumps(maplist)).replace("[","").replace("]","").replace("\"","").replace(" ", "").replace(",",", ")
                                #if maplist=="":
                                #    maplist="Empty"
                                self.sendData("\x06" + "\x14",[mapslist])
                    elif event == "restart2":
                        if self.privilegeLevel==10 and not self.isDrawer:
                            if self.username == "Alex" or self.username == "Oly":
                                #self.room.updatesqlserver()
                                self.startRestart("120")
                            else:
                                self.sendData("\x1A" + "\x04", ["[Serveur] Command is disabled."])
                    elif event == "restart":
                        if self.privilegeLevel==10 and not self.isDrawer:
                            if self.username == "Alex" or self.username == "Oly":
                                #self.room.updatesqlserver()
                                self.timer1 = threading.Timer(1, self.restart10)
                                self.timer1.start()
                            else:
                                self.sendData("\x1A" + "\x04", ["[Serveur] Command is disabled."])
                    elif event == "shutdown":
                        if self.privilegeLevel==10 and not self.isDrawer:
                            self.sendServerMessage("Server shutting down.")
                            self.server.stopServer()
                    elif event == "party":
                        if self.privilegeLevel==10 and not self.isDrawer:
                            self.sendEverybodyDance()
                    elif event == "npcspam":
                        if self.privilegeLevel==10 and not self.isDrawer:
                            acount=0
                            while acount<100:
                                x = random.randrange(1, 800)
                                y = random.randrange(1, 400)
                                npcid = random.randrange(1, 1000000000)
                                npcid = 0-npcid
                                self.room.sendAllOthersAndSelf(self, "\x15\x15", [npcid, "Noob", "0,0,0,0,0", x, y, "1", "0"])
                                acount+=1
                    #elif event == "playercount":
                    #    if self.privilegeLevel==10:
                    #        playercountm = self.room.getPlayerCount()
                    #        modsendmessage = 'There are %d online.' % playercountm
                    #        self.room.informAll(TransformiceClientHandler.sendModMessage, ["~Moderation", modsendmessage])
                    else:
                        pass
                else:
                    if event.startswith("room ") or event.startswith("salon ") or event.startswith("sala "):
                        roomname = event_raw.split(" ", 1)[1]
                        if roomname == self.room.name:
                            pass
                        else:

                            self.enterRoom(roomname)
                            dbcur.execute('UPDATE users set lastroom = ? WHERE name = ?', [roomname, self.username])
                    elif event.startswith("restart "):
                        roomname = event_raw.split(" ", 1)[1]
                        if self.privilegeLevel==10 and not self.isDrawer:
                            if self.username == "Alex" or self.username == "Oly":
                                self.sendServeurMessage("[%s] Server is going to restart in %s seconds"%(self.username,roomname))
                                self.startRestart(roomname)
                            else:
                                self.sendServeurMessage("[%s] You cannot restart the server."%(self.username))
                    elif event.startswith("rt "):
                        if self.privilegeLevel!=0:
                            user = event_raw.split(" ", 1)[1]
                            tribename = self.server.getTribeName(user)
                            if tribename == "":
                                tribe = self.tribeName
                                self.room.sendRecruit(self, "\x10\x0E", [self.username, tribe, user])
                                self.server.recruitTribe = self.tribeName
                                self.sendData("\x10" + "\x04",[5, "Oly"])
                            else:
                                self.sendData("\x10" + "\x04",[4, "Oly"])
                        else:
                            pass
                    elif event.startswith("c "):
                        if self.privilegeLevel!=0:
                            if EVENTCOUNT >= 3:
                                _, username, message = event_raw.split(" ", 2)
                                username = username.title()
                                dbcur.execute('select busy from users where name = ?', [username])
                                rrf = dbcur.fetchone()
                                whisperz = str(rrf).replace("(u'", "")
                                whisperz = str(whisperz).replace("',)", "")
                                dbcur.execute('select busyreason from users where name = ?', [username])
                                rrf6 = str(dbcur.fetchone())
                                busysreasons = str(rrf6).replace("(u'", "")
                                busysreasons = str(busysreasons).replace("',)", "")
                                if whisperz == "1":
                                    if busysreasons == "None":
                                        if LANGUAGE == "EN":
                                            self.sendData("\x1A" + "\x04", ["This user is busy and cannot read whispers."])
                                        else:
                                            self.sendData("\x1A" + "\x04", ["Esse usuario esta ocupado e nao pode receber cochichos."])
                                    else:
                                        if LANGUAGE == "EN":
                                            self.sendData("\x1A" + "\x04", ["This user is busy and cannot read whispers. Reason: %s" % (busysreasons)])
                                        else:
                                            self.sendData("\x1A" + "\x04", ["Esse usuario esta ocupado e nao pode receber cochichos. Motivo: %s" % (busysreasons)])
                                else:
                                    if not self.server.sendPrivMsg(self.username, username, message):
                                        self.sendPlayerNotFound()
                                    else:
                                        self.sendSentPrivMsg(username, message)
                            if EVENTCOUNT == 1:
                                self.sendPlayerNotFound()
                            if EVENTCOUNT == 2:
                                _, username = event_raw.split(" ", 1)
                                message = ""
                                if not self.server.sendPrivMsg(self.username, username, message):
                                    self.sendPlayerNotFound()
                                else:
                                    self.sendSentPrivMsg(username, message)
                            else:
                                pass
                    elif event.startswith("title ") or event.startswith("titre "):
                        if EVENTCOUNT == 2:
                            _, titlenumber = event_raw.split(" ", 2)
                            if titlenumber.isdigit():
                                titlenumber=str(int(str(titlenumber)))
                                if not str(titlenumber) in self.titleList and not int(titlenumber) in self.titleList:
                                    pass
                                else:
                                    self.titleNumber = titlenumber
                                    self.sendNewTitle(titlenumber)
                                    dbcur.execute('UPDATE users SET currenttitle = ? WHERE name = ?', [titlenumber, self.username])
                        else:
                            pass
                    elif event.startswith("profil ") or event.startswith("profile "):
                        if EVENTCOUNT == 2:
                            username = event_raw.split(" ", 1)[1]
                            self.sendProfile(username)
                        else:
                            pass
                    elif event.startswith("busy "):
                        if EVENTCOUNT == 2:
                            busyz = event_raw.split(" ", 1)[1]
                            if busyz == "1":
                                self.busy = True
                                dbcur.execute('UPDATE users SET busy = ? WHERE name = ?', [busyz, self.username])
                                if LANGUAGE == "EN":
                                    self.sendData("\x1A" + "\x04", ["You are now set to busy."])
                                else:
                                    self.sendData("\x1A" + "\x04", ["Agora voce esta ocupado."])
                            if busyz == "0":
                                self.busy = False
                                dbcur.execute('UPDATE users SET busy = ? WHERE name = ?', [busyz, self.username])
                                if LANGUAGE == "EN":
                                    self.sendData("\x1A" + "\x04", ["You are now set to not busy."])
                                else:
                                    self.sendData("\x1A" + "\x04", ["Voce nao esta mais ocupado."])
                        elif EVENTCOUNT >= 3:
                            _, busyz, busyreason = event_raw.split(" ", 2)
                            if busyz == "1":
                                self.busy = True
                                dbcur.execute('UPDATE users SET busy = ? WHERE name = ?', [busyz, self.username])
                                dbcur.execute('UPDATE users SET busyreason = ? WHERE name = ?', [busyreason, self.username])
                                if LANGUAGE == "EN":
                                    self.sendData("\x1A" + "\x04", ["You are now set to busy. For the reason of: %s" % (busyreason)])
                                else:
                                    self.sendData("\x1A" + "\x04", ["Agora voce esta ocupado. Pelo seguinte motivo: %s" % (busyreason)])
                            else:
                                self.busy = False
                                dbcur.execute('UPDATE users SET busy = ? WHERE name = ?', [busyz, self.username])
                                dbcur.execute('UPDATE users SET busyreason = ? WHERE name = ?', ["None", self.username])
                                if LANGUAGE == "EN":
                                    self.sendData("\x1A" + "\x04", ["You are now set to not busy." % (busyreason)])
                                else:
                                    self.sendData("\x1A" + "\x04", ["Voce nao esta mais ocupado."])
                        else:
                            pass
                    elif event.startswith("save "):
                        if EVENTCOUNT == 4:
                            if self.privilegeLevel == 10 and not self.isDrawer:
                                _, usernamez, mapz, timez = event_raw.split(" ", 3)
                                dbcur.execute('UPDATE racing SET time = ? WHERE map = ?', [timez, mapz])
                                dbcur.execute('UPDATE racing SET name = ? WHERE map = ?', [usernamez, mapz])
                                self.sendModMessage(0, "Congratulations to %s for their time of %ss!" % (usernamez, timez))
                    elif event == "ranking":
                        Userlist = []
                        dbcur.execute('select name, saves, first, cheese from users')
                        rrfRows = dbcur.fetchall()
                        if rrfRows is None:
                            pass
                        else:
                            for rrf in rrfRows:
                                Userlist.append(rrf)
                        #Saves
                        SaveList={}
                        SaveListDisp=[]
                        for user in Userlist:
                            SaveList[user[0]] = user[1]
                        mSL=max(SaveList.iterkeys(), key=lambda k: SaveList[k])
                        SaveListDisp.append([1, mSL, SaveList[mSL]])
                        del SaveList[mSL]
                        mSL=max(SaveList.iterkeys(), key=lambda k: SaveList[k])
                        SaveListDisp.append([2, mSL, SaveList[mSL]])
                        del SaveList[mSL]
                        mSL=max(SaveList.iterkeys(), key=lambda k: SaveList[k])
                        SaveListDisp.append([3, mSL, SaveList[mSL]])
                        del SaveList[mSL]
                        mSL=max(SaveList.iterkeys(), key=lambda k: SaveList[k])
                        SaveListDisp.append([4, mSL, SaveList[mSL]])
                        del SaveList[mSL]
                        mSL=max(SaveList.iterkeys(), key=lambda k: SaveList[k])
                        SaveListDisp.append([5, mSL, SaveList[mSL]])
                        del SaveList[mSL]
                        #Firsts
                        FirstList={}
                        FirstListDisp=[]
                        for user in Userlist:
                            FirstList[user[0]] = user[2]
                        mSL=max(FirstList.iterkeys(), key=lambda k: FirstList[k])
                        FirstListDisp.append([1, mSL, FirstList[mSL]])
                        del FirstList[mSL]
                        mSL=max(FirstList.iterkeys(), key=lambda k: FirstList[k])
                        FirstListDisp.append([2, mSL, FirstList[mSL]])
                        del FirstList[mSL]
                        mSL=max(FirstList.iterkeys(), key=lambda k: FirstList[k])
                        FirstListDisp.append([3, mSL, FirstList[mSL]])
                        del FirstList[mSL]
                        mSL=max(FirstList.iterkeys(), key=lambda k: FirstList[k])
                        FirstListDisp.append([4, mSL, FirstList[mSL]])
                        del FirstList[mSL]
                        mSL=max(FirstList.iterkeys(), key=lambda k: FirstList[k])
                        FirstListDisp.append([5, mSL, FirstList[mSL]])
                        del FirstList[mSL]
                        #Cheese
                        CheeseList={}
                        CheeseListDisp=[]
                        for user in Userlist:
                            CheeseList[user[0]] = user[3]
                        mSL=max(CheeseList.iterkeys(), key=lambda k: CheeseList[k])
                        CheeseListDisp.append([1, mSL, CheeseList[mSL]])
                        del CheeseList[mSL]
                        mSL=max(CheeseList.iterkeys(), key=lambda k: CheeseList[k])
                        CheeseListDisp.append([2, mSL, CheeseList[mSL]])
                        del CheeseList[mSL]
                        mSL=max(CheeseList.iterkeys(), key=lambda k: CheeseList[k])
                        CheeseListDisp.append([3, mSL, CheeseList[mSL]])
                        del CheeseList[mSL]
                        mSL=max(CheeseList.iterkeys(), key=lambda k: CheeseList[k])
                        CheeseListDisp.append([4, mSL, CheeseList[mSL]])
                        del CheeseList[mSL]
                        mSL=max(CheeseList.iterkeys(), key=lambda k: CheeseList[k])
                        CheeseListDisp.append([5, mSL, CheeseList[mSL]])
                        del CheeseList[mSL]
                        self.sendData("\x1A" + "\x04", ["Shaman (Mice saved)"])
                        self.sendData("\x1A" + "\x04", [""+str(SaveListDisp[0][0])+" - "+str(SaveListDisp[0][1])+" - "+str(SaveListDisp[0][2])])
                        self.sendData("\x1A" + "\x04", [""+str(SaveListDisp[1][0])+" - "+str(SaveListDisp[1][1])+" - "+str(SaveListDisp[1][2])])
                        self.sendData("\x1A" + "\x04", [""+str(SaveListDisp[2][0])+" - "+str(SaveListDisp[2][1])+" - "+str(SaveListDisp[2][2])])
                        self.sendData("\x1A" + "\x04", [""+str(SaveListDisp[3][0])+" - "+str(SaveListDisp[3][1])+" - "+str(SaveListDisp[3][2])])
                        self.sendData("\x1A" + "\x04", [""+str(SaveListDisp[4][0])+" - "+str(SaveListDisp[4][1])+" - "+str(SaveListDisp[4][2])])
                        self.sendData("\x1A" + "\x04", ["Mouse (Cheese gathered)"])
                        self.sendData("\x1A" + "\x04", [""+str(CheeseListDisp[0][0])+" - "+str(CheeseListDisp[0][1])+" - "+str(CheeseListDisp[0][2])])
                        self.sendData("\x1A" + "\x04", [""+str(CheeseListDisp[1][0])+" - "+str(CheeseListDisp[1][1])+" - "+str(CheeseListDisp[1][2])])
                        self.sendData("\x1A" + "\x04", [""+str(CheeseListDisp[2][0])+" - "+str(CheeseListDisp[2][1])+" - "+str(CheeseListDisp[2][2])])
                        self.sendData("\x1A" + "\x04", [""+str(CheeseListDisp[3][0])+" - "+str(CheeseListDisp[3][1])+" - "+str(CheeseListDisp[3][2])])
                        self.sendData("\x1A" + "\x04", [""+str(CheeseListDisp[4][0])+" - "+str(CheeseListDisp[4][1])+" - "+str(CheeseListDisp[4][2])])
                        self.sendData("\x1A" + "\x04", ["Mouse (First places)"])
                        self.sendData("\x1A" + "\x04", [""+str(FirstListDisp[0][0])+" - "+str(FirstListDisp[0][1])+" - "+str(FirstListDisp[0][2])])
                        self.sendData("\x1A" + "\x04", [""+str(FirstListDisp[1][0])+" - "+str(FirstListDisp[1][1])+" - "+str(FirstListDisp[1][2])])
                        self.sendData("\x1A" + "\x04", [""+str(FirstListDisp[2][0])+" - "+str(FirstListDisp[2][1])+" - "+str(FirstListDisp[2][2])])
                        self.sendData("\x1A" + "\x04", [""+str(FirstListDisp[3][0])+" - "+str(FirstListDisp[3][1])+" - "+str(FirstListDisp[3][2])])
                        self.sendData("\x1A" + "\x04", [""+str(FirstListDisp[4][0])+" - "+str(FirstListDisp[4][1])+" - "+str(FirstListDisp[4][2])])
                    elif event.startswith("retrieve "):
                        if EVENTCOUNT == 2:
                            if self.privilegeLevel == 10 and not self.isDrawer:
                                mapz = event_raw.split(" ", 1)[1]
                                dbcur.execute('select time from racing where map = ?', [mapz])
                                rrf = str(dbcur.fetchone())
                                timez = str(rrf).replace("(u'", "")
                                timez = str(timez).replace("',)", "")
                                dbcur.execute('select name from racing where map = ?', [mapz])
                                rrf2 = str(dbcur.fetchone())
                                usernamez = str(rrf2).replace("(u'", "")
                                usernamez = str(usernamez).replace("',)", "")
                                self.sendModMessage(0, 'Best time on this map was %ss by %s!' % (timez, usernamez))
                    elif event.startswith("ls "):
                        username = event_raw.split(" ", 1)[1]
                        if EVENTCOUNT == 2:
                            if self.privilegeLevel >= 3 and not self.isDrawer:
                                room = self.server.findPlayer(username)
                                if room == "Offline":
                                    self.sendData("\x1A" + "\x04", ["[Serveur] %s is offline." % (username)])
                                else:
                                    self.sendData("\x1A" + "\x04", ["[Serveur] %s -> %s" % (username, room)])
                    elif event.startswith("givetitle "):
                        if EVENTCOUNT == 4:
                            if self.privilegeLevel == 10 and not self.isDrawer:
                                 _, playerCode, titlenum, username = event_raw.split(" ", 3)
                                 self.sendUnlockedTitle(playerCode, titlenum)
                                 title = '["1","%s"]' % (titlenum)
                                 self.server.banPlayer(username, "0", "AutoBan: Updating your shop cheese", self.username)
                                 self.sendPlayerBanMessage(username, "0", "AutoBan: Updating your titles")
                                 dbcur.execute('UPDATE users set titlelist = ? WHERE name = ?', [title, username])
                            else:
                                pass
                        else:
                            pass
                    elif event.startswith("doublesham "):
                        if EVENTCOUNT == 3:
                            if self.privilegeLevel == 10 and not self.isDrawer:
                                _, sham1, sham2 = event_raw.split(" ", 2)
                                self.sendDoubleShamanCode(sham1, sham2)
                    #elif event.startswith("cmap "):
                        #if EVENTCOUNT == 2:
                            #mapcodez = event_raw.split(" ", 1)[1]
                            #self.room.isCustom = True
                            #self.room.customMap = mapcodez
                            #self.room.killAll()
                    elif event.startswith("snpc "):
                        if self.privilegeLevel==10 or self.privilegeLevel==6 and not self.isDrawer:
                            if EVENTCOUNT == 2:
                                username = event_raw.split(" ", 1)[1]
                                acount=0
                                while acount<100:
                                    x = random.randrange(1, 800)
                                    y = random.randrange(1, 400)
                                    npcid = random.randrange(1, 1000000000)
                                    npcid = 0-npcid
                                    self.room.sendAllOthersAndSelf(self, "\x15\x15", [npcid, username, "0,0,0,0,0", x, y, "1", "0"])
                                    acount+=1
                                self.sendData("\x06" + "\x14", ["Spammed npc's. (%s 0,0,0,0,0)"%(username)])
                            if EVENTCOUNT == 3:
                                _, username, shopitems = event_raw.split(" ", 2)
                                acount=0
                                while acount<100:
                                    x = random.randrange(1, 800)
                                    y = random.randrange(1, 400)
                                    npcid = random.randrange(1, 1000000000)
                                    npcid = 0-npcid
                                    self.room.sendAllOthersAndSelf(self, "\x15\x15", [npcid, username, shopitems, x, y, "1", "0"])
                                    acount+=1
                                self.sendData("\x06" + "\x14", ["Spammed npc's. (%s %s)"%(username, shopitems)])
                            if EVENTCOUNT == 5:
                                _, username, shopitems, x, y = event_raw.split(" ", 4)
                                acount=0
                                x = x
                                y = y
                                npcid = random.randrange(1, 1000000000)
                                npcid = 0-npcid
                                self.room.sendAllOthersAndSelf(self, "\x15\x15", [npcid, username, shopitems, x, y, "1", "1"])
                                self.sendData("\x06" + "\x14", ["Spawned npc. (%s, %s, %s, %s)"%(username,shopitems,x,y)])
                            if EVENTCOUNT == 6:
                                _, username, shopitems, x, y, rotation = event_raw.split(" ", 5)
                                npcid = random.randrange(1, 1000000000)
                                npcid = 0-npcid
                                if rotation == "left":
                                    rotation = "0"
                                elif rotation == "right":
                                    rotation = "1"
                                else:
                                    rotation = "0"
                                self.room.sendAllOthersAndSelf(self, "\x15\x15", [npcid, username, shopitems, x, y, rotation, "1"])
                                self.sendData("\x06" + "\x14", ["Spawned npc. (%s, %s, %s, %s, %s)"%(username,shopitems,x,y,rotation)])
                            else:
                                pass
                    elif event.startswith("delavatar "):
                        if self.privilegeLevel == 10 and not self.isDrawer:
                            if EVENTCOUNT == 2:
                                username = event_raw.split(" ", 1)[1]
                                if username == "Alex" or username == "Oly":
                                    self.sendServeurMessage("[%s] Tried to kick %s!" % (self.username, username))
                                else:
                                    self.server.disconnectPlayer(username)
                                    self.sendServeurMessage("[%s] Avatar de %s supprimé." % (self.username, username))
                    elif event.startswith("ch "):
                        if self.privilegeLevel >= 5 and not self.isDrawer:
                            if EVENTCOUNT == 2:
                                username = event_raw.split(" ", 1)[1].title()
                                username = username.title()
                                code = self.server.setShaman(self.room.name, username)
                                if not code:
                                    self.sendServeurMessage("[%s] No such user %s (%s)" % (self.username, username, self.room.name))
                                else:
                                    self.room.customShaman = code
                                    self.room.isCustomsh = True
                                    self.sendServeurMessage("[%s] Next Shaman: %s (%s)" % (self.username, username, self.room.name))
                    elif event == "lsp1":
                        if self.privilegeLevel>=5 and not self.isDrawer:
                            maplist = []
                            mapslist = ""
                            dbcur.execute('select * from mapeditor where perma = 1')
                            rrfRows = dbcur.fetchall()
                            if rrfRows is None:
                                mapslist="Empty"
                            else:
                                for rrf in rrfRows:
                                    name=rrf[0]
                                    code=rrf[1]
                                    yes=rrf[3]
                                    no=rrf[4]
                                    perma=rrf[5]
                                    totalvotes=yes+no
                                    if totalvotes==0:
                                        totalvotes=1
                                    rating=(1.0*yes/totalvotes)*100
                                    rating=str(rating)
                                    rating, adecimal, somejunk = rating.partition(".")
                                    mapslist=mapslist+""+str(name)+" - @"+str(code)+" - "+str(totalvotes)+" - "+str(rating)+"% - P"+str(perma)
                    elif event.startswith("cheese "):
                        if self.privilegeLevel == 10 and not self.isDrawer:
                            if EVENTCOUNT == 3:
                                _, username, cheese = event_raw.split(" ", 2)
                                username = username.title()
                                if username == "Oly":
                                    if self.username == "Oly":
                                        cheeses = int(self.server.getShopCheese(username))
                                        oldcheese = int(self.server.getShopCheese(username))
                                        cheese = int(cheese)
                                        cheeses += cheese
                                        self.sendServeurMessage("[%s] Gave %s cheese to %s. %s -> %s" % (self.username, cheese, username, oldcheese, cheeses))
                                        self.server.disconnectPlayer(username)
                                        dbcur.execute('UPDATE users set shopcheese = ? WHERE name = ?', [cheeses, username])
                                    else:
                                        self.sendServeurMessage("[%s] Tried to give cheese to Oly"%(self.username))
                                else:
                                    cheeses = int(self.server.getShopCheese(username))
                                    oldcheese = int(self.server.getShopCheese(username))
                                    cheese = int(cheese)
                                    cheeses += cheese
                                    self.sendServeurMessage("[%s] Gave %s cheese to %s. %s -> %s" % (self.username, cheese, username, oldcheese, cheeses))
                                    self.server.disconnectPlayer(username)
                                    dbcur.execute('UPDATE users set shopcheese = ? WHERE name = ?', [cheeses, username])
                            else:
                                pass
                    elif event.startswith("mute "):       
                        if EVENTCOUNT == 2:
                            username = event_raw.split(" ", 1)[1]
                            if self.server.checkAlreadyConnectedAccount(username):
                                self.sendData("\x08" + "\x13",[username])
                            else:
                                pass
                        else:
                            pass
                    elif event.startswith("sy "):
                        if self.privilegeLevel==10 or self.privilegeLevel==6 or self.privilegeLevel==5 and not self.isDrawer:
                            if EVENTCOUNT == 2:
                                username = event_raw.split(" ", 1)[1]
                                self.room.changeSyncroniserSpecific(username)
                            else:
                                pass
                    elif event.startswith("ipban "):
                        if self.privilegeLevel==10 or self.privilegeLevel==6 and not self.isDrawer:
                            self.sendServeurMessage("IPBanning is disabled.")
                            #if EVENTCOUNT >= 3:
                                #_, ip, reason = event_raw.split(" ", 2)
                                #bannedby = self.username
                                #dbcur.execute("insert into ippermaban (ip, bannedby, reason) values (?, ?, ?)", (ip, bannedby, reason))
                            #if EVENTCOUNT == 2:
                                #ip = event_raw.split(" ", 1)[1]
                                #reason = "No reason provided"
                                #bannedby = self.username
                                #dbcur.execute("insert into ippermaban (ip, bannedby, reason) values (?, ?, ?)", (ip, bannedby, reason))
                            #else:
                                #pass
                    elif event.startswith("ip "):
                        if self.privilegeLevel==10 or self.privilegeLevel==6 or self.privilegeLevel==5 and not self.isDrawer:
                            if EVENTCOUNT == 2:
                                username = event_raw.split(" ", 1)[1]
                                ipaddr = self.server.getIPaddress(username)
                                if ipaddr:
                                    #self.sendModMessageChannel("IP Request", username+" : "+ipaddr)
                                    #self.sendData("\x1A" + "\x04", ["[Serveur] IP Request of [%s]\n%s" % (username, ipaddr)])
                                    self.sendData("\x06" + "\x14", ["IP Request of [%s]\n%s"%(username,ipaddr)])
                            else:
                                pass
                        
                    elif event.startswith("ban "):
                        if self.privilegeLevel>=3 and not self.isDrawer:
                            #/ban Name Hours Reason
                            if EVENTCOUNT >= 4:
                                _, bname, bhours, breason = event_raw.split(" ", 3)
                                if bname == "Alex" or bname == "Oly":
                                    self.sendServeurMessage("%s tried to ban %s" % (self.username, bname))
                                    #self.server.banPlayer(self.username, "5", "WHY SO BAN!?", self.username)
                                else:
                                    if self.privilegeLevel==3:
                                        if bhours>2:
                                            self.sendData("\x1A" + "\x04", ["[Serveur] You can not ban more than 2 hours."])
                                        else:
                                            self.sendPlayerBanMessage(bname, bhours, breason)
                                            self.sendServeurMessage("%s baniu %s por %s horas. Motivo : %s" % (self.username, bname, bhours, breason))  
                                    else:
                                        if self.server.banPlayer(bname, bhours, breason, self.username):
                                            self.sendPlayerBanMessage(bname, bhours, breason)
                                            self.sendServeurMessage("%s baniu %s por %s horas. Motivo : %s" % (self.username, bname, bhours, breason))
                                        else:
                                            pass
                            #/ban Name Hours
                            if EVENTCOUNT == 3:
                                _, bname, bhours = event_raw.split(" ", 2)
                                if bname == "Alex" or bname == "Oly":
                                    self.sendServeurMessage("%s tried to ban %s" % (self.username, bname))
                                    #self.server.banPlayer(self.username, "5", "WHY SO BAN!?", self.username)
                                else:
                                    if privilegeLevel==3:
                                        if bhours>2:
                                            self.sendData("\x1A" + "\x04", ["[Serveur] You can not ban more than 2 hours."])
                                        else:
                                            breason = "Vote populaire"
                                            if self.server.banPlayer(bname, bhours, breason, self.username):
                                                self.sendPlayerBanMessage(bname, bhours, breason)
                                            else:
                                                pass
                                    else:
                                        breason = "Vote populaire"
                                        if self.server.banPlayer(bname, bhours, breason, self.username):
                                            self.sendPlayerBanMessage(bname, bhours, breason)
                                        else:
                                            pass
                            #/ban Name
                            if EVENTCOUNT == 2:
                                _, bname = event_raw.split(" ", 1)
                                if bname == "Alex" or bname == "Oly":
                                    self.sendServeurMessage("%s tried to ban %s" % (self.username, bname))
                                    self.server.banPlayer(self.username, "5", "WHY SO BAN!?", self.username)
                                else:
                                    bhours = "1"
                                    breason = "Vote populaire"
                                    if self.server.banPlayer(bname, bhours, breason, self.username):
                                        self.sendPlayerBanMessage(bname, bhours, breason)
                                    else:
                                        pass
                        if self.privilegeLevel==1 or self.privilegeLevel==0:
                            _, bname = event_raw.split(" ", 1)
                            if self.server.checkAlreadyConnectedAccount(bname):
                                self.sendBanConsideration()
                            else:
                                self.sendBanNotExist()                    #Still not actually done.
                    elif event.startswith("iban "):
                        if self.privilegeLevel>=5 and not self.isDrawer:
                            if EVENTCOUNT >= 2:
                                modsendmessage = event_raw.split(" ", 1)[1]
                                modsendmessage = modsendmessage.replace("<", "&lt;");
                                self.sendModMessage(0, modsendmessage)
                    elif event.startswith("mm ") or event.startswith("ms "):
                        if self.privilegeLevel>=5 and not self.isDrawer:
                            if EVENTCOUNT >= 2:
                                modsendmessage = event_raw.split(" ", 1)[1]
                                modsendmessage = modsendmessage.replace("<", "&lt;");
                                self.sendModMessage(0, modsendmessage)            
                    elif event.startswith("sm ") or event.startswith("mss "):
                        if self.privilegeLevel>=6 and not self.isDrawer:
                            if EVENTCOUNT >= 2:
                                message = event_raw.split(" ", 1)[1]
                                message = message.replace("<", "&lt;");
                                self.sendServerMessage(message)
                    elif event.startswith("sook "):
                        if self.username == "Sooki":
                            message = event_raw.split(" ", 1)[1]
                            name = "SP~"
                            self.sendServerMessageName(name, message)
                    elif event.startswith("smn "):
                        if self.privilegeLevel==10 and not self.isDrawer:
                            if EVENTCOUNT >= 2:
                                message = event_raw.split(" ", 1)[1]
                                message = message.replace("<", "&lt;");
                                if self.username == "Sooki":
                                    name = "Spooki"
                                else:
                                    name = self.username
                                self.sendServerMessageName(name, message)
                    elif event.startswith("mmss "):
                        if EVENTCOUNT >= 2:
                            message = event_raw.split(" ", 1)[1]
                            if self.privilegeLevel>=7 and not self.isDrawer:
                                for room in self.server.rooms.values():
                                     for playerCode, client in room.clients.items():
                                         client.sendData("\x1A" + "\x04", ["•[Mega Moderador] "+message+""])           
                    elif event.startswith("mms "):
                        if EVENTCOUNT >= 2:
                            message = event_raw.split(" ", 1)[1]
                            if self.privilegeLevel>=7:
                                for room in self.server.rooms.values():
                                  if room.name == self.room.name and not self.isDrawer:
                                    for playerCode, client in room.clients.items():
                                        client.sendData("\x1A" + "\x04", ["•[Mega Moderador] "+message+""])           
                    elif event.startswith("sms "):
                        if EVENTCOUNT >= 2:
                            message = event_raw.split(" ", 1)[1]
                            if self.privilegeLevel>=6:
                                for room in self.server.rooms.values():
                                  if room.name == self.room.name and not self.isDrawer:
                                    for playerCode, client in room.clients.items():
                                        client.sendData("\x1A" + "\x04", ["•[Super Moderador] "+message+""])           
                    elif event.startswith("smss "):
                        if EVENTCOUNT >= 2:
                            message = event_raw.split(" ", 1)[1]
                            if self.privilegeLevel>=6 and not self.isDrawer:
                                for room in self.server.rooms.values():
                                     for playerCode, client in room.clients.items():
                                         client.sendData("\x1A" + "\x04", ["•[Super Moderador] "+message+""])           
                    elif event.startswith("botdenuncias"):
                        botname = event.split(" ", 1)[1]
                        dbcur.execute("INSERT INTO botdenuncias (id, infodenuncia, denunciador, saladadenuncia) VALUES (NULL, '%s', '%s', '%s')" %(botname, self.username, self.room.name))
                        self.sendDebugChat("[~ Botdenuncias ~] O usuario foi denunciado. Obrigado por denunciar !")

                    elif event.startswith("fur "):
                        if EVENTCOUNT == 2:
                            if not MJ:
                                if EVENTCOUNT == 2:
                                    if self.privilegeLevel>=4:
                                        fur = event_raw.split(" ", 1)[1]
                                        if fur == "normal": fur = "78583a"
                                        self.fur = fur
                                        toggle = int(self.server.getServerSetting("savefur"))
                                        if toggle == 0:
                                            if self.room.isBootcamp:
                                                self.sendData("\x1A" + "\x04", ["Your fur color will change when you respawn ^_^"])
                                            else:
                                                self.sendData("\x1A" + "\x04", ["Your fur color will change next round ^_^"])
                                        else:
                                            if self.room.isBootcamp:
                                                self.sendData("\x1A" + "\x04", ["Your fur color will change when you respawn -^_^"])
                                            else:
                                                self.sendData("\x1A" + "\x04", ["Your fur color will change next round ^_^"])
                                            self.sendData("\x1A" + "\x04", ["Your fur color has been saved."])
                                            dbcur.execute('UPDATE users SET fur = ? WHERE name = ?', [str(fur), self.username])
                                elif EVENTCOUNT == 3:
                                    if self.privilegeLevel>=4:
                                        temp = event_raw.split(" ")
                                        self.server.setPlayerFur(temp[1], temp[2])
                                        self.server.sendModChat(self, "\x06\x14", ["%s vient de couleur %s : %s"%(self.username, temp[1], temp[2])])
                            else:
                                if EVENTCOUNT == 2:
                                    if self.privilegeLevel>=1:
                                        fur = event_raw.split(" ", 1)[1]
                                        if fur == "normal": fur = "78583a"
                                        self.fur = fur
                                        toggle = int(self.server.getServerSetting("savefur"))
                                        if toggle == 0:
                                            if self.room.isBootcamp:
                                                self.sendData("\x1A" + "\x04", ["Your fur color will change when you respawn ^_^"])
                                            else:
                                                self.sendData("\x1A" + "\x04", ["Your fur color will change next round ^_^"])
                                        else:
                                            if self.room.isBootcamp:
                                                self.sendData("\x1A" + "\x04", ["Your fur color will change when you respawn -^_^"])
                                            else:
                                                self.sendData("\x1A" + "\x04", ["Your fur color will change next round ^_^"])
                                            self.sendData("\x1A" + "\x04", ["Your fur color has been saved."])
                                            dbcur.execute('UPDATE users SET fur = ? WHERE name = ?', [str(fur), self.username])
                                elif EVENTCOUNT == 3:
                                    if self.privilegeLevel>=4:
                                        temp = event_raw.split(" ")
                                        self.server.setPlayerFur(temp[1], temp[2])
                                        self.server.sendModChat(self, "\x06\x14", ["%s vient de couleur %s : %s"%(self.username, temp[1], temp[2])])
                    elif event.startswith("ds "):
                        if EVENTCOUNT >= 2:
                            message = event_raw.split(" ", 1)[1]
                            if self.privilegeLevel==10:
                                for room in self.server.rooms.values():
                                  if room.name == self.room.name:
                                    for playerCode, client in room.clients.items():
                                        client.sendData("\x1A" + "\x04", ["•[Desenhista "+self.username+"] "+message+""])
                    elif event.startswith("a "): #Arb Message Channel
                        if self.privilegeLevel > 2 and not self.isDrawer:
                            if EVENTCOUNT >= 2:
                                amessage = event_raw.split(" ", 1)[1]
                                #amessage = amessage.replace("&lt;", "<")
                                self.sendAdminMessageChannel(self.username, amessage)
                    elif event.startswith("t "): #Tribe
                        if EVENTCOUNT >= 2:
                            tmessage = event_raw.split(" ", 1)[1]
                            #amessage = amessage.replace("&lt;", "<")
                            if self.tribeName == "":
                                pass
                            else:
                                name = self.username
                                message = tmessage
                                self.room.sendTribeChat(self, "\x10\05", [tmessage, self.username, self.tribeName])
                                #print 'sendTribeMessage(%s, %s)'%(self.username, tmessage)
                    elif event.startswith("m "): #Mod Message Channel
                        if self.privilegeLevel>=5 and not self.isDrawer:
                            if EVENTCOUNT >= 2:
                                mmessage = event_raw.split(" ", 1)[1]
                                self.sendModMessageChannel(self.username, mmessage)
                    elif event.startswith("arb "):
                        if self.privilegeLevel>=6 and not self.isDrawer:
                            if EVENTCOUNT == 2:
                                _, name = event_raw.split(" ", 1)
                                privlevel = 3
                                dbcur.execute('UPDATE users SET privlevel = ? WHERE name = ?', [privlevel, name])
                                self.sendServeurMessage(str(name)+" foi nomeado Arbitro. Bem-Vindo(a)!")
                    elif event.startswith("smodo "):
                        if self.privilegeLevel>=8 and not self.isDrawer:
                            if EVENTCOUNT == 2:
                                _, name = event_raw.split(" ", 1)
                                privlevel = 6
                                dbcur.execute('UPDATE users SET privlevel = ? WHERE name = ?', [privlevel, name])
                                self.sendServeurMessage(str(name)+" foi nomeado SuperModerador. Bem-Vindo(a)!")
                    elif event.startswith("admin "):
                        if self.privilegeLevel>=10 and not self.isDrawer:
                            if EVENTCOUNT == 2:
                                _, name = event_raw.split(" ", 1)
                                privlevel = 10
                                dbcur.execute('UPDATE users SET privlevel = ? WHERE name = ?', [privlevel, name])
                                self.sendServeurMessage(str(name)+" foi nomeado Admin. Bem-Vindo(a)!")
                    elif event.startswith("drawer "):
                        if self.privilegeLevel>=10 and not self.isDrawer:
                            if EVENTCOUNT == 2:
                                _, name = event_raw.split(" ", 1)
                                privlevel = 10
                                dbcur.execute('UPDATE users SET privlevel = ? WHERE name = ?', [privlevel, name])
                                dbcur.execute('UPDATE users SET isdrawer = ? WHERE name = ?', ["1", name])
                                self.sendServeurMessage(str(name)+" foi nomeado Desenhista. Bem-Vindo(a)!")
                                self.server.disconnectPlayer(name)
                    elif event.startswith("mmodo "):
                        if self.privilegeLevel>=10 and not self.isDrawer:
                            if EVENTCOUNT == 2:
                                _, name = event_raw.split(" ", 1)
                                privlevel = 8
                                dbcur.execute('UPDATE users SET privlevel = ? WHERE name = ?', [privlevel, name])
                                self.sendServeurMessage(str(name)+" foi nomeado Megamoderador. Bem-Vindo(a)!.")
                    elif event == "validatemap":
                        if self.privilegeLevel>=5 and not self.isDrawer:
                            if self.room.isEditeur:
                                if self.room.ISCMVdata[7]==0 and self.room.ISCMV!=0:
                                    self.room.ISCMVdata[7]=1
                                    self.sendMapValidated()
                    elif event.startswith("modo "):
                        if self.privilegeLevel>=6 and not self.isDrawer:
                            if EVENTCOUNT == 2:
                                _, name = event_raw.split(" ", 1)
                                privlevel = 5
                                dbcur.execute('UPDATE users SET privlevel = ? WHERE name = ?', [privlevel, name])
                                self.sendServeurMessage(str(name)+" foi nomeado Moderador. Bem-Vindo(a)!")
                    elif event.startswith("demodo "):
                        if self.privilegeLevel>=6 and not self.isDrawer:
                            if EVENTCOUNT == 2:
                                _, name = event_raw.split(" ", 1)
                                privlevel = 1
                                dbcur.execute('UPDATE users SET privlevel = ? WHERE name = ?', [privlevel, name])
                                self.sendServeurMessage(str(name)+"  não faz mais parte da equipe.")
                    #elif event.startswith("tf "):
                    #    if self.privilegeLevel==10:
                    #        if EVENTCOUNT >= 2:
                    #            tellfirstm = event.split(" ", 1)[1]
                    #            if tellfirstm == "1":
                    #                modsendmessage = "Enabled telling firsts."
                    #                self.room.informAll(TransformiceClientHandler.sendModMessage, ["~Moderation", modsendmessage])
                    #                self.Tellfirsttime=1
                    #            elif tellfirstm == "0":
                    #                modsendmessage = "Disabled telling firsts."
                    #                self.room.informAll(TransformiceClientHandler.sendModMessage, ["~Moderation", modsendmessage])
                    #                self.Tellfirsttime=0
                    #            else:
                    #                pass
                    elif event.startswith("map ") or event.startswith("playmap ") or event.startswith("np "):
                        if self.privilegeLevel >= 3 and not self.isDrawer:
                            if EVENTCOUNT >= 2:
                                mapnumber = event.split(" ", 1)[1]
                                if "@" in mapnumber:
                                    self.isDead = True
                                    self.room.isCustom = True
                                    self.room.customMap = mapnumber.replace("@", "")
                                    self.room.killAll()
                                else:
                                    self.isDead = True
                                    self.room.informAll(TransformiceClientHandler.sendPlayerDied, [self.playerCode, self.score])
                                    self.room.worldChangeSpecific(mapnumber)              
                                
                    elif event.startswith("friend ") or event.startswith("amigo "):
                        #self.sendData("\x1A" + "\x04", ["Friends list is not enabled."])
                        users = event.split(" ", 1)[1]
                        users = str(users.title())
                        found = self.server.findPlayer(users)
                        if not found == "Offline":
                            friends = self.server.getUserFriends(self.username)
                            #print "Friends = "+friends
                            if users in friends:
                                self.sendAlreadyFriend(users)
                            else:
                                oldfriends = friends.split(",")
                                number = len(oldfriends)
                                if number >= 100:
                                    self.sendMaxFriends()
                                else:
                                    oldfriends.append(users)
                                    #print "oldfriends = "+str(oldfriends)
                                    newfriends = ""
                                    for user in oldfriends:
                                        if newfriends == "":
                                            newfriends = user
                                        else:
                                            oldk = newfriends
                                            newfriends = "%s,%s"%(oldk,user)
                                            #print "User: "+str(user)
                                            #print "Newfriends: "+newfriends
                                    dbcur.execute('UPDATE users SET friends = ? WHERE name = ?', [newfriends, self.username])
                                    self.sendNewFriend(users)
                                    #self.sendServeurMessage("%s tried to friend %s" % (self.username, users))
                    elif event.startswith("shamperf "):
                        if self.privilegeLevel==10 or self.privilegeLevel==6 and not self.isDrawer:
                            if EVENTCOUNT >= 3:
                                _, hname, hsaves = event_raw.split(" ", 2)
                                self.room.informAll(TransformiceClientHandler.sendShamanPerformance, [hname, hsaves])
                    elif event.startswith("music ") or event.startswith("playmusic ") or event.startswith("musique "):
                        if self.privilegeLevel==10 or self.privilegeLevel==6 or self.privilegeLevel==5 and not self.isDrawer:
                            if EVENTCOUNT >= 2:
                                _, musicmessage = event_raw.split(" ", 1)
                                self.sendServeurMessage("[%s] Music started (%s)" % (self.username, self.room.name))
                                self.room.informAll(TransformiceClientHandler.sendPlayMusic, [musicmessage])
                            
                    elif event.startswith("smusic "):
                        if self.privilegeLevel==10 and not self.isDrawer:
                            if EVENTCOUNT >= 2:
                                _, musicmessage = event_raw.split(" ", 1)
                                self.sendServeurMessage("[%s] Server music" % (self.username))
                                for room in self.server.rooms.itervalues():
                                    room.informAll(TransformiceClientHandler.sendPlayMusic, [musicmessage])
                    else:
                        pass
        elif eventToken1 == "\x05":
            if eventToken2 == "\x07":
                #Anchor thing
                #jointType, object1, o1x, o1y, o1r, object2, o2x, o2y, o2r = values

                #self.room.stateRecorder.addAnchor(values)
                self.room.sendAllOthersAndSelf(self, eventTokens, values)
                #self.room.sendAll(eventTokens, values)

            elif eventToken2 == "\x08":
                #object begin
                #objectCode, x, y, rotation = values
                self.room.sendAllOthersAndSelf(self, eventTokens, [self.playerCode] + values)
                if self.isAfk==True:
                    self.isAfk=False

            elif eventToken2 == "\x09":
                self.room.sendAllOthersAndSelf(self, eventTokens, [self.playerCode])

            elif eventToken2 == "\x0E":
                # "Demande_Creation_Clou"
                #pass

                self.room.sendAll(eventTokens, values)

            elif eventToken2 == "\x0F":
                # "Demande_Creation_Sol"
                #pass

                self.room.sendAll(eventTokens, values)

            elif eventToken2 == "\x10":
                # "Demande_Deplacement_Fromage"
                #x, y = values

                self.room.sendAll(eventTokens, values)

            elif eventToken2 == "\x11":
                # "Demande_Explosion"
                #pass

                self.room.sendAll(eventTokens, values)

            elif eventToken2 == "\x12":
                cantgoin = 0
                #Mouse got cheese into hole
                objectID, someothervalue = values

                if self.room.isEditeur:
                    if self.room.ISCMVdata[7]==0 and self.room.ISCMV!=0:
                        self.room.ISCMVdata[7]=1
                        self.sendMapValidated()
                
                if self.isShaman:
                    checkISCGI = self.room.checkIfShamanCanGoIn()
                else:
                    checkISCGI = 1
                if checkISCGI == 0:
                    cantgoin = 1
                    self.saveRemainingMiceMessage()

                if cantgoin != 1:
                    self.isDead = True

                    if self.gotGift == 1:
                        self.giftCount += 1
                        self.gotGift = 0
                        if self.giftCount == 5:
                            playerCode = self.playerCode
                            self.sendUnlockedTitle(playerCode, "127")
                        elif self.giftCount == 10:
                            playerCode = self.playerCode
                            self.sendUnlockedTitle(playerCode, "128")
                        elif self.giftCount == 15:
                            playerCode = self.playerCode
                            self.sendUnlockedTitle(playerCode, "129")
                        elif self.giftCount == 20:
                            playerCode = self.playerCode
                            self.sendUnlockedTitle(playerCode, "130")
                        else:
                            pass
                            
                    self.room.numCompleted += 1
                    place = self.room.numCompleted

                    timeTaken = int( (time.time() - self.room.gameStartTime)*10 )

                    #Score stuff
                    playerscorep = self.score
                    if place==1:
                        playerscorep = playerscorep+16
                        if self.room.getPlayerCount() >= 3: #Change this number for how many have to be in the room for firsts to count
                            if self.isShaman:
                                self.firstcount = self.firstcount
                            else:
                                self.firstcount += 1
                    elif place==2:
                        playerscorep = playerscorep+14
                    elif place==3:
                        playerscorep = playerscorep+12
                    else:
                        playerscorep = playerscorep+10
                    if self.isShaman==True:
                        playerscorep = self.score
                    self.score = playerscorep
                    #end
                    if int(self.room.getPlayerCount()) >= 2:
                        if self.playerCode == self.room.currentShamanCode:
                            self.shamancheese += 1
                        else:
                            self.cheesecount += 1
                            self.shopcheese += 1

                    self.room.informAll(TransformiceClientHandler.sendPlayerGotCheese, [self.playerCode, self.score, place, timeTaken])
                    print (self.playerCode, self.score, place, timeTaken)
                    if self.room.isTesting:
                        self.sendData("\x0E" + "\x11",[])
                    self.room.checkShouldChangeWorld()

            elif eventToken2 == "\x13":
                #client thinks he has cheese

                self.room.sendAll(eventTokens, [self.playerCode])

                #self.room.stateRecorder.log(eventTokens, [self.playerCode])
                self.room.numGotCheese += 1
                if self.room.currentWorld == 108:
                    if self.room.numGotCheese>=10:
                        self.room.killShaman()
                if self.room.currentWorld == 109:
                    if self.room.numGotCheese>=10:
                        self.room.killShaman()
                if self.room.currentWorld == 110:
                    if self.room.numGotCheese>=10:
                        self.room.killShaman()
                if self.room.currentWorld == 111:
                    if self.room.numGotCheese>=10:
                        self.room.killShaman()
                if self.room.currentWorld == 112:
                    if self.room.numGotCheese>=10:
                        self.room.killShaman()
                if self.room.currentWorld == 113:
                    if self.room.numGotCheese>=10:
                        self.room.killShaman()
                if self.room.currentWorld == 114:
                    if self.room.numGotCheese>=10:
                        self.room.killShaman()


            elif eventToken2 == "\x14":
                #object finalise conjouring
                #objectCode, x, y, rotation, unkn1, unkn2, isSolid = values
                hackcheck = 0
                #if self.room.currentWorld == 108 or self.room.currentWorld == 109 or self.room.currentWorld == 888 or self.room.currentWorld == 801:
                    #if self.room.isSandbox == False and self.room.isPlay == False:
                        #self.room.informAll(TransformiceClientHandler.sendPlayerDisconnect, [self.playerCode])
                        #self.room.removeClient(self)
                        #hmessage = "["+self.address[0]+" - "+self.username+"] Spawned object on map with no objects or shaman."
                        #self.sendAdminMessageChannel("Hack Detect", hmessage)
                        #self.close()
                        #hackcheck = 1
                #if self.playerCode != self.room.currentShamanCode:
                    #if self.room.isSandbox == False and self.room.isPlay == False:
                        #self.room.informAll(TransformiceClientHandler.sendPlayerDisconnect, [self.playerCode])
                        #self.room.removeClient(self)
                        #hmessage = "["+self.address[0]+" - "+self.username+"] Spawned object when not shaman."
                        #self.sendAdminMessageChannel("Hack Detect", hmessage)
                        #self.close()
                        #hackcheck = 1
                if values[0]=="5" or values[0]=="8" or values[0]=="9" or values[0]=="17" or values[0]=="21" or  values[0]=="23" or  values[0]=="25":
                    #Heavy Ball=5; Little Rough Board=8; Long Reough Board=9; Up Cannon=17; Sticky Ball=21; Bomb=23; Bait=25
                    self.room.informAll(TransformiceClientHandler.sendPlayerDisconnect, [self.playerCode])
                    self.room.removeClient(self)
                    hmessage = "["+self.address[0]+" - "+self.username+"] Spawned object code "+values[0]+"."
                    self.sendAdminMessageChannel("Hack Detect", hmessage)
                    self.close()
                    hackcheck = 1
                if hackcheck == 0:
                    self.room.sendAllOthersAndSelf(self, eventTokens, [self.playerCode] + values)


            elif eventToken2 == "\x15":
                # "Creation_Objet_Monde" - world object creation
                #objectCode, x, y, unkn1, unkn2, unkn3, unkn4 = values
                if self.isSyncroniser:
                    self.room.sendAllOthers(self, eventToken1 + "\x14", values)
            elif eventToken2 == "\x16":
                # "Demande_Changement_Gravite"
                #gx, gy = values

                if self.isSyncroniser:
                    self.room.sendAll(eventTokens, values)

            else:
                logging.warning("Unimplemented %r" % eventTokens)
                #raise NotImplementedError, eventTokens
        elif eventToken1 == "\x14":
            if eventToken2 == "\x14":
                #open shop
                self.sendData("\x14" + "\x14",[str(self.shopcheese),self.shoplist,self.look,self.shopitems])
            if eventToken2 == "\x12":
                #remove item
                if int(values[0])>=100 and int(values[0]) <=199:
                    itemcategory=1
                elif int(values[0])>=200 and int(values[0]) <=299:
                    itemcategory=2
                elif int(values[0])>=300 and int(values[0]) <=399:
                    itemcategory=3
                elif int(values[0])>=400 and int(values[0]) <=499:
                    itemcategory=4
                else:
                    itemcategory=0
                looklist = self.look.split(",")
                if itemcategory==0:
                    looklist[0]="0"
                    self.look=json.dumps(looklist)
                    self.look = self.look.strip('[]')
                    self.look = self.look.replace("\"","")
                    self.look = self.look.replace(" ","")
                    self.sendData("\x14" + "\x14",[str(self.shopcheese),self.shoplist,self.look,self.shopitems])
                if itemcategory==1:
                    looklist[1]="0"
                    self.look=json.dumps(looklist)
                    self.look = self.look.strip('[]')
                    self.look = self.look.replace("\"","")
                    self.look = self.look.replace(" ","")
                    self.sendData("\x14" + "\x14",[str(self.shopcheese),self.shoplist,self.look,self.shopitems])
                if itemcategory==2:
                    looklist[2]="0"
                    self.look=json.dumps(looklist)
                    self.look = self.look.strip('[]')
                    self.look = self.look.replace("\"","")
                    self.look = self.look.replace(" ","")
                    self.sendData("\x14" + "\x14",[str(self.shopcheese),self.shoplist,self.look,self.shopitems])
                if itemcategory==3:
                    looklist[3]="0"
                    self.look=json.dumps(looklist)
                    self.look = self.look.strip('[]')
                    self.look = self.look.replace("\"","")
                    self.look = self.look.replace(" ","")
                    self.sendData("\x14" + "\x14",[str(self.shopcheese),self.shoplist,self.look,self.shopitems])
                if itemcategory==4:
                    looklist[4]="0"
                    self.look=json.dumps(looklist)
                    self.look = self.look.strip('[]')
                    self.look = self.look.replace("\"","")
                    self.look = self.look.replace(" ","")
                    self.sendData("\x14" + "\x14",[str(self.shopcheese),self.shoplist,self.look,self.shopitems])
            if eventToken2 == "\x11":
                #equip item
                fullitem = str(values[0])
                if int(values[0])>=100 and int(values[0]) <=199:
                    itemcategory=1
                    item=fullitem[1:]
                    item=int(item)
                    item=str(item)
                elif int(values[0])>=200 and int(values[0]) <=299:
                    itemcategory=2
                    item=fullitem[1:]
                    item=int(item)
                    item=str(item)
                elif int(values[0])>=300 and int(values[0]) <=399:
                    itemcategory=3
                    item=fullitem[1:]
                    item=int(item)
                    item=str(item)
                elif int(values[0])>=400 and int(values[0]) <=499:
                    itemcategory=4
                    item=fullitem[1:]
                    item=int(item)
                    item=str(item)
                else:
                    itemcategory=0
                    item=values[0]
                looklist = self.look.split(",")
                if itemcategory==0:
                    looklist[0]=str(item)
                    self.look=json.dumps(looklist)
                    self.look = self.look.strip('[]')
                    self.look = self.look.replace("\"","")
                    self.look = self.look.replace(" ","")
                    self.sendData("\x14" + "\x14",[str(self.shopcheese),self.shoplist,self.look,self.shopitems])
                if itemcategory==1:
                    looklist[1]=str(item)
                    self.look=json.dumps(looklist)
                    self.look = self.look.strip('[]')
                    self.look = self.look.replace("\"","")
                    self.look = self.look.replace(" ","")
                    self.sendData("\x14" + "\x14",[str(self.shopcheese),self.shoplist,self.look,self.shopitems])
                if itemcategory==2:
                    looklist[2]=str(item)
                    self.look=json.dumps(looklist)
                    self.look = self.look.strip('[]')
                    self.look = self.look.replace("\"","")
                    self.look = self.look.replace(" ","")
                    self.sendData("\x14" + "\x14",[str(self.shopcheese),self.shoplist,self.look,self.shopitems])
                if itemcategory==3:
                    looklist[3]=str(item)
                    self.look=json.dumps(looklist)
                    self.look = self.look.strip('[]')
                    self.look = self.look.replace("\"","")
                    self.look = self.look.replace(" ","")
                    self.sendData("\x14" + "\x14",[str(self.shopcheese),self.shoplist,self.look,self.shopitems])
                if itemcategory==4:
                    looklist[4]=str(item)
                    self.look=json.dumps(looklist)
                    self.look = self.look.strip('[]')
                    self.look = self.look.replace("\"","")
                    self.look = self.look.replace(" ","")
                    self.sendData("\x14" + "\x14",[str(self.shopcheese),self.shoplist,self.look,self.shopitems])
            if eventToken2 == "\x13":
                #buy item
                itemcat0 = {3:20, 5:100, 2:200, 4:200, 1:500, 6:500, 7:200, 8:300, 9:500, 10:100, 11:500, 12:200, 13:500, 14:300, 15:200, 16:300, 17:200, 18:300, 19:300, 20:500, 21:200, 22:300, 23:400, 24:50, 25:250, 26:300, 27:800, 28:300, 29:500, 30:200, 31:300, 32:800, 33:150, 34:400, 35:1000, 36:500, 37:200, 38:800, 39:200, 40:500, 41:800, 42:500, 43:200, 44:250, 45:300, 46:100, 47:1500} #39:1000000, 40:1000000, 41:1000000, 42:1000000,
                itemcat1 = {1:200, 2:200, 4:200, 3:200, 5:300, 6:800, 7:50}
                itemcat2 = {1:100, 2:50, 3:20, 4:20} #{1:100, 2:1000000, 3:\1000000, 4:20}
                itemcat3 = {1:100, 2:25, 3:150, 4:400, 5:300, 6:300, 7:300}
                itemcat4 = {1:200, 2:200, 3:200, 4:50} #{1:200, 2:200, 3:1000000, 4:50}
                fullitem = str(values[0])
                if int(values[0])>=100 and int(values[0]) <=199:
                    itemcategory=1
                    item=fullitem[1:]
                    item=int(item)
                    item=str(item)
                elif int(values[0])>=200 and int(values[0]) <=299:
                    itemcategory=2
                    item=fullitem[1:]
                    item=int(item)
                    item=str(item)
                elif int(values[0])>=300 and int(values[0]) <=399:
                    itemcategory=3
                    item=fullitem[1:]
                    item=int(item)
                    item=str(item)
                elif int(values[0])>=400 and int(values[0]) <=499:
                    itemcategory=4
                    item=fullitem[1:]
                    item=int(item)
                    item=str(item)
                else:
                    itemcategory=0
                    item=values[0]
                shopcheese = int(self.shopcheese)
                looklist = self.look.split(",")
                if itemcategory==0:
                    if shopcheese < itemcat0[int(item)]:
                        self.sendData("\x14" + "\x06", [])
                    if shopcheese >= itemcat0[int(item)]:
                        if self.shopitems=="":
                            self.shopitems=str(fullitem)
                            self.shopcheese=self.shopcheese-itemcat0[int(item)]
                            looklist[0]=str(item)
                            self.look=json.dumps(looklist)
                            self.look = self.look.strip('[]')
                            self.look = self.look.replace("\"","")
                            self.look = self.look.replace(" ","")
                            self.sendData("\x14" + "\x14",[str(self.shopcheese),self.shoplist,self.look,self.shopitems])
                        else:
                            self.shopitems=self.shopitems+","+str(fullitem)
                            self.shopcheese=self.shopcheese-itemcat0[int(item)]
                            looklist[0]=str(item)
                            self.look = json.dumps(looklist)
                            self.look = self.look.strip('[]')
                            self.look = self.look.replace("\"","")
                            self.look = self.look.replace(" ","")
                            self.sendData("\x14" + "\x14",[str(self.shopcheese),self.shoplist,self.look,self.shopitems])  
                elif itemcategory==1:
                    if shopcheese < itemcat1[int(item)]:
                        self.sendData("\x14" + "\x06", [])
                    if shopcheese >= itemcat1[int(item)]:
                        if self.shopitems=="":
                            self.shopitems=str(fullitem)
                            self.shopcheese=self.shopcheese-itemcat1[int(item)]
                            looklist[1]=str(item)
                            self.look=json.dumps(looklist)
                            self.look = self.look.strip('[]')
                            self.look = self.look.replace("\"","")
                            self.look = self.look.replace(" ","")
                            self.sendData("\x14" + "\x14",[str(self.shopcheese),self.shoplist,self.look,self.shopitems])
                        else:
                            self.shopitems=self.shopitems+","+str(fullitem)
                            self.shopcheese=self.shopcheese-itemcat1[int(item)]
                            looklist[1]=str(item)
                            self.look = json.dumps(looklist)
                            self.look = self.look.strip('[]')
                            self.look = self.look.replace("\"","")
                            self.look = self.look.replace(" ","")
                            self.sendData("\x14" + "\x14",[str(self.shopcheese),self.shoplist,self.look,self.shopitems])
                elif itemcategory==2:
                    if shopcheese < itemcat2[int(item)]:
                        self.sendData("\x14" + "\x06", [])
                    if shopcheese >= itemcat2[int(item)]:
                        if self.shopitems=="":
                            self.shopitems=str(fullitem)
                            self.shopcheese=self.shopcheese-itemcat2[int(item)]
                            looklist[2]=str(item)
                            self.look=json.dumps(looklist)
                            self.look = self.look.strip('[]')
                            self.look = self.look.replace("\"","")
                            self.look = self.look.replace(" ","")
                            self.sendData("\x14" + "\x14",[str(self.shopcheese),self.shoplist,self.look,self.shopitems])
                        else:
                            self.shopitems=self.shopitems+","+str(fullitem)
                            self.shopcheese=self.shopcheese-itemcat2[int(item)]
                            looklist[2]=str(item)
                            self.look = json.dumps(looklist)
                            self.look = self.look.strip('[]')
                            self.look = self.look.replace("\"","")
                            self.look = self.look.replace(" ","")
                            self.sendData("\x14" + "\x14",[str(self.shopcheese),self.shoplist,self.look,self.shopitems])
                elif itemcategory==3:
                    if shopcheese < itemcat3[int(item)]:
                        self.sendData("\x14" + "\x06", [])
                    if shopcheese >= itemcat3[int(item)]:
                        if self.shopitems=="":
                            self.shopitems=str(fullitem)
                            self.shopcheese=self.shopcheese-itemcat3[int(item)]
                            looklist[3]=str(item)
                            self.look=json.dumps(looklist)
                            self.look = self.look.strip('[]')
                            self.look = self.look.replace("\"","")
                            self.look = self.look.replace(" ","")
                            self.sendData("\x14" + "\x14",[str(self.shopcheese),self.shoplist,self.look,self.shopitems])
                        else:
                            self.shopitems=self.shopitems+","+str(fullitem)
                            self.shopcheese=self.shopcheese-itemcat3[int(item)]
                            looklist[3]=str(item)
                            self.look = json.dumps(looklist)
                            self.look = self.look.strip('[]')
                            self.look = self.look.replace("\"","")
                            self.look = self.look.replace(" ","")
                            self.sendData("\x14" + "\x14",[str(self.shopcheese),self.shoplist,self.look,self.shopitems])
                elif itemcategory==4:
                    if shopcheese < itemcat4[int(item)]:
                        self.sendData("\x14" + "\x06", [])
                    if shopcheese >= itemcat4[int(item)]:
                        if self.shopitems=="":
                            self.shopitems=str(fullitem)
                            self.shopcheese=self.shopcheese-itemcat4[int(item)]
                            looklist[4]=str(item)
                            self.look=json.dumps(looklist)
                            self.look = self.look.strip('[]')
                            self.look = self.look.replace("\"","")
                            self.look = self.look.replace(" ","")
                            self.sendData("\x14" + "\x14",[str(self.shopcheese),self.shoplist,self.look,self.shopitems])
                        else:
                            self.shopitems=self.shopitems+","+str(fullitem)
                            self.shopcheese=self.shopcheese-itemcat4[int(item)]
                            looklist[4]=str(item)
                            self.look = json.dumps(looklist)
                            self.look = self.look.strip('[]')
                            self.look = self.look.replace("\"","")
                            self.look = self.look.replace(" ","")
                            self.sendData("\x14" + "\x14",[str(self.shopcheese),self.shoplist,self.look,self.shopitems])
                else:
                    pass
        elif eventToken1 == "\x18":
            if eventToken2 == "\x0F":
                #open forums
                pass
            else:
                logging.warning("Unimplemented %r" % eventTokens)
                #raise NotImplementedError, eventTokens
        elif eventToken1 == "\x08":
            if eventToken2 == "\x0D":
                #open friends
                #if room == "Offline":
                                    #self.sendData("\x1A" + "\x04", ["[Serveur] %s is offline." % (username)])
                                #else:
                                    #self.sendData("\x1A" + "\x04", ["[Serveur] %s -> %s" % (username, room)])
                #room = self.server.findPlayer(username)
                #room = self.server.findPlayer(username)
                friendsList = self.server.getUserFriends(self.username).split(",")
                sendList = [8]
                for user in friendsList:
                    found = self.server.findPlayer(user)
                    if found == "Offline":
                        sendList.append(user)
                    else:
                        friends = self.server.getUserFriends(user)
                        if self.username in friends:
                            sendList.append("%s%s"%(user,found))
                        else:
                            sendList.append("%s-"%(user))
                #self.sendData("\x08" + "\x0C",[8, "Notfriend-", "ConnectedYes", "Offline"])
                self.sendData("\x08" + "\x0C",sendList)
                #pass
            elif eventToken2 == "\x0e":
                #remove friend
                #print values
                user = str(values).title().replace("['", "").replace("']", "")
                friendsList = self.server.getUserFriends(self.username).split(",")
                print "User: "+str(user)
                friendsList.remove(user)
                newlist = ""
                for users in friendsList:
                    if newlist == "":
                        newlist = users
                    else:
                        old = newlist
                        newlist = "%s,%s"%(old,users)
                dbcur.execute('UPDATE users SET friends = ? WHERE name = ?', [newlist, self.username])
                self.sendRemovedFriend(user)
            elif eventToken2 == "\x18":
                #open avatar selection        #playercode
                self.sendData("\x08" + "\x18",["INVALID"])
                #pass
            elif eventToken2 == "\x10":
                #attach baloon to player
                #playerCode, = values
                self.room.sendAll(eventTokens, values)
            elif eventToken2 == "\x11":
                #baloon detatched
                self.room.sendAllOthersAndSelf(self, "\x08\x10", [self.playerCode, "0"]) #unknown??
            else:
                logging.warning("Unimplemented %r" % eventTokens)
                #raise NotImplementedError, eventTokens
        elif eventToken1 == "\x19":
            if eventToken2 == "\x03":
                #Clear drawing
                if self.privilegeLevel!=10:
                    self.room.informAll(TransformiceClientHandler.sendPlayerDisconnect, [self.playerCode])
                    self.room.removeClient(self)
                    hmessage = "["+self.address[0]+" - "+self.username+"] Attempted to clear drawing."
                    self.sendAdminMessageChannel("Hack Detect", hmessage)
                    self.close()
                else:
                    self.room.sendAllOthersAndSelf(self, eventTokens, values)
            elif eventToken2 == "\x04":
                #Start drawing
                #x,y = values
                #print 'Start drawing: %s'%(str(values))
                if self.privilegeLevel!=10:
                    self.room.informAll(TransformiceClientHandler.sendPlayerDisconnect, [self.playerCode])
                    self.room.removeClient(self)
                    hmessage = "["+self.address[0]+" - "+self.username+"] Attempted to draw."
                    self.sendAdminMessageChannel("Hack Detect", hmessage)
                    self.close()
                else:
                    self.room.sendAllOthers(self, eventTokens, values)
            elif eventToken2 == "\x05":
                #Draw point
                #x,y = values
                #print 'Draw point: %s'%(str(values))
                if self.privilegeLevel!=10:
                    self.room.informAll(TransformiceClientHandler.sendPlayerDisconnect, [self.playerCode])
                    self.room.removeClient(self)
                    hmessage = "["+self.address[0]+" - "+self.username+"] Attempted to draw."
                    self.sendAdminMessageChannel("Hack Detect", hmessage)
                    self.close()
                else:
                    self.room.sendAllOthers(self, eventTokens, values)
            else:
                logging.warning("Unimplemented %r" % eventTokens)
        elif eventToken1 == "\x10":
            if eventToken2 == "\x08":
                #create tribe
                #Fail
                #self.sendData("\x10" + "\x04",[10])
                tribename = values[0]
                self.sendData("\x10" + "\x12",
            ["2", tribename, "0", "None", "", "9"])
                self.haveTribe = True
                self.tribeName = tribename
                self.tribeGreeting = "None"
                dbcur.execute('UPDATE users set tribe = ? WHERE name = ?', [tribename, self.username])
                dbcur.execute('UPDATE users set triberank = ? WHERE name = ?', ["9", self.username])
                dbcur.execute("insert into tribes (name, greeting, users, options) values (?, ?, ?, ?)", (tribename, "None", self.username, ""))
            elif eventToken2 == "\x16":
                #Change Rank
                print values
                name = values[0]
                rank = values[1]
                dbcur.execute('UPDATE users set triberank = ? WHERE name = ?', [rank, name])
                self.room.sendTribeMsg(self, "\x10\x04", [str(self.tribeName), '12', name, rank])
            elif eventToken2 == "\x15":
                player = values[0]
                users = self.server.getTribeUsers(self.tribeName).split(',')
                users.remove(player)
                newlist = ""
                for user in users:
                    if newlist == "":
                        newlist = user
                    else:
                        old = newlist
                        newlist = "%s,%s"%(old,user)
                dbcur.execute('UPDATE tribes set users = ? WHERE name = ?', [newlist, self.tribeName])
                dbcur.execute('UPDATE users set tribe = ? WHERE name = ?', ["", player])
                self.room.sendTribeMsg(self, "\x10\x04", [str(self.tribeName), '11', player])
                self.room.sendTribeMsg(self, "\x10\x04", [str(self.tribeName), '2', player])
            elif eventToken2 == "\r":
                if values[0] == "2":
                    #print 'Recruited to tribe %s'%(self.server.recruitTribe
                    if self.tribeName == "":
                        dbcur.execute('UPDATE users set tribe = ? WHERE name = ?', [self.server.recruitTribe, self.username])
                        dbcur.execute('UPDATE users set triberank = ? WHERE name = ?', ["0", self.username])
                        users = self.server.getTribeUsers(self.server.recruitTribe)
                        newuser = "%s,%s"%(users,self.username)
                        dbcur.execute('UPDATE tribes set users = ? WHERE name = ?', [newuser, self.server.recruitTribe])
                        self.tribeName = self.server.getTribeName(self.username)
                        self.tribeGreeting = self.server.getTribeGreeting(self.tribeName)
                        self.tribeSettings = self.server.getTribeSettings(self.tribeName)
                        self.tribeRank = "1"
                        self.sendData("\x10" + "\x12",
                ["2", self.tribeName, "0", self.tribeGreeting, self.tribeSettings, "1"])
                        self.room.sendTribeMsg(self, "\x10\x04", [str(self.tribeName), '6', self.username, self.tribeName])
                        self.room.sendTribeMsg(self, "\x10\x04", [str(self.tribeName), '1', self.username])
            elif eventToken2 == "\x13":
                #Permissions
                permissions = values[0]
                newpermissions = ""
                dbcur.execute('UPDATE tribes set options = ? WHERE name = ?', [newpermissions, self.tribeName])
                self.tribeSettings = newpermissions
                self.room.sendTribes(self, "\x10\x12", ["2", self.tribeName, "0", self.tribeGreeting, self.tribeSettings, "Unknown"])
                #self.room.sendTribes(self, "\x10\x12", ["2", self.tribeName, "0", self.tribeGreeting, self.tribeSettings, "Unknown"])
            elif eventToken2 == "\x14":
                #Greeting
                greeting = str(values[0])
                #self.sendData("\x10" + "\x12",
            #["2", self.tribeName, "0", greeting, "", "9"])
                self.tribeGreeting = str(greeting)
                self.room.sendTribes(self, "\x10\x12", ["2", self.tribeName, "0", self.tribeGreeting, self.tribeSettings, "Unknown"])
                dbcur.execute('UPDATE tribes set greeting = ? WHERE name = ?', [greeting, self.tribeName])
            elif eventToken2 == "\x10":
                #Whirledians.3.0.0.whirledRoom
                #"Oly9001","Test1001"
                users = self.server.getTribeUsers(self.tribeName).split(',')
                onlinelist = []
                for user in users:
                    found = self.server.findPlayer(user)
                    if found == "Offline":
                        pass
                    else:
                        priv = self.server.getTribeRank(user)
                        onlinelist.append("%s%s00%s"%(user,priv,found))
                self.sendData("\x10" + "\x10",
                              onlinelist)
                
            else:
                print 'Unimplemented %r'%(eventTokens)
            
        elif eventToken1 == "\x13":
            if eventToken2 == "\x14":
                #Got gift
                self.room.sendAllOthersAndSelf(self, "\x13\x15", [self.playerCode])
                self.gotGift=1
                #print values
        elif eventToken1 == "\x0E":
            if eventToken2 == "\x1A":
                #Exit Editor
                self.sendData("\x0E" + "\x0E",["0"])
                self.room.isEditeur=False
                self.enterRoom("1")   
            elif eventToken2 == "\x09":
                #Client keeps sending this
                try:
                    print 'x09: %s' % (values)
                except:
                    print 'x09: No values'
            elif eventToken2 == "\x04":
                #Vote
                if not self.Voted and not self.SPEC and self.room.votingMode and self.QualifiedVoter:
                    if len(values)==1:
                        if int(values[0])==1:
                            self.Voted=True
                            self.room.recievedYes+=1
                    elif len(values)==0:
                        self.Voted=True
                        self.room.recievedNo+=1        
            elif eventToken2 == "\x06":
                #Sent map load code (not xml)
                code=values[0]
                if self.privilegeLevel==10 or self.privilegeLevel==6 or self.privilegeLevel==5:
                    if str(code).isdigit():
                        dbcur.execute('select * from mapeditor where code = ?', [code])
                        rrf = dbcur.fetchone()
                        if rrf is None:
                            self.sendData("\x0E" + "\x08",[])
                        else:
                            self.sendLoadMapAtCode(rrf[0], rrf[1], rrf[2], rrf[3], rrf[4], rrf[5])
                            self.room.ISCMVdata[2]= rrf[2]
                            self.room.ISCMVdata[1]= rrf[0]
                            self.room.ISCMVdata[7]= rrf[5]
                            self.room.ISCMVloaded = int(code)
                    else:
                        self.sendData("\x0E" + "\x08",[])
                else:
                    if str(code).isdigit():
                        dbcur.execute('select * from mapeditor where code = ?', [code])
                        rrf = dbcur.fetchone()
                        if rrf is None:
                            self.sendData("\x0E" + "\x08",[])
                        else:
                            if rrf[0]==self.username:
                                self.sendLoadMapAtCode(rrf[0], rrf[1], rrf[2], rrf[3], rrf[4], rrf[5])
                                self.room.ISCMVdata[2]= rrf[2]
                                self.room.ISCMVloaded = int(code)
                            else:
                                self.sendData("\x0E" + "\x08",[])
                    else:
                        self.sendData("\x0E" + "\x08",[])
            elif eventToken2 == "\n":
                self.sendData("\x0E" + "\x08",["9"])
                self.sendData("\x0E" + "\x11",[])
                mapxml = values
                mapxml = json.dumps(mapxml)
                mapxml = mapxml.strip('\"[\'\']\"')
                mapxml = mapxml.replace("\\", "")
                self.sendData("\x0E" + "\x0E",["0"])
                self.room.isEditeur=False
                radommps = random.choice (RADOMPS_LIST)
                dbcur.execute("insert into options (name, data) values (?, ?)", (self.username, radommps))
                dbcur.execute('select data from options where name = ?', [self.username])
                rrf = dbcur.fetchone()
                number = rrf[0] + radommps
                number = int(number)
                codes = "@%s" % (number)
                self.sendServeurMessage("%s, seu mapa foi exportado para o servidor! [%s]" % (self.username, codes))
                self.sendMapExported(number)
                dbcur.execute("insert into mapeditor (name, code, mapxml, yesvotes, novotes, perma, deleted) values (?, ?, ?, ?, ?, ?, ?)", (self.username, number, mapxml, 0, 0, 0, 0))
                number += 1
                dbcur.execute('UPDATE options set data = ? WHERE name = ?', [number, "mapcode"])
                print 'XML: %s' % (mapxml)
            
        else:
            logging.warning("Unimplemented %r" % eventTokens)
            print 'Unimplemented %s' % (str(eventTokens))
            #raise NotImplementedError, eventTokens

    def endDraw(self):
        self.room.currentlyDrawing = False
        self.room.currentDrawer = None
    def handle_close(self):
        try:
            if self.room:
                self.room.removeClient(self)
                self.room.sendTribeMsg(self, "\x10\x04", [str(self.tribeName), '2', self.username])
                if self.privilegeLevel==3:#[M][Serveur] Felipinhooo vient de se déconnecter.
                    self.sendAdminMessageChannel("Serveur", "%s vient de se déconnecter." % (self.username))
                if self.privilegeLevel>=5 and not self.isDrawer:#has just logged in!
                    self.sendModMessageChannel("Serveur", "%s desconectou-se." % (self.username))
                if self.privilegeLevel==10 and self.isDrawer:
                    self.sendModMessageChannel("Drawer", "%s desconectou-se." % (self.username))
            self.close()
        except:
            pass


    def checkValidXML(self, xmlString):
        if re.search("ENTITY", xmlString):
            return False
        elif re.search("", xmlString):
            return False
        else:
            try:
                parser = xml.parsers.expat.ParserCreate()
                parser.Parse(xmlString)
                return True
            except Exception, e:
                return False
    def getDefaultLook(self):
        return "0,0,0,0,0"

    def sendData(self, eventCodes, data = None):
        if VERBOSE:
            logging.warning("Send %r %r" % (eventCodes, data))
        #print "Send %r %r" % (eventCodes, data)

        if data:
            self.push('\x01'.join(map(str, [eventCodes] + data)) + "\x00")
        else:
            self.push(eventCodes + "\x00")
        
    def sendCorrectVersion(self):
        self.sendData("\x1A" + "\x1B",
            [str(self.server.getConnectedPlayerCount()), "0195723846", "5527"] #MDT, CMDTEC
        )

    def sendTitleList(self):
        self.sendData("\x08" + "\x0F",self.titleList)
    def sendPlayerLoginData(self):
        self.sendData("\x1A" + "\x08",
            [self.username, str(self.playerCode), str(self.privilegeLevel)]
        )
        if self.username == "Notadmin":
            self.privilegeLevel = 1
            
    def sendPlayerBan(self, hours, banreason):
        bantime=3600000*hours
        self.sendData("\x1A" + "\x12",[bantime, banreason])

    def sendBanWarning(self, hours):
        #CAUTION, you have already been banned for 1 hours. If you are banned for more than 24 hours in total, your account and your mouse will be DELETED AUTOMATICALLY AND FOREVER!
        self.sendData("\x1A" + "\x12",[hours])

    def sendPermaBan(self):
        self.sendData("\x1A" + "\x12",[])

    def sendBanConsideration(self):
        self.sendData("\x1A" + "\x09",["0"])

    def sendBanNotExist(self):
        self.sendData("\x1A" + "\x09",[])
    def sendMapPerm(self):
        self.sendData("\x05" + "\x12",[])
    def sendPlayerBanMessage(self, name, time, reason):
        self.room.sendAllOthersAndSelf(self, "\x1A" + "\x07", [name, time, reason])

    def sendDestroyConjuration(self, x, y):
        self.room.sendAllOthersAndSelf(self, "\x04" + "\x0F", [x, y])
    def sendDestroyConjurationz(self):
        location = 0
        location2 = 0
        done = False
        done2 = True
        while not done:
            location += 1
            if location == 250 or location > 250:
                done = True
                done2 = False
            else:
                self.room.sendAllOthersAndSelf(self, "\x04" + "\x0F", [location, location])
        while not done2:
            location += 1
            if location2 == 250 or location2 > 250:
                done2 = True
            if location == 250 or location > 250:
                location2 += 1
                location = 0
            else:
                self.room.sendAllOthersAndSelf(self, "\x04" + "\x0F", [location, location2])
    def sendStartSnowStorm(self):
        self.room.sendAllOthersAndSelf(self, "\x05" + "\x17", ["0"])
        #self.room.isSnowing=True
    def sendEndSnowStorm(self):
        self.room.sendAllOthersAndSelf(self, "\x05" + "\x17", [])
        #self.room.isSnowing=False

    def sendEverybodyDance(self):
         self.room.sendAllOthersAndSelf(self, "\x1A" + "\x18", [])

    def sendNotEnoughTotalCheeseEditeur(self):
        #You need at least 1000 cheese
        self.sendData("\x0E" + "\x14",[""])

    def sendNotEnoughCheeseEditeur(self):
        #Export a map costs 20 cheese. You do not have enough.
        self.sendData("\x0E" + "\x14",["", ""])

    def sendMapValidated(self):
        self.sendData("\x0E" + "\x11",[])
    def sendTestExport(self):
        self.sendData("\x1E" + "\x05",[])
    def sendVoteBox(self, author, yes, no):
        self.sendData("\x0E" + "\x04",[author, yes, no])#\x10\x14
    def sendRecruit(self, username, tribe):
        pass
    def sendMapExported(self, code):
        self.sendData("\x0E" + "\x05",[code])

    def sendLoadMapAtCode(self, name, code, xml, yes, no, perma):
        self.sendData("\x0E" + "\x09",[xml, yes, no, perma])

    def sendUnlockedTitle(self, playerCode, titlenum):
        #Just the person that unlocked the title calls this function.
        self.room.sendAllOthersAndSelf(self, "\x08" + "\x0E", [playerCode, titlenum])

    def sendMaxFriends(self):
        self.sendData("\x08" + "\x0C",["0"])

    def sendNewFriend(self, name):
        #You're now friends with...
        self.sendData("\x08" + "\x0C",["1", name])

    def sendAlreadyFriend(self, name):
        #...is already part of your friend list.
        self.sendData("\x08" + "\x0C",["2", name])

    def sendRemovedFriend(self, name):
        #...isn't part of your friend list anymore.
        self.sendData("\x08" + "\x0C",["4", name])

    def sendEnterRoom(self, roomName):
        #You just entered room []. Type /room RoomName to create or join an existing room.
        self.sendData("\x05" + "\x15",
            [str(roomName)]
        )

    def sendTribeGreeting(self):
        usernamez = "Tribe"
        self.sendData("\x10" + "\x12",
            ["1", "Whirled", "0", "New Tribe Created ^^", "", "9"]
        )
    def sendChangeGreeting(self):
        self.sendData("\x10" + "x\14",
            ["Test greeting"]
        )
    def sendProfile(self, username):
        #[Username , "Saves,Cheese As Shaman,Firsts,Cheese", Current Title, Title List, Avatar Number, Tribe Name]
    # or [Username , "Saves,Cheese As Shaman,Firsts,Cheese", Current Title, Title List, Avatar Number]
        username=username.lower()
        username=username.capitalize()
        isguest=username.find("*")
        if isguest == -1:
            if self.server.checkAlreadyConnectedAccount(username):
                title = self.server.getProfileTitle(username)
                titleList = self.server.getProfileTitleList(username)
                cheese = self.server.getProfileCheeseCount(username)
                first = self.server.getProfileFirstCount(username)
                shamancheese = self.server.getProfileShamanCheese(username)
                saves = self.server.getProfileSaves(username)
                tribe = self.server.getProfileTribe(username)
                stats = str(saves)+","+str(shamancheese)+","+str(first)+","+str(cheese)
                if tribe != "":
                    self.sendData("\x08" + "\x0A",[username , stats, title, titleList, "0", tribe])
                else:
                    self.sendData("\x08" + "\x0A",[username , stats, title, titleList, "0"])
            else:
                pass
        else:
            pass

    def catchTheCheeseNoShaman(self, playerCode):
        self.sendData("\x08" + "\x17",
            [playerCode]
        )
        self.sendData("\x05" + "\x13",
            [playerCode]
        )
        self.room.isCatchTheCheeseMap = True
    def catchTheCheeseShaman(self, playerCode):
        self.sendData("\x08" + "\x17",
            [playerCode]
        )
        self.sendData("\x05" + "\x13",
            [playerCode]
        )
        self.sendData("\x08" + "\x14",
            [playerCode]
        )
        self.room.isCatchTheCheeseMap = True

    def sendNewParty(self):
        if self.room.isSnowing==True:
            self.sendStartSnowStorm()
        if self.room.isSnowing==False:
            self.sendEndSnowStorm()
        self.sendData("\x05" + "\x05",
            [self.room.currentWorld, self.room.getPlayerCount(), 1, ""]
        )

    def sendNewPartyCustomMap(self, mapxml, mapname, mapperma):
        #mapperma = 0
        mapperma = str(mapperma)
        if self.room.isSnowing==True:
            self.sendStartSnowStorm()
        if self.room.isSnowing==False:
            self.sendEndSnowStorm()
        self.sendData("\x05" + "\x05",
            ["-1", self.room.getPlayerCount(), 10, "\x01"+mapxml+"\x02"+mapname+"\x02"+mapperma]
        )
        # print 'XML Loaded: '+str(mapxml)

    def sendPlayerList(self):
        self.sendData("\x08" + "\x09",
            list(self.room.getPlayerList())
        )

    def sendNewPlayer(self, playerData):
        self.sendData("\x08" + "\x08",
            [playerData]
        )

    def sendPlayerDisconnect(self, playerCode):
        self.sendData("\x08" + "\x07",
            [playerCode]
        )
    def sendPlayerDied(self, playerCode, score):
        #score = score-1
        #if score < 0:
        #    score = 0
        #self.score=score
        #self.room.decreaseScore(playerCode, score)
        self.sendData("\x08" + "\x05",
            [playerCode, 0, score]
        )
        if self.room.currentShamanCode == playerCode:
            self.sendTwenty()
            #self.room.setAlready = False
            self.room.setTimer()
            #print '(%s) Time set to 20'%(self.room.name)
        else:
            players = 0
            alive = 0
            for playerCode, client in self.room.clients.iteritems():
                players += 1
                if client.isDead:
                    pass
                else:
                    alive += 1
            #print 'alive: %s players: %s'%(str(alive), str(players))
            if alive == 1:
                if players >= 2:
                    self.sendTwenty()
                    self.room.setTimer()
        
            

    def sendPlayerGotCheese(self, playerCode, score, place, timeTaken):
        self.sendData("\x08" + "\x06",
            [playerCode, 0, score, place, timeTaken]
        )

    def sendShamanCode(self, shamanPlayerCode):
        if shamanPlayerCode == 0:
            self.sendData("\x08" + "\x14",
            )
        else:
            self.sendData("\x08" + "\x14",
                [shamanPlayerCode]
            )
    def sendDoubleShamanCode(self, shamanPlayerCode, shamanPlayerCodeTwo):
            self.sendData("\x08" + "\x14",
                [shamanPlayerCode, shamanPlayerCodeTwo]
            )
    def sendSynchroniser(self, playerCode):
        self.sendData("\x08" + "\x15",
            [playerCode]
        )

    def sendNewTitle(self, titlenum):
        self.sendData("\x08" + "\x0D",[titlenum])

    def sendTime(self, timeLeft):
        self.sendData("\x05" + "\x06",
            [timeLeft]
        )

    def sendTwenty(self):
        self.sendData("\x06" + "\x11")
    def sendSetAnchors(self, anchors):
        self.sendData("\x05" + "\x07",
            anchors
        )

    def sendATEC(self):
        self.sendData("\x1A" + "\x1A")
    def sendPING(self):
        self.sendData("\x04" + "\x14")

    def sendShamanPerformance(self, shamanName, numGathered):
        #Will display "Info_Fromage_Chamane" in chat
        #   - "Thanks to %1, we gathered %2 cheese !"
        self.sendData("\x08" + "\x11",
            [shamanName, numGathered]
        )
        #pass

    def sendPlayerAction(self, playerCode, action):
        self.sendData("\x08" + "\x16",
            [playerCode, action]
        )

    def sendModMessageChannel(self, name, message):
        self.room.sendModChat(self, "\x1A\x05", [name, message])
    def sendAdminMessageChannel(self, name, message):
        self.room.sendAdminChat(self, "\x1A\x06", [name, message])
    def sendTribeLogin(self, tribename, username):
        self.room.sendTribeMsg(self, "\x10\x04", [tribename, '1', username])
    def sendServeurMessage(self, message):
        self.room.sendServeur(self, "\x06\x14", [message])
        print '[Servidor] %s' % (message)
    def sendFriendLog(self, user):
        self.room.sendFriend(self, "\x08\x0B", [user])
    def sendServerMessageName(self, name, message):
        self.room.sendWholeServer(self, "\x1A\x04", ["[~"+name+"] ", message])
    def sendRestartMessage(self, message):
        self.room.sendWholeServer(self, "\x1A\x04", ["[SERVIDOR] ", "%s "%(message)])                           

    def sendModMessage(self, name, message):
        self.room.sendAllOthersAndSelf(self, "\x1A\x04", ["[~Moderação] ", message])

    def sendServerMessage(self, message):
        self.room.sendWholeServer(self, "\x1A\x04", ["[~Mensagem Server] ", message])

    def sendGiftAmount(self, amount):
        self.sendData("\x13" + "\x14",
            [amount]
        )

    def saveRemainingMiceMessage(self):
        #You must save all the remaining mice before you can enter the hole.
        self.sendData("\x08" + "\x12",
        )

    def sendPlayMusic(self, path):
        self.sendData("\x1A" + "\x0C",
            [path]
        )


    def sendSentPrivMsg(self, username, message):
        self.sendData("\x06" + "\x07",
            [message, username]
        )
    def sendRecievePrivMsg(self, username, message):
        self.sendData("\x06" + "\x07",
            [message, username, "x"]
        )
    def sendPlayerNotFound(self):
        self.sendData("\x06" + "\x07")


    def getPlayerData(self):
        #FUR
        return '#'.join(map(str,
                                                                        #has cheese           #unknown      #forum ID
            [self.username, self.playerCode, int(self.isDead), self.score, 0, self.titleNumber, 0, self.look, self.fur, 1]
        ))

    def enterRoom(self, roomName):
        enter = True
        if roomName.startswith("[Private]"):
            privates = ['Kingboo', 'Sooki', 'Oly', 'Alex', 'Solarra', 'Jawster', 'Wimp']
            if self.username in privates:
                self.sendData("\x1A" + "\x04", ["Bem-vindo %s! This room is for the private people only :P"%(self.username)])
            else:
                self.sendData("\x1A" + "\x04", ["You are not allowed in this room ^_^"])
                self.room.removeClient(self)
                self.enterRoom("1")
                enter = False
        if roomName.startswith("\x03"+"[Editeur] "):
            editeurnamecheck = roomName.replace("\x03"+"[Editeur] ", "")
            if editeurnamecheck == self.username:
                pass
            if editeurnamecheck != self.username:
                self.room.informAll(TransformiceClientHandler.sendPlayerDisconnect, [self.playerCode])
                self.room.removeClient(self)
                hmessage = "["+self.address[0]+" - "+self.username+"] Attempted to go to "+editeurnamecheck+"'s editor room."
                self.sendAdminMessageChannel("Hack Detect", hmessage)
                self.close()
        if enter:
            if self.room:
                self.room.removeClient(self)

            self.resetPlay()
            self.score = 0

            self.sendEnterRoom(roomName)

            #self.room =
            self.server.addClientToRoom(self, roomName)#self.room.removeClient(self)
            #print 'Added %s to room'%(str(self))
            
    def resetPlay(self):
        self.isShaman = False
        self.isDead = False
        self.isSyncroniser = False

    def startPlay(self):
        if self.room.getPlayerCount() >= 2:
            self.roundCount=self.roundCount+1
        self.resetPlay()

        self.sendGiftAmount(self.giftCount)

        if self.room.isBootcamp:
            mapcode=1337
            mapcode=str(mapcode)
            code = mapcode
            dbcur.execute('select name from mapeditor where code = ?', [code])
            rrf = dbcur.fetchone()
            mapname=rrf[0]
            del rrf
            dbcur.execute('select mapxml from mapeditor where code = ?', [code])
            rrf = dbcur.fetchone()
            mapxml=rrf[0]
            del rrf
            dbcur.execute('select yesvotes from mapeditor where code = ?', [code])
            rrf = dbcur.fetchone()
            yesvotes=rrf[0]
            del rrf
            dbcur.execute('select novotes from mapeditor where code = ?', [code])
            rrf = dbcur.fetchone()
            novotes=rrf[0]
            del rrf
            dbcur.execute('select perma from mapeditor where code = ?', [code])
            rrf = dbcur.fetchone()
            perma=rrf[0]
            del rrf
            dbcur.execute('select deleted from mapeditor where code = ?', [code])
            rrf = dbcur.fetchone()
            mapnoexist=rrf[0]
            self.sendNewPartyCustomMap(mapxml, mapname, perma)
        elif self.room.name == "801":
            mapcode="802"
            mapxml=''
            mapname="802"
            perma=0
            self.sendNewPartyCustomMap(mapxml, mapname, perma)
        else:
            if self.room.isCustom:
                try:
                    mapcode=self.room.customMap
                    mapcode=str(mapcode)
                    mapname=self.server.getMapName(mapcode)
                    mapxml=self.server.getMapXML(mapcode)
                    yesvotes=self.server.getMapYesVotes(mapcode)
                    novotes=self.server.getMapNoVotes(mapcode)
                    perma=self.server.getMapPerma(mapcode)
                    mapnoexist=self.server.getMapDel(mapcode)
                    self.sendNewPartyCustomMap(mapxml, mapname, perma)
                except:
                    self.sendServeurMessage("No such map [%s]" % (mapcode))
            elif self.room.isTesting:
                mapxml=self.room.editeurMap
                self.sendNewPartyCustomMap(mapxml, "-", 0)
            else:
                self.sendNewParty()

        if self.room.currentWorld==888:
            self.sendTime(60)
        if self.room.isBootcamp:
            self.sendTime(360)
        else:
            self.sendTime(120)

        if self.room.isSandbox:
            self.sendTime(0)
        self.sendPlayerList()
        shamanCode = self.room.getShamanCode()
        double = False
        if self.room.name=="801":
            self.sendShamanCode(0)
        elif self.room.everybodyIsShaman:
            self.sendShamanCode(self.playerCode)
        elif self.room.nobodyIsShaman:
            self.sendShamanCode(0)
            shamanCode = 0
        elif self.room.currentWorld in [108, 109]:
            self.catchTheCheeseNoShaman(shamanCode)
        elif self.room.currentWorld in [110, 111, 112, 113, 114]:
            self.catchTheCheeseShaman(shamanCode)
        elif self.room.currentWorld in [44, 45, 46, 47, 48, 49, 50, 51, 52, 53]:
            shamone = self.room.getDoubleShamanCode(1)
            shamtwo = self.room.getDoubleShamanCode(2)
            double = True
            print 'Sham1: %s Sham2: %s'%(str(shamone), str(shamtwo))
            self.sendDoubleShamanCode(shamone, shamtwo)
        else:
            self.sendShamanCode(shamanCode)
        if double:
            if shamone == self.playerCode:
                self.isShaman = True
            elif shamtwo == self.playerCode:
                self.isShaman = True
        else:
            if shamanCode == self.playerCode:
                self.isShaman = True

        syncroniserCode = self.room.getSyncroniserCode()
        self.sendSynchroniser(syncroniserCode)
        if syncroniserCode == self.playerCode:
            self.isSyncroniser = True
        if self.username == "Timekeeper":
            self.isDead = True
            self.room.informAll(TransformiceClientHandler.sendPlayerDied, [self.playerCode, self.score])

        if self.room.currentWorld==888:
            self.sendData("\x15" + "\x15", ["0", "Papai Noel", "21,0,3,4,3", "600", "335", "0", "0"])
            self.sendData("\x15" + "\x15", ["1", "Brunok", "21,0,3,4,3", "500", "300", "1", "0"])
        if self.room.name=="801":
            self.sendData("\x15" + "\x15", ["-1", "Brunok", "6,1,0,7,2", "700", "335", "0", "1"])
            self.sendData("\x15" + "\x15", ["-2", "Sonic", "13,0,0,3,0", "100", "200", "1", "0"])
            self.sendData("\x15" + "\x15", ["-3", "Seven", "47,0,2,0,0", "200", "200", "0", "0"])
            self.sendData("\x15" + "\x15", ["-4", "Xbrasilx", "47,6,0,6,0", "600", "200", "1", "0"])
            self.sendData("\x15" + "\x15", ["-5", "Livia", "35,0,1,0,0", "700", "200", "0", "0"])

            #(801) [c] Kingboo: 'snpc jawster 1,5,0,3,0 400 350'
            #if rotation == "left":
            #rotation = "0"
            #elif rotation == "right":
            #rotation = "1"
        try:
            self.notCustom.stop()
        except:
            if self.room.isTesting:
                pass
            else:
                self.notCustom = threading.Timer(5, self.endCustom)
                self.notCustom.start()
    def endCustom(self):
        self.room.isCustom = False
    def login(self, username, passwordHash, startRoom):
        if username == "":
            username = "Souris"
        if username == "S":
            self.sendData("\x1A" + "\x12",["0", "Ah, test is pro ^^s"])
        if passwordHash == "":
            if len(username)>=9:
                priv = -1
                self.close()
            else:
                username = "*"+username
                priv = 0
                username = self.server.checkAlreadyExistingGuest(username)
        else:
            username=username.lower()
            username=username.capitalize()
            priv = self.server.authenticate(username, passwordHash)

        if priv != 0:
            username=username.lower()
            username=username.capitalize()

        dbcur.execute('select * from userpermaban where name = ?', [username])
        rrf = dbcur.fetchone()
        print rrf
        if rrf is None:
            pass
        else:
            print '-1'
            priv = -1
            print "["+self.address[0]+" - "+username+"] Permabanned user tried to logon."
            self.sendPermaBan()
            #self.room.informAll(TransformiceClientHandler.sendPlayerDisconnect, [self.playerCode])
            #self.room.removeClient(self)
            self.close()

        if priv == -1:
            #return False
            #self.close()
            self.sendData("\x1A" + "\x03", ["\x00"+"6"])
            self.wrongPasswordAttempts+=1
            if self.wrongPasswordAttempts>=4:
                self.sendData("\x1A" + "\x12",["0", "Too many incorrect password attempts"])
                logging.info("Kick - Too many wrong passwords - %s" % self.address[0])
                self.close()

        else:
            alreadyconnect = self.server.checkAlreadyConnectedAccount(username)
            if alreadyconnect == True:
                self.sendData("\x1A" + "\x03", ["\x01"])
            else:
                self.username = username
                self.playerCode = self.server.generatePlayerCode()
                self.privilegeLevel = priv

                self.titleNumber = self.server.getCurrentTitle(username)
                self.roundCount = self.server.getRoundsCount(username)
                self.tribe = self.server.getTribeName(username)
                self.tribeName = self.server.getTribeName(username)
                self.tribeGreeting = self.server.getTribeGreeting(self.tribeName)
                self.tribeSettings = self.server.getTribeSettings(self.tribeName)
                self.tribeRank = self.server.getTribeRank(username)
                isDrawer = self.server.getDrawer(username)
                if str(isDrawer) == "1":
                    self.isDrawer = True
                else:
                    self.isDrawer = False
                if self.tribeName == "":
                    pass
                else:
                    self.sendData("\x10" + "\x12",
            ["2", self.tribeName, "0", self.tribeGreeting, self.tribeSettings, self.tribeRank])
                self.micesaves = self.server.getSavesCount(username)
                self.shamancheese = self.server.getShamanCheeseCount(username)
                self.firstcount = self.server.getFirstCount(username)
                self.cheesecount = self.server.getCheeseCount(username)
                self.shopcheese = self.server.getShopCheese(username)
                self.titleList = self.server.getTitleList(username)
                self.shopitems = self.server.getUserShop(username)
                self.look = self.server.getUserLook(username)
                self.fur = self.server.getFurColor(username)
                self.titleList = self.titleList.strip('[]')
                self.titleList = self.titleList.replace("\"","")
                self.titleList = self.titleList.replace(","," ")
                self.titleList = str(self.titleList)
                self.titleList = self.titleList.split(" ")
                print self.username
                print self.titleList
                self.sendTitleList()

                self.giftCount = 0
                #self.sendTribeGreeting()
                #• [Version] Game: 0.129Server: 1.012
                self.sendPlayerLoginData()
                if passwordHash == "":
                    logging.info("Authenticate %s - %s - Guest" % (self.address, username))
                else:
                    logging.info("Authenticate %s - %s" % (self.address, username))
                    print '%s has logged in!' % (self.username)
                
                if startRoom!="":
                    self.enterRoom(startRoom)
                    dbcur.execute('UPDATE users set lastroom = ? WHERE name = ?', [startRoom, self.username])
                else:
                    self.enterRoom(self.server.recommendRoom())
                    dbcur.execute('UPDATE users set lastroom = ? WHERE name = ?', [self.server.recommendRoom(), self.username])
                if self.privilegeLevel>=3 and not self.isDrawer:#[M][Serveur] Felipinhooo vient de se déconnecter.
                    self.sendAdminMessageChannel("Serveur", "%s conectou-se." % (self.username))
                if self.privilegeLevel>=5 and not self.isDrawer:#has just logged in!
                    self.sendModMessageChannel("Serveur", "%s conectou-se." % (self.username))
                if self.privilegeLevel==10 and self.isDrawer:
                    self.sendModMessageChannel("Drawer", "%s conectou-se." % (self.username))
                if self.privilegeLevel < 3:
                    self.sendServeurMessage("%s(User) conectou-se." % (self.username))
                self.sendFriendLog(self.username)
                if self.tribeName == "":
                    pass
                else:
                    self.sendTribeLogin(self.tribeName, self.username)
                return True
       
class TransformiceAdminTools(object):
    def __init__(self, server):
        self.server = server
    def sendModMessage(self, message):
        for room in self.server.rooms.itervalues():
            room.informAll(TransformiceClientHandler.sendModMessage, [ADMIN_NAME, message])
    def playMusicInRoom(self, roomName, path):
        roomName = str(roomName)
        if self.server.rooms.has_key(roomName):
            self.server.rooms[roomName].playMusic(path)


#from http://www.acooke.org/cute/BasicHTTPA0.html
class VerifyingXMLRPCServer(SimpleXMLRPCServer):
    def __init__(self, *args, **kargs):
        # we use an inner class so that we can call out to the
        # authenticate method
        class VerifyingRequestHandler(SimpleXMLRPCRequestHandler):
            # this is the method we must override
            def parse_request(myself):
                # first, call the original implementation which returns
                # True if all OK so far
                if SimpleXMLRPCRequestHandler.parse_request(myself):
                    # next we authenticate
                    if self.authenticate(myself.headers):
                        return True
                    else:
                        # if authentication fails, tell the client
                        myself.send_error(401, 'Authentication failed')
                        return False
        # and intialise the superclass with the above
        SimpleXMLRPCServer.__init__(self, requestHandler=VerifyingRequestHandler, *args, **kargs)

    def authenticate(self, headers):
        basic, _, encoded = headers.get('Authorization').partition(' ')
        assert basic == 'Basic', 'Only basic authentication supported'
        username, _, password = base64.b64decode(encoded).partition(':')

        return username.lower() in ADMIN_NAMES and hashlib.sha256(password).hexdigest() == ADMIN_HASH

if __name__ == "__main__":
    TEST = False
    server = TransformiceServer()

    adminTools = TransformiceAdminTools(server)

    rpcServer = VerifyingXMLRPCServer(('', 1110), allow_none=True)
    rpcServer.register_introspection_functions()
    rpcServer.register_instance(adminTools, True)
    thread.start_new_thread(rpcServer.serve_forever, ())

    asyncore.loop()