def new_block(entry_id, block): return ["INSERT INTO lore_blocks (entry, description, title, level, no_break, name) values (%d, '%s', '%s', %d, %s, '%s');" % ( entry_id, database.escape(block['text']), database.escape(block.get('title', '')), lore_entry.levels.index(block.get('level', 'public')), block.get('no_break', False), database.escape(block.get('id', '')), )]
def nmsg_func(args, u413): if "step" in u413.cmddata: if u413.cmddata["step"] == 1: u413.cmddata["step"] = 2 args = args.strip().split()[0] to = user_id(args) if to == None: u413.type('"%s" is not a u413 user.' % args) return u413.cmddata["to"] = to u413.type("Enter the topic:") u413.set_context("TOPIC") u413.continue_cmd() elif u413.cmddata["step"] == 2: u413.cmddata["step"] = 3 u413.cmddata["topic"] = args u413.type("Enter your message:") u413.set_context("MESSAGE") u413.continue_cmd() elif u413.cmddata["step"] == 3: db.query( "INSERT INTO messages(sender,receiver,topic,msg,sent,seen) VALUES(%i,%i,'%s','%s',NOW(),FALSE);" % (u413.user.userid, u413.cmddata["to"], db.escape(u413.cmddata["topic"]), db.escape(args))) u413.type("Message sent.") u413.set_context('') else: params = args.split(' ', 1) if len(args) == 0: u413.cmddata["step"] = 1 u413.type("Enter the receiver:") u413.set_context("USER") u413.continue_cmd() elif len(params) == 1: u413.cmddata["step"] = 2 args = params[0].strip().split()[0] to = user_id(args) if to == None: u413.type('"%s" is not a u413 user.' % args) return u413.cmddata["to"] = to u413.type("Enter the topic:") u413.set_context("TOPIC") u413.continue_cmd() else: u413.cmddata["step"] = 3 args = params[0].strip().split()[0] to = user_id(args) if to == None: u413.type('"%s" is not a u413 user.' % args) return u413.cmddata["to"] = to u413.cmddata["topic"] = params[1] u413.type("Enter your message:") u413.set_context("MESSAGE") u413.continue_cmd()
def new_wonder(name, city, point_cost, material_cost, description): return """INSERT INTO wonders (name, city, point_cost, material_cost, description) values ('%(name)s', %(city)d, %(point_cost)d, %(material_cost)d, '%(description)s');""" % { "name": database.escape(name), "city": city, "point_cost": point_cost, "material_cost": material_cost, "description": database.escape(description), }
def new_artefact(name, team, city, description): query = """INSERT INTO artefacts (name, team, city, description) values ('%(name)s', %(team)d, %(city)d, '%(description)s');""" % { "name": database.escape(name), "team": int(team), "city": int(city), "description": database.escape(description), } return query
def create_empty_army(cursor, name, team_id, x, y): # Insert query = """INSERT INTO armies (name, team, x, y) values ( '{name}', {team}, {x}, {y} );""".format( name=database.escape(name), team=team_id, x=x, y=y, ) try: cursor.execute(query) except Exception as e: raise Exception("Database error: %s\nQuery: %s" % (str(e.args[0]).replace("\n",""), query)) # Now get the ID of the army query = """SELECT id, name FROM armies WHERE team = {team} ORDER BY id DESC LIMIT 1""".format( team=team_id, ) try: cursor.execute(query) except Exception as e: raise Exception("Database error: %s\nQuery: %s" % (str(e.args[0]).replace("\n",""), query)) for row in cursor: if name == row['name']: return row['id'] # Not entered in, this is a bad sign :( raise Exception("Army was not found in the database args:(%s, %s, %d, %d, %d)" % (cursor, name, team_id, x, y))
def topic_func(args, u413): params = args.split(' ', 2) if len(params) == 0 or not util.isint(params[0]): u413.type("Invalid topic ID.") return topic = int(params[0]) if len(params) == 1: page = 1 output_page(topic, 1, u413) elif len(params) == 2: if params[1].upper() == "REPLY": u413.j["Command"] = "REPLY" u413.cmddata["topic"] = topic u413.continue_cmd() else: page = 1 if util.isint(params[1]): page = int(params[1]) elif params[1].upper() == 'LAST': page = db.count_posts(topic) if page == 0: page = 1 else: page = math.ceil(page / 10.0) output_page(topic, page, u413) elif params[1].upper() == "REPLY": db.query( "INSERT INTO posts (topic,title,parent,owner,editor,post,locked,edited,posted) VALUES(FALSE,'',%i,%i,0,'%s',FALSE,NULL,NOW());" % (topic, u413.user.userid, db.escape(util.htmlify(params[3])))) u413.type("Reply made successfully.")
def rebuild_equipment_string(cursor, unit_id, the_world=None): if the_world == None: the_world = world.World(cursor) # Does what it says on the tin equipment_dict = the_world.equipment() equipment_list = [] equipment_list_name = [] query = """SELECT equipment FROM unit_equipment WHERE unit = %d""" % unit_id try: cursor.execute(query) except Exception as e: raise Exception("Database error: %s\nQuery: %s" % (str(e.args[0]).replace("\n",""), query)) for row in cursor: equipment_list.append(row['equipment']) equipment_list_name.append(equipment_dict[row['equipment']].name) equipment_string = "" if len(equipment_list_name) == 1: equipment_string = equipment_list_name[0] if len(equipment_list_name) > 1: equipment_string = "%s and %s" % (", ".join(equipment_list_name[0:-1]), equipment_list_name[-1]) query = """UPDATE units SET equipment_string = '%s' WHERE id = %d;""" % (database.escape(equipment_string), unit_id) try: cursor.execute(query) except Exception as e: raise Exception("Database error: %s\nQuery: %s" % (str(e.args[0]).replace("\n",""), query))
def new_unit(cursor, team_id, name, description, size, equipment_list): """Inserts a new unit into the database""" if size < 1: size = 100 # Insert unit query = """INSERT INTO units (team, name, description, size) values (%d, '%s', '%s', %d);""" % (team_id, database.escape(name), database.escape(description), size) try: cursor.execute(query) except Exception as e: raise Exception("Database error: %s\nQuery: %s" % (str(e.args[0]).replace("\n",""), query)) if len(equipment_list) < 1: return # Get unit id query = """SELECT id FROM units WHERE name = '%s' AND team = %d LIMIT 1;""" % (database.escape(name), team_id) try: cursor.execute(query) except Exception as e: raise Exception("Database error: %s\nQuery: %s" % (str(e.args[0]).replace("\n",""), query)) row = cursor.fetchone() if row == None: return unit_id = row['id'] # Insert equipment query = """INSERT INTO unit_equipment (unit, equipment) values %s;"""% ( ",".join(["(%d, %d)" % (unit_id, e) for e in equipment_list])) try: cursor.execute(query) except Exception as e: raise Exception("Database error: %s\nQuery: %s" % (str(e.args[0]).replace("\n",""), query)) return unit_id
def record_resources(the_world, the_team): """Records the end of turn resources for the team""" the_team.get_resources(the_world.cursor, force_requery=True) strings = [] for res_id, r in enumerate(resource_list.data_list): if res_id not in the_team.resources.value: continue if the_team.resources.value[res_id] == 0: continue if r.reset: continue res_value = the_team.resources.value[res_id] # Typecast if we can if res_value == int(res_value): res_value = int(res_value) strings.append("%s:%s" % (r.name, res_value)) # Log previous resources database.query(the_world.cursor, log_f.new_log("team_f.record_resources", ",".join(strings), "", team = the_team.id) ) query = """UPDATE teams SET previous_resources = '%s' WHERE id = %d;""" % (database.escape(",".join(strings)), the_team.id) try: the_world.cursor.execute(query) except Exception as e: raise Exception("Database error: %s\nQuery: %s" % (str(e.args[0]).replace("\n",""), query))
def user_id(uname): user = db.query( "SELECT username,id FROM users WHERE LCASE(username)='%s';" % db.escape(uname.lower())) if len(user) == 0: return None return int(user[0]["id"])
def make_founding_query(team_id, name, city_location, is_port, is_nomadic, city_size, city_list): """Makes a set of queries for founding a new city""" if city_list == []: return [] queries = [] queries.append("""INSERT INTO cities (name, team, x, y, port, nomadic, population, founded, dead, secret) values ('%(name)s', %(team)s, %(x)s, %(y)s, %(port)s, %(nomadic)s, %(population)s, %(founded)s, 0, False);""".replace("\n", "") % { "name": database.escape(name), "team": team_id, "port": is_port, "nomadic": is_nomadic, "population": city_size, "x": city_location[0], "y": city_location[1], "founded": int(common.current_turn()), }) amount_per_city = math.ceil(city_size/len(city_list)) for c in city_list: queries.append("""UPDATE cities SET population = population-%d WHERE id = %d;""" % (amount_per_city, c)) return queries
def main(cursor): query = "SELECT id FROM teams ORDER BY id DESC LIMIT 1;" try: cursor.execute(query) except Exception as e: raise Exception("Database error: %s\nQuery: %s" % (str(e.args[0]).replace("\n",""), query)) row = cursor.fetchone() if row == None: start_at = 1 else: start_at = row['id'] + 1 getter_data = "p=%s&mode=teams&startat=%d" % (common.data['getterPass'], start_at) getter_results = str(urllib.request.urlopen(common.data['getter_url'], getter_data).read()) count = int(re.search(r'count:([0-9]{1,5})', getter_results).group(1)) if count < 1: return """No more teams to add. Started counting at %d<br /> Rob getter URL: %s""" % (start_at, common.data['getter_url']) else: reMatches = re.findall(r'group_id:([0-9]{1,5}), group_name:([^\n\\]*)', getter_results) teams = [] for teamMatch in reMatches: teams.append("(%s, '%s')" % (teamMatch[0], database.escape(teamMatch[1]))) query = "INSERT INTO teams (id, name) values %s;" % ", ".join(teams) try: cursor.execute(query) except Exception as e: raise Exception("Database error: %s\nQuery: %s" % (str(e.args[0]).replace("\n",""), query)) return "%s teams added successfully" % len(teams)
def download_orders(cursor, topic_id, turn_number, recache=False): """Goes after the post cache, if it's not there it DL's it""" # Cache if not recache: cache = check_orders_cache(cursor, topic_id, turn_number) if cache != None: return cache # Need to work out from and till turn_dict = system_q.get_all_turns(cursor) # Allow 300 seconds leeway time_from = turn_dict[turn_number] - 300 time_till = turn_dict[turn_number+1] + 300 getter_data = "p=%s&mode=posts&topic=%d&from=%d&till=%d" % ( common.data['getterPass'], topic_id, time_from, time_till) orders_result = urllib.request.urlopen(common.data['getter_url'], getter_data).read().strip() # We used to use this to blott out UTF-8 characters - Now we do again! regex = r"""[^a-zA-Z0-9! *$@?_#\-'"+<>()\[\]:=,.;/&\\{}%\n]""" orders_result = re.sub(regex.encode('utf-8'), b'', orders_result) """ Test code getter_data = "p=123qwfpgjluy_098&mode=posts&topic=3222&till=1280571856&from=1278780343" orders_result = urllib.request.urlopen(common.data['getter_url'], getter_data).read().strip() orders_result = orders_result.decode('utf-8') print(orders_result) """ orders_result = convert_donwloaded_orders(orders_result) # Delete it first, just incase query = """DELETE FROM post_cache WHERE topic = %d AND turn = %d""" % (topic_id, turn_number) try: cursor.execute(query) except Exception as e: print("Query: %s\n" % query) raise Exception("Database error: %s\nQuery: %s" % (str(e.args[0]).replace("\n",""), query)) # Delete order cache too query = """DELETE FROM orders WHERE topic = %d AND turn = %d""" % (topic_id, turn_number) try: cursor.execute(query) except Exception as e: print("Query: %s\n" % query) raise Exception("Database error: %s\nQuery: %s" % (str(e.args[0]).replace("\n",""), query)) # Save it to the database query = """INSERT INTO post_cache (topic, turn, content) values (%d, %d, '%s');""" % (topic_id, turn_number, database.escape(orders_result)) try: cursor.execute(query) except Exception as e: raise Exception("Database error: %s\nQuery: %s" % (str(e.args[0]).replace("\n",""), query)) return orders_result
def new_campaign(name, turn, sides): return """INSERT INTO campaigns (name, turn, sides) values ('%(name)s', %(turn)d, %(sides)d);""" % { "name": database.escape(name), "turn": int(turn), "sides": int(sides), }
def whois_func(args,u413): args=args.split(' ')[0] if len(args)==0: u413.cmds["WHO"].callback('',u413) else: u=db.query("SELECT * FROM users WHERE UCASE(username)='%s';"%db.escape(args.upper())) if len(u)==0: u413.type('"%s" is not a u413 member.'%util.htmlify(args.upper())) else: u=u[0] s=db.query("SELECT user FROM sessions WHERE user='******';"%db.escape(u["id"])) if len(s)==0: s=False else: s=True u413.donttype('Username: '******'User ID: '+u["id"]) u413.donttype('User access: '+user.userlvl(int(u["access"]))+' ('+u["access"]+')') u413.donttype('Logged in: '+str(s))
def approve(self, team, title, content, turn=-1): if turn < 1: turn = common.current_turn() return ["""INSERT INTO interactive_orders (team, turn, title, content) values ({team}, {turn}, '{title}', '{content}');""".format( team = team, turn = turn, title = title, content = database.escape(content), )]
def get_one_artefact(cursor, the_artefact): if int(the_artefact) > 0: query = "SELECT * FROM artefacts WHERE id = %d LIMIT 1;" % int(the_artefact) else: query = "SELECT * FROM artefacts WHERE name = '%s' LIMIT 1;" % database.escape(the_artefact) try: cursor.execute(query) except Exception as e: raise Exception("Database error: %s\nQuery: %s" % (str(e.args[0]).replace("\n",""), query)) for row in cursor: return artefact.Artefact(row)
def get_one_deity(cursor, the_deity): if type(the_deity) != str and int(the_deity) > 0: query = "SELECT * FROM deity_list WHERE id = {0:d} LIMIT 1;".format(int(the_deity)) else: query = "SELECT * FROM deity_list WHERE name = '{0:s}' LIMIT 1;".format(database.escape(the_deity)) try: cursor.execute(query) except Exception as e: raise Exception("Database error: %s\nQuery: %s" % (str(e.args[0]).replace("\n",""), query)) for row in cursor: return deity.Deity(row)
def get_one_operative(cursor=None, the_op = ''): if type(the_op) == str: query = "SELECT * FROM operatives WHERE name = '{0:s}' LIMIT 1;".format(database.escape(the_op)) else: query = "SELECT * FROM operatives WHERE id = {0:d} LIMIT 1;".format(int(the_op)) try: cursor.execute(query) except Exception as e: raise Exception("Database error: %s\nQuery: %s" % (str(e.args[0]).replace("\n",""), query)) for row in cursor: return operative.Operative(row)
def get_one_team(cursor, the_team): if int(the_team) > 0: query = "SELECT * FROM teams WHERE id = {0:d} LIMIT 1;".format(int(the_team)) else: query = "SELECT * FROM teams WHERE name = '{0:s}' LIMIT 1;".format(database.escape(the_team)) try: cursor.execute(query) except Exception as e: raise Exception("Database error: %s\nQuery: %s" % (str(e.args[0]).replace("\n",""), query)) for row in cursor: return team.Team(row)
def get_one_spell(cursor, the_spell): if type(the_spell) == int: query = "SELECT * FROM spell_list WHERE id = {0:d} LIMIT 1;".format(int(the_spell)) else: query = "SELECT * FROM spell_list WHERE name = '{0:s}' LIMIT 1;".format(database.escape(the_spell)) try: cursor.execute(query) except Exception as e: raise Exception("Database error: %s\nQuery: %s" % (str(e.args[0]).replace("\n",""), query)) for row in cursor: return spell.Spell(row)
def new_army(name, team, x, y, garrison=0): query = """INSERT INTO armies (name, team, x, y, garrison) values ('%(name)s', %(team)d, %(x)s, %(y)s, %(city_id)d)""" % { "name": database.escape(name), "team": int(team), "city_id": int(garrison), "x": int(x), "y": int(y), } return query
def login(self,username,password): password=sha256(password) r=db.query("SELECT * FROM users WHERE LCASE(username)='%s' AND password='******';"%(db.escape(util.htmlify(username.lower())),password)) if len(r)==0: return False r=r[0] self.name=r["username"] self.level=int(r["access"]) self.userid=int(r["id"]) self.mute=bool(ord(r["muted"])) db.query("UPDATE sessions SET username='******',user=%i,access=%i WHERE id='%s';"%(self.name,self.userid,self.level,self.session)) return True
def log_query(cursor, query_data, subject="No subject"): query = """INSERT INTO queries (query_data, time, turn, subject) values ('%(data)s', %(time)s, %(turn)s, %(subject)s);""" % { "data": database.escape(query_data), "time": int(time.time()), "turn": common.current_turn(), "subject": queries.subjects.index(subject), } try: cursor.execute(query) except Exception as e: raise Exception("Database error: %s\nQuery: %s" % (str(e.args[0]).replace("\n",""), query))
def insert_stat(cursor, the_stat): values = ["'%s'" % database.escape(str(the_stat.__dict__[s])) for s in stat.stat_tuple] query = """INSERT INTO team_stats (team, turn, {fields}) values ({team}, {turn}, {field_values})""".format( team=the_stat.team, turn=the_stat.turn, fields=",".join(stat.stat_tuple), field_values=",".join(values) ) try: cursor.execute(query) except Exception as e: raise Exception("Database error: %s\nQuery: %s" % (str(e.args[0]).replace("\n", ""), query))
def new_battle(name, campaign, start, duration, x, y, btype, city=0): return """INSERT INTO battles (campaign, name, start, duration, x, y, type, city) values ({c}, '{n}', {s}, {d}, {x}, {y}, {btype}, {city});""".format( c = campaign, n = database.escape(name), s = start, d = duration, x = x, y = y, btype = btype, city = city, )
def new_log(tags, content, cost, player = -1, team = -1, turn = -1): from pages import common if type(cost) != str: cost = str(cost) if turn < 0: turn = common.current_turn() query = """INSERT INTO logs (tags, content, cost, player, team, turn) values ('{tags}', '{content}', '{cost}', {player}, {team}, {turn})""".format( tags = database.escape(tags), content = database.escape(content), cost = database.escape(cost), player = player, team = team, turn = turn, ) return query
def get_one_battle(cursor, the_battle): if type(the_battle) == str: query = "SELECT * FROM battles WHERE name = '{0:s}' ORDER BY id DESC LIMIT 1;".format( database.escape(the_battle) ) else: query = "SELECT * FROM battles WHERE id = {0:d} LIMIT 1;".format(int(the_battle)) try: cursor.execute(query) except Exception as e: raise Exception("Database error: %s\nQuery: %s" % (str(e.args[0]).replace("\n", ""), query)) for row in cursor: return battle.Battle(row)
def new_operative(city, team, arrival, size, stealth, observation, integration, sedition, sabotage, assassination, name=""): if name == "": name = "".join([chars[randint(0,9)] for c in range(0, 6)]) if team < 100: name = "00%s%s" % (str(team)[0:2], name) elif team < 1000: name = "0%s%s" % (str(team)[0:3], name) else: name = "%s%s" % (str(team)[0:4], name) return """INSERT INTO operatives (name, city, team, arrival, size, stealth, observation, integration, sedition, sabotage, assassination) values ('%s', %d, %d, %d, %d, %d, %d, %d, %d, %d, %d);""" % (database.escape(name), city, team, arrival, size, stealth, observation, integration, sedition, sabotage, assassination)
def whois_func(args, u413): args = args.split(' ')[0] if len(args) == 0: u413.cmds["WHO"].callback('', u413) else: u = db.query("SELECT * FROM users WHERE UCASE(username)='%s';" % db.escape(args.upper())) if len(u) == 0: u413.type('"%s" is not a u413 member.' % util.htmlify(args.upper())) else: u = u[0] s = db.query("SELECT user FROM sessions WHERE user='******';" % db.escape(u["id"])) if len(s) == 0: s = False else: s = True u413.donttype('Username: '******'User ID: ' + u["id"]) u413.donttype('User access: ' + user.userlvl(int(u["access"])) + ' (' + u["access"] + ')') u413.donttype('Logged in: ' + str(s))
def main(cursor): table_name = common.get_val("table", "") field_name = common.get_val("field", "") new_value = common.get_val("value", "").strip() where = common.get_val("where", "") new_value_db = new_value try: if new_value_db != float(new_value_db) and new_value_db != int(new_value_db): new_value_db = "'%s'" % database.escape(new_value_db) except Exception as e: new_value_db = "'%s'" % database.escape(new_value_db) query = """UPDATE %(table)s SET %(field)s = %(value)s WHERE %(where)s;""" % { "table": table_name, "field": field_name, "value": new_value_db, "where": where, } try: cursor.execute(query) except Exception as e: raise Exception("Database error: %s\nQuery: %s" % (str(e.args[0]).replace("\n",""), query)) return new_value
def move_func(args,u413): args=database.escape(args) params=args.split(' ') if args=="" or args==" " or len(params)!=2: u413.type("Invalid Parameters") elif isint(params[0]) and isint(params[1]): rows=database.query("SELECT * FROM posts WHERE topic=TRUE AND id=%i;"%int(params[0])) checkrows=database.query("SELECT * FROM boards WHERE id=%i;"%int(params[1])) if len(rows)==0 or len(checkrows)==0: u413.type("Invalid Parameters") else: database.query("UPDATE posts SET parent=%i WHERE id=%i;"%(int(param[1]),int(param[0]))) else: u413.type("Invalid Parameters")
def new_city(name, team, x, y, port, secret, dead, nomadic, population, slaves): return """INSERT INTO cities (name, team, x, y, port, secret, dead, nomadic, population, slaves, founded) values ('%(name)s', %(team)s, %(x)s, %(y)s, %(port)s, %(secret)s, %(dead)s, %(nomadic)s, %(population)s, %(slaves)s, %(founded)s);""" % { "name": database.escape(name), "team": team, "port": port, "secret": secret, "dead": int(dead), "nomadic": nomadic, "population": population, "slaves": slaves, "x": x, "y": y, "founded": int(common.current_turn()), }
def respond(cli,u413,ashtml=True): cmdarg=cli.split(' ',1) cmd=cmdarg[0].upper() args="" if len(cmdarg)>1: args=cmdarg[1] #update history and cmd if it's not a command that handles sensitive data sensitive=['LOGIN','REGISTER'] if u413.user.cmd not in sensitive and cmd not in sensitive: if args!='': u413.user.history.append(cmd+' '+args) else: u413.user.history.append(cmd) if u413.user.cmd=='': u413.j["Command"]=cmd if cmd in cmds and cmds[cmd].level<=u413.user.level: cmds[cmd].callback(args,u413) else: a=getalias(cli,u413) if a!=None: execalias(cli,a,u413) elif util.isint(cmd): if u413.user.context!='TOPIC' and 'TOPIC' in u413.user.context: cmds["TOPIC"].callback('%i %i'%(int(u413.user.context.split(' ')[1]),int(cmd)),u413) elif u413.user.context!='BOARD' and 'BOARD' in u413.user.context: cmds["BOARD"].callback('%s %i'%(u413.user.context.split(' ')[1],int(cmd)),u413) else: u413.type('"%s" is not a valid command or is not available in the current context.'%cmd) else: u413.type('"%s" is not a valid command or is not available in the current context.'%cmd) else: u413.j["Command"]=u413.user.cmd.upper() if cmd=="CANCEL": #Note: this works because commands must actively request continuation u413.type("Action cancelled.") u413.set_context("") else: cmds[u413.user.cmd.upper()].callback(cli,u413) db.query("UPDATE sessions SET history='%s' WHERE id='%s';"%(db.escape(str(u413.user.history)),u413.user.session)) #change title if user is logged in if u413.user.name!="Guest": u413.set_title("Terminal - "+u413.user.name)
def move_func(args, u413): args = database.escape(args) params = args.split(' ') if args == "" or args == " " or len(params) != 2: u413.type("Invalid Parameters") elif isint(params[0]) and isint(params[1]): rows = database.query( "SELECT * FROM posts WHERE topic=TRUE AND id=%i;" % int(params[0])) checkrows = database.query("SELECT * FROM boards WHERE id=%i;" % int(params[1])) if len(rows) == 0 or len(checkrows) == 0: u413.type("Invalid Parameters") else: database.query("UPDATE posts SET parent=%i WHERE id=%i;" % (int(params[1]), int(params[0]))) u413.type("Moved topic " + params[0] + " to board " + params[1]) else: u413.type("Invalid Parameters")
def nsfwall_func(args,u413): r=db.query("SELECT * FROM nsfwall ORDER BY posted;") if args.strip()=='': if len(r)==0: u413.type("There are no notes on the nsfwall.") else: u413.type("The wall for all your NSFW needs.") out='<br/><table style="padding-right:8px;">' for entry in r: u=db.query("SELECT username FROM users WHERE id=%i"%int(entry["user"])) out+='<tr><td>{%s}</td><td style="padding-left:1em;">%s <span class="dim">%s</span></td></tr>'%(u[0]["username"],bbcodify(entry["text"]),util.ago(entry["posted"])) u413.donttype(out+'</table>') u413.set_context("NSFWALL") u413.clear_screen() else: if len(r)>=256: db.query("DELETE FROM nsfwall ORDER BY posted LIMIT 1;") db.query("INSERT INTO nsfwall(user,text) VALUES(%i,'%s');"%(u413.user.userid,db.escape(util.htmlify(args)))) nsfwall_func('',u413)
def __init__(self,session=None): if session==None: self.guest_login() else: r=db.query("SELECT * FROM sessions WHERE id='%s';"%db.escape(session)) if len(r)==0: self.guest_login() return r=r[0] self.session=session self.userid=int(r["user"]) self.name=r["username"] self.level=int(r["access"]) self.expire=str(r["expire"]) self.context=r["context"] self.history=eval(r["history"]) self.cmd=r["cmd"] self.cmddata=eval(r["cmddata"]) user=db.query("SELECT muted,alias FROM users WHERE id=%i;"%self.userid)[0] self.mute=bool(ord(user["muted"])) self.alias=eval(user["alias"])
def wall_func(args, u413): r = db.query("SELECT * FROM wall ORDER BY posted;") if args.strip() == '': if len(r) == 0: u413.type("There are no notes on the wall.") else: u413.type("Welcome to the wall!") out = '<br/><table style="padding-right:8px;">' for entry in r: u = db.query("SELECT username FROM users WHERE id=%i" % int(entry["user"])) out += '<tr><td>{{<span class="transmit" data-transmit="WHOIS {0}">{0}</span>}}</td><td style="padding-left:1em;">{1} <span class="dim">{2}</span></td></tr>'.format( u[0]["username"], bbcodify(entry["text"]), util.ago(entry["posted"])) u413.donttype(out + '</table>') u413.set_context("WALL") u413.clear_screen() else: if len(r) >= 256: db.query("DELETE FROM wall ORDER BY posted LIMIT 1;") db.query("INSERT INTO wall(user,text) VALUES(%i,'%s');" % (u413.user.userid, db.escape(util.htmlify(args)))) wall_func('', u413)
def is_taken(u): r = db.query("SELECT * FROM users WHERE LCASE(username)='%s';" % db.escape(u.lower())) return len(r) != 0
def index(req): import user import command cli = req.form.get("cli", None) if cli != None: cli = cli.value session = req.form.get("session", None) if session != None: session = session.value #no session if session == None: jar = Cookie.get_cookies(req) if "session" in jar: session = jar.get("session", None) if session != None: session = session.value currentuser = user.User(session) if cli == None: cli = "LOGIN" else: currentuser = user.User() if cli == None: cli = "INITIALIZE" else: currentuser = user.User(session) if cli == None: cli = "LOGIN" cmdarg = cli.split(' ', 1) cmd = cmdarg[0] args = "" if len(cmdarg) > 1: args = cmdarg[1] callback = req.form.get("callback", None) class u413(object): def __init__(self, u): self.j = { "Command": "", "ContextText": u.context, "CurrentUser": u.name, "EditText": None, "SessionId": u.session, "TerminalTitle": "Terminal - " + u.name, "ClearScreen": False, "Exit": False, "PasswordField": False, "ScrollToBottom": True, "DisplayItems": [], "Notification": None } self.cmds = command.cmds self.user = u self.cont = False self.cookies = [] self.cmddata = u.cmddata self.mute = u.mute def type(self, text, mute=None): if mute == None: mute = self.mute self.j["DisplayItems"].append({ "Text": text, "DontType": False, "Mute": mute }) def donttype(self, text, mute=None): if mute == None: mute = self.mute self.j["DisplayItems"].append({ "Text": text, "DontType": True, "Mute": mute }) def set_context(self, context): self.j["ContextText"] = context self.user.context = context def set_title(self, title): self.j["TerminalTitle"] = title def edit_text(self, text): self.j["EditText"] = text def clear_screen(self): self.j["ClearScreen"] = True def scroll_down(self): self.j["ScrollToBottom"] = True def use_password(self): self.j["PasswordField"] = True def continue_cmd(self): self.cont = True self.user.cmd = self.j["Command"] def set_cookie(self, cookie, value): self.cookies.append({"name": cookie, "value": value}) def exit(self): self.j["Exit"] = True def notify(self, notification): self.j["Notification"] = notification def exec_js(self, start, cleanup=''): out = '' if cleanup != '': out += '<div id="mark"></div>' out += '<script type="text/javascript">' + start if cleanup != '': out += '$("#mark").data("cleanup",function(){%s});' % cleanup out += '</script>' self.donttype(out) u = u413(currentuser) try: import database as db import time import initialize import echo import ping import login import logout import register import who import desu import clear import boards import wall import nsfwall import history import whois import users import mute import alias import topic import reply import newtopic import board import edit import delete import move import first import last import prev import next import refresh import help import messages import message import newmessage import chat import sql import pi import pirates import b import turkey import cosmos import do import rude command.respond(cli, u) if u.cont: u.j["Command"] = currentuser.cmd if currentuser.cmd != '': cmd = currentuser.cmd db.query( "UPDATE sessions SET expire=DATE_ADD(NOW(),INTERVAL 6 HOUR),cmd='%s',cmddata='%s',context='%s' WHERE id='%s';" % (cmd, db.escape(repr( u.cmddata)), currentuser.context, currentuser.session)) else: db.query( "UPDATE sessions SET expire=DATE_ADD(NOW(),INTERVAL 6 HOUR),cmd='',cmddata='{}',context='%s' WHERE id='%s';" % (currentuser.context, currentuser.session)) if callback == None: req.content_type = 'application/json' else: req.content_type = 'application/javascript' for cookie in u.cookies: Cookie.add_cookie(req, Cookie.Cookie(cookie["name"], cookie["value"])) session = Cookie.Cookie('session', currentuser.session) session.expires = time.time() + 6 * 60 * 60 Cookie.add_cookie(req, session) msgs = int( db.query( "SELECT COUNT(*) FROM messages WHERE receiver=%i AND seen=FALSE;" % currentuser.userid)[0]["COUNT(*)"]) if msgs > 0: u.notify("You have %i new messages in your inbox." % msgs) if callback == None: return json.dumps(u.j) else: return callback + '(' + json.dumps(u.j) + ')' except Exception as e: import traceback u.donttype('<span class="error">' + traceback.format_exc().replace( '&', '&').replace('<', '<').replace('>', '>').replace( '\n', '<br/>').replace(' ' * 4, '<span class="tab"></tab>') + '</span>') req.content_type = "application/json" session = Cookie.Cookie('session', currentuser.session) session.expires = time.time() + 6 * 60 * 60 if callback == None: return json.dumps(u.j) else: return callback + '(' + json.dumps(u.j) + ')'
def reply_func(args, u413): #already used REPLY if "step" in u413.cmddata: if args.strip() == '': u413.type("Action cancelled.") u413.set_context("") #ID> elif u413.cmddata["step"] == 1: if util.isint(args): u413.cmddata["step"] = 2 u413.cmddata["topic"] = int(args) u413.type("Enter your reply:") u413.set_context("REPLY") u413.continue_cmd() else: u413.type("Invalid topic ID.") u413.set_context("") #REPLY> elif u413.cmddata["step"] == 2: db.query( "INSERT INTO posts (topic,title,parent,owner,editor,post,locked,edited,posted) VALUES(FALSE,'',%i,%i,0,'%s',FALSE,NULL,NOW());" % (u413.cmddata["topic"], u413.user.userid, db.escape(util.htmlify(args)))) reload_topic(u413.cmddata["topic"], u413.cmddata["page"], u413) #first use of REPLY else: params = args.split(' ', 1) context = u413.user.context.split(' ') #REPLY if args.strip() == '': if "TOPIC" in u413.user.context: u413.cmddata["step"] = 2 u413.cmddata["topic"] = int(u413.user.context.split(' ')[1]) u413.type("Enter your reply:") u413.set_context("REPLY") u413.continue_cmd() else: u413.cmddata["step"] = 1 u413.type("Enter the topic ID:") u413.set_context("TOPIC ID") u413.continue_cmd() #REPLY [id] elif len(params) == 1: if util.isint(params[0]): u413.cmddata["step"] = 2 u413.cmddata["topic"] = int(params[0]) u413.type("Enter your reply:") u413.continue_cmd() elif "TOPIC" in u413.user.context: topic = int(u413.user.context.split(' ')[1]) db.query( "INSERT INTO posts (topic,title,parent,owner,editor,post,locked,edited,posted) VALUES(FALSE,'',%i,%i,0,'%s',FALSE,NULL,NOW());" % (topic, u413.user.userid, db.escape(util.htmlify(args)))) page = 1 if len(context) > 2: page = int(context[2]) reload_topic(int(context[1]), page, u413) else: u413.type("Invalid topic ID.") #REPLY [[id] message] else: if util.isint(params[0]): if len(params) == 2: db.query( "INSERT INTO posts (topic,title,parent,owner,editor,post,locked,edited,posted) VALUES(FALSE,'',%i,%i,0,'%s',FALSE,NULL,NOW());" % (int(params[0]), u413.user.userid, db.escape(util.htmlify(params[1])))) page = 1 if len(context) > 2: page = int(context[2]) u413.type("Reply added successfully.") else: u413.cmddata["step"] = 2 u413.cmddata["topic"] = int(params[0]) u413.type("Enter your reply:") u413.set_context("REPLY") u413.continue_cmd() elif "TOPIC" in u413.user.context: topic = int(u413.user.context.split(' ')[1]) db.query( "INSERT INTO posts (topic,title,parent,owner,editor,post,locked,edited,posted) VALUES(FALSE,'',%i,%i,0,'%s',FALSE,NULL,NOW());" % (topic, u413.user.userid, db.escape(util.htmlify(args)))) page = 1 if len(context) > 2: page = int(context[2]) reload_topic(topic, page, u413) else: u413.type("Topic ID required.") u413.cmddata["page"] = 1 if len(context) > 2: u413.cmddata["page"] = int(context[2])
def alias_func(args, u413): if "step" in u413.cmddata: if u413.cmddata["step"] == 1: u413.cmddata["step"] = 2 u413.cmddata["to"] = args u413.type("Enter the pattern to be replaced:") u413.set_context("FROM") u413.continue_cmd() elif u413.cmddata["step"] == 2: u413.user.alias.append({"to": u413.cmddata["to"], "from": args}) db.query("UPDATE users SET alias='%s' WHERE id=%i;" % (db.escape(repr(u413.user.alias)), u413.user.userid)) u413.type("Alias created successfully.") u413.set_context(u413.cmddata["context"]) elif u413.cmddata["step"] == 3: x = None for a in range(len(u413.user.alias)): if args.upper() == u413.user.alias[a]["from"].upper(): x = a if x == None: u413.type('"%s" is not an alias.' % args) else: del u413.user.alias[x] db.query("UPDATE users SET alias='%s' WHERE id=%i;" % (db.escape(repr(u413.user.alias)), u413.user.userid)) u413.type("Alias deleted.") u413.set_context(u413.cmddata["context"]) else: params = args.split(' ', 1) #ALIAS if len(args.split(' ', 1)[0]) == 0: aliases = eval( db.query("SELECT alias FROM users WHERE id=%i;" % u413.user.userid)[0]["alias"]) if len(aliases) == 0: u413.type("You have no aliases.") else: u413.type("Your aliases:") out = '<table>' for alias in aliases: out += '<tr><td style="width:2em;"></td><td>%s -> %s</td></tr>' % ( util.htmlify(alias["from"]), util.htmlify(alias["to"])) u413.donttype(out + '</table>') #ALIAS to | --delete | --new elif len(params) == 1: if params[0].upper() == "--DELETE": u413.cmddata["step"] = 3 u413.cmddata["context"] = u413.user.context u413.type("Enter the pattern to be deleted:") u413.set_context("PATTERN") u413.continue_cmd() elif params[0].upper() == "--NEW": u413.cmddata["step"] = 1 u413.cmddata["context"] = u413.user.context u413.type("Enter the command to alias:") u413.set_context("TO") u413.continue_cmd() else: u413.cmddata["step"] = 2 u413.cmddata["context"] = u413.user.context u413.cmddata["to"] = params[0] u413.type("Enter the pattern to be replaced:") u413.set_context("FROM") u413.continue_cmd() #ALIAS to from | --delete from else: if params[0].upper() == "--DELETE": x = None for a in range(len(u413.user.alias)): if params[1].upper() == u413.user.alias[a]["from"].upper(): x = a if x == None: u413.type('"%s" is not an alias.' % params[1]) else: del u413.user.alias[x] db.query( "UPDATE users SET alias='%s' WHERE id=%i;" % (db.escape(repr(u413.user.alias)), u413.user.userid)) u413.type("Alias deleted.") else: u413.user.alias.append({"to": params[0], "from": params[1]}) db.query("UPDATE users SET alias='%s' WHERE id=%i;" % (db.escape(repr(u413.user.alias)), u413.user.userid)) u413.type("Alias created successfully.")
def newtopic_func(args, u413): params = args.split(' ', 1) #continued NEWTOPIC if "step" in u413.cmddata: if args == '': u413.type("Action cancelled.") u413.set_context("") return #BOARD> if u413.cmddata["step"] == 1: if isint(args) and int(params[0]) != 0: u413.cmddata["step"] = 2 u413.cmddata["board"] = args u413.type("Enter the topic's title:") u413.set_context("TITLE") u413.continue_cmd() else: u413.type('Invalid board ID.') u413.set_context("") #TITLE> elif u413.cmddata["step"] == 2: u413.cmddata["step"] = 3 u413.cmddata["title"] = args u413.type("Enter the topic's body:") u413.set_context("BODY") u413.continue_cmd() #BODY> elif u413.cmddata["step"] == 3: db.query( "INSERT INTO posts (topic,title,parent,owner,editor,post,locked,edited,posted) VALUES(TRUE,'%s',%i,%i,0,'%s',FALSE,NULL,NOW());" % (db.escape(u413.cmddata["title"]), int(u413.cmddata["board"]), u413.user.userid, db.escape(util.htmlify(args)))) topic = int( db.query("SELECT id FROM posts ORDER BY id DESC LIMIT 1;")[0] ["id"]) u413.type("Topic %i was created successfully." % topic) u413.set_context("") #first use else: #NEWTOPIC if args.strip() == '': if "BOARD" in u413.user.context: u413.cmddata["step"] = 2 u413.cmddata["board"] = int(u413.user.context[6:]) u413.type("Enter the topic's title:") u413.set_context("TITLE") else: u413.cmddata["step"] = 1 u413.type("Enter the board ID:") u413.set_context("BOARD") u413.continue_cmd() #NEWTOPIC board elif len(params) == 1: if isint(params[0]) and int(params[0]) != 0: u413.cmddata["step"] = 2 u413.cmddata["board"] = int(params[0]) u413.type("Enter the topic's title:") u413.set_context("TITLE") u413.continue_cmd() else: u413.type('Invalid board ID') #NEWTOPIC board topic else: if isint(params[0]) and int(params[0]) != 0: u413.cmddata["step"] = 3 u413.cmddata["board"] = int(params[0]) u413.cmddata["topic"] = params[1] u413.type("Enter the topic's body:") u413.set_context("BODY") u413.continue_cmd() else: u413.donttype('<span class="error">Invalid board ID</span>')
def edit_func(args, u413): #EDIT already requested continuation if "step" in u413.cmddata: #ID> if u413.cmddata["step"] == 1: u413.donttype('"' + args + '"') if util.isint(args): u413.cmddata["id"] = int(args) u413.cmddata["step"] = 2 u413.set_context("NEW BODY") u413.type("Enter the new post body:") u413.edit_text( util.dehtmlify( db.query("SELECT post FROM posts WHERE id=%i;" % int(args))[0]["post"])) u413.continue_cmd() else: u413.type("Invalid post ID.") u413.set_context("") #NEW BODY> elif u413.cmddata["step"] == 2: post = int( db.query("SELECT owner FROM posts WHERE id=%i;" % u413.cmddata["id"])[0]["owner"]) owner = int( db.query("SELECT access FROM users WHERE id=%i;" % post)[0]["access"]) if post != u413.user.userid: if u413.user.level < user.User.halfmod or u413.user.level <= owner: u413.type( "You do not have permission to edit other user's posts." ) return db.query( "UPDATE posts SET post='%s',editor=%i,edited=NOW() WHERE id=%i;" % (db.escape( util.htmlify(args)), u413.user.userid, u413.cmddata["id"])) u413.type("Post edited successfully.") u413.set_context(u413.cmddata["context"]) #EDIT used for the first time else: params = args.split(' ', 1) #EDIT if len(args) == 0: u413.cmddata["step"] = 1 u413.cmddata["context"] = u413.user.context u413.type("Enter the post's ID:") u413.set_context("Post ID") u413.continue_cmd() #EDIT id elif len(params) == 1: if util.isint(args): u413.cmddata["step"] = 2 u413.cmddata["context"] = u413.user.context u413.cmddata["id"] = int(args) u413.type("Enter the new post body:") u413.set_context("NEW BODY") u413.edit_text( util.dehtmlify( db.query("SELECT post FROM posts WHERE id=%i;" % int(args))[0]["post"])) u413.continue_cmd() else: u413.type("Invalid post ID.") #EDIT id body else: if util.isint(params[0]): post = int( db.query("SELECT owner FROM posts WHERE id=%i;" % int(params[0]))[0]["owner"]) owner = int( db.query("SELECT access FROM users WHERE id=%i;" % post)[0]["access"]) if post != u413.user.userid: if u413.user.level < user.User.halfmod or u413.user.level <= owner: u413.type( "You do not have permission to edit other user's posts." ) return db.query( "UPDATE posts SET post='%s',editor=%i,edited=NOW() WHERE id=%i;" % (db.escape(util.htmlify( params[1])), u413.user.userid, int(params[0]))) u413.type("Post edited successfully.") u413.set_context("") else: u413.type("Invalid post ID.")
def register_func(args, u413): #check for special cases if u413.user.name != "Guest": u413.type("You need to be logged out to register.") return params = args.split() #REGISTER has already requested continuation if "step" in u413.cmddata: if args == "": u413.type("Action cancelled.") u413.set_context("") return #Note: For all, ignore extra arguments #USERNAME> if u413.cmddata["step"] == 1: if is_taken(params[0]): u413.type("Username already in use.") u413.set_context("") else: u413.cmddata["username"] = params[0] u413.cmddata["step"] = 2 u413.type("Enter a password:"******"PASSWORD") u413.continue_cmd() u413.use_password() #PASSWORD> elif u413.cmddata["step"] == 2: if is_stupid(u413.cmddata["username"], params[0]): u413.type("That's a stupid password. Pick another one.") else: u413.cmddata["password"] = params[0] u413.cmddata["step"] = 3 u413.type("Confirm your password:"******"CONFIRM PASSWORD") u413.continue_cmd() u413.use_password() #CONFIRM PASSWORD> elif u413.cmddata["step"] == 3: if u413.cmddata["password"] == params[0]: if is_taken(u413.cmddata["username"]): u413.type("Username already in use.") else: db.query( "INSERT INTO users(username,password,access,alias) VALUES('%s','%s',%i,'[]');" % (db.escape( util.htmlify( util.stripctrl(u413.cmddata["username"]))), user.sha256(params[0]), user.User.member)) u413.type("You are now registered.") else: u413.type("The passwords do not match.") u413.set_context("") #initial use of command else: #REGISTER if len(args) == 0: u413.cmddata["step"] = 1 u413.type("Enter your desired username:"******"USERNAME") u413.continue_cmd() #REGISTER username elif len(params) == 1: if is_taken(params[0]): u413.type("Username already in use.") else: u413.cmddata["username"] = params[0] u413.cmddata["step"] = 2 u413.type("Enter a password:"******"PASSWORD") u413.use_password() u413.continue_cmd() #REGISTER username password #Note: ignore anything after username/password else: if is_taken(params[0]): u413.type("Username already in use.") elif is_stupid(params[0], params[1]): u413.cmddata["username"] = params[0] u413.cmddata["step"] = 2 u413.type("That's a stupid password. Pick another one.") u413.continue_cmd() u413.use_password() else: u413.cmddata["username"] = params[0] if is_taken(u413.cmddata["username"]): u413.type("Username already in use.") else: u413.cmddata["password"] = params[1] u413.cmddata["step"] = 3 u413.type("Confirm your password:"******"CONFIRM PASSWORD") u413.continue_cmd() u413.use_password()