Exemple #1
0
    def add(self, triples):
        """Write a list of triples in the store"""
        for t in triples:
            db.sql(
                """
				insert ignore into rdf_triple(subject, predicate, object) 
				values (%s, %s, %s)""", (t[0], t[1], t[2]))
Exemple #2
0
def cleanup():
	"""logout testuser and cleanup"""
	from lib.chai import db
	db.begin()
	db.sql("""delete from session where user=%s""", userobj['name'])
	db.sql("""delete from user where name=%s""", userobj['name'])
	db.commit()
Exemple #3
0
def update_password(**args):
    """update user password"""
    userobj = model.get(dict(type="user", name="any"))
    db.sql("""update user set password=%s, reset_password_id=NULL
		where reset_password_id=%s""", \
     (userobj.encrypt_password(args['password']), args['requestid']))

    return 'ok'
Exemple #4
0
    def before_post(self):
        """set parent and idx in child pages"""
        if 'subpage' in self.obj:
            for idx in range(len(self.obj['subpage'])):
                db.sql("""update page set parent=%s, idx=%s, _updated=%s where name=%s""", \
                 (self.obj['name'], idx, datetime.datetime.now(), self.obj['subpage'][idx]))

            del self.obj['subpage']
Exemple #5
0
def update_password(**args):
	"""update user password"""
	userobj = model.get(dict(type="user", name="any"))
	db.sql("""update user set password=%s, reset_password_id=NULL
		where reset_password_id=%s""", \
		(userobj.encrypt_password(args['password']), args['requestid']))

	return 'ok'
	
Exemple #6
0
def rebuild(type):
	"""
	rebuld lft, rgt in all elements
	needs columns `parent` and `idx`
	"""
	global all_nodes
	all_nodes = []
	db.sql("update `%s` set lft=0, rgt=0" % type)
	build(type)
Exemple #7
0
	def before_post(self):
		"""set parent and idx in child pages"""
		if 'subpage' in self.obj:
			for idx in range(len(self.obj['subpage'])):
				db.sql("""update page set parent=%s, idx=%s, _updated=%s where name=%s""", \
					(self.obj['name'], idx, datetime.datetime.now(), self.obj['subpage'][idx]))
		
			del self.obj['subpage']
			
def post_single(obj, action='insert'):
	"""post an object in db, ignore extra columns"""
	import MySQLdb

	obj_copy = get_valid_obj(obj)

	if action=='insert':
		query = insert_query(obj, obj_copy)
	else:
		query = update_query(obj, obj_copy)

	db.sql(query, tuple(obj_copy.values()))
Exemple #9
0
def post_single(obj, action='insert'):
    """post an object in db, ignore extra columns"""
    import MySQLdb

    obj_copy = get_valid_obj(obj)

    if action == 'insert':
        query = insert_query(obj, obj_copy)
    else:
        query = update_query(obj, obj_copy)

    db.sql(query, tuple(obj_copy.values()))
Exemple #10
0
def build(type, name=None):
	"""
	update lft, rgt in this node and all children
	adds the node at the right-most end of the parent
	take the rgt of parent and add it at rgt - 1
	
	if root, take the last rgt and add +1
	"""
	global all_nodes
		
	if not name:
		name, parent = '', ''
	else:
		parent = db.getvalue(type, name, 'parent')
		all_nodes.append(name)
	
	if parent:
		lft = db.getvalue(type, parent, 'rgt')
	else:
		lft = db.sql("select ifnull(max(rgt),0)+1 as lft from `%s`" % type)[0]['lft']
		
	now = datetime.datetime.now()
	
	# insert this node
	db.sql("update `%s` set rgt=rgt+2, _updated=%s where rgt >= %s" % (type, '%s', '%s'), (now, lft))
	db.sql("update `%s` set lft=lft+2, _updated=%s where lft >= %s" % (type, '%s', '%s'), (now, lft))
	db.sql("update `%s` set lft=%s, rgt=%s, _updated=%s where name=%s" % \
		(type, '%s', '%s', '%s', '%s'), \
		(lft, lft+1, now, name))
	
	for c in db.sql("""select name from `%s` where ifnull(parent,'')=%s""" % (type, '%s'), name):
		if c['name'] in all_nodes:
			raise Exception, '[nestedset] Circular Reference: %s' % c['name']
		build(type, c['name'])
Exemple #11
0
	def before_get(self):
		"""
		load list of child pages in `subpage` and `subpages`
		load list of ancestors in `ancestors`
		"""
		subpages = db.sql("""
			select name, label from page where parent=%s order by idx""", self.obj['name'])
			
		self.obj['subpage'] = [d['name'] for d in subpages]
		self.obj['subpages'] = subpages
		
		if 'lft' in self.obj and self.obj['lft']:
			self.obj['ancestors'] = db.sql("""select name, label from page 
				where lft < %s and rgt > %s
				order by lft""" % (self.obj['lft'], self.obj['rgt']))
Exemple #12
0
def getchildren(node):
	"""get children <ol>"""
	global all_nodes, level
	
	cl = db.sql("""select name, label from page
		where parent = %s order by idx""", node)

	if not cl:
		return None

	level += 1

	out = '\n' + ('\t'*level) + '<ol>'
	for node in cl:
		if node['name'] in all_nodes:
			raise Exception, 'Circular Page Reference'

		all_nodes.append(node['name'])
		out += '\n' + ('\t'*(level+1)) + '<li>'+nodehtml(node)+'</li>'
		
	out +='\n' + ('\t'*level) + '</ol>'
	
	level -= 1
	
	return out
Exemple #13
0
    def triples(self, s, p, o=None):
        """Return matching triples"""
        cond, values = self.get_matching_conditions(s, p, o)
        return db.sql("""select `subject`, `predicate`, `object` 
			from rdf_triple where %s""" % ' and '.join(cond),
                      values,
                      as_dict=False)
Exemple #14
0
    def before_get(self):
        """
		load list of child pages in `subpage` and `subpages`
		load list of ancestors in `ancestors`
		"""
        subpages = db.sql(
            """
			select name, label from page where parent=%s order by idx""",
            self.obj['name'])

        self.obj['subpage'] = [d['name'] for d in subpages]
        self.obj['subpages'] = subpages

        if 'lft' in self.obj and self.obj['lft']:
            self.obj['ancestors'] = db.sql("""select name, label from page 
				where lft < %s and rgt > %s
				order by lft""" % (self.obj['lft'], self.obj['rgt']))
Exemple #15
0
def get_user_fullname(**args):
	"""get user fullname"""
	ret = db.sql("""
		select ifnull(fullname, name) as fullname 
		from user where reset_password_id=%s""", args['requestid'])
	if ret:
		return ret[0]['fullname']
	else:
		return 'bad id'
	def test_logout(self):
		from webob import Request
		import lib.chai

		self.test_login()
		lib.chai.req = Request.blank('server/?_method=lib.chai.session.logout', \
			headers=[('Cookie','sid='+self.sid+';')])
		session.logout()
		self.assertFalse(db.sql("""select * from session where user='******'"""))
Exemple #17
0
def forgot_password(**args):
	"""email the user with a unique link to generate the password"""	
	user = db.sql("""select name from user where name=%s or email=%s""", (args['email'], args['email']))
	if not user:
		return 'No such user'
		
	userobj = model.get(objstore.get(type="user", name=user[0]['name']))
	userobj.request_reset_password()
	return 'ok'
Exemple #18
0
def mywblist(**args):
	"""get list of my whiteboards and those i am shared"""
	from lib.chai import sess
	
	if sess['user']=='guest':
		return {"error":"not logged in"}
	
	return {'result': db.sql("""
			select name, label from whiteboard
			where owner = %(user)s
			order by label asc""", sess) + \
			db.sql("""
			select wb.name, wb.label
			from whiteboard wb, whiteboarduser wbuser
			where 
				wbuser.user=%(user)s and 
				wbuser.parent = wb.name
			order by wb.label asc""", sess), 'user':sess['user']}
Exemple #19
0
    def test_logout(self):
        from webob import Request
        import lib.chai

        self.test_login()
        lib.chai.req = Request.blank('server/?_method=lib.chai.session.logout', \
         headers=[('Cookie','sid='+self.sid+';')])
        session.logout()
        self.assertFalse(db.sql("""select * from session where user='******'"""))
Exemple #20
0
def get_user_fullname(**args):
    """get user fullname"""
    ret = db.sql(
        """
		select ifnull(fullname, name) as fullname 
		from user where reset_password_id=%s""", args['requestid'])
    if ret:
        return ret[0]['fullname']
    else:
        return 'bad id'
Exemple #21
0
def forgot_password(**args):
    """email the user with a unique link to generate the password"""
    user = db.sql("""select name from user where name=%s or email=%s""",
                  (args['email'], args['email']))
    if not user:
        return 'No such user'

    userobj = model.get(objstore.get(type="user", name=user[0]['name']))
    userobj.request_reset_password()
    return 'ok'
Exemple #22
0
    def check_allow(self, method):
        """raise exception if user is not owner or in shared"""
        from lib.chai import common, db, sess

        # rest only allowed if owner or shared
        if sess["user"] == self.obj.get("owner"):
            return
        if sess["user"] in [
            a["user"] for a in db.sql("select user from whiteboarduser where parent=%s", self.obj["name"])
        ]:
            return

        raise Exception, "This whiteboard is private"
Exemple #23
0
def _get_obj(type, name):
	"""load an object without any events"""	
	obj = db.sql("select * from `%s` where name=%s" % (type, '%s'), 
		name, as_dict=1)
	if not obj:
		return {}
	else:
		obj = obj[0]
		# add "type" property		
		obj['type'] = type

	load_children(obj, type, name)
		
	return obj
Exemple #24
0
def get():
	import urllib

	site_map = ''
	if getattr(conf, 'app_url', None):
		# list of all Guest pages (static content)
		for r in db.sql("""select name, _updated 
			from page where published=1 and name!='index'
			order by _updated desc"""):
			
			page_url = conf.app_url + '?page=' + urllib.quote(r['name'])
			site_map += link_xml % (page_url, r['_updated'].strftime('%Y-%m-%d'))

	return frame_xml % site_map
Exemple #25
0
def load_children(obj, ttype, name):
	"""get children rows"""	
	for childtype in children_types(ttype):
		obj_list = db.sql("""select * from `%s` where parent=%s and parent_type=%s 
			order by idx asc""" % (childtype,'%s','%s'), (name, ttype))
		obj[childtype] = []
		for child in obj_list:
			del child['parent']
			del child['parent_type']
			del child['idx']

			if len(child.keys())==1 and 'value' in child:
				obj[childtype].append(child['value'])
			else:
				obj[childtype].append(child)
Exemple #26
0
def get():
    import urllib

    site_map = ''
    if getattr(conf, 'app_url', None):
        # list of all Guest pages (static content)
        for r in db.sql("""select name, _updated 
			from page where published=1 and name!='index'
			order by _updated desc"""):

            page_url = conf.app_url + '?page=' + urllib.quote(r['name'])
            site_map += link_xml % (page_url,
                                    r['_updated'].strftime('%Y-%m-%d'))

    return frame_xml % site_map
Exemple #27
0
def _get_obj(type, name):
    """load an object without any events"""
    obj = db.sql("select * from `%s` where name=%s" % (type, '%s'),
                 name,
                 as_dict=1)
    if not obj:
        return {}
    else:
        obj = obj[0]
        # add "type" property
        obj['type'] = type

    load_children(obj, type, name)

    return obj
Exemple #28
0
def load_children(obj, ttype, name):
    """get children rows"""
    for childtype in children_types(ttype):
        obj_list = db.sql(
            """select * from `%s` where parent=%s and parent_type=%s 
			order by idx asc""" % (childtype, '%s', '%s'), (name, ttype))
        obj[childtype] = []
        for child in obj_list:
            del child['parent']
            del child['parent_type']
            del child['idx']

            if len(child.keys()) == 1 and 'value' in child:
                obj[childtype].append(child['value'])
            else:
                obj[childtype].append(child)
	def test_login(self):
		# make a user
		from webob import Request, Response
		import lib.chai

		objstore.insert(type='user', name='test',password='******')
		lib.chai.req = Request.blank('server/?_method=lib.chai.session.login&user=test&password=pass')
		lib.chai.res = Response()

		# login
		ret = session.login(**lib.chai.req.params)
		
		self.sid = lib.chai.res.headers.get('Set-Cookie').split(';')[0].split('=')[1]
		self.assertTrue(ret['userobj']['name']=='test')
		self.assertTrue(ret['message']=='ok')
		self.assertTrue(db.sql("""select * from session where user='******'""")[0]['user']=='test')
Exemple #30
0
def login(**args):
	"""login"""
	from lib.chai import res
	
	import hashlib
	pwd = db.sql("select password from user where name=%s", (args['user'],))
	if pwd: 
		pwd = pwd[0]['password']
	
	if pwd == hashlib.sha256(args.get("password")).hexdigest():
		d = dict(type='session', name=new_sid(), user=args['user'])
		objstore.insert(**d)
		res.set_cookie('sid', d['name'])
		d.update({"message":"ok", "userobj":objstore.get(type='user', name=args['user'])})
		return d
	else:
		return {"error":"Invalid Login"}
Exemple #31
0
def make():
    import os
    from lib.chai import db

    messages = []

    container = '<div class="main container">'

    pages_path = os.path.join(os.path.dirname(__file__), '../../../pages')

    with open(
            os.path.join(os.path.dirname(__file__), '../../..',
                         'template.html'), 'r') as f:
        index_html = f.read()

    index_html = index_html.split(container)

    if len(index_html) != 2:
        return "%s not found" % container

    for page in db.sql("select * from page", as_dict=1):
        html = index_html[0] + container +\
         '\n<!-- generated via pages.py -->' +\
         ('\n<div class="content active" id="%s">' % page['name']) +\
         '\n' + page.get('html') +\
         (page.get('css') and '\n<style>\n%s\n</style>' % page['css'] or '') +\
         (page.get('js') and '\n<script>\n%s\n</script>' % page['js'] or '') +\
         '\n</div>\n' +\
         index_html[1]

        # title
        html = html.split('<title>')
        html = html[0] +\
         '<title>' + page.get('label', page.get('name')) + '</title>' +\
          html[1].split('</title>')[1]

        with open(os.path.join(pages_path, page['name'] + '.html'), 'w') as f:
            f.write(html)

        messages.append("wrote %s %sk" %
                        (page['name'] + '.html', len(html) / 1024))

    return messages
Exemple #32
0
def login(**args):
    """login"""
    from lib.chai import res

    import hashlib
    pwd = db.sql("select password from user where name=%s", (args['user'], ))
    if pwd:
        pwd = pwd[0]['password']

    if pwd == hashlib.sha256(args.get("password")).hexdigest():
        d = dict(type='session', name=new_sid(), user=args['user'])
        objstore.insert(**d)
        res.set_cookie('sid', d['name'])
        d.update({
            "message": "ok",
            "userobj": objstore.get(type='user', name=args['user'])
        })
        return d
    else:
        return {"error": "Invalid Login"}
Exemple #33
0
    def test_login(self):
        # make a user
        from webob import Request, Response
        import lib.chai

        objstore.insert(type='user', name='test', password='******')
        lib.chai.req = Request.blank(
            'server/?_method=lib.chai.session.login&user=test&password=pass')
        lib.chai.res = Response()

        # login
        ret = session.login(**lib.chai.req.params)

        self.sid = lib.chai.res.headers.get('Set-Cookie').split(';')[0].split(
            '=')[1]
        self.assertTrue(ret['userobj']['name'] == 'test')
        self.assertTrue(ret['message'] == 'ok')
        self.assertTrue(
            db.sql("""select * from session where user='******'""")[0]['user'] ==
            'test')
Exemple #34
0
def make():
	import os
	from lib.chai import db
	
	messages = []
	
	container = '<div class="main container">'

	pages_path = os.path.join(os.path.dirname(__file__), '../../../pages')
	
	with open(os.path.join(os.path.dirname(__file__), '../../..', 'template.html'),'r') as f:
		index_html = f.read()

	index_html = index_html.split(container)

	if len(index_html)!=2:
		return "%s not found" % container
	
	for page in db.sql("select * from page", as_dict=1):
		html = index_html[0] + container +\
			'\n<!-- generated via pages.py -->' +\
			('\n<div class="content active" id="%s">' % page['name']) +\
			'\n' + page.get('html') +\
			(page.get('css') and '\n<style>\n%s\n</style>' % page['css'] or '') +\
			(page.get('js') and '\n<script>\n%s\n</script>' % page['js'] or '') +\
			'\n</div>\n' +\
			index_html[1]
		
		# title
		html = html.split('<title>')
		html = html[0] +\
			'<title>' + page.get('label', page.get('name')) + '</title>' +\
		 	html[1].split('</title>')[1]
		
		with open(os.path.join(pages_path, page['name'] + '.html'), 'w') as f:
			f.write(html)

		messages.append("wrote %s %sk" % (page['name'] + '.html', len(html)/1024))

	return messages
Exemple #35
0
def get(**args):
	"""
	execute a select query
	
	Parameters:
	type
	columns = "a,b,c"
	filters = [["a","=","5"],]
	order_by = "a asc"
	limit = "20, 20"
	"""
	import json
	
	if 'json' in args:
		args.update(json.loads(args['json']))

	if 'order_by' in args:
		args['order_by'] = ' order by ' + args['order_by']

	if 'limit' in args:
		args['limit'] = ' limit ' + args['limit']
	
	args.setdefault('order_by','')
	args.setdefault('limit','')
	args.setdefault('conditions','')
	args.setdefault('values', ())

	# conditions
	if 'filters' in args:
		if typemethod(args['filters']) in (str, unicode):
			args['filters'] = json.loads(args['filters'])
			
		args['conditions'] = 'where ' + \
			' and '.join(['`%s` %s %s' % (f[0], f[1], '%s') for f in args['filters']])
		args['values'] = tuple([f[2] for f in args['filters']])
	
	return {"result": db.sql("""select %(columns)s 
		from `%(type)s` 
		%(conditions)s 
		%(order_by)s %(limit)s""" % args, args['values'], as_dict=1)}
Exemple #36
0
def get():
    """generate"""
    items = []
    if getattr(conf, 'app_url', None):
        # list of all Guest pages (static content)
        for r in db.sql("""select name, label, _updated
		from page where published=1 and name!='index'
		order by _updated desc"""):
            link = conf.app_url + '?page=' + urllib.quote(r['name'])
            items.append(
                rssgen.RSS2(title=r['label'],
                            link=link,
                            description=r.get('description', ''),
                            pubDate=r['_updated']))

        rss = rssgen.RSS2(title=conf.app_title,
                          link=conf.app_url,
                          description=getattr(conf, 'description', ''),
                          lastBuildDate=datetime.datetime.utcnow(),
                          items=items)

        return rss.to_xml()
Exemple #37
0
def get():
	"""generate"""
	items = []
	if getattr(conf, 'app_url', None):
		# list of all Guest pages (static content)
		for r in db.sql("""select name, label, _updated
		from page where published=1 and name!='index'
		order by _updated desc"""):
			link = conf.app_url + '?page=' + urllib.quote(r['name'])
			items.append(rssgen.RSS2(
				title = r['label'],
				link = link,
				description = r.get('description', ''),
				pubDate = r['_updated']
			))

		rss = rssgen.RSS2(
			title=conf.app_title,
			link=conf.app_url,
			description = getattr(conf, 'description', ''),
			lastBuildDate = datetime.datetime.utcnow(),
			items = items)		
		
		return rss.to_xml()
Exemple #38
0
def delete_children(parenttype, parent):
	"""delete all children of the given object"""
	for child_tab in children_types(parenttype):
		db.sql("""delete from `%s` where parent=%s and parent_type=%s""" \
			% (child_tab,'%s','%s'), (parent, parenttype))
Exemple #39
0
 def test_delete(self):
     self.test_insert()
     objstore.delete(type="user", name="testuser")
     self.assertFalse(
         db.sql("""select * from user where name='testuser'"""))
Exemple #40
0
 def test_insert(self):
     objstore.insert(type="user", name="testuser", email="testmail")
     obj = db.sql("""select * from user where name='testuser'""")[0]
     self.assertTrue(obj['email'] == 'testmail')
Exemple #41
0
def children_types(parenttype):
	"""get children types for parent type from table `_parent_child`"""
	return [c['child'] for c in \
		db.sql("select child from _parent_child where parent=%s", parenttype)]				
Exemple #42
0
 def test_delete(self):
     self.test_get()
     rdfstore.delete(name='o1')
     self.assertFalse(
         db.sql("select * from rdf_triple where subject=%s", 'o1'))
Exemple #43
0
def delete_obj(type, name):
    """delete object and its children"""
    db.sql("""delete from `%s` where name=%s""" % (type, '%s'), name)
    delete_children(type, name)
Exemple #44
0
def exists(obj):
    """check exists by name"""
    if obj.get('name') and obj.get('type'):
        return db.sql("select name from `%s` where name=%s" % \
          (obj['type'],'%s'), obj['name'])
Exemple #45
0
def logout(**args):
	"""logout"""
	from lib.chai import req
	user = db.sql("""select user from session where name=%s""", req.cookies['sid'])[0]['user']
	db.sql("delete from session where user=%s", user)
Exemple #46
0
	def triples(self, s, p, o=None):
		"""Return matching triples"""
		cond, values = self.get_matching_conditions(s, p, o)
		return db.sql("""select `subject`, `predicate`, `object` 
			from rdf_triple where %s""" % ' and '.join(cond), values, as_dict=False)
Exemple #47
0
def exists(obj):
	"""check exists by name"""	
	if obj.get('name') and obj.get('type'):
		return db.sql("select name from `%s` where name=%s" % \
		 	(obj['type'],'%s'), obj['name'])
Exemple #48
0
def delete_obj(type, name):
	"""delete object and its children"""
	db.sql("""delete from `%s` where name=%s""" % (type, '%s'), name)
	delete_children(type, name)
Exemple #49
0
 def remove(self, s, p, o):
     """Remove matching triples"""
     cond, values = self.get_matching_conditions(s, p, o)
     return db.sql("""delete from rdf_triple where %s""" % \
      ' and '.join(cond), values)
Exemple #50
0
def delete_children(parenttype, parent):
    """delete all children of the given object"""
    for child_tab in children_types(parenttype):
        db.sql("""delete from `%s` where parent=%s and parent_type=%s""" \
         % (child_tab,'%s','%s'), (parent, parenttype))
Exemple #51
0
def logout(**args):
    """logout"""
    from lib.chai import req
    user = db.sql("""select user from session where name=%s""",
                  req.cookies['sid'])[0]['user']
    db.sql("delete from session where user=%s", user)
	def test_insert(self):
		objstore.insert(type="user", name="testuser", email="testmail")
		obj = db.sql("""select * from user where name='testuser'""")[0]
		self.assertTrue(obj['email'] == 'testmail')
	def test_delete(self):
		self.test_insert()
		objstore.delete(type="user", name="testuser")
		self.assertFalse(db.sql("""select * from user where name='testuser'"""))
Exemple #54
0
    def tearDown(self):
        # cleanup
        objstore.delete(type='user', name='test')
        db.sql("""delete from session where user='******'""")

        db.rollback()
Exemple #55
0
 def test_delete(self):
     self.test_get()
     rdfstore.delete(name="o1")
     self.assertFalse(db.sql("select * from rdf_triple where subject=%s", "o1"))