Exemplo n.º 1
0
def create(req):
	"""Create a new user in the database."""
	post = req.post()
	if post is not None:
		email = post['email']
		if '/' in email:
			return template(req, 'user-create', msg='Invalid character: emails cannot contain "/"')
		name = post['name'] or None
		if post['password1'] != post['password2']:
			return template(req, 'user-create', msg='Mismatched passwords')
		password = post['password1']
		if not email:
			return template(req, 'user-create', msg='Email required')
		cur = req.db.cursor()
		cur.execute("""
			INSERT INTO users (email, name, password) 
			VALUES (%(email)s, %(name)s, md5(%(password)s))
			""", 
			{'email': email, 'name': name, 'password': post['password1']}
			)
		if cur.rowcount:
			req.status(303)
			req.header('Location', req.fullurl('/user/%s/edit' % email))
			return
		else:
			return template(req, 'user-create', msg='Email already exists: %s' % email)
	else:
		# No POST
		return template(req, 'user-create')
Exemplo n.º 2
0
def login(req):
	"""Log a user into the system for a session."""
	error = None
	url = req.query().get('returnto', None)
	post = req.post()
	if post is not None:
		url = post.get('returnto', None)
		user = post['user']
		pword = post['password']
		hp = hashlib.md5()
		hp.update(pword)
		
		cur = req.db.cursor()
		cur.execute("SELECT * FROM users WHERE email=%(user)s AND password=%(hash)s", 
			{'user': user, 'hash': hp.hexdigest()})
		if cur.rowcount == 0:
			error = "User/password pair does not exist."
		else:
			req.session['user'] = user # This is the actual "login" code.
			req.status(303)
			req.header('Location', req.fullurl(url))
			return
	# Print the form, possibly with error
	print post, error
	return template(req, 'login', returnto=url, error=error)
Exemplo n.º 3
0
def details(req, eid, rid):
	"""Details page for a specific reservation."""
	try:
		eid = int(eid)
		rid = int(rid)
	except:
		raise HTTPError(404)
	
	cur = req.execute("SELECT * FROM reservation NATURAL JOIN room WHERE rid=%(r)i", r=rid)
	if cur.rowcount == 0:
		raise HTTPError(404)
	resv = first(result2obj(cur, Reservation))
	
	if resv.eid != eid:
		raise HTTPError(404)
	
	cur = req.execute("SELECT * FROM event WHERE eid=%(e)i", e=eid)
	if cur.rowcount == 0:
		raise HTTPError(404)
	event = first(result2obj(cur, Event))
	
	cur = req.execute("""SELECT * 
	FROM resconflicts NATURAL JOIN reservation NATURAL JOIN room 
	WHERE against=%(r)i
	ORDER BY starttime""", r=rid)
	confs = list(result2obj(cur, Reservation))
	
	return template(req, 'reservation', reservation=resv, event=event, conflicts=confs)
Exemplo n.º 4
0
def index(req):
	"""Create the index page for users."""
	cur = req.db.cursor()
	cur.execute("""SELECT * FROM users ORDER BY name;""")
	data = list(result2obj(cur, User))
	
	return template(req, 'user-list', users=data)
Exemplo n.º 5
0
def create(req):
    """Page for creating a new room and adding it to the database."""
    if not req.isadmin():
        raise ActionNotAllowed

    post = req.post()
    if post:
        building = post['building']
        roomnum = int(post['roomnum'])
        dn = post['display']
        occ = None
        if post['occupancy']:
            occ = int(post['occupancy'])
        cur = req.execute(
            """INSERT INTO room (building, roomnum, displayname, occupancy)
			VALUES (%(b)s, %(rn)s, %(dn)s, %(o)s)""",
            b=building,
            rn=roomnum,
            dn=dn,
            o=occ)
        assert cur.rowcount
        req.status(303)
        req.header('Location',
                   req.fullurl('/room/%s/%s' % (building, roomnum)))

    return template(req, 'room-create')
Exemplo n.º 6
0
def edit(req, eid, rid):
	"""Edit a specific reservation."""
	try:
		eid = int(eid)
		rid = int(rid)
	except:
		raise HTTPError(404)
	
	cur = req.execute("SELECT * FROM reservation NATURAL JOIN room WHERE rid=%(r)i", r=rid)
	if cur.rowcount == 0:
		raise HTTPError(404)
	resv = first(result2obj(cur, Reservation))
	
	if resv.eid != eid:
		raise HTTPError(404)
	
	cur = req.execute("SELECT * FROM event WHERE eid=%(e)i", e=eid)
	if cur.rowcount == 0:
		raise HTTPError(404)
	event = first(result2obj(cur, Event))
	
	if not (req.user == resv.semail or req.issuper()):
		raise ActionNotAllowed
	
	post = req.post()
	if post:
		raise NotImplementedError
	
	return template(req, 'reservation-edit', event=event, reservation=resv)
Exemplo n.º 7
0
def edit(req, building, room):
    """Edit a room page."""
    # Handle occupancy, equipment
    if not req.isadmin():
        raise ActionNotAllowed

    cur = req.execute(
        "SELECT * FROM room WHERE building=%(b)s AND roomnum=%(r)s",
        b=building,
        r=room)
    if not cur.rowcount:
        raise HTTPError(404)
    rdata = first(result2obj(cur, Room))

    cur = req.execute(
        "SELECT equipname FROM isin WHERE building=%(b)s AND roomnum=%(r)s",
        b=building,
        r=room)
    equipment = [r[0] for r in itercursor(cur)]

    post = req.post()
    if post:
        raise NotImplementedError

    return template(req, 'room-edit', room=rdata, equipment=equipment)
Exemplo n.º 8
0
def index(req):
    """Creates a link to all events, ordered by name."""
    cur = req.db.cursor()
    cur.execute("SELECT * FROM event ORDER BY name;")
    data = list(result2obj(cur, Event))

    return template(req, 'event-list', events=data)
Exemplo n.º 9
0
def index(req):
	"""Create the front page for room browsing."""
	cur = req.db.cursor()
	cur.execute("""SELECT * FROM room ORDER BY building, roomnum;""")
	data = result2obj(cur, Room)

	return template(req, 'room-list', rooms=data)
Exemplo n.º 10
0
def index(req):
	"""Creates a link to all events, ordered by name."""
	cur = req.db.cursor()
	cur.execute("SELECT * FROM event ORDER BY name;")
	data = list(result2obj(cur, Event))
	
	return template(req, 'event-list', events=data)
Exemplo n.º 11
0
def index(req):
    """Create the front page for room browsing."""
    cur = req.db.cursor()
    cur.execute("""SELECT * FROM room ORDER BY building, roomnum;""")
    data = result2obj(cur, Room)

    return template(req, 'room-list', rooms=data)
Exemplo n.º 12
0
def details(req, userid): # The group from the regex is passed as a positional parameter
	"""Create the details page for specific users."""
	cur = req.db.cursor()
	cur.execute("""
SELECT * FROM users 
	LEFT OUTER JOIN admin ON email = aEmail 
	LEFT OUTER JOIN student ON email = sEmail
	LEFT OUTER JOIN club ON email = cEmail
WHERE email = %(email)s;
""", {'email': userid})
	if cur.rowcount == 0:
		raise HTTPError(404)
	data = first(result2obj(cur, User))
	
	clubs = None
	if data.semail:
		cur = req.execute("""SELECT * FROM memberof NATURAL JOIN clubusers 
	WHERE semail=%(u)s""",
			u=userid)
		clubs = list(result2obj(cur, User))
	events=None
	if data.cemail:
		eventscur = req.execute("""SELECT * FROM event NATURAL JOIN runBy WHERE cEmail=%(user)s;""",user=userid)
		events = result2obj(eventscur,struct)
	
	return template(req, 'user', user=data, clubs=clubs,events=events) # user is a variable that the template references
Exemplo n.º 13
0
def create(req, eid):
	"""Create a new reservation."""
	try:
		eid = int(eid)
	except:
		raise HTTPError(404)
	
	if not (req.isstudent() or req.issuper()):
		raise ActionNotAllowed
	
	cur = req.execute("SELECT * FROM event WHERE eid=%(id)i", id=eid)
	if cur.rowcount == 0:
		raise HTTPError(404)
	event = first(result2obj(cur, Event))
	
	cur = req.execute(
		"SELECT * FROM runBy NATURAL JOIN clubusers WHERE eid=%(id)i ORDER BY name", 
		id=eid)
	clubs = list(result2obj(cur, User))
	
	if not (req.inclub(c.cemail for c in clubs) or req.issuper()):
		raise ActionNotAllowed
	
	post = req.post()
	if post:
		if req.issuper():
			semail = post['semail']
		else:
			semail = req.user
		
		building = post['building']
		roomnum = post['roomnum']
		#FIXME: Parse datetimes
		st = post['starttime']
		et = post['endtime']
		
		cur = req.execute("""INSERT INTO reservation 
			(eid, semail, timebooked, starttime, endtime, roomnum, building)
			VALUES
			(%(e)i, %(s)s, NOW(), %(st)s, %(et)s, %(rn)s, %(build)s)
			RETURNING rid""", e=eid, s=semail, st=st, et=et, rn=roomnum, 
			build=building)
		assert cur.rowcount
		rid = first(itercursor(cur))[0]
		
		req.status(303)
		req.header('Location', req.fullurl('/event/%i/reservation/%i' % (eid, rid)))
	
	query = req.query()
	building = query.get('building', None)
	roomnum = query.get('roomnum', None)
	st = query.get('starttime', None)
	et = query.get('endtime', None)
	
	return template(req, 'reservation-create', event=event, 
		building=building, roomnum=roomnum, starttime=st, endtime=et)
Exemplo n.º 14
0
def building_index(req, building):
	"""Create the index page of for buildings."""
	cur = req.db.cursor()
	cur.execute("""
SELECT * FROM room 
	WHERE building=%(building)s 
	ORDER BY roomnum
""", {'building': building})
	data = result2obj(cur, Room)

	return template(req, 'room-list-building', rooms=data, building=building)
Exemplo n.º 15
0
def building_index(req, building):
    """Create the index page of for buildings."""
    cur = req.db.cursor()
    cur.execute(
        """
SELECT * FROM room 
	WHERE building=%(building)s 
	ORDER BY roomnum
""", {'building': building})
    data = result2obj(cur, Room)

    return template(req, 'room-list-building', rooms=data, building=building)
Exemplo n.º 16
0
def comment(req, eid):
	"""Handle comment functionality such as displaying what comments reply to each other correctly."""
	try:
		eid = int(eid)
	except:
		raise HTTPError(404)
	get = req.query()
	post = req.post()
	
	cur = req.db.cursor()
	cur.execute("SELECT * FROM event WHERE eid=%(id)i", {'id': eid})
	if cur.rowcount == 0:
		raise HTTPError(404)
	event = first(result2obj(cur, Event))
	#manage how comments link to each other
	if post:
		replyto=None
		if 'replyto' in post:
			replyto = int(post['replyto'])
		
		txt = post['txt'].replace('\r\n', '\n').replace('\r', '\n')
		
		if replyto is None:
			cur = req.execute("""
INSERT INTO comments (eid, madeat, email, txt)
	VALUES (%(eid)i, NOW(), %(user)s, %(txt)s)""",
				eid=eid, user=req.user, txt=txt)
		else:
			cur = req.execute("""
INSERT INTO comments (eid, madeat, email, txt, parent)
	VALUES (%(eid)i, NOW(), %(user)s, %(txt)s, %(replyto)i)""", 
				eid=eid, user=req.user, txt=txt, replyto=replyto)
		
		assert cur.rowcount
		cid = cur.lastrowid
		req.status(303)
		req.header('Location', req.fullurl('/event/%i#comment%i' % (eid, cid)))
		return
	else:
		quoted = ''
		parent = None
		if get is not None and 'replyto' in get:
			try:
				r2 = int(get['replyto'])
			except: pass
			else:
				cur.execute(
					"SELECT * FROM comments NATURAL JOIN users WHERE cid=%(id)i", 
					id=r2)
				parent = first(result2obj(cur, Event))
				quoted = '\n'.join('> '+l for l in parent.txt.split('\n')) + '\n'
		return template(req, 'event-comment', event=event, parent=parent, quoted=quoted)
Exemplo n.º 17
0
def approve(req, eid, rid):
	"""Approve an event with conflict checking."""
	try:
		eid = int(eid)
		rid = int(rid)
	except:
		raise HTTPError(404)
	
	if not req.isadmin():
		raise ActionNotAllowed
	
	cur = req.execute("SELECT * FROM reservation NATURAL JOIN room WHERE rid=%(r)i", r=rid)
	if cur.rowcount == 0:
		raise HTTPError(404)
	resv = first(result2obj(cur, Reservation))
	
	if resv.eid != eid:
		raise HTTPError(404)
	
	cur = req.execute("SELECT * FROM event WHERE eid=%(e)i", e=eid)
	if cur.rowcount == 0:
		raise HTTPError(404)
	event = first(result2obj(cur, Event))
	
	cur = req.execute("""SELECT * 
	FROM resconflicts NATURAL JOIN reservation NATURAL JOIN room 
	WHERE against=%(r)i
	ORDER BY starttime""", r=rid)
	confs = list(result2obj(cur, Reservation))
	
	post = req.post()
	if post and not resv.aemail:
		# in 2.5, we could just use any()/all()
		canapprove = True
		for c in confs:
			if c.aemail:
				canapprove = False
				break
		
		if 'yes' in post and canapprove:
			cur = req.execute(
				"UPDATE reservation SET aemail=%(a)s WHERE rid=%(r)i",
				a=req.user, r=rid)
			assert cur.rowcount
			
		req.status(303)
		req.header('Location', req.fullurl('/event/%i/reservation/%i'%(eid,rid)))
		return
	
	return template(req, 'reservation-approve', event=event, reservation=resv, 
		conflicts=confs)
Exemplo n.º 18
0
def details(req, building, room):
	"""Create the page for a specific room."""
	cur = req.db.cursor()
	cur.execute("""
SELECT * FROM room 
	WHERE roomnum=%(room)s AND building=%(building)s
""", {'room': room, 'building': building})
	roomdata = first(result2obj(cur, Room))
	cur.execute("""
SELECT equipname FROM isIn 
	WHERE roomnum=%(room)s AND building=%(building)s 
	ORDER BY equipname
""", {'room': room, 'building': building})
	equipdata = [r[0] for r in itercursor(cur)]
	
	return template(req, 'room', room=roomdata, equipment=equipdata)
Exemplo n.º 19
0
def delete(req, eid, rid):
	"""Delete a reservation from the database."""
	try:
		eid = int(eid)
		rid = int(rid)
	except:
		raise HTTPError(404)
	
	if not req.isadmin():
		raise ActionNotAllowed
	
	cur = req.execute("SELECT * FROM reservation NATURAL JOIN room WHERE rid=%(r)i", r=rid)
	if cur.rowcount == 0:
		raise HTTPError(404)
	resv = first(result2obj(cur, Reservation))
	
	if resv.eid != eid:
		raise HTTPError(404)
	
	cur = req.execute("SELECT * FROM event WHERE eid=%(e)i", e=eid)
	if cur.rowcount == 0:
		raise HTTPError(404)
	event = first(result2obj(cur, Event))
	
	cur = req.execute(
		"SELECT COUNT(*) FROM runby WHERE eid=%(e)i AND cemail=%(c)s", 
		e=eid, c=req.user)
	isclub = first(itercursor(cur))[0]
	
	# running groups, booking user, admin
	if not (isclub or req.user == resv.semail or req.isadmin()):
		raise ActionNotAllowed
	
	post = req.post()
	if post:
		if 'yes' in post:
			cur = req.execute(
				"DELETE reservation WHERE rid=%(r)i", r=rid)
			assert cur.rowcount
			req.status(303)
			req.header('Location', req.fullurl('/event/%i'%eid))
		else:
			req.status(303)
			req.header('Location', req.fullurl('/event/%i/reservation/%i'%(eid,rid)))
		return
		
	return template(req, 'reservation-delete', event=event, reservation=resv)
Exemplo n.º 20
0
def details(req, eid):
    """Populates all the detail pages for specific events."""
    from reservations import Reservation
    try:
        eid = int(eid)
    except:
        raise HTTPError(404)
    cur = req.execute("SELECT * FROM event WHERE eid=%(id)i", id=eid)
    if cur.rowcount == 0:
        raise HTTPError(404)
    event = first(result2obj(cur, Event))
    #who runs
    cur = req.execute(
        "SELECT * FROM runBy NATURAL JOIN clubusers WHERE eid=%(id)i ORDER BY name",
        id=eid)
    clubs = list(result2obj(cur, User))
    #find reservations, mark conflicts
    cur = req.execute("""
SELECT * FROM reservation NATURAL LEFT OUTER JOIN (
		SELECT COUNT(against) AS conflicts, rid
			FROM resconflicts NATURAL JOIN reservation 
			WHERE EID=%(event)i 
			GROUP BY rid
		) AS conflicting NATURAL LEFT OUTER JOIN room
	WHERE reservation.eid = %(event)i
	ORDER BY starttime""",
                      event=eid)
    reservations = list(result2obj(cur, Reservation))
    #comments ordered by time made
    cur = req.execute(
        "SELECT * FROM comments NATURAL JOIN users WHERE EID=%(id)i ORDER BY madeat",
        id=eid)
    comments = list(result2obj(cur, Comment))
    #equipment present ordered by name
    cur = req.execute(
        "SELECT equipname FROM uses WHERE EID=%(id)i ORDER BY equipname",
        id=eid)
    equipment = [r[0] for r in itercursor(cur)]

    return template(req,
                    'event',
                    event=event,
                    clubs=clubs,
                    equipment=equipment,
                    comments=comments,
                    reservations=reservations)
Exemplo n.º 21
0
def details(req, eid):
	"""Populates all the detail pages for specific events."""
	from reservations import Reservation
	try:
		eid = int(eid)
	except:
		raise HTTPError(404)
	cur = req.execute("SELECT * FROM event WHERE eid=%(id)i", id=eid)
	if cur.rowcount == 0:
		raise HTTPError(404)
	event = first(result2obj(cur, Event))
	#who runs
	cur = req.execute(
		"SELECT * FROM runBy NATURAL JOIN clubusers WHERE eid=%(id)i ORDER BY name", 
		id=eid)
	clubs = list(result2obj(cur, User))
	#find reservations, mark conflicts
	cur = req.execute("""
SELECT * FROM reservation NATURAL LEFT OUTER JOIN (
		SELECT COUNT(against) AS conflicts, rid
			FROM resconflicts NATURAL JOIN reservation 
			WHERE EID=%(event)i 
			GROUP BY rid
		) AS conflicting NATURAL LEFT OUTER JOIN room
	WHERE reservation.eid = %(event)i
	ORDER BY starttime""", event=eid)
	reservations = list(result2obj(cur, Reservation))
	#comments ordered by time made
	cur = req.execute(
		"SELECT * FROM comments NATURAL JOIN users WHERE EID=%(id)i ORDER BY madeat", 
		id=eid)
	comments = list(result2obj(cur, Comment))
	#equipment present ordered by name
	cur = req.execute(
		"SELECT equipname FROM uses WHERE EID=%(id)i ORDER BY equipname", 
		id=eid)
	equipment = [r[0] for r in itercursor(cur)]
	
	return template(req, 'event', 
		event=event, clubs=clubs, equipment=equipment, comments=comments, 
		reservations=reservations)
Exemplo n.º 22
0
def create(req):
	"""Page for creating a new room and adding it to the database."""
	if not req.isadmin():
		raise ActionNotAllowed
	
	post = req.post()
	if post:
		building = post['building']
		roomnum = int(post['roomnum'])
		dn = post['display']
		occ = None
		if post['occupancy']:
			occ = int(post['occupancy'])
		cur = req.execute("""INSERT INTO room (building, roomnum, displayname, occupancy)
			VALUES (%(b)s, %(rn)s, %(dn)s, %(o)s)""",
			b=building, rn=roomnum, dn=dn, o=occ)
		assert cur.rowcount
		req.status(303)
		req.header('Location', req.fullurl('/room/%s/%s' % (building, roomnum)))
	
	return template(req, 'room-create')
Exemplo n.º 23
0
def edit(req, building, room):
	"""Edit a room page."""
	# Handle occupancy, equipment
	if not req.isadmin():
		raise ActionNotAllowed
	
	cur = req.execute("SELECT * FROM room WHERE building=%(b)s AND roomnum=%(r)s",
		b=building, r=room)
	if not cur.rowcount:
		raise HTTPError(404)
	rdata = first(result2obj(cur, Room))
	
	cur = req.execute("SELECT equipname FROM isin WHERE building=%(b)s AND roomnum=%(r)s",
		b=building, r=room)
	equipment = [r[0] for r in itercursor(cur)]
	
	post = req.post()
	if post:
		raise NotImplementedError
	
	return template(req, 'room-edit', room=rdata, equipment=equipment)
Exemplo n.º 24
0
def index(req):
    """Create the index page for use statistics."""
    #FIXME: Join against room so we can use Room
    #most used rooms
    roomscur = req.execute("""SELECT COUNT(*) AS c, building, roomnum
	FROM room NATURAL JOIN reservation 
	GROUP BY building, roomnum 
	ORDER BY COUNT(*) DESC 
	LIMIT 10;""")
    usedrooms = result2obj(roomscur, struct)

    # FIXME: Join against users so we can use User
    # students who run events
    studentcur = req.execute("""SELECT COUNT(*) AS c, semail 
	FROM reservation NATURAL JOIN student
	GROUP BY semail 
	ORDER BY COUNT(*) DESC 
	LIMIT 10;""")
    studentsevents = result2obj(studentcur, struct)
    #majors which run events
    majorcur = req.execute("""
SELECT major, COUNT(rid) AS count
	FROM 
		(
			(SELECT rid, major1 AS major FROM reservation NATURAL JOIN student)
		UNION
			(SELECT rid, major2 AS major FROM reservation NATURAL JOIN student 
				WHERE major2 IS NOT NULL)
		) AS counts
	GROUP BY major
	ORDER BY count DESC 
	LIMIT 10;""")
    majorevents = result2obj(majorcur, struct)

    return template(req,
                    'stats',
                    usedrooms=usedrooms,
                    studentsevents=studentsevents,
                    majorevents=majorevents)
Exemplo n.º 25
0
def index(req):
	"""Create the index page for use statistics."""
	#FIXME: Join against room so we can use Room
	#most used rooms
	roomscur = req.execute("""SELECT COUNT(*) AS c, building, roomnum
	FROM room NATURAL JOIN reservation 
	GROUP BY building, roomnum 
	ORDER BY COUNT(*) DESC 
	LIMIT 10;""")
	usedrooms = result2obj(roomscur,struct)
	
	
	# FIXME: Join against users so we can use User
	# students who run events
	studentcur =req.execute("""SELECT COUNT(*) AS c, semail 
	FROM reservation NATURAL JOIN student
	GROUP BY semail 
	ORDER BY COUNT(*) DESC 
	LIMIT 10;""")
	studentsevents = result2obj(studentcur,struct)
	#majors which run events
	majorcur=req.execute("""
SELECT major, COUNT(rid) AS count
	FROM 
		(
			(SELECT rid, major1 AS major FROM reservation NATURAL JOIN student)
		UNION
			(SELECT rid, major2 AS major FROM reservation NATURAL JOIN student 
				WHERE major2 IS NOT NULL)
		) AS counts
	GROUP BY major
	ORDER BY count DESC 
	LIMIT 10;""")
	majorevents = result2obj(majorcur,struct)

	return template(req, 'stats', 
		usedrooms=usedrooms, studentsevents=studentsevents, 
		majorevents=majorevents)
Exemplo n.º 26
0
def details(req, building, room):
    """Create the page for a specific room."""
    cur = req.db.cursor()
    cur.execute(
        """
SELECT * FROM room 
	WHERE roomnum=%(room)s AND building=%(building)s
""", {
            'room': room,
            'building': building
        })
    roomdata = first(result2obj(cur, Room))
    cur.execute(
        """
SELECT equipname FROM isIn 
	WHERE roomnum=%(room)s AND building=%(building)s 
	ORDER BY equipname
""", {
            'room': room,
            'building': building
        })
    equipdata = [r[0] for r in itercursor(cur)]

    return template(req, 'room', room=roomdata, equipment=equipdata)
Exemplo n.º 27
0
def index(req, eid):
	"""Format the reservation page."""
	try:
		eid = int(eid)
	except:
		raise HTTPError(404)
	
	cur = req.execute("SELECT * FROM event WHERE eid=%(id)i", id=eid)
	if cur.rowcount == 0:
		raise HTTPError(404)
	event = first(result2obj(cur, Event))
	#find conflicts
	cur = req.execute("""
SELECT * FROM reservation NATURAL LEFT OUTER JOIN (
		SELECT COUNT(against) AS conflicts, rid
			FROM resconflicts NATURAL JOIN reservation 
			WHERE EID=%(event)i 
			GROUP BY rid
		) AS conflicting NATURAL LEFT OUTER JOIN room
	WHERE reservation.eid = %(event)i
	ORDER BY starttime""", event=eid)
	reservations = list(result2obj(cur, Reservation))
	
	return template(req, 'reservation-list', event=event, reservations=reservations)
Exemplo n.º 28
0
def edit(req, eid):
    """Change information on the event."""
    try:
        eid = int(eid)
    except:
        raise HTTPError(404)

    cur = req.execute("SELECT * FROM event WHERE eid=%(id)i", id=eid)
    if cur.rowcount == 0:
        raise HTTPError(404)
    event = first(result2obj(cur, Event))

    cur = req.execute(
        "SELECT * FROM runBy NATURAL JOIN clubusers WHERE eid=%(id)i ORDER BY name",
        id=eid)
    clubs = list(result2obj(cur, User))

    cur = req.execute(
        "SELECT equipname FROM uses WHERE EID=%(id)i ORDER BY equipname",
        id=eid)
    equipment = [r[0] for r in itercursor(cur)]

    if not (req.inclub(c.email for c in clubs) or req.issuper()):
        raise ActionNotAllowed

    post = req.post()
    if post:
        if 'basicinfo' in post:
            size = None
            if post['expectedsize']:
                size = int(post['expectedsize'])

            req.execute("""UPDATE event 
SET name=%(name)s, description=%(desc)s, expectedsize=%(size)s 
WHERE eid=%(eid)i""",
                        name=post['name'],
                        desc=post['description'],
                        size=size,
                        eid=eid)

        elif 'club-delete' in post and len(clubs) > 1:
            # Broken?
            if req.inclub(post['cemail']) or req.issuper():
                req.execute(
                    "DELETE FROM runby WHERE eid=%(e)i AND cemail=%(c)s",
                    e=eid,
                    c=post['cemail'])
        elif 'club-add' in post:
            if (req.isstudent() and req.inclub([post['cemail']])) \
              or req.isclub() or req.issuper():
                req.execute(
                    "INSERT INTO runby (eid, cemail) VALUES (%(e)i, %(c)s)",
                    e=eid,
                    c=post['cemail'])

        elif 'equip-delete' in post:
            req.execute(
                "DELETE FROM uses WHERE eid=%(e)i AND equipname=%(eq)s",
                e=eid,
                eq=post['equipname'])
        elif 'equip-add' in post:
            req.execute(
                """INSERT INTO uses (eid, equipname) VALUES (%(e)i, %(eq)s)""",
                e=eid,
                eq=post['equipname'])

        req.status(303)
        req.header('Location', req.fullurl('/event/%i/edit' % (eid)))
    else:
        userclubs = None
        if req.isstudent():
            cur = req.execute("""
SELECT * FROM memberof NATURAL JOIN clubusers WHERE semail=%(email)s ORDER BY name""",
                              email=req.user)
            userclubs = list(result2obj(cur, User))
        return template(req,
                        'event-edit',
                        event=event,
                        clubs=clubs,
                        equipment=equipment,
                        userclubs=userclubs)
Exemplo n.º 29
0
def create(req):
    """Handles the form for creating a new event and adding it to the database."""
    if not (req.isstudent() or req.isclub() or req.issuper()):
        raise ActionNotAllowed

    clubs = None
    if req.isstudent():
        cur = req.execute(
            "SELECT * FROM memberof NATURAL JOIN clubusers WHERE semail=%(u)s",
            u=req.user)
        clubs = list(result2obj(cur, User))
    elif req.issuper():
        cur = req.execute("SELECT * FROM clubusers")
        clubs = list(result2obj(cur, User))

    post = req.post()
    if post:
        name = post['name']
        desc = post['description']
        size = None
        if post['expectedsize']:
            size = int(post['expectedsize'])

        if req.isclub():
            clubs = [req.user]
        else:
            clubs = [v for n, v in req.postall() if n == 'cemail']

        equipment = post['equipment'].split()

        if len(clubs) and name and desc:
            cur = req.db.cursor()
            cur.execute("BEGIN")
            try:
                cur.execute(
                    """INSERT INTO event (name, description, expectedsize)
					VALUES (%(name)s, %(desc)s, %(size)s)
					RETURNING eid""", {
                        'name': name,
                        'desc': desc,
                        'size': size
                    })
                assert cur.rowcount
                eid = first(itercursor(cur))[0]

                for c in clubs:
                    cur.execute(
                        "INSERT INTO runby (eid, cemail) VALUES (%(e)i, %(c)s)",
                        {
                            'e': eid,
                            'c': c
                        })
                    assert cur.rowcount

                for e in equipment:
                    cur.execute(
                        "INSERT INTO uses (eid, equipname) VALUES (%(e)i, %(q)s)",
                        {
                            'e': eid,
                            'q': e
                        })
                    assert cur.rowcount
            finally:
                if sys.exc_info()[0] is None:
                    cur.execute("COMMIT")
                else:
                    cur.execute("ROLLBACK")

            req.status(303)
            req.header("Location", req.fullurl("/event/%i" % eid))
            return

    return template(req, 'event-create', clubs=clubs)
Exemplo n.º 30
0
def index(req):
	"""Creates an index page for reservations."""
	cur = req.execute("""SELECT reservation.*, event.name FROM reservation NATURAL JOIN event WHERE aEmail IS NULL AND startTime > now() ORDER BY startTime;""")
	reservations = list(result2obj(cur, Reservation))

	return template(req, 'unapproved-reservations', reservations=reservations)
Exemplo n.º 31
0
def comment(req, eid):
    """Handle comment functionality such as displaying what comments reply to each other correctly."""
    try:
        eid = int(eid)
    except:
        raise HTTPError(404)
    get = req.query()
    post = req.post()

    cur = req.db.cursor()
    cur.execute("SELECT * FROM event WHERE eid=%(id)i", {'id': eid})
    if cur.rowcount == 0:
        raise HTTPError(404)
    event = first(result2obj(cur, Event))
    #manage how comments link to each other
    if post:
        replyto = None
        if 'replyto' in post:
            replyto = int(post['replyto'])

        txt = post['txt'].replace('\r\n', '\n').replace('\r', '\n')

        if replyto is None:
            cur = req.execute("""
INSERT INTO comments (eid, madeat, email, txt)
	VALUES (%(eid)i, NOW(), %(user)s, %(txt)s)""",
                              eid=eid,
                              user=req.user,
                              txt=txt)
        else:
            cur = req.execute("""
INSERT INTO comments (eid, madeat, email, txt, parent)
	VALUES (%(eid)i, NOW(), %(user)s, %(txt)s, %(replyto)i)""",
                              eid=eid,
                              user=req.user,
                              txt=txt,
                              replyto=replyto)

        assert cur.rowcount
        cid = cur.lastrowid
        req.status(303)
        req.header('Location', req.fullurl('/event/%i#comment%i' % (eid, cid)))
        return
    else:
        quoted = ''
        parent = None
        if get is not None and 'replyto' in get:
            try:
                r2 = int(get['replyto'])
            except:
                pass
            else:
                cur.execute(
                    "SELECT * FROM comments NATURAL JOIN users WHERE cid=%(id)i",
                    id=r2)
                parent = first(result2obj(cur, Event))
                quoted = '\n'.join('> ' + l
                                   for l in parent.txt.split('\n')) + '\n'
        return template(req,
                        'event-comment',
                        event=event,
                        parent=parent,
                        quoted=quoted)
Exemplo n.º 32
0
def edit(req, eid):
	"""Change information on the event."""
	try:
		eid = int(eid)
	except:
		raise HTTPError(404)
	
	cur = req.execute("SELECT * FROM event WHERE eid=%(id)i", id=eid)
	if cur.rowcount == 0:
		raise HTTPError(404)
	event = first(result2obj(cur, Event))
	
	cur = req.execute(
		"SELECT * FROM runBy NATURAL JOIN clubusers WHERE eid=%(id)i ORDER BY name", 
		id=eid)
	clubs = list(result2obj(cur, User))
	
	cur = req.execute(
		"SELECT equipname FROM uses WHERE EID=%(id)i ORDER BY equipname", 
		id=eid)
	equipment = [r[0] for r in itercursor(cur)]
	
	if not (req.inclub(c.email for c in clubs) or req.issuper()):
		raise ActionNotAllowed
	
	post = req.post()
	if post:
		if 'basicinfo' in post:
			size = None
			if post['expectedsize']:
				size = int(post['expectedsize'])
			
			req.execute("""UPDATE event 
SET name=%(name)s, description=%(desc)s, expectedsize=%(size)s 
WHERE eid=%(eid)i""",
			name=post['name'], desc=post['description'], size=size, eid=eid)
		
		elif 'club-delete' in post and len(clubs) > 1:
			# Broken?
			if req.inclub(post['cemail']) or req.issuper():
				req.execute("DELETE FROM runby WHERE eid=%(e)i AND cemail=%(c)s",
					e=eid, c=post['cemail'])
		elif 'club-add' in post:
			if (req.isstudent() and req.inclub([post['cemail']])) \
					or req.isclub() or req.issuper():
				req.execute("INSERT INTO runby (eid, cemail) VALUES (%(e)i, %(c)s)",
					e=eid, c=post['cemail'])
		
		elif 'equip-delete' in post:
			req.execute("DELETE FROM uses WHERE eid=%(e)i AND equipname=%(eq)s",
				e=eid, eq=post['equipname'])
		elif 'equip-add' in post:
			req.execute("""INSERT INTO uses (eid, equipname) VALUES (%(e)i, %(eq)s)""",
				e=eid, eq=post['equipname'])
		
		req.status(303)
		req.header('Location', req.fullurl('/event/%i/edit' % (eid)))
	else:
		userclubs = None
		if req.isstudent():
			cur = req.execute("""
SELECT * FROM memberof NATURAL JOIN clubusers WHERE semail=%(email)s ORDER BY name""", 
				email=req.user)
			userclubs = list(result2obj(cur, User))
		return template(req, 'event-edit', 
			event=event, clubs=clubs, equipment=equipment, userclubs=userclubs)
Exemplo n.º 33
0
def create(req):
	"""Handles the form for creating a new event and adding it to the database."""
	if not (req.isstudent() or req.isclub() or req.issuper()):
		raise ActionNotAllowed
	
	clubs = None
	if req.isstudent():
		cur = req.execute(
			"SELECT * FROM memberof NATURAL JOIN clubusers WHERE semail=%(u)s",
			u=req.user)
		clubs = list(result2obj(cur, User))
	elif req.issuper():
		cur = req.execute("SELECT * FROM clubusers")
		clubs = list(result2obj(cur, User))
	
	post = req.post()
	if post:
		name = post['name']
		desc = post['description']
		size = None
		if post['expectedsize']:
			size = int(post['expectedsize'])
		
		if req.isclub():
			clubs = [req.user]
		else:
			clubs = [v for n,v in req.postall() if n == 'cemail']
		
		equipment = post['equipment'].split()
		
		if len(clubs) and name and desc:
			cur = req.db.cursor();
			cur.execute("BEGIN")
			try:
				cur.execute("""INSERT INTO event (name, description, expectedsize)
					VALUES (%(name)s, %(desc)s, %(size)s)
					RETURNING eid""",
					{'name': name, 'desc': desc, 'size': size})
				assert cur.rowcount
				eid = first(itercursor(cur))[0]
				
				for c in clubs:
					cur.execute(
						"INSERT INTO runby (eid, cemail) VALUES (%(e)i, %(c)s)",
						{'e': eid, 'c': c})
					assert cur.rowcount
				
				for e in equipment:
					cur.execute(
						"INSERT INTO uses (eid, equipname) VALUES (%(e)i, %(q)s)",
						{'e': eid, 'q': e})
					assert cur.rowcount
			finally:
				if sys.exc_info()[0] is None:
					cur.execute("COMMIT")
				else:
					cur.execute("ROLLBACK")
			
			req.status(303)
			req.header("Location", req.fullurl("/event/%i" % eid))
			return
	
	return template(req, 'event-create', clubs=clubs)
Exemplo n.º 34
0
def logout(req):
	"""Log a user out of the system."""
	if 'user' in req.session:
		del req.session['user']
	url = req.query().get('returnto', None)
	return template(req, 'logout', returnto=url)
Exemplo n.º 35
0
def user_edit(req, user):
	"""Edit a user in the database."""
	cur = req.db.cursor()
	# Handles:
	# * user/student/admin/club info
	# * changing the type of user
	# * making admins super
	# * Adding club adminship
	cur.execute("""
SELECT * FROM users 
	LEFT OUTER JOIN admin ON email = aEmail 
	LEFT OUTER JOIN student ON email = sEmail
	LEFT OUTER JOIN club ON email = cEmail
WHERE email = %(email)s;
""", {'email': user})
	userdata = first(result2obj(cur, User))
	if cur.rowcount == 0:
		raise HTTPError(404)
	post = req.post()
	
	clubs = None
	if userdata.semail:
		cur = req.execute("""SELECT * FROM memberof NATURAL JOIN clubusers 
	WHERE semail=%(u)s""",
			u=user)
		clubs = list(result2obj(cur, User))
	
	if post is not None:
		# Save
		if 'club-remove' in post and userdata.semail: #TODO: Add permissions checking
			cur = req.execute("DELETE FROM memberOf WHERE semail=%(email)s AND cemail=%(cemail)s",email=user,cemail=post['cemail'])
		elif 'club-add' in post and userdata.semail:
			cur = req.execute("INSERT INTO memberOf VALUES (%(semail)s, %(cemail)s)",semail=user,cemail=post['cemail'])
		elif 'mkadmin' in post and req.issuper() and not userdata.aemail and not userdata.cemail:
			cur = req.execute("INSERT INTO admin (aemail) VALUES (%(email)s)", email=user)
			assert cur.rowcount
		elif 'mkstudent' in post and not userdata.semail and not userdata.cemail:
			cur = req.execute("INSERT INTO student (semail) VALUES (%(email)s)", email=user)
			assert cur.rowcount
		elif 'mkclub' in post and req.issuper() and not userdata.semail and not userdata.aemail and not userdata.cemail:
			cur = req.execute("INSERT INTO club (cemail) VALUES (%(email)s)", email=user)
			assert cur.rowcount
		else:
			cur.execute("BEGIN");
			try:
				password = None
				print repr(post)
				if post['oldpassword'] or (req.issuper() and post['password1']):
					if post['password1'] != post['password2']:
						return template(req, 'user-edit', user=userdata, msg='Mismatched passwords')
					cur.execute("""
						UPDATE users 
						SET password=md5(%(password)s)
						WHERE email=%(email)s AND password=md5(%(old)s);
						""", 
						{'email': user, 'old': post['oldpassword'], 'password': post['password1']}
						)
					assert cur.rowcount
			
				cur.execute("""
					UPDATE users 
					SET name=%(name)s
					WHERE email=%(email)s;
					""", 
					{'name': post['name'], 'email': user}
					)
				assert cur.rowcount
				if userdata.aemail and 'aemail' in post:
					title = None
					if post['title']:
						title = post['title']
					if request.issuper():
						cur.execute("""
							UPDATE admin 
							SET title=%(title)s, super=%(super)s
							WHERE aemail=%(email)s;
							""", 
							{'title': title, 'super': 'super' in post, 'email': user}
							)
					else:
						cur.execute("""
							UPDATE admin 
							SET title=%(title)s
							WHERE aemail=%(email)s;
							""", 
							{'title': title, 'email': user}
							)
					assert cur.rowcount
				if userdata.semail and 'semail' in post:
					year = major1 = major2 = None
					if post['year']: year = int(post['year'])
					if post['major1']: major1 = post['major1']
					if post['major2']: major2 = post['major2']
					if major2 and not major1:
						major1, major2 = major2, None
					cur.execute("""
						UPDATE student 
						SET year=%(year)i, major1=%(major1)s, major2=%(major2)s
						WHERE semail=%(email)s;
						""", 
						{'year': year, 'major1': major1, 'major2': major2, 'email': user}
						)
					assert cur.rowcount
				if userdata.cemail and 'cemail' in post:
					cls = desc = None
					if post['class']: cls = int(post['class'])
					if post['description']: desc = post['description']
					cur.execute("""
						UPDATE club 
						SET class=%(cls)i, description=%(desc)s 
						WHERE cemail=%(email)s;
						""", 
						{'cls': cls, 'desc': desc, 'email': user}
						)
					assert cur.rowcount
			finally:
				if sys.exc_info()[0] is None:
					cur.execute("COMMIT")
				else:
					cur.execute("ROLLBACK")
		req.status(303)
		req.header('Location', req.fullurl('/user/%s/edit' % user))
		return

	cur.execute("""
SELECT * FROM users 
	LEFT OUTER JOIN admin ON email = aEmail 
	LEFT OUTER JOIN student ON email = sEmail
	LEFT OUTER JOIN club ON email = cEmail
WHERE email = %(email)s;
""", {'email': user})
	userdata = first(result2obj(cur, User))
	
	return template(req, 'user-edit', user=userdata, clubs=clubs)