def output( ):

	user = request.player
	try:
		id = getSingleField( 'id', request, getSingleFieldPOST('id', request )  )
		lad = db.GetLadder( id )
		if not db.AccessCheck( id, request.player.nick, Roles.GlobalAdmin ):
			template = env.get_template('error.html')
			return template.render( err_msg="you're not allowed to delete ladder #%s"%(str(id)) )
		ask = True
		if getSingleField( 'confirm', request  ) == 'yes':
			session = db.session()
			#figure out proper delete cascade instead
			SYNC_STRAT = 'fetch'
			session.query( Result ).filter( Result.ladder_id == id ).delete(synchronize_session=SYNC_STRAT)
			session.query( Option ).filter( Option.ladder_id == id ).delete(synchronize_session=SYNC_STRAT)
			session.query( Bans ).filter( Bans.ladder_id == id ).delete(synchronize_session=SYNC_STRAT)
			session.query( GlickoRanks ).filter( GlickoRanks.ladder_id == id ).delete(synchronize_session=SYNC_STRAT)
			session.query( SimpleRanks ).filter( SimpleRanks.ladder_id == id ).delete(synchronize_session=SYNC_STRAT)
			session.query( TrueskillRanks ).filter( TrueskillRanks.ladder_id == id ).delete(synchronize_session=SYNC_STRAT)
			matches = session.query( Match.id ).filter( Match.ladder_id == id )
			session.query( MatchSetting ).filter( MatchSetting.match_id.in_(matches) ).delete(synchronize_session=SYNC_STRAT)
			matches.delete()
			session.delete( lad )
			session.commit()
			session.close()
			ask = False
		template = env.get_template('deleteladder.html')
		return template.render( ladder=lad, ask=ask )

	except ElementNotFoundException, e:
		err = str(e)
Exemple #2
0
def output():
	try:
		s = db.session()
		limit = 10
		matches_header = 'Recent Matches'
		matches = s.query( Match ).order_by(Match.date.desc())[:limit]

		players_header = 'Active Players'
		player_ids = s.query( func.count( Result.player_id ), Result.player_id ).group_by( Result.player_id ).order_by( func.count(Result.player_id).desc() )[:limit]
		players = []
		for (count,pid) in player_ids:
			players.append( (s.query( Player ).filter( Player.id == pid ).one(), count ) )

		ladders_header = 'Active Ladders'
		ladder_ids = s.query( func.count( Match.ladder_id ), Match.ladder_id ).group_by( Match.ladder_id ).order_by( func.count(Match.ladder_id).desc() ).all()
		ladders = []
		for (count,lid) in ladder_ids:
			q = s.query( Ladder ).filter( Ladder.id == lid )
			if q.first():
				ladders.append( ( q.first(), count ) )


		template = env.get_template('index.html')
		ret = template.render( matches=matches, matches_header= matches_header, ladders_header=ladders_header, ladders=ladders, players_header=players_header, players=players  )
		s.close()
		return ret
		
	except Exception, m:
		if s:
			s.close()
		template = env.get_template('error.html')
		return template.render( err_msg=(str(m)) )
Exemple #3
0
def output( ):

	user = request.player
	try:
		session = db.sessionmaker()
		id = getSingleField( 'id', request )
		mid = getSingleField( 'mid', request )
		if mid:
			if not db.AccessCheck( id, request.player.nick, Roles.LadderAdmin ):
				template = env.get_template('error.html')
				return template.render( err_msg="you're not allowed to delete match #%s"%(str(mid)) )
			lid = getSingleField( 'lid', request )
			db.DeleteMatch( lid, mid )
		if id:
			if db.AccessCheck( id, user.nick, Roles.LadderAdmin ):
				ladder_ids = [id]
			else:
				ladder_ids = []
		else:
			if user.role < Roles.GlobalAdmin:
				ladder_ids = session.query( Option.ladder_id ).filter( Option.key == Option.adminkey ) \
					.filter( Option.value == user.nick ).group_by( Option.ladder_id )
			else:
				ladder_ids = session.query( Ladder.id )
			
		matches = session.query( Match ).filter( Match.ladder_id.in_ ( ladder_ids ) )\
					.order_by( Match.ladder_id ).order_by( Match.date.desc() ).all()
		template = env.get_template('adminmatch.html')
		return template.render( matches=matches, lid=id )

	except ElementNotFoundException, e:
		err = str(e)
Exemple #4
0
def output( ):
	try:
		template = env.get_template('help.html')
		return template.render(\
			ladder_admin_commands=tokenizeHelp(helpstrings.helpstring_ladder_admin_manager),\
			global_admin_commands=tokenizeHelp(helpstrings.helpstring_global_admin_manager),\
			user_commands=tokenizeHelp(helpstrings.helpstring_user_manager),\
			battleroom_commands=tokenizeHelp(helpstrings.helpstring_user_slave) )

	except Exception, m:
		template = env.get_template('error.html')
		return template.render( err_msg=(str(m)) )
Exemple #5
0
def output( ):
	id = getSingleField( 'id', request )

	try:
		ladder = db.GetLadder( id )
		template = env.get_template('viewrules.html')
		opts = db.GetOptions( id )
		options = LadderOptionsAdapter( opts , ladder )
		return template.render(ladder=ladder, laddertable=LadderInfoToTableAdapter(ladder), options=options )

	except ElementNotFoundException, e:
		template = env.get_template('error.html')
		return template.render( err_msg="ladder with id %s not found"%(str(id)) )
Exemple #6
0
def output( ):
	player_name = getSingleField( 'player', request )
	order = getSingleField( 'order', request , 'nick')
	ladder_id = getSingleField( 'ladder', request )
	try:
		s = db.sessionmaker()
		if player_name:
			player = db.GetPlayer( player_name )
			ladders = db.GetLadderByPlayer( player.id )
			played = dict()
			positions = dict()
			for ladder in ladders:
				positions[ladder.id] = db.GetPlayerPosition( ladder.id, player.id )
				played[ladder.id] = s.query( Result.id ).filter( Result.ladder_id == ladder.id ).filter( Result.player_id == player.id ).count()

			results = s.query( Result ).filter( Result.player_id == player.id).order_by(Result.date.desc())[0:5]
			matches = []
			for r in results:
				matches.append( r.match )

			template = env.get_template('viewplayer.html')
			s.close()
			return template.render(player=player,ladders=ladders, positions=positions,played=played,matches=matches )
		else:
			asc = getSingleField( 'asc', request, 'False' )
			if not asc:
				asc = 'False'
			q = s.query( Player, func.count(Result.id).label('played')).outerjoin( (Result, Result.player_id == Player.id ) )\
				.filter( Player.id.in_(s.query( Result.player_id ).filter( Player.id == Result.player_id  ) ) ) \
				.filter( Result.player_id == Player.id ).group_by( Player.id )
			if ladder_id:
				q = q.filter( Player.id.in_( s.query( Result.player_id ).filter( Result.ladder_id == ladder_id ) ) )
			if order == 'nick':
				q = q.order_by( SortAsc( Player.nick, asc ) )
			elif order == 'id' :
				q = q.order_by( SortAsc( Player.id, asc ) )
			else:
				order = 'played'
				q = q.order_by( SortAsc( func.count(Result.id), asc ) )

			limit = int(getSingleField( 'limit', request, q.count() ))
			offset = int(getSingleField( 'offset', request, 0 ))
			players = q[offset:offset+limit-1]
			template = env.get_template('viewplayerlist.html')
			s.close()
			return template.render(players=players,offset=offset,limit=limit,order=order,asc=asc )

	except ElementNotFoundException, e:
		err_msg="player %s not found"%(str(player_name))
Exemple #7
0
def output( ):
	try:
		s = db.session()
		stats = dict()
		stats['playercount'] = s.query(Player.id).count()
		matches = s.query(Match)
		stats['matchcount'] = matches.count()
		#stats['totalduration'] = s.query(func.sum(Match.duration).label('sum'))['sum']
		#kk = s.query(Match.duration).all()
		#print kk
		def _total_seconds(timedelta):
			if not hasattr(datetime.timedelta, 'total_seconds'):
				return timedelta.days * 86400.0 + timedelta.seconds + timedelta.microseconds * 1e-6
			return timedelta.total_seconds()
		stats['totalduration'] = sum([f[0] for f in s.query(Match.duration).all()], datetime.timedelta())
		stats['avgduration'] = str(datetime.timedelta(seconds=_total_seconds(stats['totalduration']) / float(stats['matchcount'])))
		stats['totalduration'] = str(stats['totalduration'] )
		stats['mostplayedmap'] = s.query(Match.mapname,func.count(Match.mapname).label('count')).group_by(Match.mapname).order_by('count DESC').first()
		stats['mostplayedgame'] = s.query(Match.modname,func.count(Match.modname).label('count')).group_by(Match.modname).order_by('count DESC').first()
		#stats['avgplayercount'] = func.avg(Match.
		print stats

		s.close()
		template = env.get_template('stats.html')
		return template.render(stats=stats)
		
	except ElementNotFoundException, e:
		err_msg="ladder with id %s not found"%(str(id))
Exemple #8
0
	def get_rss_out(l_id):
		s = None
		try:
			base_url = config.get('ladder','base_url')
			s = db.session()			
			lad = db.GetLadder( ladder_id )
			rank_table = GlobalRankingAlgoSelector.GetWebRepresentation( db.GetRanks( ladder_id ), db )
			#template = env.get_template('scoreboard.html')
			template = env.get_template('rss_scoreboard.html')
			desc = template.render( rank_table=rank_table, ladder=lad )
			url = '%sscoreboard?id=%s'%(base_url,ladder_id)
			#$postdate = date("Y-m-d H:i", $row['topic_time']);
			title = "%s -- updated scoreboard"%lad.name
			
			item = PyRSS2Gen.RSSItem( title = title, link=url, guid = PyRSS2Gen.Guid( url ), pubDate=datetime.datetime.now(), description = desc )
			rss = PyRSS2Gen.RSS2(
				title = "%s -- Scoreboard"%lad.name,
				link = "%sfeeds/scores/%s"%(base_url,l_id),
				description = "DESCRIPTION",
				lastBuildDate = datetime.datetime.now(),
				items = [item] )
			output = cStringIO.StringIO()
			rss.write_xml(output)
			return output.getvalue()
		
		except Exception, m:
			if 's' in locals() and s:
				s.close()
			return str(m)
Exemple #9
0
def output(  ):
	try:
		limit = 10
		template = env.get_template('fame.html')
		s = db.session()
		player_ids = s.query( Result.player_id ).group_by( Result.player_id )
		ladder_playerpos = dict()
		playerpos = []
		for pid in player_ids:
			pid = pid[0]
			ladders = s.query( Ladder ).filter( Ladder.id.in_( s.query( Result.ladder_id ).filter( Result.player_id == pid ).group_by( Result.ladder_id ) ) )
			score = 0
			l_names = []
			for l in ladders:
				player_per_ladder = s.query( Result.player_id ).filter( Result.ladder_id == l.id ).group_by( Result.player_id ).count()
				pos = db.GetPlayerPosition( l.id, pid )
				score += ( 0.5 - ( pos / float( player_per_ladder ) ) ) * 1000
				l_names.append( '%s (%d)'%(l.name,pos) )
			if ladders.count() > 0:
				playername = s.query( Player.nick ).filter( Player.id == pid ).first()[0]
				playerpos.append( (playername, int(score), ', '.join(l_names) ) )

		playerpos.sort( lambda x, y: cmp(y[1], x[1]) )
		header = ['Name', 'Score', 'Active on (position on ladder)' ]

		leaders = []
		losers = []
		for name, id in s.query( Ladder.name, Ladder.id ):
			try:
				r = db.GetRanks( id )
				if len(r) > 1:
					s.add( r[0] )
					s.add( r[-1] )
					leaders.append( (r[0].player.nick, name, r[-1].player.nick  ) )
			except ElementNotFoundException:
				continue #empty ladder
		losers.sort( lambda x, y: cmp(x[1], y[1]) )
		leaders.sort( lambda x, y: cmp(x[1], y[1]) )
		s.close()
		return template.render( playerpos_top=playerpos[0:limit],playerpos_bottom=playerpos[-limit:], header=header, leaders=leaders,losers=losers )

	except Exception, m:
		if s:
			s.close()
		template = env.get_template('error.html')
		return template.render( err_msg=(str(m)) )
Exemple #10
0
def output( ):
	id = getSingleField( 'id', request )
	player_name = getSingleField( 'player', request )
	ladder_id = getSingleField( 'ladder', request )
	limit = getSingleField( 'limit', request, 18 )
	ret = ''
	try:
		s = db.sessionmaker()
		if player_name and ladder_id:
			ladder = db.GetLadder( ladder_id )
			player = db.GetPlayer( player_name )
			template = env.get_template('viewmatchlist.html')
			header_string = 'Matches for %s on ladder %s'%(player.nick,ladder.name)
			matches = s.query( Match ).filter(Match.ladder_id == ladder_id).order_by(Match.date.desc()).all()
			ret = template.render(matches=matches, header=header_string )
		elif ladder_id:
			ladder = db.GetLadder( ladder_id )
			header_string = 'Matches on ladder %s'%(ladder.name)
			template = env.get_template('viewmatchlist.html')
			matches = s.query( Match ).filter(Match.ladder_id == ladder_id).order_by(Match.date.desc()).all()
			ret = template.render(matches=matches, header=header_string )
		elif player_name:
			player = db.GetPlayer( player_name )
			template = env.get_template('viewmatchlist.html')
			header_string = 'Matches for %s'%(player.nick)
			results = s.query( Result ).filter( Result.player_id == player.id).order_by(Result.date.desc())
			matches = []
			for r in results:
				matches.append( r.match )
			ret = template.render(matches=matches, header=header_string )
		elif not id:
			template = env.get_template('viewmatchgrid.html')
			matches = s.query( Match ).order_by(Match.date.desc())[:limit]
			ret = template.render( matches=matches, limit=limit )
		else:
			match = s.query( Match ).options(eagerload('settings')).filter(Match.id == id ).first()
			template = env.get_template('viewmatch.html')
			opt_headers = ['key','val','wl/bl']
			ret = template.render(ladder=match.ladder, matchinfo=MatchInfoToTableAdapter(match) )
		s.close()
		return ret
		
	except ElementNotFoundException, e:
		err_msg="ladder with id %s not found"%(str(id))
Exemple #11
0
def output( ):
	try:
		id = getSingleField( 'id', request )
		lad = db.GetLadder( id )
		rank_table = GlobalRankingAlgoSelector.GetWebRepresentation( db.GetRanks( id ), db )
		template = env.get_template('scoreboard.html')
		return template.render( rank_table=rank_table, ladder=lad )

	except ElementNotFoundException, e:
		err_msg="ladder with id %s not found"%(str(id))
Exemple #12
0
def get_items(query):
	items = []
	base_url = config.get('ladder', 'base_url')
	for match in query:	
		url = '%s/%s' % (base_url, urllib.quote('match?id=%s'%(match.id)))
		#$postdate = date("Y-m-d H:i", $row['topic_time']);
		title = '%s'%(match.mapname)
		template = env.get_template('rss_match.html')
		desc = template.render(ladder=match.ladder, matchinfo=MatchInfoToTableAdapter(match),base_url=base_url )
		items.append( PyRSS2Gen.RSSItem( title = title, link=url, guid = PyRSS2Gen.Guid( url ), pubDate=match.date, description = desc ) )
	return items
Exemple #13
0
def output( ):

	session = db.session()
	user = request.player
	try:
		id = getSingleField( 'id', request, getSingleFieldPOST('id', request )  )
		if not db.AccessCheck( id, request.player.nick, Roles.LadderAdmin ):
			template = env.get_template('error.html')
			session.close()
			return template.render( err_msg="you're not allowed to edit ladder #%s"%(str(id)) )
		pre = GlobalRankingAlgoSelector.GetWebRepresentation( db.GetRanks( id ), db )
		db.RecalcRankings(id)
		post = GlobalRankingAlgoSelector.GetWebRepresentation( db.GetRanks( id ), db )
		lad = db.GetLadder( id )
		template = env.get_template('recalc.html')
		session.close()
		return template.render( pre=pre, post=post, ladder=lad )

	except ElementNotFoundException, e:
		err = str(e)
Exemple #14
0
def output():

    session = db.sessionmaker()
    user = request.player
    try:
        if getSingleFieldPOST("addladder", request) == "add":
            if user.role >= Roles.GlobalAdmin:
                name = getSingleFieldPOST("laddername", request)
                if name and len(name) > 0 and len(name) <= 100:
                    ladderid = db.AddLadder(name)
                    session.close()
                    return bottle.redirect("/admin/ladder?id=%d" % ladderid)
                else:
                    template = env.get_template("error.html")
                    session.close()
                    return template.render(err_msg="you're not allowed to add a ladder")
            else:
                template = env.get_template("error.html")
                session.close()
                return template.render(err_msg="you're not allowed to add a ladder")
        if user.role < Roles.GlobalAdmin:
            ladder_ids = (
                session.query(Option.ladder_id)
                .filter(Option.key == Option.adminkey)
                .filter(Option.value == user.nick)
                .group_by(Option.ladder_id)
            )
        else:
            ladder_ids = session.query(Ladder.id)
        ladders = session.query(Ladder).filter(Ladder.id.in_(ladder_ids)).all()
        template = env.get_template("adminindex.html")
        session.close()
        if len(ladders) < 1:
            # no admin whatsoever
            return bottle.redirect("/")
        return template.render(ladders=ladders, isglobal=user.role >= Roles.GlobalAdmin)

    except ElementNotFoundException, e:
        template = env.get_template("error.html")
        session.close()
        return template.render(err_msg=str(e))
Exemple #15
0
def output( ):

	user = request.player
	try:
		id = getSingleField( 'id', request, getSingleFieldPOST('id', request )  )
		lad = db.GetLadder( id )
		if not db.AccessCheck( id, request.player.nick, Roles.GlobalAdmin ):
			template = env.get_template('error.html')
			return template.render( err_msg="you're not allowed to delete ladder #%s"%(str(id)) )
		ask = True
		if getSingleField( 'confirm', request  ) == 'yes':
			session = db.sessionmaker()
			session.delete( lad )
			session.commit()
			session.close()
			ask = False
		template = env.get_template('deleteladder.html')
		return template.render( ladder=lad, ask=ask )

	except ElementNotFoundException, e:
		err = str(e)
Exemple #16
0
def output( ):
	limit = int(getSingleField( 'limit', request, 18 ))
	s = db.session()
	template = env.get_template('viewmaplist.html')
	if limit > -1:
		maps = s.query( Map ).all()#order_by(Map.name.desc()).limit(limit).all()
	else:
		maps = s.query( Map ).order_by(Map.name.desc()).all()
	ret = template.render( maps=maps, limit=limit )
	try:

		s.close()
		return ret
		
	except ElementNotFoundException, e:
		err_msg="map with id %s not found"%(str(id))
Exemple #17
0
def output( ):
	id = getSingleField( 'id', request, '-1' )
	try:
		s = db.session()
		if id == '-1':
			print 'LPLP %s'%id
			ladder_list = []
			ladder_triple_list = s.query(Ladder).order_by( Ladder.name )
			if ladder_triple_list.count() < 1:
				raise ElementNotFoundException('djwp')
			#ladder_triple_list = [db.GetLadder( 17 )]
			for  l in ladder_triple_list:
				ladder_id = l.id
				ladder_name = l.name
				ladder_description = l.description
				player_count = s.query( Result.id ).group_by( Result.player_id ).\
					filter(Result.ladder_id == ladder_id).count()
				match_query = s.query( Match.id,Match.date ).\
					filter(Match.ladder_id == ladder_id)
				match_count = match_query.count()
				last_match = match_query.order_by( Match.date.desc() ).first()

				item = dict()
				item['player_count'] = player_count
				item['match_count'] = match_count
				item['last_match'] = last_match
				item['name'] = ladder_name
				item['description'] = ladder_description
				item['id'] = ladder_id
				try:
					ranks = db.GetRanks( ladder_id, None, 3 )
					item['ranks'] = GlobalRankingAlgoSelector.GetWebRepresentation( ranks, db )
				except Exception, e:
					item['ranks'] = None
				ladder_list.append( item )
			template = env.get_template('viewladderlist.html')
			s.close()
			return template.render(ladders=ladder_list )
		else:
Exemple #18
0
		if mid:
			if not db.AccessCheck( id, request.player.nick, Roles.LadderAdmin ):
				template = env.get_template('error.html')
				return template.render( err_msg="you're not allowed to delete match #%s"%(str(mid)) )
			lid = getSingleField( 'lid', request )
			db.DeleteMatch( lid, mid )
		if id:
			if db.AccessCheck( id, user.nick, Roles.LadderAdmin ):
				ladder_ids = [id]
			else:
				ladder_ids = []
		else:
			if user.role < Roles.GlobalAdmin:
				ladder_ids = session.query( Option.ladder_id ).filter( Option.key == Option.adminkey ) \
					.filter( Option.value == user.nick ).group_by( Option.ladder_id )
			else:
				ladder_ids = session.query( Ladder.id )
			
		matches = session.query( Match ).filter( Match.ladder_id.in_ ( ladder_ids ) )\
					.order_by( Match.ladder_id ).order_by( Match.date.desc() ).all()
		template = env.get_template('adminmatch.html')
		return template.render( matches=matches, lid=id )

	except ElementNotFoundException, e:
		err = str(e)

	except Exception, f:
		err = str(f)

	template = env.get_template('error.html')
	return template.render( err_msg=err )
Exemple #19
0
				item['name'] = ladder_name
				item['description'] = ladder_description
				item['id'] = ladder_id
				try:
					ranks = db.GetRanks( ladder_id, None, 3 )
					item['ranks'] = GlobalRankingAlgoSelector.GetWebRepresentation( ranks, db )
				except Exception, e:
					item['ranks'] = None
				ladder_list.append( item )
			template = env.get_template('viewladderlist.html')
			s.close()
			return template.render(ladders=ladder_list )
		else:
			ladder = db.GetLadder( id )
			plot_url = plots.matches_per_ladder( id )
			template = env.get_template('viewladder.html')
			limit = 10
			try:
				ranks = db.GetRanks( id, None, limit )
				rank_table = GlobalRankingAlgoSelector.GetWebRepresentation( ranks, db )
			except:
				rank_table = None
			matches = s.query( Match ).filter( Match.ladder_id == id ).order_by(Match.date.desc())[:limit]
			
			s.close()
			return template.render(ladder=ladder, rank_table=rank_table, matches=matches, plot_url=plot_url )

	except ElementNotFoundException, e:
		err_msg="ladder with id %s not found"%(str(id))

	except EmptyRankingListException, m:
Exemple #20
0
                ladder_ids = []
        else:
            if user.role < Roles.GlobalAdmin:
                ladder_ids = (
                    session.query(Option.ladder_id)
                    .filter(Option.key == Option.adminkey)
                    .filter(Option.value == user.nick)
                    .group_by(Option.ladder_id)
                )
            else:
                ladder_ids = session.query(Ladder.id)

        matches = (
            session.query(Match)
            .filter(Match.ladder_id.in_(ladder_ids))
            .order_by(Match.ladder_id)
            .order_by(Match.date.desc())
            .all()
        )
        template = env.get_template("adminmatch.html")
        return template.render(matches=matches, lid=id)

    except ElementNotFoundException, e:
        err = str(e)

    except Exception, f:
        err = str(f)

    template = env.get_template("error.html")
    return template.render(err_msg=err)
def output():

    id = getSingleField("id", request, getSingleFieldPOST("id", request))
    session = db.session()
    user = request.player
    note = ""
    extrainfo = None
    try:
        if not db.AccessCheck(id, request.player.nick, Roles.LadderAdmin):
            template = env.get_template("error.html")
            session.close()
            return template.render(err_msg="you're not allowed to edit ladder #%s" % (str(id)))
        lad = db.GetLadder(id)
        session.add(lad)
        options = lad.options
        to_delete = getFieldsByPrefixPOST("delete", request)
        if to_delete and len(to_delete) > 0:
            del_key = to_delete.keys()[0]
            if to_delete[del_key] == "delete":
                del_idx = int(del_key.split("-")[-1])
                del_opt = options[del_idx]
                session.delete(del_opt)
                session.commit()
                # redirect to same page here cause i had troubles with double session elements otherwise
                return bottle.redirect("/admin/ladder?id=%s" % id)
        if getSingleFieldPOST("addadmin", request) == "add":
            if not db.AccessCheck(id, request.player.nick, Roles.GlobalAdmin):
                template = env.get_template("error.html")
                session.close()
                return template.render(err_msg="you're not allowed to add an admin to ladder #%s" % (str(id)))
            admin_name = getSingleFieldPOST("adminname", request, "koko")
            db.AddLadderAdmin(id, admin_name)
            session.close()
            return bottle.redirect("/admin/ladder?id=%s" % id)
        if getSingleFieldPOST("new", request) == "add new option":
            opt = Option("", "")
            opt.ladder_id = id
            session.add(opt)
            session.commit()
            session.add(lad)
            options = lad.options
        form = forms.Ladder(request.POST, lad, options=options)
        if getSingleFieldPOST("submit", request) == "submit" and form.validate():
            extrainfo = handleAlgoChange(db, env, request, lad)
            form.populate_obj(lad)
            session.add(lad)
            session.commit()
            note = "Ladder updated"
            # else:#enable this for debug
            # if len(form.errors) > 0:
            # note= form.errors
        textfields = []
        for var in forms.Ladder.field_order:
            textfields.append(getattr(form, var))
        template = env.get_template("change_ladder.html")
        session.close()
        return template.render(
            form=form,
            ladder_id=id,
            note=note,
            textfields=textfields,
            isglobal=user.role >= Roles.GlobalAdmin,
            extrainfo=extrainfo,
        )

    except ElementNotFoundException, e:
        template = env.get_template("error.html")
        session.close()
        return template.render(err_msg=str(e))