def sendmail_to_signatory(user, pid): p = db.select('petition', where='id=$pid', vars=locals())[0] p.url = 'http//watchdog.net/c/%s' % (pid) token = auth.get_secret_token(user.email) msg = render_plain.signatory_mailer(user, p, token) #@@@ shouldn't this web.utf8 stuff taken care by in web.py? web.sendmail(web.utf8(config.from_address), web.utf8(user.email), web.utf8(msg.subject.strip()), web.utf8(msg))
def getkeys(self, namespace, lang=None): namespace = web.utf8(namespace) lang = web.utf8(lang) # making a simplified assumption here. # Keys for a language are all the strings defined for that language and # all the strings defined for default language. By doing this, once a key is # added to default lang, then it will automatically appear in all other languages. keys = set(self._data.get((namespace, lang), {}).keys() + self._data.get((namespace, DEFAULT_LANG), {}).keys()) return sorted(keys)
def simple_diff(a, b): a = a or '' b = b or '' if a is None: a = '' if b is None: b = '' a = web.utf8(a).split(' ') b = web.utf8(b).split(' ') out = [] for (tag, i1, i2, j1, j2) in SequenceMatcher(a=a, b=b).get_opcodes(): out.append(web.storage(tag=tag, left=' '.join(a[i1:i2]), right=' '.join(b[j1:j2]))) return out
def simple_diff(a, b): a = a or '' b = b or '' if a is None: a = '' if b is None: b = '' a = web.utf8(a).split(' ') b = web.utf8(b).split(' ') out = [] for (tag, i1, i2, j1, j2) in SequenceMatcher(a=a, b=b).get_opcodes(): out.append( web.storage(tag=tag, left=' '.join(a[i1:i2]), right=' '.join(b[j1:j2]))) return out
def replace_macros(html, macros): """Replaces the macro place holders with real macro output.""" for placeholder, macro_info in macros.items(): name, args = macro_info html = html.replace("<p>%s\n</p>" % placeholder, web.utf8(call_macro(name, args))) return html
def output(string_): """Appends `string_` to the response.""" string_ = web.utf8(string_) if web.ctx.get('flush'): web.ctx._write(string_) else: web.ctx.output += str(string_)
def __disabled_POST(self): i = web.input(_method='post') i['type.key'] = '/type/comment' i['_comment'] = '' path = '/c/'+ str(get_random_string()) # prevent most common spam if 'url' in i['comment'] and 'link' in i['comment'] and 'http://' in i['comment']: return web.seeother(i['article.key']) if '<a href' in i['comment'] and 'http://' in i['comment']: return web.seeother(i['article.key']) if i['website'] in ['http://www.yahoo.com/', 'http://www.google.com/', 'http://www.bing.com/', "http://www.facebook.com/"]: return web.seeother(i['article.key']) query = { 'key': path, 'type': {'key': "/type/comment"}, 'article': {"key": i["article.key"]}, 'comment': {'type': '/type/text', 'value': i['comment']}, 'author': i['author'], 'website': i['website'], 'email': i['email'], 'permission': {'key': '/permission/restricted'} } web.ctx.site.save(query, comment='new comment') c = web.ctx.site.get(path) msg = render.comment_email(c, web.ctx.home) try: web.sendmail(config.from_address, config.comment_recipients, web.utf8(msg.subject).strip(), web.utf8(msg)) except: import traceback traceback.print_exc() web.seeother(i['article.key']+"#comments")
def __str__(self): def get(lang): return self._i18n._data.get((self._namespace, lang)) default_data = get(DEFAULT_LANG) or {} data = get(web.ctx.lang) or default_data text = data.get(self._key) or default_data.get(self._key) or self._key return web.utf8(text)
def __call__(self, *a): try: a = [x or "" for x in a] return str(self) % tuple(web.utf8(x) for x in a) except: print >> web.debug, 'failed to substitute (%s/%s) in language %s' % (self._namespace, self._key, web.ctx.lang) return str(self)
def _load_template(page, lazy=False): """load template from a wiki page.""" if lazy: page = web.storage(key=page.key, body=web.utf8(_stringify(page.body))) wikitemplates[page.key] = LazyTemplate(lambda: _load_template(page)) else: wikitemplates[page.key] = _compile_template(page.key, page.body)
def __call__(self, handler): # temp hack to handle languages and users during upstream-to-www migration if web.ctx.path.startswith("/l/"): raise web.seeother("/languages/" + web.ctx.path[len("/l/"):]) if web.ctx.path.startswith("/user/"): if not web.ctx.site.get(web.ctx.path): raise web.seeother("/people/" + web.ctx.path[len("/user/"):]) real_path, readable_path = get_readable_path(web.ctx.site, web.ctx.path, self.patterns, encoding=web.ctx.encoding) #@@ web.ctx.path is either quoted or unquoted depends on whether the application is running #@@ using builtin-server or lighttpd. Thats probably a bug in web.py. #@@ take care of that case here till that is fixed. # @@ Also, the redirection must be done only for GET requests. if readable_path != web.ctx.path and readable_path != urllib.quote( web.utf8(web.ctx.path)) and web.ctx.method == "GET": raise web.redirect( web.safeunicode(readable_path) + web.safeunicode(web.ctx.query)) web.ctx.readable_path = readable_path web.ctx.path = real_path web.ctx.fullpath = web.ctx.path + web.ctx.query out = handler() V2_TYPES = ['works', 'books'] if any(web.ctx.path.startswith('/%s/' % _type) for _type in V2_TYPES): out.v2 = True return out
def __call__(self, handler): # temp hack to handle languages and users during upstream-to-www migration if web.ctx.path.startswith("/l/"): raise web.seeother("/languages/" + web.ctx.path[len("/l/"):]) if web.ctx.path.startswith("/user/"): if not web.ctx.site.get(web.ctx.path): raise web.seeother("/people/" + web.ctx.path[len("/user/"):]) real_path, readable_path = get_readable_path(web.ctx.site, web.ctx.path, self.patterns, encoding=web.ctx.encoding) #@@ web.ctx.path is either quoted or unquoted depends on whether the application is running #@@ using builtin-server or lighttpd. Thats probably a bug in web.py. #@@ take care of that case here till that is fixed. # @@ Also, the redirection must be done only for GET requests. if readable_path != web.ctx.path and readable_path != urllib.quote(web.utf8(web.ctx.path)) and web.ctx.method == "GET": raise web.redirect(web.safeunicode(readable_path) + web.safeunicode(web.ctx.query)) web.ctx.readable_path = readable_path web.ctx.path = real_path web.ctx.fullpath = web.ctx.path + web.ctx.query out = handler() V2_TYPES = ['works', 'books', 'people', 'authors', 'publishers', 'languages', 'account'] if out and any(web.ctx.path.startswith('/%s/' % _type) for _type in V2_TYPES): out.v2 = True return out
def GET(self): i = web.input(prefix="") if len(i.prefix) > 2: q = { 'type': '/type/author', 'name~': i.prefix + '*', 'sort': 'name', 'limit': 5 } things = web.ctx.site.things(q) things = [web.ctx.site.get(key) for key in things] result = [ dict(type=[{ 'id': t.key, 'name': t.key }], name=web.utf8(t.name), guid=t.key, id=t.key, article=dict(id=t.key)) for t in things ] else: result = [] callback = i.pop('callback', None) d = dict(status="200 OK", query=dict(i, escape='html'), code='/api/status/ok', result=result) if callback: data = '%s(%s)' % (callback, simplejson.dumps(d)) else: data = simplejson.dumps(d) raise web.HTTPError('200 OK', {}, data)
def replace_header(hdr, value): """ 设置header """ hdr, value = web.utf8(hdr), web.utf8(value) # protection against HTTP response splitting attack if '\n' in hdr or '\r' in hdr or '\n' in value or '\r' in value: raise ValueError, 'invalid characters in header' for i, temp in enumerate(web.ctx.headers): h, v = temp if h.lower() == hdr.lower(): web.ctx.headers[i] = (hdr, value) break else: web.ctx.headers.append((hdr, value))
def _load_macro(page, lazy=False): if lazy: page = web.storage(key=page.key, macro=web.utf8(_stringify(page.macro)), description=page.description or "") wikimacros[page.key] = LazyTemplate(lambda: _load_macro(page)) else: t = _compile_template(page.key, page.macro) t.__doc__ = page.description or '' wikimacros[page.key] = t
def POST(self): post = web.input() if post.get('u_email') and post.get('u_pass'): user = pduser.loaduser_by_email(post.u_email) if user and user.u_pass==md5.new(web.utf8(post.u_pass)).hexdigest(): login.Login.encode_cookie(user.u_id) return web.seeother(web.ctx.sitehost+web.input().get('ref',"/")) return render.login(post)
def safeeval_args(args): """Evalues the args string safely using templator.""" result = [None] def f(*args, **kwargs): result[0] = args, kwargs code = "$def with (f)\n$f(%s)" % args web.template.Template(web.utf8(code))(f) return result[0]
def internal_redirect(path, method, query, data): # does an internal redirect within the application from webapp import app env = web.ctx.env env['REQUEST_METHOD'] = method env['PATH_INFO'] = path env['QUERY_STRING'] = web.utf8(query) cookie_headers = [(k, v) for k, v in web.ctx.headers if k == 'Set-Cookie'] app.load(env) env['HTTP_COOKIE'] = env.get('HTTP_COOKIE', '') + ';' + ";".join([v for (k, v) in cookie_headers]) web.ctx.headers = cookie_headers if method == 'POST': web.ctx.data = web.utf8(data) return app.handle()
def internal_redirect(path, method, query, data): # does an internal redirect within the application from webapp import app env = web.ctx.env env['REQUEST_METHOD'] = method env['PATH_INFO'] = path env['QUERY_STRING'] = web.utf8(query) cookie_headers = [(k, v) for k, v in web.ctx.headers if k == 'Set-Cookie'] app.load(env) env['HTTP_COOKIE'] = env.get('HTTP_COOKIE', '') + ';' + ";".join( [v for (k, v) in cookie_headers]) web.ctx.headers = cookie_headers if method == 'POST': web.ctx.data = web.utf8(data) return app.handle()
def POST(self): post = web.input() post.u_create_time = int(time.time()) post.u_email = web.utf8(post.get('u_email')) post.u_name = web.utf8(post.get('u_name')) #change to md5 post.u_pass = md5.new(web.utf8(post.u_pass)).hexdigest() try: idlist = pduser.insert_by_list([post]) newid = idlist.pop() if newid: #表示注册成功 login.Login.encode_cookie(newid) #保存注册信息 #return web.seeother(web.ctx.sitehost+"/me/setting/basic") # go to accounts index return web.seeother(web.ctx.sitehost) # go to accounts index except: pass return render.register(post)
def POST(self): post = web.input() if post.get('u_email') and post.get('u_pass'): user = pduser.loaduser_by_email(post.u_email) if user and user.u_pass == md5.new(web.utf8( post.u_pass)).hexdigest(): login.Login.encode_cookie(user.u_id) return web.seeother(web.ctx.sitehost + web.input().get('ref', "/")) return render.login(post)
def _compile_template(name, text): text = web.utf8(_stringify(text)) try: return web.template.Template(text, filter=web.websafe, filename=name) except (web.template.ParseError, SyntaxError) as e: print('Template parsing failed for ', name, file=web.debug) import traceback traceback.print_exc() raise ValidationException("Template parsing failed: " + str(e))
def _compile_template(name, text): text = web.utf8(_stringify(text)) try: return web.template.Template(text, filter=web.websafe, filename=name) except (web.template.ParseError, SyntaxError), e: print >> web.debug, 'Template parsing failed for ', name import traceback traceback.print_exc() raise ValidationException("Template parsing failed: " + str(e))
def header(self, hdr, value, unique=True): """ Adds 'hdr: value' to the response. @type hdr: str @param hdr: valid http header key @type value: str @param value: valid value for corresponding header key @type unique: bool @param unique: whether only one instance of the header is permitted. """ hdr = web.utf8(hdr) value = web.utf8(value) previous = [] for h, v in web.ctx.headers: if h.lower() == hdr.lower(): previous.append((h, v)) if unique: for p in previous: web.ctx.headers.remove(p) web.ctx.headers.append((hdr, value))
def GET(self, id): db = NovelDB() novel = db.get_novel_info(id) file = get_txt_file(str(id), web.utf8(novel.title)) if file: web.replace_header("Content-Type", "text/plaintext") web.replace_header("Content-Disposition", "attachment; filename=%s.txt" % id) web.header("X-Accel-Redirect", "/download_txt/%s" % file) return "ok" else: return "出错了,请联系[email protected]"
def header(hdr, value, unique=True): """ Adds 'hdr: value' to the response. This function has, in some regards, the opposite semantics of the web.header function. If unique is True, the hdr will be overwritten if it already exists in the response. Otherwise it will be appended. @type hdr: str @param hdr: valid http header key @type value: str @param value: valid value for corresponding header key @type unique: bool @param unique: whether only one instance of the header is in the response """ hdr = web.utf8(hdr) value = web.utf8(value) previous = [] for h, v in web.ctx.headers: if h.lower() == hdr.lower(): previous.append((h, v)) if unique: for p in previous: web.ctx.headers.remove(p) web.ctx.headers.append((hdr, value))
def __call__(self, handler): real_path, readable_path = self.get_readable_path(web.ctx.path, encoding=web.ctx.encoding) #@@ web.ctx.path is either quoted or unquoted depends on whether the application is running #@@ using builtin-server or lighttpd. Thats probably a bug in web.py. #@@ take care of that case here till that is fixed. # @@ Also, the redirection must be done only for GET requests. if readable_path != web.ctx.path and readable_path != urllib.quote(web.utf8(web.ctx.path)) and web.ctx.method == "GET": raise web.seeother(web.safeunicode(readable_path) + web.safeunicode(web.ctx.query)) web.ctx.readable_path = readable_path web.ctx.path = real_path web.ctx.fullpath = web.ctx.path + web.ctx.query return handler()
def GET(self): i = web.input(prefix="") if len(i.prefix) > 2: q = {'type': '/type/author', 'name~': i.prefix + '*', 'sort': 'name', 'limit': 5} things = web.ctx.site.things(q) things = [web.ctx.site.get(key) for key in things] result = [dict(type=[{'id': t.key, 'name': t.key}], name=web.utf8(t.name), guid=t.key, id=t.key, article=dict(id=t.key)) for t in things] else: result = [] callback = i.pop('callback', None) d = dict(status="200 OK", query=dict(i, escape='html'), code='/api/status/ok', result=result) if callback: data = '%s(%s)' % (callback, simplejson.dumps(d)) else: data = simplejson.dumps(d) raise web.HTTPError('200 OK', {}, data)
def readable_url_processor(handler): patterns = [ (r'/b/OL\d+M', '/type/edition', 'title'), (r'/a/OL\d+A', '/type/author', 'name'), (r'/w/OL\d+W', '/type/work', 'title'), (r'/s/OL\d+S', '/type/series', 'title'), ] def get_readable_path(): path = get_real_path() if web.ctx.get('encoding') is not None: return web.ctx.path for pat, type, property in patterns: if web.re_compile('^' + pat + '$').match(path): thing = web.ctx.site.get(path) if thing is not None and thing.type.key == type and thing[property]: title = thing[property].replace(' ', '-').encode('utf-8') return path + '/' + urllib.quote(title) return web.ctx.path def get_real_path(): pat = '^(' + '|'.join(p[0] for p in patterns) + ')(?:/.*)?' rx = web.re_compile(pat) m = rx.match(web.ctx.path) if m: path = m.group(1) return m.group(1) else: return web.ctx.path readable_path = get_readable_path() #@@ web.ctx.path is either quoted or unquoted depends on whether the application is running #@@ using builtin-server or lighttpd. Thats probably a bug in web.py. #@@ take care of that case here till that is fixed. # @@ Also, the redirection must be done only for GET requests. if readable_path != web.ctx.path and readable_path != urllib.quote(web.utf8(web.ctx.path)) and web.ctx.method == "GET": raise web.seeother(readable_path + web.ctx.query.encode('utf-8')) web.ctx.readable_path = readable_path web.ctx.path = get_real_path() web.ctx.fullpath = web.ctx.path + web.ctx.query return handler()
def sendfindpass(user, hash): link = "%s/account/newpass?%s" % (web.ctx.sitehost, urllib.urlencode({ 'email': user.u_email, "v": hash })) mail_body = """ <html> <head></head> <body> <h4>%s,你好</h4> 您刚才在 liulin.info 申请了找回密码。<br> 请点击下面的链接来重置密码:<br> <a href="%s">%s</a><br> 如果无法点击上面的链接,您可以复制该地址,并粘帖在浏览器的地址栏中访问。<br> </body> </html> """ % (web.utf8(user.u_name), link, link) #mail_body = web.utf8(mail_body) if isinstance(mail_body, unicode): mail_body = str(mail_body) mail_from = "liulin.info<*****@*****.**>" mail_to = user.u_email mail_subject = 'liulin.info重置密码邮件' msg = MIMEText(mail_body, 'html', 'utf-8') #msg=MIMEText(mail_body,'html') if not isinstance(mail_subject, unicode): mail_subject = unicode(mail_subject) msg['Subject'] = mail_subject msg['From'] = mail_from msg['To'] = mail_to msg["Accept-Language"] = "zh-CN" msg["Accept-Charset"] = "ISO-8859-1,utf-8" smtp = smtplib.SMTP() smtp.connect('smtp.163.com') smtp.login('*****@*****.**', '831112') smtp.sendmail(mail_from, mail_to, msg.as_string()) smtp.quit()
def GET(self, path): i = web.input() callback = i.pop('callback', None) author = web.ctx.site.get('/' +path) body = '' if author.birth_date or author.death_date: body = "%s - %s" % (author.birth_date, author.death_date) else: body = "%s" % author.date body += "<br/>" if author.bio: body += web.utf8(author.bio) result = dict(body=body, media_type="text/html", text_encoding="utf-8") d = dict(status="200 OK", code="/api/status/ok", result=result) if callback: data = '%s(%s)' % (callback, simplejson.dumps(d)) else: data = simplejson.dumps(d) raise web.HTTPError('200 OK', {}, data)
def __call__(self, handler): # temp hack to handle languages and users during upstream-to-www migration if web.ctx.path.startswith("/l/"): raise web.seeother("/languages/" + web.ctx.path[len("/l/"):]) if web.ctx.path.startswith("/user/"): if not web.ctx.site.get(web.ctx.path): raise web.seeother("/people/" + web.ctx.path[len("/user/"):]) real_path, readable_path = self.get_readable_path(web.ctx.path, encoding=web.ctx.encoding) #@@ web.ctx.path is either quoted or unquoted depends on whether the application is running #@@ using builtin-server or lighttpd. Thats probably a bug in web.py. #@@ take care of that case here till that is fixed. # @@ Also, the redirection must be done only for GET requests. if readable_path != web.ctx.path and readable_path != urllib.quote(web.utf8(web.ctx.path)) and web.ctx.method == "GET": raise web.redirect(web.safeunicode(readable_path) + web.safeunicode(web.ctx.query)) web.ctx.readable_path = readable_path web.ctx.path = real_path web.ctx.fullpath = web.ctx.path + web.ctx.query return handler()
def GET(self, path): i = web.input() callback = i.pop('callback', None) author = web.ctx.site.get('/' + path) body = '' if author.birth_date or author.death_date: body = "%s - %s" % (author.birth_date, author.death_date) else: body = "%s" % author.date body += "<br/>" if author.bio: body += web.utf8(author.bio) result = dict(body=body, media_type="text/html", text_encoding="utf-8") d = dict(status="200 OK", code="/api/status/ok", result=result) if callback: data = '%s(%s)' % (callback, simplejson.dumps(d)) else: data = simplejson.dumps(d) raise web.HTTPError('200 OK', {}, data)
def sendfindpass(user,hash): link = "%s/account/newpass?%s" %(web.ctx.sitehost,urllib.urlencode({'email':user.u_email,"v":hash})) mail_body = """ <html> <head></head> <body> <h4>%s,你好</h4> 您刚才在 liulin.info 申请了找回密码。<br> 请点击下面的链接来重置密码:<br> <a href="%s">%s</a><br> 如果无法点击上面的链接,您可以复制该地址,并粘帖在浏览器的地址栏中访问。<br> </body> </html> """ % (web.utf8(user.u_name),link,link) #mail_body = web.utf8(mail_body) if isinstance(mail_body,unicode): mail_body = str(mail_body) mail_from = "liulin.info<*****@*****.**>" mail_to = user.u_email mail_subject = 'liulin.info重置密码邮件' msg = MIMEText(mail_body,'html','utf-8') #msg=MIMEText(mail_body,'html') if not isinstance(mail_subject,unicode): mail_subject = unicode(mail_subject) msg['Subject']= mail_subject msg['From']=mail_from msg['To'] = mail_to msg["Accept-Language"]="zh-CN" msg["Accept-Charset"]="ISO-8859-1,utf-8" smtp=smtplib.SMTP() smtp.connect('smtp.163.com') smtp.login('*****@*****.**','831112') smtp.sendmail(mail_from,mail_to,msg.as_string()) smtp.quit()
def __getitem__(self, key): namespace = web.ctx.get('i18n_namespace', '/') key = web.utf8(key) return i18n_string(self, namespace, key)
def _generate_salted_hash(self, key, text, salt=None): salt = salt or hmac.HMAC(key, str(random.random())).hexdigest()[:5] hash = hmac.HMAC(key, web.utf8(salt) + web.utf8(text)).hexdigest() return '%s$%s' % (salt, hash)
def get_email(user): try: delegate.admin_login() return web.utf8(web.ctx.site.get_user_email(user.key).email) finally: web.ctx.headers = []
def process(self, query): query = web.utf8(query) tokens = query.split(' ') return " ".join(self.process_token(t) for t in tokens)
def _update_strings(self, namespace, lang, data): namespace = web.utf8(namespace) lang = web.utf8(lang) self._data.setdefault((namespace, lang), {}).update(data)
def _set_strings(self, namespace, lang, data): namespace = web.utf8(namespace) lang = web.utf8(lang) self._data[namespace, lang] = dict(data)
def get(self, namespace, key): namespace = web.utf8(namespace) key = web.utf8(key) return i18n_string(self, namespace, key)
def __str__(self): return web.utf8(self.key)
def generate_hash(secret_key, text, salt=None): salt = salt or hmac.HMAC(secret_key, str(random.random())).hexdigest()[:5] hash = hmac.HMAC(secret_key, salt + web.utf8(text)).hexdigest() return '%s$%s' % (salt, hash)
def template(page, *a, **kw): default_template = getattr(render, 'default_' + name, None) key = page.type.key[1:] + '/' + name t = getattr(render, web.utf8(key), default_template) return t(page, *a, **kw)