code stringlengths 1 1.72M | language stringclasses 1 value |
|---|---|
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Carrasco <jose.carrasco[a]vikuit.com>
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
import wsgiref.handlers
from handlers import *
from handlers import Updater
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
# webapp.template.register_template_library('django.contrib.markup.templatetags.markup')
webapp.template.register_template_library('templatefilters')
def main():
Updater.update()
application = webapp.WSGIApplication(
[('/', MainPage),
# Module articles
('/module/article.list', ArticleList),
('/module/article.edit', ArticleEdit),
('/module/article.favourite', ArticleFavourite),
('/module/article.vote', ArticleVote),
('/module/article/.*', ArticleView),
('/module/article.comment.subscribe',ArticleCommentSubscribe),
('/module/article.comment', ArticleComment),
('/module/article.delete', ArticleDelete),
('/module/article.comment.delete', ArticleCommentDelete),
('/module/article.add.communities', ArticleAddCommunities),
('/module/article.comment.edit', ArticleCommentEdit),
('/module/article.visit', ArticleVisit),
# Module users
('/module/user.list', UserList),
('/module/user/.*', UserView),
('/module/user.edit', UserEdit),
('/module/user.register', UserRegister),
('/module/user.login', UserLogin),
('/module/user.logout', UserLogout),
('/module/user.changepassword', UserChangePassword),
('/module/user.forgotpassword', UserForgotPassword),
('/module/user.resetpassword', UserResetPassword),
('/module/user.drafts', UserDrafts),
('/module/user.articles/.*', UserArticles),
('/module/user.communities/.*', UserCommunities),
('/module/user.favourites/.*', UserFavourites),
('/module/user.contacts/.*', UserContacts),
('/module/user.contact', UserContact),
('/module/user.promote', UserPromote),
('/module/user.events', UserEvents),
('/module/user.forums/.*', UserForums),
# Module Community
('/module/community.list', CommunityList),
('/module/community.edit', CommunityEdit),
('/module/community.move', CommunityMove),
('/module/community.delete', CommunityDelete),
('/module/community/.*', CommunityView),
('/module/community.add.related', CommunityAddRelated),
# Community forums
('/module/community.forum.list/.*', CommunityForumList),
('/module/community.forum.edit', CommunityForumEdit),
('/module/community.forum/.*', CommunityForumView),
('/module/community.forum.reply', CommunityForumReply),
('/module/community.forum.subscribe',CommunityForumSubscribe),
('/module/community.forum.delete', CommunityForumDelete),
('/module/community.thread.edit', CommunityThreadEdit),
('/module/community.forum.move', CommunityForumMove),
('/module/community.forum.visit', CommunityForumVisit),
# Community articles
('/module/community.article.list/.*',CommunityArticleList),
('/module/community.article.add', CommunityNewArticle),
('/module/community.article.delete', CommunityArticleDelete),
# Community users
('/module/community.user.list/.*', CommunityUserList),
('/module/community.user.unjoin', CommunityUserUnjoin),
('/module/community.user.join', CommunityUserJoin),
# messages
('/message.edit', MessageEdit),
('/message.sent', MessageSent),
('/message.inbox', MessageInbox),
('/message.read/.*', MessageRead),
('/message.delete', MessageDelete),
# forums,
('/forum.list', ForumList),
# inviting contacts
('/invite', Invite),
# rss
('/feed/.*', Feed),
('/module/mblog.edit', MBlogEdit),
('/module/mblog/mblog.list', Dispatcher),
('/tag/.*', Tag),
('/search', Search),
('/search.result', SearchResult),
# images
('/images/upload', ImageUploader),
('/images/browse', ImageBrowser),
('/images/.*', ImageDisplayer),
# module admin
('/admin', Admin),
('/module/admin.application', AdminApplication),
('/module/admin.categories', AdminCategories),
('/module/admin.category.edit', AdminCategoryEdit),
('/module/admin.users', AdminUsers),
('/module/admin.lookandfeel', AdminLookAndFeel),
('/module/admin.modules', AdminModules),
('/module/admin.mail', AdminMail),
('/module/admin.google', AdminGoogle),
('/module/admin.stats', AdminStats),
('/module/admin.cache', AdminCache),
# Ohters
('/mail.queue', MailQueue),
('/task.queue', TaskQueue),
#General
('/about', Dispatcher),
#('/initialization', Initialization),
('/html/.*', Static),
('/.*', NotFound)],
debug=True)
wsgiref.handlers.CGIHandler().run(application)
if __name__ == "__main__":
main()
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from django import template
from google.appengine.ext import webapp
from utilities.AppProperties import AppProperties
register = webapp.template.create_template_register()
import datetime
def relativize(value):
now = datetime.datetime.now()
diff = now - value
days = diff.days
seconds = diff.seconds
if days > 365:
return getLocale("%d years") % (days / 365, )
if days > 30:
return getLocale("%d months") % (days / 30, )
if days > 0:
return getLocale("%d days") % (days, )
if seconds > 3600:
return getLocale("%d hours") % (seconds / 3600, )
if seconds > 60:
return getLocale("%d minutes") % (seconds / 60, )
return getLocale("%d seconds") % (seconds, )
register.filter(relativize)
def nolinebreaks(value):
return ' '.join(str(value).splitlines())
register.filter(nolinebreaks)
def markdown(value, arg=''):
try:
import markdown
except ImportError:
return "error"
else:
extensions=arg.split(",")
return markdown.markdown(value, extensions, safe_mode=True)
register.filter(markdown)
def smiley(value):
value = value.replace(' :)', ' <img src="/static/images/smileys/smile.png" class="icon" alt=":)" />')
value = value.replace(' :-)', ' <img src="/static/images/smileys/smile.png" class="icon" alt=":-)" />')
value = value.replace(' :D', ' <img src="/static/images/smileys/jokingly.png" class="icon" alt=":D" />')
value = value.replace(' :-D', ' <img src="/static/images/smileys/jokingly.png" class="icon" alt=":-D" />')
value = value.replace(' :(', ' <img src="/static/images/smileys/sad.png" class="icon" alt=":(" />')
value = value.replace(' :-(', ' <img src="/static/images/smileys/sad.png" class="icon" alt=":-(" />')
value = value.replace(' :|', ' <img src="/static/images/smileys/indifference.png" class="icon" alt=":|" />')
value = value.replace(' :-|', ' <img src="/static/images/smileys/indifference.png" class="icon" alt=":-|" />')
value = value.replace(' :O', ' <img src="/static/images/smileys/surprised.png" class="icon" alt=":O" />')
value = value.replace(' :/', ' <img src="/static/images/smileys/think.png" class="icon" alt=":/" />')
value = value.replace(' :P', ' <img src="/static/images/smileys/tongue.png" class="icon" alt=":P" />')
value = value.replace(' :-P', ' <img src="/static/images/smileys/tongue.png" class="icon" alt=":-P" />')
value = value.replace(' ;)', ' <img src="/static/images/smileys/wink.png" class="icon" alt=";)" />')
value = value.replace(' ;-)', ' <img src="/static/images/smileys/wink.png" class="icon" alt=";-)" />')
value = value.replace(' :*)', ' <img src="/static/images/smileys/embarrassed.png" class="icon" alt=":*)" />')
value = value.replace(' 8-)', ' <img src="/static/images/smileys/cool.png" class="icon" alt="8-)" />')
# value = value.replace(' :'(', ' <img src="/static/images/smileys/cry.png" class="icon" alt=":'(" />')
value = value.replace(' :_(', ' <img src="/static/images/smileys/cry.png" class="icon" alt=":_(" />')
value = value.replace(' :-X', ' <img src="/static/images/smileys/crossedlips.png" class="icon" alt=":-X" />')
return value
register.filter(smiley)
#This Pagination is deprecated
class Pagination(template.Node):
def render(self,context):
prev = self.get('prev', context)
next = self.get('next', context)
params = []
p = self.get('p', context)
q = self.get('q', context)
a = self.get('a', context)
t = self.get('article_type', context)
if a:
a = '#%s' % str(a)
else:
a = ''
if t:
t = '&article_type=%s' % str(t)
else:
t = ''
s = ''
if prev or next:
s = '<p class="paginator">'
if prev:
if prev == 1:
if q:
qp = 'q=%s' % str(q)
else:
qp = ''
s = '%s<a href="?%s%s%s">« %s</a> |' % (s, qp, t, a, getLocale("Previous"))
else:
if q:
qp = '&q=%s' % str(q)
else:
qp = ''
s = '%s<a href="?p=%d%s%s%s">« %s</a> |' % (s, prev, qp, t, a, getLocale("Previous"))
s = '%s '+getLocale("Page")+' %d ' % (s, p)
if next:
if q:
q = '&q=%s' % str(q)
else:
q = ''
s = '%s| <a href="?p=%d%s%s%s">%s »</a>' % (s, next, q, t, a, getLocale("Next"))
s = '%s</p>' % s
return s
def get(self, key, context):
try:
return template.resolve_variable(key, context)
except template.VariableDoesNotExist:
return None
### i18n
def getLocale(label):
env = AppProperties().getJinjaEnv()
t = env.get_template("/translator-util.html")
return t.render({"label": label})
@register.tag
def pagination(parser, token):
return Pagination() | Python |
import urllib
from google.appengine.api import urlfetch
"""
Adapted from http://pypi.python.org/pypi/recaptcha-client
to use with Google App Engine
by Joscha Feth <joscha@feth.com>
Version 0.1
"""
API_SSL_SERVER ="https://api-secure.recaptcha.net"
API_SERVER ="http://api.recaptcha.net"
VERIFY_SERVER ="api-verify.recaptcha.net"
class RecaptchaResponse(object):
def __init__(self, is_valid, error_code=None):
self.is_valid = is_valid
self.error_code = error_code
def displayhtml (public_key,
use_ssl = False,
error = None):
"""Gets the HTML to display for reCAPTCHA
public_key -- The public api key
use_ssl -- Should the request be sent over ssl?
error -- An error message to display (from RecaptchaResponse.error_code)"""
error_param = ''
if error:
error_param = '&error=%s' % error
if use_ssl:
server = API_SSL_SERVER
else:
server = API_SERVER
return """<script type="text/javascript" src="%(ApiServer)s/challenge?k=%(PublicKey)s%(ErrorParam)s"></script>
<noscript>
<iframe src="%(ApiServer)s/noscript?k=%(PublicKey)s%(ErrorParam)s" height="300" width="500" frameborder="0"></iframe><br />
<textarea name="recaptcha_challenge_field" rows="3" cols="40"></textarea>
<input type='hidden' name='recaptcha_response_field' value='manual_challenge' />
</noscript>
""" % {
'ApiServer' : server,
'PublicKey' : public_key,
'ErrorParam' : error_param,
}
def submit (recaptcha_challenge_field,
recaptcha_response_field,
private_key,
remoteip):
"""
Submits a reCAPTCHA request for verification. Returns RecaptchaResponse
for the request
recaptcha_challenge_field -- The value of recaptcha_challenge_field from the form
recaptcha_response_field -- The value of recaptcha_response_field from the form
private_key -- your reCAPTCHA private key
remoteip -- the user's ip address
"""
if not (recaptcha_response_field and recaptcha_challenge_field and
len (recaptcha_response_field) and len (recaptcha_challenge_field)):
return RecaptchaResponse (is_valid = False, error_code = 'incorrect-captcha-sol')
headers = {
'Content-type': 'application/x-www-form-urlencoded',
"User-agent" : "reCAPTCHA GAE Python"
}
params = urllib.urlencode ({
'privatekey': private_key,
'remoteip' : remoteip,
'challenge': recaptcha_challenge_field,
'response' : recaptcha_response_field,
})
httpresp = urlfetch.fetch(
url = "http://%s/verify" % VERIFY_SERVER,
payload = params,
method = urlfetch.POST,
headers = headers
)
if httpresp.status_code == 200:
# response was fine
# get the return values
return_values = httpresp.content.splitlines();
# get the return code (true/false)
return_code = return_values[0]
if return_code == "true":
# yep, filled perfectly
return RecaptchaResponse (is_valid=True)
else:
# nope, something went wrong
return RecaptchaResponse (is_valid=False, error_code = return_values [1])
else:
# recaptcha server was not reachable
return RecaptchaResponse (is_valid=False, error_code = "recaptcha-not-reachable") | Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Carrasco <jose.carrasco[a]vikuit.com>
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
import os
import sha
import time
import Cookie
COOKIE_NAME = 'vikuit'
class Session(object):
def __init__(self, seed):
self.time = None
self.user = None
self.auth = None
self.seed = seed
def load(self):
string_cookie = os.environ.get('HTTP_COOKIE', '')
string_cookie = string_cookie.replace(';', ':') # for old sessions
self.cookie = Cookie.SimpleCookie()
self.cookie.load(string_cookie)
if self.cookie.get(COOKIE_NAME):
value = self.cookie[COOKIE_NAME].value
tokens = value.split(':')
if len(tokens) != 3:
return False
else:
h = tokens[2]
tokens = tokens[:-1]
tokens.append(self.seed)
if h == self.hash(tokens):
self.time = tokens[0]
self.user = tokens[1]
self.auth = h
try:
t = int(self.time)
except:
return False
if t > int(time.time()):
return True
return False
def store(self, user, expire):
self.time = str(int(time.time())+expire)
self.user = user
params = [self.time, self.user, self.seed]
self.auth = self.hash(params)
params = [self.time, self.user, self.auth]
self.cookie[COOKIE_NAME] = ':'.join(params)
self.cookie[COOKIE_NAME]['expires'] = expire
self.cookie[COOKIE_NAME]['path'] = '/'
print 'Set-Cookie: %s; HttpOnly' % (self.cookie.output().split(':', 1)[1].strip())
def hash(self, params):
return sha.new(';'.join(params)).hexdigest()
"""
def __str__(self):
params = [self.time, self.user, self.auth]
self.cookie[COOKIE_NAME] = ':'.join(params)
self.cookie[COOKIE_NAME]['path'] = '/'
return self.cookie.output()
s = Session('1234')
s.load()
if s.load():
print s.auth
print s.user
s.store('anabel', 3200)
""" | Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# (C) Copyright 2008 Ignacio Andreu <plunchete at gmail dot com>
#
# This file is part of "debug_mode_on".
#
# "debug_mode_on" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "debug_mode_on" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "debug_mode_on". If not, see <http://www.gnu.org/licenses/>.
#
import simplejson
import model
from google.appengine.api import memcache
from google.appengine.ext import webapp
class BaseRest(webapp.RequestHandler):
def render_json(self, data):
self.response.headers['Content-Type'] = 'application/json;charset=UTF-8'
self.response.headers['Pragma'] = 'no-cache'
self.response.headers['Cache-Control'] = 'no-cache'
self.response.headers['Expires'] = 'Wed, 27 Aug 2008 18:00:00 GMT'
self.response.out.write(simplejson.dumps(data))
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# (C) Copyright 2008 Néstor Salceda <nestor.salceda at gmail dot com>
# (C) Copyright 2008 Alberto Gimeno <gimenete at gmail dot com>
#
# This file is part of "debug_mode_on".
#
# "debug_mode_on" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "debug_mode_on" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "debug_mode_on". If not, see <http://www.gnu.org/licenses/>.
#
import model
from google.appengine.api import mail
from google.appengine.runtime import apiproxy_errors
from google.appengine.ext import webapp
class MailQueue(webapp.RequestHandler):
def get(self):
self.response.headers['Content-Type'] = 'text/plain'
n = 10
next = model.MailQueue.all().get()
sent = None
if not next:
self.response.out.write('No pending mail')
return
if not next.bcc and not next.to:
self.response.out.write('email without recipients')
next.delete()
return
if next.bcc:
bcc = next.bcc[:n]
del next.bcc[:n]
sent = self.send_mail(next, bcc=bcc)
elif next.to:
to = next.to[:n]
del next.to[:n]
sent = self.send_mail(next, to=to)
if not sent:
self.response.out.write('error. Mail was not sent')
return
if next.bcc or next.to:
next.put()
self.response.out.write('mail sent, something pending')
else:
next.delete()
self.response.out.write('mail sent, mail queue deleted')
def send_mail(self, queue, bcc=[], to=[]):
app = model.Application.all().get()
message = mail.EmailMessage(sender=app.mail_sender,
subject=queue.subject, body=queue.body)
if not to:
to = app.mail_sender
message.to = to
if bcc:
message.bcc = bcc
try:
message.send()
except apiproxy_errors.OverQuotaError, message:
return False
return True
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# (C) Copyright 2008 Ignacio Andreu <plunchete at gmail dot com>
#
# This file is part of "debug_mode_on".
#
# "debug_mode_on" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "debug_mode_on" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "debug_mode_on". If not, see <http://www.gnu.org/licenses/>.
#
from handlers.BaseHandler import *
class SearchResult(BaseHandler):
def execute(self):
self.render('templates/search-result.html')
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# (C) Copyright 2008 Alberto Gimeno <gimenete at gmail dot com>
#
# This file is part of "debug_mode_on".
#
# "debug_mode_on" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "debug_mode_on" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "debug_mode_on". If not, see <http://www.gnu.org/licenses/>.
#
from handlers.BaseHandler import *
class Tag(BaseHandler):
def execute(self):
tag = self.request.path.split('/', 2)[2]
query = model.Article.all().filter('tags =', tag).filter('draft', False).filter('deletion_date', None).order('-creation_date')
self.values['articles'] = self.paging(query, 10)
self.add_tag_cloud()
self.values['tag'] = tag
self.render('templates/tag.html')
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from handlers.BaseHandler import BaseHandler
class NotFound(BaseHandler):
def execute(self):
self.not_found() | Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
import model
import logging
from google.appengine.api import memcache
from google.appengine.ext import webapp
from handlers.BaseHandler import BaseHandler
class ImageBrowser(BaseHandler):
def execute(self):
user = self.values['user']
#TODO PAGINATE
if user:
list = ""
if user.rol == 'admin':
images = model.Image.all()
else:
images = model.Image.gql('WHERE author_nickname=:1', user.nickname)
self.values['images'] = images
self.render('templates/editor/browse.html')
return
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
import datetime
import os
import model
import logging
from google.appengine.api import memcache
from google.appengine.ext import webapp
from handlers.AuthenticatedHandler import AuthenticatedHandler
class ImageUploader(AuthenticatedHandler):
def execute(self):
method = self.request.method
user = self.values['user']
if method == 'GET':#Request identifies actions
action = self.get_param('act')
url_path = self.get_param('url')
query = model.Image.gql('WHERE url_path=:1', url_path )
image = query.get()
if not image:
self.render_json({ 'saved': False, 'msg': self.getLocale('Not found') })
elif user.nickname != image.author_nickname and user.rol != 'admin':
self.render_json({ 'saved': False, 'msg': self.getLocale('Not allowed') })
elif action == 'del': #delete image
image.delete()
self.render_json({ 'saved': True })
else:
self.render_json({ 'saved': False })
else:#File upload
# Get the uploaded file from request.
upload = self.request.get("upload")
nick = user.nickname
dt = datetime.datetime.now()
prnt = dt.strftime("%Y%m%d%H%M%S")
url_path = nick +"/"+ prnt
try:
query = model.Image.all(keys_only=True).filter('url_path', url_path)
entity = query.get()
if entity:
raise Exception('unique_property must have a unique value!')
image = model.Image(author=user,
author_nickname=nick,
thumbnail=upload,
url_path=url_path)
image.put()
self.values["label"] = self.getLocale("Uploaded as: %s") % url_path
except:
self.values["label"] = self.getLocale('Error saving image')
self.render("/translator-util.html")
return | Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
import re
import model
import datetime
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.api import users
from google.appengine.api import memcache
from google.appengine.runtime.apiproxy_errors import CapabilityDisabledError
from utilities import Constant
from utilities.AppProperties import AppProperties
class BaseHandler(webapp.RequestHandler):
#########################
### Handler functions ###
#########################
def get(self):
if self.request.url.split('/')[2] == AppProperties().getAppDic().get(Constant.domain):#'vikuit.com':
self.redirect(self.get_application().url + self.request.url.split('/', 3)[3], permanent=True)# 'http://www.vikuit.com/'
return
try:
self.common_stuff()
self.pre_execute()
except CapabilityDisabledError:
self.values = {}
self.render('templates/maintenace.html')
return
def post(self):
self.common_stuff()
self.pre_execute()
def pre_execute(self):
self.execute()
def common_stuff(self):
self.values = {}
self.user = None
import session
#app = model.Application.all().get()
app = self.get_application()
if app:
self.sess = session.Session(app.session_seed)
if self.sess.load():
self.user = self.get_current_user()
elif self.is_google_account():
#google account users.get_current_user()
#user only arrives here 1 time per session
self.user = self.get_current_user()
if self.user:
redirect, self.user = self.store_google_account()
self.sess.store(str(self.user.key()), 7200)
if redirect:
# redirect to preferences page
self.redirect("/module/user.edit")
if self.user.banned_date is not None:
msg = self.getLocale("User '%s' was blocked. Contact with an administrator.") % self.user.nickname()
self.show_error( msg )
else:
self.sess = None
redirect = '%s?%s' % (self.request.path, self.request.query)
self.values['sess'] = self.sess
self.values['redirect'] = redirect
self.values['app'] = self.get_application()
self.values['activity_communities'] = self.communities_by_activity()
if self.user:
self.values['auth'] = self.sess.auth
self.values['logout'] = '/module/user.logout?redirect_to=%s&auth=%s' % (self.quote(redirect), self.sess.auth)
"""
user_data = model.UserData.gql('WHERE email=:1', user.email()).get()
if not user_data:
user_data = model.UserData(email=user.email(),
nickname=user.nickname(),
articles=0,
draft_articles=0,
messages=0,
draft_messages=0,
comments=0,
rating_count=0,
rating_total=0,
rating_average=0,
threads=0,
responses=0,
communities=0,
favourites=0,
public=False)
user_data.put()
self.values['user'] = user_data
"""
# TODO deprecated, use self.user instead
self.values['user'] = self.user
else:
self.user = None
self.values['user'] = None
self.values['login'] = '/module/user.login?redirect_to=%s' % self.quote(redirect) # users.create_login_url(self.values['redirect'])
self.values['glogin'] = users.create_login_url(self.values['redirect'])
#################################################
### Authentication and Autorization functions ###
#################################################
def hash(self, login, p, times=100):
import sha
p = p.encode('ascii', 'ignore')
p = '%s:%s' % (login, p)
for i in range(0, times):
p = sha.new(p).hexdigest()
return p
def can_write(self, community):
if community.all_users is None or community.all_users:
return True
user = self.values['user']
if not user:
return False
if model.CommunityUser.all().filter('community', community).filter('user', user).get():
return True
return False
def check_password(self, user, password):
times = 100
user_password = user.password
s = user.password.split(':')
if len(s) > 1:
times = int(s[0])
user_password = s[1]
return self.hash(user.nickname, password, times) == user_password
def hash_password(self, nickname, password):
times = 1
return '%d:%s' % (times, self.hash(nickname, password, times))
def auth(self):
token = self.values['auth']
b = token == self.get_param('auth')
if not b:
self.forbidden()
return b
def get_current_user(self):
if self.sess.user:##first
return db.get(self.sess.user)
user = users.get_current_user()#login with google account
# if user:
# user = model.UserData.gql('WHERE email=:1', user.email()).get()
return user
def is_google_account(self):
user = users.get_current_user()
if user:
return True
else:
return False
def store_google_account(self):
googleAcc = users.get_current_user()
user = model.UserData.gql('WHERE email=:1', googleAcc.email()).get()
redirectPreferences = False
if user is None:
redirectPreferences = True
nick = self.getNickname(googleAcc.nickname())
user = model.UserData(nickname=nick,
email=googleAcc.email(),
password=None,#Change to optional
articles=0,
draft_articles=0,
messages=0,
draft_messages=0,
comments=0,
rating_count=0,
rating_total=0,
rating_average=0,
threads=0,
responses=0,
communities=0,
favourites=0,
public=False,
contacts=0)
user.registrationType = 1 #Google identifier
user.last_login = datetime.datetime.now()
user.put()
if redirectPreferences:
# Is new user
app = model.Application.all().get()
if app:
app.users += 1
app.put()
memcache.delete('app')
return redirectPreferences, user
def getNickname(self, nick, isMail=True):
if isMail:
return nick.split('@')[0]
else:
return nick
###########################
### Bussiness functions ###
###########################
def add_user_subscription(self, user, subscription_type, subscription_id):
user_subscription = model.UserSubscription(user=user,
user_nickname=user.nickname,
user_email=user.email,
subscription_type=subscription_type,
subscription_id=subscription_id,
creation_date = datetime.datetime.now())
subscription = model.UserSubscription.all().filter('user', user).filter('subscription_type', subscription_type).filter('subscription_id', subscription_id).get()
if subscription is None:
user_subscription.put()
def remove_user_subscription(self, user, subscription_type, subscription_id):
user_subscription = model.UserSubscription.all().filter('user', user).filter('subscription_type', subscription_type).filter('subscription_id', subscription_id).get()
if user_subscription is not None:
user_subscription.delete()
def add_follower(self, community=None, user=None, article=None, thread=None, nickname=None):
object_type = None
obj = None
if user is not None:
object_type = 'user'
obj = user
elif community is not None:
object_type = 'community'
obj = community
elif thread is not None:
object_type = 'thread'
obj = thread
elif article is not None:
object_type = 'article'
obj = article
if object_type is None:
return None
follower = model.Follower.all().filter('object_type', object_type).filter('object_id', obj.key().id()).get()
if follower:
if nickname not in follower.followers:
follower.followers.append(nickname)
follower.put()
else:
follower = model.Follower(object_type=object_type,
object_id=obj.key().id(),
followers=[nickname])
follower.put()
def remove_follower(self, community=None, user=None, article=None, thread=None, nickname=None):
object_type = None
obj = None
if user is not None:
object_type = 'user'
obj = user
elif community is not None:
object_type = 'community'
obj = community
elif thread is not None:
object_type = 'thread'
obj = thread
elif article is not None:
object_type = 'article'
obj = article
if object_type is None:
return None
follower = model.Follower.all().filter('object_type', object_type).filter('object_id', obj.key().id()).get()
if follower:
if nickname in follower.followers:
follower.followers.remove(nickname)
follower.put()
def create_event(self, event_type, followers,
user, user_to=None, community=None, article=None, thread=None, creation_date=None,
response_number=0):
event = model.Event(event_type=event_type,
followers=followers,
user=user,
user_nickname=user.nickname,
response_number=response_number)
if user_to is not None:
event.user_to = user_to
event.user_to_nickname = user_to.nickname
if community is not None:
event.community = community
event.community_title = community.title
event.community_url_path = community.url_path
if article is not None:
event.article = article
event.article_title = article.title
event.article_author_nickname = article.author_nickname
event.article_url_path = article.url_path
if thread is not None:
event.thread = thread
event.thread_title = thread.title
event.thread_url_path = thread.url_path
if creation_date is None:
event.creation_date = datetime.datetime.now()
else:
event.creation_date = creation_date
event.put()
def get_followers(self, user=None, community=None, thread=None, article=None):
object_type = None
obj = None
if user is not None:
object_type = 'user'
obj = user
elif community is not None:
object_type = 'community'
obj = community
elif thread is not None:
object_type = 'thread'
obj = thread
elif article is not None:
object_type = 'article'
obj = article
if object_type is None:
return None
object_id = obj.key().id()
follower = model.Follower.all().filter('object_type', object_type).filter('object_id', object_id).get()
if not follower:
follower = model.Follower(object_type=object_type, object_id=object_id, followers=[])
follower.put()
return follower.followers
def create_task(self, task_type, priority, data):
import simplejson
t = model.Task(task_type=task_type, priority=priority, data=simplejson.dumps(data))
t.put()
def is_contact(self, this_user):
user = self.values['user']
if not user:
return False
if model.Contact.all().filter('user_from', user).filter('user_to', this_user).get():
return True
return False
def create_community_subscribers(self, community):
if not community.subscribers:
com = [g.user.email for g in model.CommunityUser.all().filter('community', community).fetch(1000) ]
community.subscribers = list(set(com))
# I use strings in order to distinguish three values into the templates
# 'True', 'False', and None
def joined(self, community):
gu = model.CommunityUser.gql('WHERE community=:1 and user=:2', community, self.values['user']).get()
if gu is not None:
return 'True'
return 'False'
def communities_by_activity(self):
key = 'activity_communities'
g = memcache.get(key)
if g is not None:
return g
else:
communities = model.Community.all().order('-activity').fetch(15)
memcache.add(key, communities, 3600)
return communities
def add_categories(self):
cats = list(model.Category.all().order('title'))
categories = {}
for category in cats:
# legacy code
if not category.url_path:
category.url_path = self.to_url_path(category.title)
category.put()
# end
if category.parent_category is None:
categories[str(category.key())] = category
for category in cats:
if category.parent_category is not None:
parent_category = categories[str(category.parent_category.key())]
if not parent_category.subcategories:
parent_category.subcategories = []
parent_category.subcategories.append(category)
ret = [categories[key] for key in categories]
ret.sort()
self.values['categories'] = ret
def add_tag_cloud(self):
self.values['tag_cloud'] = self.cache('tag_cloud', self.get_tag_cloud)
def get_tag_cloud(self):
return self.tag_list(model.Tag.all().order('-count').fetch(30))
def parse_tags(self, tag_string):
tags = [self.to_url_path(t) for t in tag_string.split(',')]
return list(set(tags))
def delete_tags(self, tags):
tags=set(tags)
for tag in tags:
t = model.Tag.gql('WHERE tag=:1', tag).get()
if t:
if t.count == 1:
t.delete()
else:
t.count = t.count - 1
t.put()
def update_tags(self, tags):
tags=set(tags)
for tag in tags:
t = model.Tag.gql('WHERE tag=:1', tag).get()
if not t:
tg = model.Tag(tag=tag,count=1)
tg.put()
else:
t.count = t.count + 1
t.put()
def tag_list(self, tags):
tagdict={}
for t in tags:
tagdict[t.tag] = t.count
if not tagdict:
return []
maxcount = max(t.count for t in tags)
taglist = [(tag, 6*tagdict[tag]/maxcount, tagdict[tag]) for tag in tagdict.keys()]
taglist.sort()
return taglist
###############################
### Evnironment And Renders ###
###############################
def create_jinja_environment(self):
env = AppProperties().getJinjaEnv()
env.filters['relativize'] = self.relativize
env.filters['markdown'] = self.markdown
env.filters['smiley'] = self.smiley
env.filters['pagination'] = self.pagination
env.filters['media'] = self.media_content
env.filters['quote'] = self.quote
return env
def get_template(self, env, f):
p = f.split('/')
if p[0] == 'templates':
f = '/'.join(p[1:])
t = env.get_template(f)
return t
def render_chunk(self, f, params):
env = self.create_jinja_environment()
t = self.get_template(env, f)
return t.render(params)
def render(self, f):
self.response.headers['Content-Type'] = 'text/html;charset=UTF-8'
self.response.headers['Pragma'] = 'no-cache'
self.response.headers['Cache-Control'] = 'no-cache'
self.response.headers['Expires'] = 'Wed, 27 Aug 2008 18:00:00 GMT'
self.response.out.write(self.render_chunk(f, self.values))
def render_json(self, data):
import simplejson
self.response.headers['Content-Type'] = 'application/json;charset=UTF-8'
self.response.headers['Pragma'] = 'no-cache'
self.response.headers['Cache-Control'] = 'no-cache'
self.response.headers['Expires'] = 'Wed, 27 Aug 2008 18:00:00 GMT'
self.response.out.write(simplejson.dumps(data))
def relativize(self, value):
now = datetime.datetime.now()
try:
diff = now - value
except TypeError:
return ''
days = diff.days
seconds = diff.seconds
if days > 365:
return self.getLocale("%d years") % (days / 365, ) #u"%d años" % (days / 365, )
if days > 30:
return self.getLocale("%d months") % (days / 30, ) #u"%d meses" % (days / 30, )
if days > 0:
return self.getLocale("%d days") % (days, ) # u"%d días" % (days, )
if seconds > 3600:
return self.getLocale("%d hours") % (seconds / 3600, ) # u"%d horas" % (seconds / 3600, )
if seconds > 60:
return self.getLocale("%d minutes") % (seconds / 60, ) # u"%d minutos" % (seconds / 60, )
return self.getLocale("%d seconds") % (seconds, ) # u"%d segundos" % (seconds, )
def smiley(self, value):
return value
def markdown(self, value):
try:
import markdown
except ImportError:
return "error"
else:
return markdown.markdown(value, [], safe_mode='escape')
def quote(self, value):
import urllib
value = self.get_unicode(value)
return urllib.quote((value).encode('UTF-8'))
def media_content(self,value):
import MediaContentFilters as contents
value=contents.media_content(value)
return value
###########################
### Utilities functions ###
###########################
def mail(self, subject, body, to=[], bcc=[]):
app = self.get_application()
subject = "%s %s" % (app.mail_subject_prefix, subject)
body = """
%s
%s
""" % (body,app.mail_footer)
queue = model.MailQueue(subject=subject, body=body, to=to, bcc=bcc)
queue.put()
def show_error(self, message):
self.values['message'] = message
self.render('templates/error.html')
"""
def handle_exception(self, exception):
self.response.clear()
self.response.set_status(500)
self.render('templates/error500.html')
"""
def not_found(self):
self.response.clear()
self.response.set_status(404)
self.render('templates/error404.html')
def forbidden(self):
self.response.clear()
self.response.set_status(403)
self.render('templates/error403.html')
def getLocale(self, label):
return self.render_chunk("/translator-util.html", {"label": label})
def get_application(self):
return self.cache('app', self.fetch_application)
def fetch_application(self):
return model.Application.all().get()
def value(self, key):
try:
return self.values[key]
except KeyError:
return None
def not_none(self, value):
if not value:
return ''
return value
def get_param(self, key):
return self.get_unicode(self.request.get(key))
def get_unicode(self, value):
try:
value = unicode(value, "utf-8")
except TypeError:
return value
return value
def cache(self, key, function, timeout=0):
# import logging
# logging.debug('looking for %s in the cache' % key)
data = memcache.get(key)
if data is not None:
# logging.debug('%s is already in the cache' % key)
return data
else:
data = function.__call__()
# logging.debug('inserting %s in the cache' % key)
memcache.add(key, data, timeout)
return data
"""
def cache_this(self, function, timeout=600):
key = '%s?%s' % (self.request.path, self.request.query)
return self.cache(key, function, timeout)
def pre_pag(self, query, max, default_order=None):
try:
p = int(self.get_param('p'))
except ValueError:
p = 1
offset = (p-1)*max
o = self.get_param('o')
if o:
query = query.order(o)
self.values['o'] = o
elif default_order:
query = query.order(default_order)
return [obj for obj in query.fetch(max+1, offset)]
def post_pag(self, a, max):
try:
p = int(self.get_param('p'))
except ValueError:
p = 1
self.values['p'] = p
if p > 1:
self.values['prev'] = p-1
l = len(a)
if l > max:
self.values['len'] = max
self.values['next'] = p+1
return a[:max]
self.values['len'] = l
o = self.get_param('o')
if o:
self.values['o'] = o
return a
"""
def paging(self, query, max, default_order=None, total=-1, accepted_orderings=[], key=None, timeout=300):
if total > 0:
pages = total / max
if total % max > 0:
pages += 1
self.values['pages'] = pages
i = 1
pagesList = []
while i <= pages:
pagesList.append(i)
i += 1
self.values['pagesList'] = pagesList
try:
p = int(self.get_param('p'))
if p < 1:
p = 1
except ValueError:
p = 1
self.values['p'] = p
offset = (p-1)*max
#if offset > 1000:
# return None
o = self.get_param('o')
if o and o in accepted_orderings:
query = query.order(o)
self.values['o'] = o
elif default_order:
query = query.order(default_order)
# caching
if not key is None:
a = memcache.get(key)
if a is None:
a = [obj for obj in query.fetch(max+1, offset)]
memcache.add(key, a, timeout)
else:
a = [obj for obj in query.fetch(max+1, offset)]
#
if p > 1:
self.values['prev'] = p-1
l = len(a)
if l > max:
self.values['len'] = max
self.values['next'] = p+1
return a[:max]
self.values['len'] = l
return a
def pagination(self, value):
##Pagination
if self.value('prev') or self.value('next'):
params = []
p = self.value('p')
q = self.value('q')
a = self.value('a')
t = self.value('t')
o = self.value('o')
cat = self.value('cat')
pages = self.value('pages')
# order
if cat:
params.append('cat=%s' % cat)
# query string
if q:
params.append('q=%s' % q)
# type
if t:
params.append('t=%s' % t)
# order
if o:
params.append('o=%s' % o)
# anchor
if a:
a = '#%s' % str(a)
else:
a = ''
self.values['p'] = p
self.values['common'] = '%s%s' % ('&'.join(params), a)
return ''
def to_url_path(self, value):
value = value.lower()
# table = maketrans(u'áéíóúÁÉÍÓÚñÑ', u'aeiouAEIOUnN')
# value = value.translate(table)
value = value.replace(u'á', 'a')
value = value.replace(u'é', 'e')
value = value.replace(u'í', 'i')
value = value.replace(u'ó', 'o')
value = value.replace(u'ú', 'u')
value = value.replace(u'Á', 'A')
value = value.replace(u'É', 'E')
value = value.replace(u'Í', 'I')
value = value.replace(u'Ó', 'O')
value = value.replace(u'Ú', 'U')
value = value.replace(u'ñ', 'n')
value = value.replace(u'Ñ', 'N') # TODO improve + review URL path allowed chars
value = '-'.join(re.findall('[a-zA-Z0-9]+', value))
return value
def clean_ascii(self, value):
# table = maketrans(u'áéíóúÁÉÍÓÚñÑ', u'aeiouAEIOUnN')
# value = value.translate(table)
value = value.replace(u'á', 'a')
value = value.replace(u'é', 'e')
value = value.replace(u'í', 'i')
value = value.replace(u'ó', 'o')
value = value.replace(u'ú', 'u')
value = value.replace(u'Á', 'A')
value = value.replace(u'É', 'E')
value = value.replace(u'Í', 'I')
value = value.replace(u'Ó', 'O')
value = value.replace(u'Ú', 'U')
value = value.replace(u'ñ', 'n')
value = value.replace(u'Ñ', 'N') # TODO improve + review URL path allowed chars
value = ' '.join(re.findall('[a-zA-Z0-9()_\.:;-]+', value))
return value
def unique_url_path(self, model, url_path):
c = 1
url_path_base = url_path
while True:
query = db.Query(model)
query.filter('url_path =', url_path)
count = query.count(1)
if count > 0:
url_path = '%s-%d' % (url_path_base, c)
c = c + 1
continue
break
return url_path | Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from google.appengine.api import mail
from google.appengine.ext import db
from handlers.BaseHandler import *
import re
class Invite(BaseHandler):
def execute(self):
user = self.values['user']
method = self.request.method
app = self.get_application()
if not user:
self.redirect('/module/user.login')
if method == 'GET':
#u"""Te invito a visitar %s, %s.\n %s
self.values['personalmessage'] = self.getLocale("Let me invite you to visit %s, %s. %s") % (app.name, app.subject, app.url)
self.render('templates/invite-friends.html')
return
elif self.auth():
contacts = self.get_param('contacts').replace(' ','')
contacts = contacts.rsplit(',',19)
if contacts[0]=='' or not contacts:
self.values['failed']=True
self.render('templates/invite-friends.html')
return
self.values['_users'] = []
invitations = []
for contact in contacts:
#FIXME inform the user about bad formed mails
if re.match('\S+@\S+\.\S+', contact):
u = model.UserData.gql('WHERE email=:1', contact).get()
if u:
self.values['_users'].append(u)
else:
invitations.append(contact)
personalmessage = self.get_param('personalmessage')
subject = self.getLocale("%s invites you to participate in %s") % (user.nickname, app.name)
body = self.getLocale("Let me invite you to visit %s, %s. %s") % (app.name, app.subject, app.url)
if personalmessage:
body = u"%s \n\n\n\n\t %s" % (self.clean_ascii(personalmessage), self.get_application().url)
self.mail(subject=subject, body=body, bcc=invitations)
self.values['sent'] = True
self.values['invitations'] = invitations
self.render('templates/invite-friends.html')
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
import time
import model
import datetime
import markdown
from google.appengine.api import memcache
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from time import strftime, gmtime, time
from utilities.AppProperties import AppProperties
class Feed(webapp.RequestHandler):
def get(self):
data = memcache.get(self.request.path)
if not data:
time = 600
params = self.request.path.split('/', 4)
if not params[2]:
latest = model.Article.gql('WHERE draft=:1 AND deletion_date=:2 ORDER BY creation_date DESC LIMIT 20', False, None)
data = self.to_rss(self.get_application().name, latest)
elif params[2] == 'mblog':
query = model.Mblog.all().filter('deletion_date', None).order('-creation_date')
latest = [o for o in query.fetch(25)]
data = self.posts_to_rss(self.getLocale("Microbblogging"), latest)
time = 200
elif params[2] == 'tag':
query = model.Article.all().filter('deletion_date', None).filter('tags =', params[3]).order('-creation_date')
latest = [o for o in query.fetch(10)]
data = self.to_rss(self.getLocale("Articles labeled with %s") % params[3], latest)
elif params[3] == 'community.forum':
community = model.Community.gql('WHERE url_path=:1',params[4]).get()
if not community:
community = model.Community.gql('WHERE old_url_path=:1',params[4]).get()
threads = model.Thread.gql('WHERE community=:1 ORDER BY creation_date DESC LIMIT 20', community)
data = self.threads_to_rss(self.getLocale("Forum %s") % community.title, threads)
elif params[3] == 'community':
community = model.Community.gql('WHERE url_path=:1',params[4]).get()
if not community:
community = model.Community.gql('WHERE old_url_path=:1',params[4]).get()
community_articles = model.CommunityArticle.gql('WHERE community=:1 ORDER BY creation_date DESC LIMIT 20', community)
latest = [gi.article for gi in community_articles]
data = self.to_rss(self.getLocale("Articles by community %s") % community.title, latest)
elif params[3] == 'user':
latest = model.Article.gql('WHERE author_nickname=:1 AND draft=:2 AND deletion_date=:3 ORDER BY creation_date DESC LIMIT 20', params[4], False, None)
data = self.to_rss(self.getLocale("Articles by %s") % params[3], latest)
else:
data = self.not_found()
memcache.add(self.request.path, data, time)
self.response.headers['Content-Type'] = 'application/rss+xml'
self.response.out.write(template.render('templates/feed.xml', data))
def threads_to_rss(self, title, threads):
articles = []
url = self.get_application().url
md = markdown.Markdown()
for i in threads:
article = {
'title': i.title,
'link': "%s/module/community.forum/%s" % (url, i.url_path),
'description': md.convert(i.content),
'pubDate': self.to_rfc822(i.creation_date),
'guid':"%s/module/community.forum/%s" % (url,i.url_path),
'author': i.author_nickname
# guid como link para mantener compatibilidad con feed.xml
}
articles.append(article)
values = {
'title': title,
'self': url+self.request.path,
'link': url,
'description': '',
'articles': articles
}
return values
def posts_to_rss(self, title, list):
posts = []
url = self.get_application().url
for i in list:
post = {
'title': "%s" % i.content,
'link': "%s/module/mblog.edit/%s" % (url, i.key().id()),
'description': "%s" % i.content,
'pubDate': self.to_rfc822(i.creation_date),
'guid':"%s/module/mblog.edit/%s" % (url,i.key().id()),
'author': i.author_nickname
}
posts.append(post)
values = {
'title': title,
'self': url+self.request.path,
'link': url,
'description': '%s Microbblogging' % self.get_application().name,
'articles': posts
}
return values
def to_rss(self, title, latest):
import MediaContentFilters as contents
articles = []
url = self.get_application().url
md = markdown.Markdown()
for i in latest:
if i.author.not_full_rss:
content = md.convert(i.description)
else:
content = md.convert(i.content)
content = contents.media_content(content)
article = {
'title': i.title,
'link': "%s/module/article/%s" % (url, i.url_path),
'description': content,
'pubDate': self.to_rfc822(i.creation_date),
'guid':"%s/module/article/%d/" % (url, i.key().id()),
'author': i.author_nickname
}
articles.append(article)
values = {
'title': title,
'self': url+self.request.path,
'link': url,
'description': '',
'articles': articles
}
return values
def to_rfc822(self, date):
return date.strftime("%a, %d %b %Y %H:%M:%S GMT")
def get_application(self):
app = memcache.get('app')
import logging
if not app:
app = model.Application.all().get()
memcache.add('app', app, 0)
return app
def not_found(self):
url = self.get_application().url
values = {
'title': self.get_application().name,
'self': url,
'link': url,
'description': '',
'articles': ''
}
return values
### i18n
def getLocale(self, label):
env = AppProperties().getJinjaEnv()
t = env.get_template("/translator-util.html")
return t.render({"label": label})
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# (C) Copyright 2008 Alberto Gimeno <gimenete at gmail dot com>
#
# This file is part of "debug_mode_on".
#
# "debug_mode_on" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "debug_mode_on" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "debug_mode_on". If not, see <http://www.gnu.org/licenses/>.
#
from handlers.BaseHandler import *
class ForumList(BaseHandler):
def execute(self):
self.values['tab'] = '/forum.list'
query = model.Thread.all().filter('parent_thread', None)
app = self.get_application()
key = '%s?%s' % (self.request.path, self.request.query)
results = 10
if app.max_results:
results = app.max_results
threads = self.paging(query, results, '-last_response_date', app.threads, ['-last_response_date'], key)
# migration
for t in threads:
if not t.last_response_date:
last_response = model.Thread.all().filter('parent_thread', t).order('-creation_date').get()
if last_response:
t.last_response_date = last_response.creation_date
else:
t.last_response_date = t.creation_date
t.put()
# end migration
self.values['threads'] = threads
self.add_tag_cloud()
self.render('templates/forum-list.html')
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
import time
import datetime
import re
from google.appengine.ext import db
from google.appengine.api import memcache
from handlers.AuthenticatedHandler import *
class MBlogEdit(AuthenticatedHandler):
def execute(self):
method = self.request.method
user = self.values['user']
key = self.get_param('key')
action = self.get_param('act')
if method == 'GET':
if key:#Unused - This case is to allow edit a post and add comments in a single post page
# show edit form
post = model.Mblog.get_by_id(key)
if not post:
self.not_found()
return
if not user.nickname == post.author.nickname and user.rol != 'admin':
self.forbidden()
return
self.values['key'] = key
self.values['content'] = post.content
self.render('templates/module/mblog/mblog-edit.html')
else:
self.not_found()
return
elif self.auth():
# new post
if not action:
content = self.get_param('content')
if not content or len(content) == 0:
self.render_json({ 'saved': False, 'msg': self.getLocale('Content is empty') })
return
if len(content) > 150:
self.render_json({ 'saved': False, 'msg': self.getLocale('Content is too large') })
return
if not re.match(u"^[A-Za-z0-9_-àáèéíòóúÀÁÈÉÍÒÓÚïü: ,=\./&¿\?!¡#\(\)]*$", content):
self.render_json({ 'saved': False, 'msg': self.getLocale('Content is invalid') })
return
post = model.Mblog(author=user,
author_nickname=user.nickname,
content=content,
responses=0)
post.put()
self.render_json({ "saved": True, 'key' : str(post.key()) })
return
elif action == 'del' and key:
post = model.Mblog.get_by_id(long(key))
if not post:
self.render_json({ 'saved': False, 'msg': self.getLocale('Not found') })
return
if not user.nickname == post.author.nickname and user.rol != 'admin':
self.render_json({ 'saved': False, 'msg': self.getLocale('Not allowed') })
return
post.deletion_date = datetime.datetime.now()
post.deletion_user = user.nickname
post.put()
self.render_json({ 'saved': True })
return
else:
self.render_json({ 'saved': False, 'msg': self.getLocale('Not found') })
return
#UPDATE CACHE
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from handlers.AuthenticatedHandler import *
class MessageEdit(AuthenticatedHandler):
def execute(self):
user = self.values['user']
user_to = model.UserData.all().filter('nickname', self.get_param('user_to')).get()
if not user_to:
self.not_found()
return
method = self.request.method
if method == 'GET':
self.values['user_to'] = self.get_param('user_to')
title = self.get_param('title')
if not title:
title = "New message..."
elif not title.startswith('Re:'):
title = 'Re:%s' % title
self.values['title'] = title
self.render('templates/module/message/message-edit.html')
return
elif self.auth():
title = self.get_param('title')
message = model.Message(user_from = user,
user_from_nickname = user.nickname,
user_to = user_to,
user_to_nickname = user_to.nickname,
content=self.get_param('content'),
title=self.get_param('title'),
url_path = '-',
read=False)
message.put()
message.url_path = ('%d/%s') % (message.key().id(), self.to_url_path(title))
message.put()
if not user.sent_messages:
user.sent_messages = 0
if not user_to.unread_messages:
user_to.unread_messages = 0
user.sent_messages += 1
user_to.unread_messages += 1
user.put()
user_to.put()
app = self.get_application()
subject = self.getLocale("%s has send you a missage") % user.nickname # "%s te ha enviado un mensaje"
# %s te ha enviado un mensaje.\nLeelo en:\n%s/message.inbox\n
body = self.getLocale("%s has send you a missage.\nRead it at:\n%s/message.inbox\n") % (user.nickname, app.url)
self.mail(subject=subject, body=body, to=[user_to.email])
self.redirect('/message.sent')
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
import datetime
from handlers.AuthenticatedHandler import *
class MessageDelete(AuthenticatedHandler):
def execute(self):
user = self.values['user']
key = self.request.get('key')
message = model.Message.get(key)
if not message:
self.not_found()
return
if not self.auth():
return
if user.nickname == message.user_to_nickname:
message.to_deletion_date = datetime.datetime.now()
message.put()
self.redirect('/message.inbox')
elif user.nickname == message.user_from_nickname:
message.from_deletion_date = datetime.datetime.now()
message.put()
self.redirect('/message.sent')
else:
self.forbidden() | Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from handlers.AuthenticatedHandler import *
class MessageRead(AuthenticatedHandler):
def execute(self):
user = self.values['user']
url_path = self.request.path.split('/', 2)[2]
message = model.Message.gql('WHERE url_path=:1', url_path).get()
if message.user_to_nickname != user.nickname and message.user_from_nickname != user.nickname:
self.forbidden()
return
if message.user_to_nickname == user.nickname and not message.read:
message.read = True
message.put()
user.unread_messages -= 1
user.put()
self.values['message'] = message
self.render('templates/module/message/message-read.html') | Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from handlers.AuthenticatedHandler import *
class MessageInbox(AuthenticatedHandler):
def execute(self):
user = self.values['user']
query = model.Message.all().filter('user_to', user).filter('to_deletion_date', None)
self.values['messages'] = self.paging(query, 10, '-creation_date', user.messages, ['-creation_date'])
self.render('templates/module/message/message-inbox.html')
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from handlers.AuthenticatedHandler import *
class MessageSent(AuthenticatedHandler):
def execute(self):
user = self.values['user']
query = model.Message.all().filter('user_from', user).filter('from_deletion_date', None)
self.values['messages'] = self.paging(query, 10, '-creation_date', user.sent_messages, ['-creation_date'])
self.render('templates/module/message/message-sent.html')
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from handlers.BaseHandler import *
from google.appengine.api import users
class UserFavourites(BaseHandler):
def execute(self):
self.values['tab'] = '/module/user.list'
nickname = self.request.path.split('/')[3]
this_user = model.UserData.gql('WHERE nickname=:1', nickname).get()
if not this_user:
self.not_found()
return
# TODO: not show if the user profile is not public
self.values['this_user'] = this_user
query = model.Favourite.all().filter('user', this_user)
favs = self.paging(query, 10, '-creation_date', this_user.favourites, ['-creation_date'])
self.values['favourites'] = favs
self.render('templates/module/user/user-favourites.html')
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
import model
from handlers.BaseHandler import *
class UserResetPassword(BaseHandler):
def execute(self):
method = self.request.method
if method == 'GET':
nickname = self.request.get('nickname')
token = self.request.get('token')
u = model.UserData.all().filter('nickname =', nickname).filter('token =', token).get()
if not u:
self.render('templates/module/user/user-resetpassword-error.html')
else:
self.values['token'] = token
self.values['nickname'] = nickname
self.render('templates/module/user/user-resetpassword.html')
else:
token = self.request.get('token')
nickname = self.request.get('nickname')
password = self.request.get('password')
re_password = self.request.get('re_password')
if not password or len(password) < 4:
self.show_error(nickname, token, "Password must contain 4 chars at least")
return
if password != re_password:
self.show_error(nickname, token, "New password and validation password are not equal")
return
u = model.UserData.all().filter('nickname =', nickname).filter('token =', token).get()
if not u:
self.render('templates/module/user/user-resetpassword-error.html')
return
u.token = None
u.password = self.hash_password(nickname, password)
u.put()
self.render('templates/module/user/user-resetpassword-login.html')
def show_error(self, nickname, token, error):
self.values['nickname'] = nickname
self.values['token'] = token
self.values['error'] = error
self.render('templates/module/user/user-resetpassword.html') | Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from handlers.AuthenticatedHandler import *
from google.appengine.api import users
class UserEvents(AuthenticatedHandler):
def execute(self):
user = self.get_current_user()
query = model.Event.all().filter('followers', user.nickname)
self.values['events'] = self.paging(query, 10, '-creation_date')
self.render('templates/module/user/user-events.html')
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from handlers.AuthenticatedHandler import *
class UserPromote(AuthenticatedHandler):
def execute(self):
self.values['tab'] = '/module/user.list'
user = self.values['user']
app = self.get_application()
self.values['user_url'] = '%s/module/user/%s' % (app.url, user.nickname)
self.render('templates/module/user/user-promote.html')
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from google.appengine.api import mail
from handlers.AuthenticatedHandler import *
class UserContact(AuthenticatedHandler):
def execute(self):
user = self.values['user']
user_to = model.UserData.all().filter('nickname', self.get_param('user_to')).get()
if not user_to:
self.not_found()
return
if not self.auth():
return
contact = model.Contact.all().filter('user_from', user).filter('user_to', user_to).get()
if not contact:
contact = model.Contact(user_from=user,
user_to=user_to,
user_from_nickname=user.nickname,
user_to_nickname=user_to.nickname)
contact.put()
user.contacts += 1
user.put()
self.add_follower(user=user_to, nickname=user.nickname)
followers = list(self.get_followers(user=user))
followers.append(user.nickname)
if not user_to.nickname in followers:
followers.append(user_to.nickname)
self.create_event(event_type='contact.add', followers=followers, user=user, user_to=user_to)
app = self.get_application()
subject = self.getLocale("%s has added you as contact") % user.nickname # "%s te ha agregado como contacto"
# %s te ha agregado como contacto en %s\nPuedes visitar su perfil en: %s/module/user/%s\n
body = self.getLocale("%s has added you as contact in %s\nVisit profile page: %s/module/user/%s\n") % (user.nickname, app.url, app.url, user.nickname)
self.mail(subject=subject, body=body, to=[user_to.email])
if self.get_param('x'):
self.render_json({ 'action': 'added' })
else:
self.redirect('/module/user/%s' % user_to.nickname)
else:
contact.delete()
user.contacts -= 1
user.put()
self.remove_follower(user=user_to, nickname=user.nickname)
if self.get_param('x'):
self.render_json({ 'action': 'deleted' })
else:
self.redirect('/module/user/%s' % user_to.nickname)
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from handlers.BaseHandler import *
from google.appengine.api import users
class UserArticles(BaseHandler):
def execute(self):
self.values['tab'] = '/module/user.list'
nickname = self.request.path.split('/')[3]
this_user = model.UserData.gql('WHERE nickname=:1', nickname).get()
if not this_user:
self.not_found()
return
# TODO: not show if the user profile is not public
self.values['this_user'] = this_user
query = model.Article.all().filter('author =', this_user).filter('draft =', False).filter('deletion_date', None)
self.values['articles'] = self.paging(query, 10, '-creation_date', this_user.articles, ['-creation_date'])
self.render('templates/module/user/user-articles.html')
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
import img
from google.appengine.ext import db
from google.appengine.api import images
from google.appengine.api import memcache
from handlers.AuthenticatedHandler import *
class UserEdit(AuthenticatedHandler):
def execute(self):
method = self.request.method
user = self.values['user']
if method == 'GET':
self.values['google_adsense'] = self.not_none(user.google_adsense)
self.values['google_adsense_channel'] = self.not_none(user.google_adsense_channel)
self.values['real_name'] = self.not_none(user.real_name)
self.values['links'] = [(link.split('##', 2)[1], link.split('##', 2)[0]) for link in user.list_urls]
self.values['im_addresses'] = [(link.split('##', 2)[1], link.split('##', 2)[0]) for link in user.im_addresses]
self.values['country'] = self.not_none(user.country)
self.values['city'] = self.not_none(user.city)
self.values['about'] = self.not_none(user.about_user)
self.values['personal_message'] = self.not_none(user.personal_message);
if user.not_full_rss:
self.values['not_full_rss'] = user.not_full_rss
self.render('templates/module/user/user-edit.html')
elif self.auth():
user.google_adsense = self.get_param('google_adsense')
user.google_adsense_channel = self.get_param('google_adsense_channel')
user.real_name = self.get_param('real_name')
user.personal_message = self.get_param('personal_message')
user.country = self.get_param('country')
if self.get_param('not_full_rss'):
user.not_full_rss = True
else:
user.not_full_rss = False
image = self.request.get("img")
if image:
image = images.im_feeling_lucky(image, images.JPEG)
user.avatar = img.resize(image, 128, 128)
user.thumbnail = img.resize(image, 48, 48)
if not user.image_version:
user.image_version = 1
else:
memcache.delete('/images/user/avatar/%s/%d' % (user.nickname, user.image_version))
memcache.delete('/images/user/thumbnail/%s/%d' % (user.nickname, user.image_version))
user.image_version += 1
memcache.delete('/images/user/avatar/%s' % (user.nickname))
memcache.delete('/images/user/thumbnail/%s' % (user.nickname))
user.city = self.get_param('city')
user.list_urls = []
blog = self.get_param('blog')
if blog:
if not blog.startswith('http'):
linkedin = 'http://' + blog
user.list_urls.append(blog + '##blog')
linkedin = self.get_param('linkedin')
if linkedin:
if not linkedin.startswith('http'):
linkedin = 'http://' + linkedin
user.list_urls.append(linkedin + '##linkedin')
ohloh = self.get_param('ohloh')
if ohloh:
if not ohloh.startswith('http'):
linkedin = 'http://' + ohloh
user.list_urls.append(ohloh + '##ohloh')
user.im_addresses = []
msn = self.get_param('msn')
if msn:
user.im_addresses.append(msn + '##msn')
jabber = self.get_param('jabber')
if jabber:
user.im_addresses.append(jabber + '##jabber')
gtalk = self.get_param('gtalk')
if gtalk:
user.im_addresses.append(gtalk + '##gtalk')
user.about_user = self.get_param('about_user')
user.put()
followers = list(self.get_followers(user=user))
followers.append(user.nickname)
self.create_event(event_type='user.edit', followers=followers, user=user)
self.redirect('/module/user/%s' % user.nickname)
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from handlers.BaseHandler import *
from google.appengine.api import users
class UserForums(BaseHandler):
def execute(self):
self.values['tab'] = '/module/user.list'
nickname = self.request.path.split('/')[3]
this_user = model.UserData.gql('WHERE nickname=:1', nickname).get()
if not this_user:
self.not_found()
return
# TODO: not show if the user profile is not public
self.values['this_user'] = this_user
query = model.Thread.all().filter('author', this_user).filter('parent_thread', None)
self.values['threads'] = self.paging(query, 10, '-creation_date', this_user.threads, ['-creation_date'])
self.render('templates/module/user/user-forums.html')
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from handlers.AuthenticatedHandler import *
from google.appengine.api import users
class UserDrafts(AuthenticatedHandler):
def execute(self):
user = self.get_current_user()
query = model.Article.all().filter('author =', user).filter('draft =', True).filter('deletion_date', None)
self.values['articles'] = self.paging(query, 10, '-last_update', user.draft_articles, ['-last_update'])
self.render('templates/module/user/user-drafts.html')
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
import datetime
from handlers.BaseHandler import *
from google.appengine.api import users
class UserList(BaseHandler):
def execute(self):
self.values['tab'] = '/module/user.list'
app = self.get_application()
query = model.UserData.all()
key = '%s?%s' % (self.request.path, self.request.query)
results = 10
if app.max_results:
results = app.max_results
users = self.paging(query, results, '-articles', app.users, ['-creation_date', '-articles'], key)
if users is not None:
self.values['users'] = users
self.add_tag_cloud()
self.render('templates/module/user/user-list.html')
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
import re
import model
from img import *
from utilities import session
from google.appengine.ext import webapp
from google.appengine.ext import db
from handlers.AuthenticatedHandler import *
class UserChangePassword(AuthenticatedHandler):
def execute(self):
method = self.request.method
if method == 'GET':
self.values['redirect_to'] = self.request.get('redirect_to')
self.render('templates/module/user/user-changepassword.html')
elif self.auth():
old_password = self.request.get('old_password')
password = self.request.get('password')
re_password = self.request.get('re_password')
if not password or len(password) < 4:
self.show_error( "Password must contain 4 chars at least")
return
if password != re_password:
self.show_error("New password and validation password are not equal")
return
user = self.values['user']
if self.check_password(user, old_password):
user.password = self.hash_password(user.nickname, password)
user.put()
rt = self.request.get('redirect_to')
if not rt:
rt = '/'
self.redirect(rt)
else:
self.show_error("Incorrect password")
return
def show_error(self, error):
self.values['error'] = error
self.render('templates/module/user/user-changepassword.html') | Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from handlers.BaseHandler import *
from google.appengine.api import users
class UserContacts(BaseHandler):
def execute(self):
self.values['tab'] = '/module/user.list'
nickname = self.request.path.split('/')[3]
this_user = model.UserData.gql('WHERE nickname=:1', nickname).get()
if not this_user:
self.not_found()
return
# TODO: not show if the user profile is not public
self.values['this_user'] = this_user
query = model.Contact.all().filter('user_from', this_user)
contacts = self.paging(query, 27, '-creation_date', this_user.contacts, ['-creation_date'])
self.values['users'] = contacts
self.render('templates/module/user/user-contacts.html')
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from handlers.BaseHandler import *
from google.appengine.api import users
class UserView(BaseHandler):
def execute(self):
self.values['tab'] = '/module/user.list'
nickname = self.request.path.split('/')[3]
this_user = model.UserData.gql('WHERE nickname=:1', nickname).get()
if not this_user:
self.not_found()
return
# TODO: not show if the user profile is not public
user = self.values['user']
contact = False
if user and user.nickname != this_user.nickname:
self.values['canadd'] = True
contact = self.is_contact(this_user)
self.values['is_contact'] = contact
if (user is not None and this_user.nickname == user.nickname) or contact:
self.values['im_addresses'] = [(link.split('##', 2)[1], link.split('##', 2)[0]) for link in this_user.im_addresses]
else:
self.values['im_addresses'] = []
self.values['this_user'] = this_user
linksChanged = False
counter = 0
for link in this_user.list_urls:
if not link.startswith('http'):
linksChanged = True
link = 'http://' + link
this_user.list_urls[counter] = link
if link.startswith('http://https://'):
linksChanged = True
link = link[7:len(link)]
this_user.list_urls[counter] = link
counter += 1
if linksChanged:
this_user.put()
links = [(link.split('##', 2)[1], link.split('##', 2)[0]) for link in this_user.list_urls]
self.values['links'] = links
self.values['personal_message'] = this_user.personal_message
self.values['articles'] = model.Article.all().filter('author =', this_user).filter('draft =', False).filter('deletion_date', None).order('-creation_date').fetch(5)
self.values['communities'] = model.CommunityUser.all().filter('user =', this_user).order('-creation_date').fetch(18)
self.values['contacts'] = model.Contact.all().filter('user_from', this_user).order('-creation_date').fetch(18)
self.render('templates/module/user/user-view.html')
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
import model
from handlers.BaseHandler import *
from google.appengine.api import users
class UserLogout(BaseHandler):
def execute(self):
#Check if google account is in use
#User registered with different user in vikuit and google
user = users.get_current_user()
userLocalId = self.sess.user
googleAc = False
if user and userLocalId:
userLocal = db.get(userLocalId)
if userLocal and user.email() == userLocal.email:
googleAc = True
redirect = '/'
try:
if self.auth():
self.sess.store('', 0)
if self.request.referrer:
redirect = self.request.referrer
except KeyError:
self.redirect(redirect)
return
if googleAc:
self.redirect(users.create_logout_url(redirect))
else:
self.redirect(redirect) | Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
import model
import random
from handlers.BaseHandler import *
from google.appengine.api import mail
from utilities.AppProperties import AppProperties
class UserForgotPassword(BaseHandler):
def execute(self):
method = self.request.method
if method == 'GET':
self.values['redirect_to'] = self.request.get('redirect_to')
self.render('templates/module/user/user-forgotpassword.html')
else:
email = self.request.get('email')
u = model.UserData.all().filter('email =', email).get()
if not u:
self.show_error(email, "No user found with this mail")
return
# only local accounts can reset password
app = self.get_application()
subject = self.getLocale("Password recovery")#u"Recuperar password"
if u.registrationType is None or u.registrationType == 0:
u.token = self.hash(str(random.random()), email)
u.put()
#Haz click en el siguiente enlace para proceder a establecer tu password.\n%s/module/user.resetpassword?nickname=%s&token=%s
body = self.getLocale("Click this link to set your password.\n%s/module/user.resetpassword?nickname=%s&token=%s") % (app.url, u.nickname, u.token)
else:
accountProvider = AppProperties().getAccountProvider(u.registrationType)
body = self.getLocale("You have requested to recover password but credentials you use in %s are from %s. Review your login information.") % (app.name, accountProvider)
self.mail(subject=subject, body=body, to=[u.email])
self.values['token'] = u.token
self.values['email'] = email
self.values['redirect_to'] = self.request.get('redirect_to')
self.render('templates/module/user/user-forgotpassword-sent.html')
def show_error(self, email, error):
self.values['email'] = email
self.values['error'] = error
self.render('templates/module/user/user-forgotpassword.html') | Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from handlers.BaseHandler import *
from google.appengine.api import users
class UserCommunities(BaseHandler):
def execute(self):
self.values['tab'] = '/module/user.list'
nickname = self.request.path.split('/')[3]
this_user = model.UserData.gql('WHERE nickname=:1', nickname).get()
if not this_user:
self.not_found()
return
# TODO: not show if the user profile is not public
self.values['this_user'] = this_user
query = model.CommunityUser.all().filter('user', this_user)
communities = self.paging(query, 10, '-creation_date', this_user.communities, ['-creation_date'])
self.values['communities'] = communities
self.render('templates/module/user/user-communities.html')
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
import re
import random
import model
from handlers.BaseHandler import *
from os import environ
from recaptcha import captcha
class UserRegister(BaseHandler):
def execute(self):
method = self.request.method
if method == 'GET':
self.send_form(None)
else:
if self.get_param('x'):
# check if nickname is available
nickname = self.request.get('nickname')
email = self.request.get('email')
message = self.validate_nickname(nickname)
if message:
self.render_json({'valid': False, 'message': message})
else :
self.render_json({'valid': True })
return
else:
# Validate captcha
challenge = self.request.get('recaptcha_challenge_field')
response = self.request.get('recaptcha_response_field')
remoteip = environ['REMOTE_ADDR']
cResponse = captcha.submit(
challenge,
response,
self.get_application().recaptcha_private_key,
remoteip)
if not cResponse.is_valid:
# If the reCAPTCHA server can not be reached,
# the error code recaptcha-not-reachable will be returned.
self.send_form(cResponse.error_code)
return
nickname = self.request.get('nickname')
email = self.request.get('email')
password = self.request.get('password')
re_email = self.request.get('re_email')
re_password = self.request.get('re_password')
if not self.get_param('terms-and-conditions'):
self.show_error(nickname, email, "You must accept terms and conditions" )
return
if not re.match('^[\w\.-]{3,}@([\w-]{2,}\.)*([\w-]{2,}\.)[\w-]{2,4}$', email):
self.show_error(nickname, email, "Enter a valid mail" )
return
if not re.match('^[\w\.-]+$', nickname):
self.show_error(nickname, email, "Username can contain letters, numbers, dots, hyphens and underscores" )
return
if not password or len(password) < 4 or len(password) > 30:
self.show_error(nickname, email, "Password must contain between 4 and 30 chars" )
return
message = self.validate_nickname(nickname)
if message:
self.show_error(nickname, email, message)
return
u = model.UserData.all().filter('email =', email).get()
if u:
self.show_error(nickname, email, "This mail already exists" )
return
if email != re_email:
self.show_error(nickname, email, "Mail and validation mail are not equals" )
return
if password != re_password:
self.show_error(nickname, email, "New password and validation password are not equal" )
return
times = 5
user = model.UserData(nickname=nickname,
email=email,
password=self.hash_password(nickname, password),
articles=0,
draft_articles=0,
messages=0,
draft_messages=0,
comments=0,
rating_count=0,
rating_total=0,
rating_average=0,
threads=0,
responses=0,
communities=0,
favourites=0,
public=False,
contacts=0)
user.registrationType = 0#local identifier
user.put()
app = model.Application.all().get()
if app:
app.users += 1
app.put()
memcache.delete('app')
#send welcome email
app = self.get_application()
subject = self.getLocale("Welcome to %s") % app.name
bt = "Thanks for signing in %s. %s team welcome you to our social network. \n\nComplete your profile \n%s/module/user.edit\n\nPublish articles, \n\n\nBe part of the communities that interest you. Each community has a forum to share or discuss with people to whom the same interests as you.\nCommunities list %s/module/community.list\nThread list %s/forum.list\n\n\n\nFor futher information check our FAQ page\n%s/html/faq.html\n\nBest regards,\n\n%s Team."
body = self.getLocale(bt) % (app.name, app.name, app.url, app.url, app.url, app.url, app.name)
self.mail(subject=subject, body=body, to=[user.email])
self.sess.store(str(user.key()), 7200)
rt = self.request.get('redirect_to')
if not rt:
rt = '/'
self.redirect(rt)
def show_error(self, nickname, email, error):
chtml = self.get_captcha(None)
self.values['captchahtml'] = chtml
self.values['nickname'] = nickname
self.values['email'] = email
self.values['error'] = error
self.render('templates/module/user/user-register.html')
def match(self, pattern, value):
m = re.match(pattern, value)
if not m or not m.string[m.start():m.end()] == value:
return None
return value
def send_form(self, error):
chtml = self.get_captcha(error)
self.values['captchahtml'] = chtml
self.values['redirect_to'] = self.request.get('redirect_to')
self.render('templates/module/user/user-register.html')
def get_captcha(self, error):
chtml = captcha.displayhtml(
public_key = self.get_application().recaptcha_public_key,
use_ssl = False,
error = error)
return chtml
def validate_nickname(self, nickname):
if len(nickname) < 4:
return self.getLocale("Username must contain 4 chars at least")
if len(nickname) > 20:
return self.getLocale("Username must contain less than 20 chars")
u = model.UserData.all().filter('nickname =', nickname).get()
if u:
return self.getLocale("User already exists")
return '' | Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
import model
import random
import datetime
from handlers.BaseHandler import *
class UserLogin(BaseHandler):
def execute(self):
self.sess.valid = False
method = self.request.method
if method == 'GET':
self.values['redirect_to'] = self.request.get('redirect_to')
self.render('templates/module/user/user-login.html')
else:
nickname = self.request.get('nickname')
password = self.request.get('password')
user = model.UserData.gql('WHERE nickname=:1', nickname).get()
if user:
if user.registrationType is not None and user.registrationType > 0:
self.show_error("", "Invalid login method")
return##No es posible cambiar el pass si el user no es de vikuit
if self.check_password(user, password):
if user.banned_date is not None:
self.show_error(nickname, "User '%s' was blocked. Contact with an administrator.")
return
user.last_login = datetime.datetime.now()
user.password = self.hash_password(user.nickname, password) # if you want to change the way the password is hashed
user.put()
if self.get_param('remember') == 'remember':
expires = 1209600
else:
expires = 7200
self.sess.store(str(user.key()), expires)
rt = self.request.get('redirect_to')
if rt:
if rt.find("user.login") >-1:
self.redirect('/')
else:
self.redirect(rt)
else:
self.redirect('/')
else:
self.show_error("", "Invalid user or password")
else:
self.show_error("", "Invalid user or password")
def show_error(self, nickname, error):
self.values['nickname'] = nickname
self.values['error'] = error
self.render('templates/module/user/user-login.html') | Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from handlers.AuthenticatedHandler import *
class AdminUsers(AuthenticatedHandler):
def execute(self):
method = self.request.method
user = self.values['user']
self.values['tab'] = '/admin'
if user.rol != 'admin':
self.forbidden()
return
if method == 'GET':
self.render('templates/module/admin/admin-users.html')
elif self.auth():
nickname = self.get_param('nickname')
if nickname is None or nickname == '':
self.values['m'] = "Complete Nickname field"
self.render('/admin-users.html')
return
u = model.UserData.all().filter('nickname', nickname).get()
if u is None:
self.values['m'] = "User '%s' doesn't exists"
self.values['arg'] = nickname
self.render('/admin-users.html')
return
action = self.get_param('action')
if action == 'block_user':
u.banned_date = datetime.datetime.now()
u.put()
self.values['m'] = "User '%s' was blocked"
self.values['arg'] = nickname
elif action == 'unblock_user':
u.banned_date = None
u.put()
self.values['m'] = "User '%s' was unlocked"
self.values['arg'] = nickname
else:
self.values['m'] = "Action '%s' not found"
self.values['arg'] = action
self.render('/admin-users.html') | Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
# (C) Copyright 2011 Jose Carrasco <jose.carrasco[a]vikuit.com>
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
import img
from google.appengine.api import images
from google.appengine.api import memcache
from handlers.AuthenticatedHandler import *
from utilities.AppProperties import AppProperties
class AdminApplication(AuthenticatedHandler):
def execute(self):
method = self.request.method
user = self.values['user']
self.values['tab'] = '/admin'
if user.rol != 'admin':
self.forbidden()
return
if method == 'GET':
app = self.get_application()
self.values['m'] = self.get_param('m')
if not app:
app = model.Application()
self.values['app'] = app
self.values['appName'] = self.not_none(app.name)
self.values['appSubject'] = self.not_none(app.subject)
self.values['locale'] = self.not_none(app.locale)
self.values['url'] = self.not_none(app.url)
self.render('templates/module/admin/admin-application.html')
elif self.auth():
app = self.get_application()
if not app:
app = model.Application()
app.users = model.UserData.all().count()
app.communities = model.Community.all().count()
app.threads = model.Thread.all().filter('parent_thread', None).count()
app.articles = model.Article.all().filter('draft =', False).filter('deletion_date', None).count()
app.name = self.get_param('appName')
app.subject = self.get_param("appSubject")
app.locale = self.get_param("locale")
app.url = self.get_param('url')
app.put()
memcache.delete('app')
AppProperties().updateJinjaEnv()
self.redirect('/module/admin.application?m='+self.getLocale('Updated')) | Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
# (C) Copyright 2011 Jose Carrasco <jose.carrasco[a]vikuit.com>
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
import img
from google.appengine.api import images
from google.appengine.api import memcache
from handlers.module.admin.AdminApplication import *
from handlers.AuthenticatedHandler import *
from utilities.AppProperties import AppProperties
class AdminLookAndFeel(AuthenticatedHandler):
def execute(self):
method = self.request.method
user = self.values['user']
self.values['tab'] = '/admin'
if user.rol != 'admin':
self.forbidden()
return
if method == 'GET':
app = self.get_application()
self.values['m'] = self.get_param('m')
if not app:
app = model.Application()
self.values['app'] = app
self.values['theme'] = self.not_none(app.theme)
self.values['max_results'] = self.not_none(app.max_results)
self.values['max_results_sublist'] = self.not_none(app.max_results_sublist)
self.render('templates/module/admin/admin-lookandfeel.html')
elif self.auth():
app = self.get_application()
if not app:
app = model.Application()
logo = self.request.get("logo")
if logo:
app.logo = images.im_feeling_lucky(logo, images.JPEG)
memcache.delete('/images/application/logo')
app.theme = self.get_param("theme")
if self.get_param('max_results'):
app.max_results = int(self.get_param('max_results'))
if self.get_param('max_results_sublist'):
app.max_results_sublist = int(self.get_param('max_results_sublist'))
app.put()
memcache.delete('app')
AppProperties().updateJinjaEnv()
self.redirect('/module/admin.lookandfeel?m='+self.getLocale('Updated')) | Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from handlers.AuthenticatedHandler import *
class AdminCategoryEdit(AuthenticatedHandler):
def execute(self):
method = self.request.method
user = self.values['user']
self.values['tab'] = '/admin'
if user.rol != 'admin':
self.forbidden()
return
key = self.get_param('key')
self.values['parent_categories'] = list(model.Category.all().filter('parent_category', None).order('title'))
self.values['parent_category'] = None
if method == 'GET':
if key:
# show edit form
category = model.Category.get(key)
self.values['key'] = key
self.values['title'] = category.title
self.values['description'] = category.description
self.values['parent_category'] = str(category.parent_category.key())
self.render('templates/module/admin/admin-category-edit.html')
else:
# show an empty form
self.values['key'] = None
self.values['title'] = "New category"
self.values['description'] = "Description"
self.render('templates/module/admin/admin-category-edit.html')
elif self.auth():
title = self.get_param('title')
desc = self.get_param('description')
if title is None or len(title.strip()) == 0 or desc is None or len(desc.strip()) == 0:
self.values['m'] = "Title and description are mandatory fields"
self.values['key'] = key
self.values['title'] = title
self.values['description'] = desc
self.values['parent_category'] = self.request.get('parent_category')
self.render('templates/module/admin/admin-category-edit.html')
return
if key:
# update category
category = model.Category.get(key)
category.title = self.get_param('title')
category.description = self.get_param('description')
category.url_path = self.to_url_path(category.title)
parent_key = self.request.get('parent_category')
if parent_key:
category.parent_category = model.Category.get(parent_key)
category.put()
self.redirect('/module/admin.categories')
else:
category = model.Category(title=self.get_param('title'),
description=self.get_param('description'),
articles = 0,
communities = 0)
category.url_path = self.to_url_path(category.title)
parent_key = self.request.get('parent_category')
if parent_key:
category.parent_category = model.Category.get(parent_key)
category.put()
self.redirect('/module/admin.categories') | Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
# (C) Copyright 2011 Jose Carrasco <jose.carrasco[a]vikuit.com>
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
import img
from google.appengine.api import images
from google.appengine.api import memcache
from handlers.AuthenticatedHandler import *
from utilities.AppProperties import AppProperties
class AdminModules(AuthenticatedHandler):
def execute(self):
method = self.request.method
user = self.values['user']
self.values['tab'] = '/admin'
if user.rol != 'admin':
self.forbidden()
return
if method == 'GET':
app = self.get_application()
self.values['m'] = self.get_param('m')
if not app:
app = model.Application()
self.values['app'] = app
self.values['appName'] = self.not_none(app.name)
self.values['appSubject'] = self.not_none(app.subject)
self.values['locale'] = self.not_none(app.locale)
self.values['theme'] = self.not_none(app.theme)
self.values['url'] = self.not_none(app.url)
self.values['mail_contact'] = self.not_none(app.mail_contact)
self.values['mail_subject_prefix'] = self.not_none(app.mail_subject_prefix)
self.values['mail_sender'] = self.not_none(app.mail_sender)
self.values['mail_footer'] = self.not_none(app.mail_footer)
self.values['recaptcha_public_key'] = self.not_none(app.recaptcha_public_key)
self.values['recaptcha_private_key']= self.not_none(app.recaptcha_private_key)
self.values['google_adsense'] = self.not_none(app.google_adsense)
self.values['google_adsense_channel']= self.not_none(app.google_adsense_channel)
self.values['google_analytics'] = self.not_none(app.google_analytics)
self.values['max_results'] = self.not_none(app.max_results)
self.values['max_results_sublist'] = self.not_none(app.max_results_sublist)
self.render('templates/module/admin/admin-modules.html')
elif self.auth():
app = self.get_application()
if not app:
app = model.Application()
app.users = model.UserData.all().count()
app.communities = model.Community.all().count()
app.threads = model.Thread.all().filter('parent_thread', None).count()
app.articles = model.Article.all().filter('draft =', False).filter('deletion_date', None).count()
app.name = self.get_param('appName')
app.subject = self.get_param("appSubject")
app.locale = self.get_param("locale")
logo = self.request.get("logo")
if logo:
app.logo = images.im_feeling_lucky(logo, images.JPEG)
memcache.delete('/images/application/logo')
app.theme = self.get_param("theme")
app.url = self.get_param('url')
app.mail_subject_prefix = self.get_param('mail_subject_prefix')
app.mail_contact = self.get_param('mail_contact')
app.mail_sender = self.get_param('mail_sender')
app.mail_footer = self.get_param('mail_footer')
app.recaptcha_public_key = self.get_param('recaptcha_public_key')
app.recaptcha_private_key = self.get_param('recaptcha_private_key')
app.google_adsense = self.get_param('google_adsense')
app.google_adsense_channel = self.get_param('google_adsense_channel')
app.google_analytics = self.get_param('google_analytics')
if self.get_param('max_results'):
app.max_results = int(self.get_param('max_results'))
if self.get_param('max_results_sublist'):
app.max_results_sublist = int(self.get_param('max_results_sublist'))
app.put()
memcache.delete('app')
AppProperties().updateJinjaEnv()
self.redirect('/module/admin.application?m='+self.getLocale('Updated')) | Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from handlers.AuthenticatedHandler import *
class CommunityAddRelated(AuthenticatedHandler):
def execute(self):
method = self.request.method
user = self.values['user']
self.values['tab'] = '/admin'
if user.rol != 'admin':
self.forbidden()
return
if method == 'GET':
self.values['m'] = self.get_param('m')
self.render('templates/module/community/community-add-related.html')
elif self.auth():
fromId = self.request.get('community_from')
toId = self.request.get('community_to')
if fromId is None or len(fromId.strip()) == 0 or not fromId.isdigit():
self.values['m'] = "Enter a valid source community"
self.render('templates/module/community/community-add-related.html')
return
if toId is None or len(toId.strip()) == 0:
self.values['m'] = "Enter a valid target community"
self.render('templates/module/community/community-add-related.html')
return
community_from = model.Community.get_by_id(int(fromId))
community_to = model.Community.get_by_id(int(toId))
related = model.RelatedCommunity.all().filter('community_from', community_from).filter('community_to', community_to).get()
if related:
self.redirect('/module/community.add.related?m=Already_exists')
return
if community_from is None:
self.values['m'] = "Source community not found"
self.render('templates/module/community/community-add-related.html')
return
if community_to is None:
self.values['m'] = "Target community not found"
self.render('templates/module/community/community-add-related.html')
return
self.create_related(community_from, community_to)
self.create_related(community_to, community_from)
self.redirect('/module/community.add.related?m=Updated')
def create_related(self, community_from, community_to):
related = model.RelatedCommunity(community_from = community_from,
community_to = community_to,
community_from_title = community_from.title,
community_from_url_path = community_from.url_path,
community_to_title = community_to.title,
community_to_url_path = community_to.url_path)
related.put() | Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
# (C) Copyright 2011 Jose Carrasco <jose.carrasco[a]vikuit.com>
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
import img
from google.appengine.api import images
from google.appengine.api import memcache
from handlers.AuthenticatedHandler import *
from utilities.AppProperties import AppProperties
class AdminMail(AuthenticatedHandler):
def execute(self):
method = self.request.method
user = self.values['user']
self.values['tab'] = '/admin'
if user.rol != 'admin':
self.forbidden()
return
if method == 'GET':
app = self.get_application()
self.values['m'] = self.get_param('m')
if not app:
app = model.Application()
self.values['app'] = app
self.values['mail_contact'] = self.not_none(app.mail_contact)
self.values['mail_subject_prefix'] = self.not_none(app.mail_subject_prefix)
self.values['mail_sender'] = self.not_none(app.mail_sender)
self.values['mail_footer'] = self.not_none(app.mail_footer)
self.render('templates/module/admin/admin-mail.html')
elif self.auth():
app = self.get_application()
if not app:
app = model.Application()
app.mail_subject_prefix = self.get_param('mail_subject_prefix')
app.mail_contact = self.get_param('mail_contact')
app.mail_sender = self.get_param('mail_sender')
app.mail_footer = self.get_param('mail_footer')
app.put()
memcache.delete('app')
AppProperties().updateJinjaEnv()
self.redirect('/module/admin.mail?m='+self.getLocale('Updated')) | Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
# (C) Copyright 2011 Jose Carrasco <jose.carrasco[a]vikuit.com>
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
import img
from google.appengine.api import images
from google.appengine.api import memcache
from handlers.AuthenticatedHandler import *
from utilities.AppProperties import AppProperties
class AdminGoogle(AuthenticatedHandler):
def execute(self):
method = self.request.method
user = self.values['user']
self.values['tab'] = '/admin'
if user.rol != 'admin':
self.forbidden()
return
if method == 'GET':
app = self.get_application()
self.values['m'] = self.get_param('m')
if not app:
app = model.Application()
self.values['app'] = app
self.values['recaptcha_public_key'] = self.not_none(app.recaptcha_public_key)
self.values['recaptcha_private_key']= self.not_none(app.recaptcha_private_key)
self.values['google_adsense'] = self.not_none(app.google_adsense)
self.values['google_adsense_channel']= self.not_none(app.google_adsense_channel)
self.values['google_analytics'] = self.not_none(app.google_analytics)
self.render('templates/module/admin/admin-google.html')
elif self.auth():
app = self.get_application()
if not app:
app = model.Application()
app.recaptcha_public_key = self.get_param('recaptcha_public_key')
app.recaptcha_private_key = self.get_param('recaptcha_private_key')
app.google_adsense = self.get_param('google_adsense')
app.google_adsense_channel = self.get_param('google_adsense_channel')
app.google_analytics = self.get_param('google_analytics')
app.put()
memcache.delete('app')
AppProperties().updateJinjaEnv()
self.redirect('/module/admin.google?m='+self.getLocale('Updated')) | Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
import img
from google.appengine.api import images
from google.appengine.api import memcache
from handlers.AuthenticatedHandler import *
from utilities.AppProperties import AppProperties
class AdminCache(AuthenticatedHandler):
def execute(self):
method = self.request.method
user = self.values['user']
self.values['tab'] = '/admin'
if user.rol != 'admin':
self.forbidden()
return
if method == 'POST':
memcache.flush_all()
self.values['m'] = "Cache is clean"
self.getRelevantCacheData()
self.render('templates/module/admin/admin-cache.html')
def getRelevantCacheData(self):
cacheData = memcache.get_stats()
self.values['cdItems'] = cacheData['items']
self.values['cdBytes'] = cacheData['bytes']
self.values['cdOldest'] = cacheData['oldest_item_age'] | Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from handlers.AuthenticatedHandler import *
class Admin(AuthenticatedHandler):
def execute(self):
method = self.request.method
user = self.values['user']
self.values['tab'] = '/admin'
if user.rol != 'admin':
self.forbidden()
return
self.redirect('/module/admin.application')
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from handlers.AuthenticatedHandler import *
class AdminCategories(AuthenticatedHandler):
def execute(self):
method = self.request.method
user = self.values['user']
self.values['tab'] = '/admin'
if user.rol != 'admin':
self.forbidden()
return
self.add_categories()
self.render('templates/module/admin/admin-categories.html') | Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from handlers.AuthenticatedHandler import *
class AdminStats(AuthenticatedHandler):
def execute(self):
method = self.request.method
user = self.values['user']
self.values['tab'] = '/admin'
if user.rol != 'admin':
self.forbidden()
return
self.render('templates/module/admin/admin-stats.html')
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
import time
import datetime
from google.appengine.ext import db
from google.appengine.api import memcache
from handlers.AuthenticatedHandler import *
class ArticleEdit(AuthenticatedHandler):
def execute(self):
self.values['tab'] = '/module/article.list'
method = self.request.method
user = self.values['user']
key = self.get_param('key')
x = self.get_param('x')
draft = False
if self.get_param('save_draft'):
draft = True
licenses = [ { 'id': 'copyright', 'lic': '© Todos los derechos reservados' },
{ 'id': 'pd', 'lic': u'Dominio público' },
{ 'id': 'by', 'lic': 'Creative Commons: Reconocimiento' },
{ 'id': 'by-nc', 'lic': 'Creative Commons: Reconocimiento-No comercial' },
{ 'id': 'by-nc-nd', 'lic': 'Creative Commons: Reconocimiento-No comercial-Sin obras derivadas' },
{ 'id': 'by-nc-sa', 'lic': 'Creative Commons: Reconocimiento-No comercial-Compartir bajo la misma licencia' },
{ 'id': 'by-nd', 'lic': 'Creative Commons: Reconocimiento-Sin obras derivadas' },
{ 'id': 'by-sa', 'lic': 'Creative Commons: Reconocimiento-Compartir bajo la misma licencia' }
]
self.values['licenses'] = licenses
if method == 'GET':
if key:
# show edit form
article = model.Article.get(key)
if not article:
self.not_found()
return
if not user.nickname == article.author.nickname and user.rol != 'admin':
self.forbidden()
return
self.values['key'] = key
self.values['title'] = article.title
self.values['lic'] = article.lic
self.values['tags'] = ', '.join(article.tags)
self.values['description'] = article.description
self.values['content'] = article.content
self.values['draft'] = article.draft
self.render('templates/module/article/article-edit.html')
else:
# show an empty form
self.values['title'] = u'Título...'
self.values['lic'] = 'copyright'
self.values['draft'] = True
self.render('templates/module/article/article-edit.html')
elif self.auth():
if x and draft:
# check mandatory fields
if not self.get_param('title') or not self.get_param('tags') or not self.get_param('description') or not self.get_param('content'):
self.render_json({ 'saved': False })
return
if key:
# update article
article = model.Article.get(key)
memcache.delete(str(article.key().id()) + '_html')
if not article:
self.not_found()
return
if not user.nickname == article.author.nickname and user.rol != 'admin':
self.forbidden()
return
lic = self.get_param('lic')
lics = [license['id'] for license in licenses]
if not lic in lics:
lic = 'copyright'
if not article.draft:
self.delete_tags(article.tags)
article.lic = lic
article.tags = self.parse_tags(self.get_param('tags'))
article.description = ' '.join(self.get_param('description').splitlines())
article.content = self.get_param('content')
if article.draft:
# title and url_path can change only if the article hasn't already been published
article.title = self.get_param('title')
article.url_path = '%d/%s' % (article.key().id(), self.to_url_path(article.title))
add_communities = False
if article.draft and not draft:
article.draft = draft
user.articles += 1
user.draft_articles -=1
user.put()
article.creation_date = datetime.datetime.now()
self.add_follower(article=article, nickname=user.nickname)
followers = list(self.get_followers(user=user))
followers.append(user.nickname)
self.create_event(event_type='article.new', followers=followers, user=user, article=article)
app = model.Application.all().get()
if app:
app.articles += 1
app.put()
memcache.delete('app')
add_communities = True
if not article.draft:
self.create_recommendations(article)
if not article.author_nickname:
article.author_nickname = user.nickname
if not article.content_html:
html = model.ArticleHtml(content=article.content)
html.put()
article.content_html = html
else:
html_content = article.content
html_content = self.media_content(html_content)
article.content_html.content = html_content
article.content_html.put()
article.put()
#memcache.delete('index_articles')
#memcache.delete('tag_cloud')
#memcache.delete(str(article.key().id()))
self.delete_articles_cache(str(article.key().id()))
if not draft:
self.update_tags(article.tags)
if x:
self.render_json({ 'saved': True, 'key' : str(article.key()), 'updated' : True, "draft_articles" : str(user.draft_articles) })
else:
if add_communities:
self.redirect('/module/article.add.communities?key=%s' % str(article.key()))
else:
self.redirect('/module/article/%s' % article.url_path)
else:
# new article
today = datetime.date.today()
title = self.get_param('title')
tags = self.parse_tags(self.get_param('tags'))
lic = self.get_param('lic')
lics = [license['id'] for license in licenses]
if not lic in lics:
lic = 'copyright'
article = model.Article(author=user,
author_nickname=user.nickname,
title=title,
description=' '.join(self.get_param('description').splitlines()),
content=self.get_param('content'),
lic=lic,
url_path='empty',
tags=tags,
draft=draft,
article_type='article',
views=0,
responses=0,
rating_count=0,
rating_total=0,
favourites=0)
html_content = article.content
html = model.ArticleHtml(content=self.media_content(html_content))
html.put()
article.content_html = html
article.subscribers = [user.email]
article.put()
self.add_user_subscription(user, 'article', article.key().id())
article.url_path = '%d/%s' % (article.key().id(), self.to_url_path(article.title))
article.put()
#memcache.delete('index_articles')
#memcache.delete('tag_cloud')
#memcache.delete(str(article.key().id()))
self.delete_articles_cache(str(article.key().id()))
if not draft:
self.create_recommendations(article)
user.articles += 1
user.put()
self.update_tags(tags)
self.add_follower(article=article, nickname=user.nickname)
followers = list(self.get_followers(user=user))
followers.append(user.nickname)
self.create_event(event_type='article.new', followers=followers, user=user, article=article)
app = model.Application.all().get()
if app:
app.articles += 1
app.put()
memcache.delete('app')
else:
user.draft_articles += 1
user.put()
if x:
self.render_json({ 'saved': True, 'key' : str(article.key()), "updated" : False, "draft_articles" : str(user.draft_articles) })
else:
if article.draft:
self.redirect('/module/article/%s' % article.url_path)
else:
self.redirect('/module/article.add.communities?key=%s' % str(article.key()))
def create_recommendations(self, article):
self.create_task('article_recommendation', 1, {'article': article.key().id(), 'offset': 0})
def delete_articles_cache(self, article_id):
"""
Deletes cache for 5 first pages of articles list, initial article list in the init page,
tag_cloud and current article
"""
str = '/module/article.list'
keys = [str]
keys = ['%s?' % str]
x = 1
while x < 6 :
keys.append('%s?p=%s&' % (str, x))
x = x+1
keys.append('index_articles')
keys.append('tag_cloud')
keys.append(article_id)
memcache.delete_multi(keys)
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from handlers.BaseRest import *
class ArticleVisit(BaseRest):
def get(self):
article_id = self.request.get('id')
memcache.delete(article_id + '_article')
article = model.Article.get_by_id(int(article_id))
article.views += 1
article.put()
memcache.add(str(article.key().id()) + '_article', article, 0)
content = []
self.render_json("{\"views\" : "+str(article.views)+"}")
return | Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from google.appengine.ext import db
from handlers.AuthenticatedHandler import *
class ArticleVote(AuthenticatedHandler):
def execute(self):
article = model.Article.get(self.get_param('key'))
if not article or article.draft or article.deletion_date:
self.not_found()
return
if not self.auth():
return
memcache.delete(str(article.key().id()) + '_article')
rating = int(self.get_param('rating'))
if rating < 0:
rating = 0
elif rating > 5:
rating = 5
user = self.values['user']
avg = article.rating_average
if article and article.author.nickname != user.nickname:
vote = model.Vote.gql('WHERE user=:1 and article=:2', user, article).get()
if not vote:
vote = model.Vote(user=user,rating=rating,article=article)
vote.put()
article.rating_count += 1
article.rating_total += rating
article.rating_average = int(article.rating_total / article.rating_count)
article.put()
author = article.author
author.rating_count += 1
author.rating_total += rating
author.rating_average = int(author.rating_total / author.rating_count)
author.put()
avg = article.rating_average
memcache.add(str(article.key().id()) + '_article', article, 0)
if self.get_param('x'):
self.render_json({ 'average': avg, 'votes': article.rating_count })
else:
self.redirect('/module/article/%s' % article.url_path)
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from google.appengine.ext import db
from handlers.AuthenticatedHandler import *
class ArticleCommentEdit(AuthenticatedHandler):
def execute(self):
self.values['tab'] = '/module/article.list'
method = self.request.method
user = self.values['user']
comment_key = self.get_param('key')
if method == 'GET':
if comment_key:
# show edit form
comment = model.Comment.get(comment_key)
if user.nickname != comment.author_nickname and user.rol != 'admin':
self.forbidden()
return
if comment is None:
self.not_found()
return
self.values['article'] = comment.article
self.values['comment'] = comment
self.values['comment_key'] = comment.key
self.render('templates/module/article/article-comment-edit.html')
return
else:
self.show_error("Comment not found")
return
elif self.auth():
if comment_key:
# update comment
comment = model.Comment.get(comment_key)
if user.nickname != comment.author_nickname and user.rol != 'admin':
self.forbidden()
return
if not comment:
self.not_found()
return
content = self.get_param('content')
if not content:
self.values['article'] = comment.article
self.values['comment'] = comment
self.values['comment_key'] = comment.key
self.values['m'] = "Content is mandatory"
self.render('templates/module/article/article-comment-edit.html')
return
comment.content = content
if user.rol != 'admin':
if comment.editions is None:
comment.editions = 0
comment.editions +=1
comment.last_edition = datetime.datetime.now()
comment.put()
results = 10
app = self.get_application()
if app.max_results_sublist:
results = app.max_results_sublist
page = comment.response_number / results
if (comment.response_number % results) > 0:
page += 1
self.redirect('/module/article/%s?p=%d#comment-%s' % (comment.article.url_path, page, comment.response_number))
else:
self.show_error("Comment not found")
return | Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
import time
import datetime
from google.appengine.ext import db
from google.appengine.api import mail
from handlers.AuthenticatedHandler import *
class ArticleComment(AuthenticatedHandler):
def execute(self):
user = self.values['user']
key = self.get_param('key')
article = model.Article.get(key)
memcache.delete(str(article.key().id()) + '_article')
if not article or article.draft or article.deletion_date:
self.not_found()
return
if not self.auth():
return
content = self.get_param('content')
if not content:
self.show_error("Content is mandatory")
return
preview = self.get_param('preview')
if preview:
comment = model.Comment(article=article,
author=user,
author_nickname=user.nickname,
content=content)
self.values['comment'] = comment
self.values['preview'] = True
self.render('templates/module/article/article-comment-edit.html')
return
if self.check_duplicate(article, user, content):
self.show_error("Duplicated comment")
return
# migration
if not article.subscribers:
com = [c.author.email for c in model.Comment.all().filter('article', article).fetch(1000) ]
com.append(article.author.email)
article.subscribers = list(set(com))
# end migration
comment = model.Comment(article=article,
author=user,
author_nickname=user.nickname,
content=content,
editions = 0,
response_number=article.responses+1)
comment.put()
results = 10
app = self.get_application()
if app.max_results_sublist:
results = app.max_results_sublist
page = comment.response_number / results
if (comment.response_number % results) > 0:
page += 1
comment_url = '/module/article/%s?p=%d#comment-%d' % (article.url_path, page, comment.response_number)
user.comments += 1
user.put()
article.responses += 1
article.put()
followers = list(self.get_followers(user=user))
followers.append(user.nickname)
followers.extend(self.get_followers(article=article))
followers = list(set(followers))
self.create_event(event_type='article.comment',
followers=followers, user=user, article=article, response_number=comment.response_number)
memcache.add(str(article.key().id()) + '_article', article, 0)
subscribers = article.subscribers
if subscribers and user.email in subscribers:
subscribers.remove(user.email)
if subscribers:
subject = self.getLocale("New comment in: '%s'") % self.clean_ascii(article.title)
#Nuevo comentario en el artículo: '%s':\n%s%s\n\nTodos los comentarios en:\n%s/module/article/%s#comments\n\nEliminar suscripción a este artículo:\n%s/module/article.comment.subscribe?key=%s\n
body = self.getLocale("New comment in article: '%s':\n%s%s\n\nAll comments at:\n%s/module/article/%s#comments\n\nUnsuscribe this article:\n%s/module/article.comment.subscribe?key=%s\n") % (self.clean_ascii(article.title), app.url, comment_url, app.url, article.url_path, app.url, str(article.key()))
self.mail(subject=subject, body=body, bcc=subscribers)
subscribe = self.get_param('subscribe')
if subscribe and not user.email in article.subscribers:
article.subscribers.append(user.email)
self.redirect(comment_url)
def check_duplicate(self, article, user, content):
last_comment = model.Comment.all().filter('article', article).filter('author', user).order('-creation_date').get()
if last_comment is not None:
if last_comment.content == content:
return True
return False
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from google.appengine.ext import db
from handlers.AuthenticatedHandler import *
class ArticleFavourite(AuthenticatedHandler):
def execute(self):
article = model.Article.get(self.get_param('key'))
user = self.values['user']
if not article or article.draft or article.deletion_date:
self.not_found()
return
if not self.auth():
return
favourite = model.Favourite.gql('WHERE user=:1 AND article=:2', user, article).get()
if not favourite:
favourite = model.Favourite(article=article,
user=user,
article_author_nickname=article.author_nickname,
article_title=article.title,
article_url_path=article.url_path,
user_nickname=user.nickname)
favourite.put()
user.favourites += 1
user.put()
followers = list(self.get_followers(user=user))
followers.append(user.nickname)
followers.extend(self.get_followers(article=article))
followers = list(set(followers))
self.create_event(event_type='article.favourite', followers=followers, user=user, article=article)
if self.get_param('x'):
self.render_json({ 'action': 'added' })
else:
self.redirect('/module/article/%s' % article.url_path)
else:
favourite.delete()
user.favourites -= 1
user.put()
if self.get_param('x'):
self.render_json({ 'action': 'deleted' })
else:
self.redirect('/module/article/%s' % article.url_path)
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from google.appengine.ext import db
from handlers.BaseHandler import *
class ArticleView(BaseHandler):
def execute(self):
url_path = self.request.path.split('/', 3)[3]
article_id = self.request.path.split('/')[3]
article = self.cache(article_id + '_article', self.get_article)
if not article:
self.not_found()
return
if article.url_path != url_path:
self.redirect('/module/article/%s' % article.url_path, permanent=True)
return
if not article.author_nickname:
article.author_nickname = article.author.nickname
article.put()
user = self.values['user']
if article.deletion_date and (not user or (user.rol != 'admin' and article.author_nickname != user.nickname)):
self.values['article'] = article
self.error(404)
self.render('templates/module/article/article-deleted.html')
return
self.values['tab'] = '/module/article.list'
if article.draft and (not user or not user.nickname == article.author_nickname):
self.not_found()
return
if user and user.nickname != article.author_nickname:
vote = model.Vote.gql('WHERE user=:1 AND article=:2', user, article).get()
if not vote:
self.values['canvote'] = True
if user:
added = model.Favourite.gql('WHERE user=:1 AND article=:2',user,article).get()
if not added:
self.values['canadd'] = True
if user:
if user.email in article.subscribers:
self.values['cansubscribe'] = False
else:
self.values['cansubscribe'] = True
self.values['article'] = article
results = 10
app = self.get_application()
if app.max_results_sublist:
results = app.max_results_sublist
query = model.Comment.all().filter('article =', article)
comments = self.paging(query, results, 'creation_date', article.responses, 'creation_date')
# migration
i = 1
for c in comments:
if not c.author_nickname:
c.author_nickname = c.author.nickname
c.put()
if not c.response_number:
c.response_number = i
c.put()
i += 1
# end migration
self.values['comments'] = comments
self.values['a'] = 'comments'
self.values['keywords'] = ', '.join(article.tags)
communities = model.CommunityArticle.all().filter('article', article).order('community_title')
# communities = self.cache(str(article.key().id()) + '_communities', self.get_communities)
self.values['communities'] = list(communities)
if user and article.author_nickname == user.nickname:
all_communities = list(model.CommunityUser.all().filter('user', user).order('community_title'))
# TODO: this could be improved
for g in communities:
for gr in all_communities:
if gr.community_url_path == g.community_url_path:
all_communities.remove(gr)
if all_communities:
self.values['all_communities'] = all_communities
self.values['content_html'] = self.cache(str(article.key().id()) + '_html', self.to_html)
self.values['related'] = list(model.Recommendation.all().filter('article_from', article).order('-value').fetch(5))
self.render('templates/module/article/article-view.html')
def to_html(self):
article = self.values['article']
if not article.content_html:
html = model.ArticleHtml(content=self.markdown(article.content))
html = model.ArticleHtml(content=self.media_content(article.content))
html.put()
article.content_html = html
article.put()
return article.content_html.content
def get_communities(self):
article = self.values['article']
return model.CommunityArticle.all().filter('article', article).order('community_title')
def get_author(self):
article = self.values['article']
return model.UserData.all().filter('nickname', article.author_nickname).get()
def get_article(self):
article_id = self.request.path.split('/')[3]
return model.Article.get_by_id(int(article_id))
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
import datetime
from google.appengine.ext import db
from handlers.AuthenticatedHandler import *
class ArticleCommentDelete(AuthenticatedHandler):
def execute(self):
user = self.values['user']
if user.rol != 'admin':
self.forbidden()
return
if not self.auth():
return
comment = model.Comment.get(self.get_param('key'))
if not comment:
self.not_found()
return
url = comment.article.url_path
message = self.get_param('message')
#decrement nomber of comments in the User
comment.author.comments -= 1
comment.author.put()
#delete comment
comment.deletion_date = datetime.datetime.now()
comment.deletion_message = message
comment.put()
self.redirect('/module/article/%s' % url)
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from handlers.BaseHandler import *
class ArticleList(BaseHandler):
def execute(self):
self.values['tab'] = '/module/article.list'
query = model.Article.all().filter('draft =', False).filter('deletion_date', None)
app = self.get_application()
key = '%s?%s' % (self.request.path, self.request.query)
results = 10
if app.max_results:
results = app.max_results
self.values['articles'] = self.paging(query, results, '-creation_date', app.articles, ['-creation_date', '-rating_average', '-responses'], key)
self.add_tag_cloud()
self.render('templates/module/article/article-list.html')
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from google.appengine.ext import db
from handlers.AuthenticatedHandler import *
class ArticleCommentSubscribe( AuthenticatedHandler ):
def execute(self):
key = self.get_param('key')
article = model.Article.get(key)
memcache.delete(str(article.key().id()) + '_article')
user = self.values['user']
mail = user.email
if not mail in article.subscribers:
if not self.auth():
return
article.subscribers.append(mail)
article.put()
self.add_user_subscription(user, 'article', article.key().id())
memcache.add(str(article.key().id()) + '_article', article, 0)
if self.get_param('x'):
self.render_json({ 'action': 'subscribed' })
else:
self.redirect('/module/article/%s' % (article.url_path, ))
else:
auth = self.get_param('auth')
if not auth:
memcache.add(str(article.key().id()) + '_article', article, 0)
self.values['article'] = article
self.render('templates/module/article/article-comment-subscribe.html')
else:
if not self.auth():
return
article.subscribers.remove(mail)
article.put()
self.remove_user_subscription(user, 'article', article.key().id())
memcache.add(str(article.key().id()) + '_article', article, 0)
if self.get_param('x'):
self.render_json({ 'action': 'unsubscribed' })
else:
self.redirect('/module/article/%s' % (article.url_path, ))
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
import datetime
from google.appengine.ext import db
from handlers.AuthenticatedHandler import *
class ArticleDelete(AuthenticatedHandler):
def execute(self):
method = self.request.method
user = self.values['user']
article = model.Article.get(self.get_param('key'))
memcache.delete(str(article.key().id()))
if not article:
self.not_found()
return
if user.rol != 'admin' and user.nickname != article.author.nickname:
self.forbidden()
return
if method == 'GET':
self.values['article'] = article
self.render('templates/module/article/article-delete.html')
elif self.auth():
# mark as deleted
article.deletion_message = self.get_param('message')
article.deletion_date = datetime.datetime.now()
article.deletion_user = user
article.put()
# decrement tag counters
self.delete_tags(article.tags)
# decrement author counters
if article.draft:
article.author.draft_articles -= 1
else:
article.author.articles -=1
article.author.rating_total -= article.rating_total
article.author.rating_count -= article.rating_count
if article.author.rating_count > 0:
article.author.rating_average = int(article.author.rating_total / article.author.rating_count)
else:
article.author.rating_average = 0
article.author.put()
# decrement community counters and delete relationships
gi = model.CommunityArticle.all().filter('article =', article)
for g in gi:
g.community.articles -= 1
if g.community.activity:
g.community.activity -= 15
g.community
g.community.put()
g.delete()
# decrement favourites and delete relationships
fv = model.Favourite.all().filter('article =', article)
for f in fv:
f.user.favourites -= 1
f.user.put()
f.delete()
rc = model.Recommendation.all().filter('article_from', article)
for r in rc:
r.delete()
rc = model.Recommendation.all().filter('article_to', article)
for r in rc:
r.delete()
# decrement votes and delete relationships
# vt = model.Vote.all().filter('article =', article)
# for v in vt:
# v.delete()
# comments?
memcache.delete('index_articles')
memcache.delete('tag_cloud')
app = model.Application.all().get()
if app:
app.articles -= 1
app.put()
memcache.delete('app')
self.redirect('/module/article/%s' % article.url_path)
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from handlers.AuthenticatedHandler import *
class ArticleAddCommunities(AuthenticatedHandler):
def execute(self):
method = self.request.method
user = self.values['user']
key = self.get_param('key')
article = model.Article.get(key)
if not article or article.draft or article.deletion_date:
self.not_found()
return
if not user.nickname == article.author.nickname:
self.forbidden()
return
if method == 'GET':
self.values['key'] = key
self.values['article'] = article
communities = list(model.CommunityUser.all().filter('user', user).order('community_title'))
self.values['communities'] = communities
if not communities:
self.redirect('/module/article/%s' % article.url_path)
return
self.render('templates/module/article/article-add-communities.html')
elif self.auth():
arguments = self.request.arguments()
for gu in model.CommunityUser.all().filter('user', user).order('community_title'):
community = gu.community
if self.request.get('community-%d' % community.key().id()):
gi = model.CommunityArticle.all().filter('community', community).filter('article', article).count(1)
if not gi:
community.articles += 1
if community.activity:
community.activity += 15
community.put()
gi = model.CommunityArticle(community=community,
article=article,
article_author_nickname = article.author_nickname,
article_title = article.title,
article_url_path = article.url_path,
community_title = community.title,
community_url_path = community.url_path)
gi.put()
followers = list(self.get_followers(community=community))
self.create_event(event_type='community.addarticle', followers=followers, user=user, community=community, article=article)
self.redirect('/module/article/%s' % article.url_path) | Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
import logging
from google.appengine.api import mail
from handlers.AuthenticatedHandler import *
from google.appengine.runtime import apiproxy_errors
class CommunityNewArticle(AuthenticatedHandler):
def execute(self):
article = model.Article.get(self.get_param('article'))
community = model.Community.get(self.get_param('community'))
if not community or not article or article.draft or article.deletion_date:
self.not_found()
return
if not self.auth():
return
user = self.values['user']
gu = self.joined(community)
if gu and not article.draft:
gi = model.CommunityArticle.gql('WHERE community=:1 and article=:2', community, article).get()
if not gi and user.nickname == article.author.nickname:
gi = model.CommunityArticle(article=article,
community=community,
article_author_nickname=article.author_nickname,
article_title=article.title,
article_url_path=article.url_path,
community_title=community.title,
community_url_path=community.url_path)
gi.put()
community.articles += 1
if community.activity:
community.activity += 15
community.put()
followers = list(self.get_followers(community=community))
self.create_event(event_type='community.addarticle', followers=followers, user=user, community=community, article=article)
subscribers = community.subscribers
if subscribers and user.email in subscribers:
subscribers.remove(user.email)
if subscribers:
app = self.get_application()
subject = self.getLocale("New article: '%s'") % self.clean_ascii(article.title) # u"Nuevo articulo: '%s'"
body = self.getLocale("New article at community %s.\nArticle title: %s\nRead more at:\n%s/module/article/%s\n") % (self.clean_ascii(community.title), self.clean_ascii(article.title), app.url, article.url_path)
self.mail(subject=subject, body=body, bcc=community.subscribers)
self.redirect('/module/article/%s' % article.url_path)
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from google.appengine.ext import db
from handlers.BaseHandler import *
class CommunityUserList(BaseHandler):
def execute(self):
self.values['tab'] = '/module/community.list'
url_path = self.request.path.split('/', 3)[3]
community = model.Community.gql('WHERE url_path=:1', url_path).get()
if not community:
self.not_found()
return
self.values['community'] = community
self.values['joined'] = self.joined(community)
query = model.CommunityUser.all().filter('community', community)
self.values['users'] = self.paging(query, 27, '-creation_date', community.members, ['-creation_date'])
self.render('templates/module/community/community-user-list.html') | Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from google.appengine.ext import db
from handlers.AuthenticatedHandler import *
class CommunityThreadEdit(AuthenticatedHandler):
def execute(self):
self.values['tab'] = '/module/community.list'
method = self.request.method
user = self.values['user']
key = self.get_param('key')
if method == 'GET':
if key:
# show edit form
thread = model.Thread.get(key)
if user.nickname!= thread.author_nickname and user.rol != 'admin':
self.forbidden()
return
if thread is None:
self.not_found()
return
#TODO Check if it's possible
if thread.parent_thread is None:
self.values['is_parent_thread'] = True
self.values['thread'] = thread
self.render('templates/module/community/community-thread-edit.html')
return
else:
self.show_error("Thread not found")
return
elif self.auth():
if key:
# update comment
thread = model.Thread.get(key)
if user.nickname!= thread.author_nickname and user.rol != 'admin':
self.forbidden()
return
if thread is None:
self.not_found()
return
if user.rol != 'admin':
if thread.editions is None:
thread.editions = 0
thread.editions +=1
thread.last_edition = datetime.datetime.now()
if thread.parent_thread is None:
if thread.responses <= 5:
thread.title = self.get_param('title')
for comment in model.Thread.all().filter('parent_thread', thread):
comment.title = thread.title
comment.put()
thread.content = self.get_param('content')
thread.put()
if thread.parent_thread is None:
memcache.delete(str(thread.key().id()) + '_thread')
memcache.add(str(thread.key().id()) + '_thread', thread, 0)
self.redirect('/module/community.forum/%s' % (thread.url_path))
else:
results = 20
app = self.get_application()
if app.max_results_sublist:
results = app.max_results_sublist
page = thread.response_number / results
if (thread.response_number % results) > 0:
page += 1
if page != 1:
response_url = '/module/community.forum/%s?p=%d' % (thread.url_path, page)
else:
response_url = '/module/community.forum/%s?' % (thread.url_path)
memcache.delete(response_url)
response_url = response_url + '#comment-%d' % (thread.response_number)
self.redirect(response_url)
else:
self.show_error("Comment not found")
return | Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from handlers.BaseHandler import *
class CommunityList(BaseHandler):
def execute(self):
self.values['tab'] = '/module/community.list'
query = model.Community.all()
key = '%s?%s' % (self.request.path, self.request.query)
cat = self.get_param('cat')
app = self.get_application()
if cat:
category = model.Category.all().filter('url_path', cat).get()
self.values['category'] = category
self.values['cat'] = cat
query = query.filter('category', category)
max = category.communities
else:
max = app.communities
results = 10
if app.max_results:
results = app.max_results
communities = self.paging(query, results, '-members', max, ['-creation_date', '-members', '-articles'], key)
self.values['communities'] = communities
# denormalization
for g in communities:
if not g.owner_nickname:
g.owner_nickname = g.owner.nickname
g.put()
self.add_categories()
self.add_tag_cloud()
self.render('templates/module/community/community-list.html')
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
import img
from google.appengine.api import images
from google.appengine.ext import db
from google.appengine.api import memcache
from handlers.AuthenticatedHandler import *
class CommunityEdit(AuthenticatedHandler):
def execute(self):
self.values['tab'] = '/module/community.list'
method = self.request.method
user = self.values['user']
key = self.get_param('key')
if method == 'GET':
if key:
# show edit form
community = model.Community.get(key)
if user.nickname != community.owner.nickname and user.rol != 'admin':
self.forbidden()
return
self.values['key'] = key
self.values['title'] = community.title
self.values['description'] = community.description
if community.all_users is not None:
self.values['all_users'] = community.all_users
else:
self.values['all_users'] = True
if community.category:
self.values['category'] = community.category
self.add_categories()
self.render('templates/module/community/community-edit.html')
else:
# show an empty form
self.values['title'] = "New community..."
self.values['all_users'] = True
self.add_categories()
self.render('templates/module/community/community-edit.html')
elif self.auth():
if key:
# update community
community = model.Community.get(key)
if user.nickname != community.owner.nickname and user.rol != 'admin':
self.forbidden()
return
# community title is not editable since many-to-many relationships are denormalizated
# community.title = self.get_param('title')
community.description = self.get_param('description')
image = self.request.get("img")
if image:
image = images.im_feeling_lucky(image, images.JPEG)
community.avatar = img.resize(image, 128, 128)
community.thumbnail = img.resize(image, 48, 48)
if not community.image_version:
community.image_version = 1
else:
memcache.delete('/images/community/avatar/%s/%d' % (community.key().id(), community.image_version))
memcache.delete('/images/community/thumbnail/%s/%d' % (community.key().id(), community.image_version))
community.image_version += 1
memcache.delete('/images/community/avatar/%s' % community.key().id())
memcache.delete('/images/community/thumbnail/%s' % community.key().id())
if self.get_param('all_users'):
community.all_users = True
else:
community.all_users = False
category = model.Category.get(self.request.get('category'))
prev_category = community.category
community.category = category
community.put()
if prev_category:
prev_category.communities -= 1
prev_category.put()
category.communities += 1
category.put()
memcache.delete('index_communities')
self.redirect('/module/community/%s' % (community.url_path, ))
else:
# new community
title = self.get_param('title')
url_path = '-'
all_users = False
if self.get_param('all_users'):
all_users = True
community = model.Community(owner=user,
owner_nickname=user.nickname,
title=title,
description=self.get_param('description'),
url_path=url_path,
members=1,
all_users = all_users,
articles=0,
threads=0,
responses=0,
subscribers=[user.email],
activity=1)
category = model.Category.get(self.request.get('category'))
community.category = category
image = self.request.get("img")
if image:
image = images.im_feeling_lucky(image, images.JPEG)
community.avatar = img.resize(image, 128, 128)
community.thumbnail = img.resize(image, 48, 48)
community.image_version = 1
community.put()
self.add_user_subscription(user, 'community', community.key().id())
community.url_path = '%d/%s' % (community.key().id(), self.to_url_path(community.title))
community.put()
category.communities += 1
category.put()
user.communities += 1
user.put()
app = model.Application.all().get()
if app:
app.communities += 1
app.put()
memcache.delete('app')
community_user = model.CommunityUser(user=user,
community=community,
user_nickname=user.nickname,
community_title=community.title,
community_url_path=community.url_path)
community_user.put()
memcache.delete('index_communities')
followers = list(self.get_followers(user=user))
followers.append(user.nickname)
self.create_event(event_type='community.new', followers=followers, user=user, community=community)
self.add_follower(community=community, nickname=user.nickname)
# TODO: update a user counter to know how many communities is owner of?
self.redirect('/module/community/%s' % (community.url_path, )) | Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
import datetime
from google.appengine.runtime import apiproxy_errors
from google.appengine.ext import db
from google.appengine.api import mail
from google.appengine.api import memcache
from handlers.AuthenticatedHandler import *
class CommunityForumReply(AuthenticatedHandler):
def execute(self):
method = self.request.method
if method == "GET" or not self.auth():
return
user = self.values['user']
key = self.get_param('key')
thread = model.Thread.get(key)
memcache.delete(str(thread.key().id()) + '_thread')
if not thread:
self.not_found()
return
community = thread.community
if community.all_users is not None and not self.can_write(community):
self.forbidden()
return
content = self.get_param('content')
preview = self.get_param('preview')
if preview:
response = model.Thread(community=community,
author=user,
author_nickname=user.nickname,
title=thread.title,
content=content,
parent_thread=thread,
responses=0)
self.values['thread'] = response
self.values['preview'] = True
self.render('templates/module/community/community-thread-edit.html')
return
if self.check_duplicate(community, user, thread, content):
self.show_error("Duplicated reply")
return
response = model.Thread(community=community,
community_title=community.title,
community_url_path=community.url_path,
author=user,
author_nickname=user.nickname,
title=thread.title,
url_path=thread.url_path,
content=content,
parent_thread=thread,
response_number=thread.responses+1,
responses=0,
editions=0)
response.put()
results = 20
app = self.get_application()
if app.max_results_sublist:
results = app.max_results_sublist
page = response.response_number / results
if (response.response_number % results) == 1:
#delete previous page from the cache
if page != 1:
previous_url = '/module/community.forum/%s?p=%d' % (thread.url_path, page)
else:
previous_url = '/module/community.forum/%s?' % (thread.url_path)
memcache.delete(previous_url)
if (response.response_number % results) > 0:
page += 1
if page != 1:
response_url = '/module/community.forum/%s?p=%d' % (thread.url_path, page)
else:
response_url = '/module/community.forum/%s?' % (thread.url_path)
memcache.delete(response_url)
response_url = response_url + '#comment-%d' % (response.response_number)
self.create_community_subscribers(community)
community.responses = community.responses + 1
community.put()
followers = list(self.get_followers(user=user))
followers.append(user.nickname)
followers.extend(self.get_followers(thread=thread))
followers = list(set(followers))
self.create_event(event_type='thread.reply', followers=followers,
user=user, thread=thread, community=community, response_number=response.response_number)
subscribers = thread.subscribers
email_removed = False
if subscribers and user.email in subscribers:
email_removed = True
subscribers.remove(user.email)
if subscribers:
subject = self.getLocale("New reply to: '%s'") % self.clean_ascii(thread.title) # "Nueva respuesta en: '%s'"
body = self.getLocale("New reply to %s.\n%s%s\n\nAll replies:\n%s/module/community.forum/%s\n\nRemove this subscription:\n%s/module/community.forum.subscribe?key=%s") % (self.clean_ascii(thread.title), app.url, response_url, app.url, thread.url_path, app.url, str(thread.key()))
self.mail(subject=subject, body=body, bcc=thread.subscribers)
subscribe = self.get_param('subscribe')
if email_removed:
thread.subscribers.append(user.email)
if subscribe and not user.email in thread.subscribers:
thread.subscribers.append(user.email)
self.add_user_subscription(user, 'thread', thread.key().id())
thread.responses += 1
thread.last_response_date = datetime.datetime.now()
thread.put()
memcache.add(str(thread.key().id()) + '_thread', thread, 0)
community = thread.community
if community.activity:
community.activity += 2
community.put()
memcache.delete('index_threads')
self.redirect(response_url)
def check_duplicate(self, community, user, parent_thread, content):
last_thread = model.Thread.all().filter('community', community).filter('parent_thread', parent_thread).filter('author', user).order('-creation_date').get()
if last_thread is not None:
if last_thread.content == content:
return True
return False
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from handlers.AuthenticatedHandler import *
class CommunityUserUnjoin(AuthenticatedHandler):
def execute(self):
user = self.values['user']
community = model.Community.get(self.get_param('community'))
if not community:
self.not_found()
return
if not self.auth():
return
redirect = self.get_param('redirect')
gu = model.CommunityUser.gql('WHERE community=:1 and user=:2', community, user).get()
if gu and user != community.owner:
self.create_community_subscribers(community)
gu.delete()
if user.email in community.subscribers:
community.subscribers.remove(user.email)
community.members -= 1
if community.activity:
community.activity -= 1
community.put()
self.remove_user_subscription(user, 'community', community.key().id())
self.remove_follower(community=community, nickname=user.nickname)
user.communities -= 1
user.put()
self.redirect(redirect)
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from handlers.AuthenticatedHandler import *
class CommunityUserJoin(AuthenticatedHandler):
def execute(self):
user = self.values['user']
community = model.Community.get(self.get_param('community'))
if not community:
self.not_found()
return
if not self.auth():
return
redirect = self.get_param('redirect')
gu = self.joined(community)
if gu == 'False':
self.create_community_subscribers(community)
gu = model.CommunityUser(user=user,
community=community,
user_nickname=user.nickname,
community_title=community.title,
community_url_path=community.url_path)
gu.put()
community.subscribers.append(user.email)
community.members += 1
if community.activity:
community.activity += 1
community.put()
self.add_follower(community=community, nickname=user.nickname)
self.add_user_subscription(user, 'community', community.key().id())
user.communities += 1
user.put()
self.redirect(redirect)
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from google.appengine.ext import db
from handlers.AuthenticatedHandler import *
class CommunityMove(AuthenticatedHandler):
def execute(self):
method = self.request.method
user = self.values['user']
if user.rol != 'admin':
self.forbidden()
return
if method == 'GET':
action = self.get_param('action')
key = self.get_param('key_orig')
if key:
community_orig = model.Community.get(key)
self.values['key_orig'] = community_orig.key
self.render('templates/module/community/community-move.html')
return
elif self.auth():
action = action = self.get_param('action')
if not action:
self.render('templates/module/community/community-move.html')
return
key_orig = self.get_param('key_orig')
if key_orig:
community_orig = model.Community.get(key_orig)
key_dest = self.get_param('key_dest')
if key_dest:
community_dest = model.Community.get(key_dest)
mesagge = ''
if not community_orig:
message = self.getLocale("Source community not exists")
self.values['message'] = message
self.render('templates/module/community/community-move.html')
return
elif not community_dest:
message = self.getLocale("Taget community not exists")
self.values['message'] = message
self.render('templates/module/community/community-move.html')
return
elif action == 'mu':
#move users
message = self.move_users(community_orig, community_dest)
elif action == 'mt':
#move threads
message = self.move_threads(community_orig, community_dest)
memcache.delete('index_threads')
elif action == 'mi':
#move articles
message = self.move_articles(community_orig, community_dest)
elif action == 'delete':
message = self.delete_community(community_orig)
memcache.delete('index_communities')
if action != 'delete':
self.values['key_orig'] = community_orig.key
self.values['key_dest'] = community_dest.key
self.values['message'] = message
self.render('templates/module/community/community-move.html')
return
def move_articles(self, community_orig, community_dest):
community_articles = model.CommunityArticle.all().filter('community', community_orig).fetch(10)
counter = 0
for community_article in community_articles:
article_dest = model.CommunityArticle.all().filter('community', community_dest).filter('article', community_article.article).get()
if article_dest:
community_article.delete()
else:
community_article.community = community_dest
community_article.community_title = community_dest.title
community_article.community_url_path = community_dest.url_path
community_article.put()
community_dest.articles += 1
if community_dest.activity:
community_dest.activity += 15
community_dest.put()
counter +=1
community_orig.articles -= 1
if community_dest.activity:
community_dest.activity -= 15
community_orig.put()
return self.getLocale("%s articles moved. Source community contains %s more.") % (counter, community_orig.articles)
def move_threads(self, community_orig, community_dest):
counter = 0
for community_thread in model.Thread.all().filter('community', community_orig).filter('parent_thread', None).fetch(1):
community_thread.community = community_dest
community_thread.community_url_path = community_dest.url_path
community_thread.community_title = community_dest.title
responses = model.Thread.all().filter('parent_thread', community_thread)
if responses:
for response in responses:
response.community = community_dest
response.community_url_path = community_dest.url_path
response.community_title = community_dest.title
response.put()
counter +=1
community_thread.put()
community_orig.threads -= 1
community_orig.comments -= community_thread.comments
value = 5 + (2 * thread.responses)
if community_orig.activity:
community_dest.activity -= value
community_orig.put()
community_dest.threads += 1
community_dest.comments += community_thread.comments
if community_dest.activity:
community_dest.activity += value
community_dest.put()
return self.getLocale("Moved thread with %s replies. %s threads remain.") % (counter, community_orig.threads)
def move_users(self, community_orig, community_dest):
community_users = model.CommunityUser.all().filter('community', community_orig).fetch(10)
counter = 0
for community_user in community_users:
user_dest = model.CommunityUser.all().filter('community', community_dest).filter('user', community_user.user).get()
if user_dest:
community_user.user.communities -= 1
community_user.user.put()
self.remove_user_subscription(community_user.user, 'community', community_orig.key().id())
community_user.delete()
else:
community_user.community = community_dest
community_dest.members += 1
community_dest.subscribers.append(community_user.user.email)
self.add_follower(community=community_dest, nickname=community_user.user.nickname)
self.add_user_subscription(community_user.user, 'community', community_dest.key().id())
if community_dest.activity:
community_dest.activity += 1
community_dest.put()
counter += 1
community_user.community_title = community_dest.title
community_user.community_url = community_dest.url_path
community_user.put()
community_orig.members -= 1
if community_orig.activity:
community_orig.activity -= 1
community_orig.put()
return self.getLocale("Moved %s users. Source community contains %s more.") % (counter, community_orig.members)
def delete_community(self, community_orig):
community_orig.delete()
app = model.Application.all().get()
if app:
app.communities -= 1
app.put()
memcache.delete('app')
return self.getLocale("Deleted community. %s communities remain.") % (app.communities)
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
import logging
import datetime
from google.appengine.runtime import apiproxy_errors
from google.appengine.ext import db
from google.appengine.api import mail
from google.appengine.api import memcache
from handlers.AuthenticatedHandler import *
class CommunityForumEdit(AuthenticatedHandler):
def execute(self):
method = self.request.method
if method == "GET" or not self.auth():
return
user = self.values['user']
key = self.get_param('key')
community = model.Community.get(key)
if not community:
self.not_found()
return
if community.all_users is not None and not self.can_write(community):
self.forbidden()
return
title = self.get_param('title')
url_path = ''
content = self.get_param('content')
preview = self.get_param('preview')
if preview:
thread = model.Thread(community=community,
community_url_path=community.url_path,
author=user,
author_nickname = user.nickname,
title=title,
content=content,
responses=0)
self.values['thread'] = thread
self.values['preview'] = True
self.values['is_parent_thread'] = True
self.render('templates/module/community/community-thread-edit.html')
return
if self.check_duplicate(community, user, content, title):
self.show_error("Duplicated thread")
return
thread = model.Thread(community=community,
community_title=community.title,
community_url_path=community.url_path,
author=user,
author_nickname=user.nickname,
title=title,
url_path=url_path,
content=content,
last_response_date = datetime.datetime.now(),
responses=0,
editions=0,
views=0)
user.threads += 1
user.put()
self.create_community_subscribers(community)
app = model.Application.all().get()
if app:
if not app.threads:
app.threads = 0
app.threads += 1
app.put()
memcache.delete('app')
thread.put()
self.add_follower(thread=thread, nickname=user.nickname)
thread.url_path = ('%d/%s/%s') % (thread.key().id(), self.to_url_path(community.title), self.to_url_path(title))
subscribe = self.get_param('subscribe')
if subscribe:
thread.subscribers.append(user.email)
self.add_user_subscription(user, 'thread', thread.key().id())
thread.put()
memcache.add(str(thread.key().id()) + '_thread', thread, 0)
community.threads += 1
if community.activity:
community.activity += 5
community.put()
followers = list(self.get_followers(community=community))
followers.extend(self.get_followers(user=user))
if not user.nickname in followers:
followers.append(user.nickname)
followers = list(set(followers))
self.create_event(event_type='thread.new', followers=followers, user=user, thread=thread, community=community)
subscribers = community.subscribers
if subscribers and user.email in subscribers:
subscribers.remove(user.email)
if subscribers:
app = self.get_application()
subject = self.getLocale("New subject: '%s'") % self.clean_ascii(thread.title)
body = self.getLocale("New subject by community %s.\nSubject title: %s\nFollow forum at:\n%s/module/community.forum/%s") % (self.clean_ascii(community.title), self.clean_ascii(thread.title), app.url, thread.url_path)
self.mail(subject=subject, body=body, bcc=community.subscribers)
memcache.delete('index_threads')
self.redirect('/module/community.forum/%s' % thread.url_path)
def check_duplicate(self, community, user, content, title):
last_thread = model.Thread.all().filter('community', community).filter('parent_thread', None).filter('author', user).order('-creation_date').get()
if last_thread is not None:
if last_thread.title == title and last_thread.content == content:
return True
return False
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from google.appengine.ext import db
from handlers.BaseHandler import *
class CommunityArticleList(BaseHandler):
def execute(self):
self.values['tab'] = '/module/community.list'
url_path = self.request.path.split('/', 3)[3]
community = model.Community.gql('WHERE url_path=:1', url_path).get()
if not community:
self.not_found()
return
self.values['community'] = community
self.values['joined'] = self.joined(community)
query = model.CommunityArticle.all().filter('community', community)
self.values['articles'] = self.paging(query, 10, '-creation_date', community.articles, ['-creation_date'])
self.render('templates/module/community/community-article-list.html') | Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from google.appengine.ext import db
from handlers.BaseHandler import *
class CommunityView(BaseHandler):
def execute(self):
self.values['tab'] = '/module/community.list'
url_path = self.request.path.split('/', 3)[3]
community = model.Community.gql('WHERE url_path=:1', url_path).get()
if not community:
community = model.Community.gql('WHERE old_url_path=:1', url_path).get()
if community:
self.redirect('/module/community/%s' % community.url_path, permanent=True)
return
self.not_found()
return
self.values['community'] = community
self.values['joined'] = self.joined(community)
self.values['articles'] = list(model.CommunityArticle.all().filter('community', community).order('-creation_date').fetch(5))
self.values['threads'] = list(model.Thread.all().filter('community', community).filter('parent_thread', None).order('-last_response_date').fetch(5))
self.values['users'] = list(model.CommunityUser.all().filter('community', community).order('-creation_date').fetch(27))
self.values['related'] = list(model.RelatedCommunity.all().filter('community_from', community).order('-creation_date').fetch(10))
self.render('templates/module/community/community-view.html') | Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from handlers.AuthenticatedHandler import *
class CommunityArticleDelete(AuthenticatedHandler):
def execute(self):
article = model.Article.get(self.get_param('article'))
community = model.Community.get(self.get_param('community'))
if not article or not community:
self.not_found()
return
if not self.auth():
return
gi = model.CommunityArticle.gql('WHERE community=:1 and article=:2', community, article).get()
if self.values['user'].nickname == article.author.nickname:
gi.delete()
community.articles -= 1
if community.activity:
community.activity -= 15
community.put()
self.redirect('/module/article/%s' % article.url_path)
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from google.appengine.ext import db
from google.appengine.api import memcache
from handlers.AuthenticatedHandler import *
class CommunityDelete(AuthenticatedHandler):
def execute(self):
user = self.values['user']
if user.rol != 'admin':
self.forbidden()
return
if not self.auth():
return
community=model.Community.get(self.get_param('key'))
db.delete(community.communityuser_set)
db.delete(community.communityarticle_set)
db.delete(community.thread_set)
community.delete()
app = app = model.Application.all().get()
if app:
app.communities -=1
app.put()
memcache.delete('app')
# TODO: some other memcache value should be removed? most active communities?
self.redirect('/')
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from handlers.BaseRest import *
class CommunityForumVisit(BaseRest):
def get(self):
thread_id = self.request.get('id')
memcache.delete(thread_id + '_thread')
thread = model.Thread.get_by_id(int(thread_id))
thread.views += 1
thread.put()
memcache.add(str(thread.key().id()) + '_thread', thread, 0)
content = []
self.render_json({'views' : thread.views})
return | Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from google.appengine.ext import db
from handlers.AuthenticatedHandler import *
class CommunityForumView(BaseHandler):
def execute(self):
self.values['tab'] = '/module/community.list'
user = self.values['user']
url_path = self.request.path.split('/', 3)[3]
thread_id = self.request.path.split('/')[3]
thread = self.cache(thread_id + '_thread', self.get_thread)
#thread = model.Thread.all().filter('url_path', url_path).filter('parent_thread', None).get()
if not thread:
# TODO: try with the id in the url_path and redirect
self.not_found()
return
if thread.deletion_date:
self.not_found()
return
# migration. supposed to be finished
if len(thread.url_path.split('/')) == 2:
thread.url_path = '%d/%s' % (thread.key().id(), thread.url_path)
thread.parent_thread = None
thread.put()
self.redirect('/module/community.forum/%s' % thread.url_path)
return
# end migration
'''if thread.views is None:
thread.views = 0;
thread.views += 1
thread.put()'''
community = thread.community
self.values['community'] = community
self.values['joined'] = self.joined(community)
self.values['thread'] = thread
query = model.Thread.all().filter('parent_thread', thread)
results = 20
app = self.get_application()
if app.max_results_sublist:
results = app.max_results_sublist
key = '%s?%s' % (self.request.path, self.request.query)
responses = self.paging(query, results, 'creation_date', thread.responses, ['creation_date'], key=key, timeout=0)
#responses = self.cache(url_path, self.get_responses)
# migration
if not thread.author_nickname:
thread.author_nickname = thread.author.nickname
thread.put()
i = 1
for t in responses:
if not t.response_number:
t.response_number = i
t.put()
i += 1
# end migration
self.values['responses'] = responses
if community.all_users:
self.values['can_write'] = True
else:
self.values['can_write'] = self.can_write(community)
if user:
if user.email in thread.subscribers:
self.values['cansubscribe'] = False
else:
self.values['cansubscribe'] = True
self.values['a'] = 'comments'
self.render('templates/module/community/community-forum-view.html')
def get_thread(self):
url_path = self.request.path.split('/', 3)[3]
return model.Thread.all().filter('url_path', url_path).filter('parent_thread', None).get()
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from google.appengine.ext import db
from handlers.AuthenticatedHandler import *
class CommunityForumSubscribe( AuthenticatedHandler ):
def execute(self):
key = self.get_param('key')#TODO if key is empty app crashed
thread = model.Thread.get(key)
memcache.delete(str(thread.key().id()) + '_thread')
user = self.values['user']
mail = user.email
if not mail in thread.subscribers:
if not self.auth():
return
thread.subscribers.append(user.email)
thread.put()
self.add_user_subscription(user, 'thread', thread.key().id())
memcache.add(str(thread.key().id()) + '_thread', thread, 0)
if self.get_param('x'):
self.render_json({ 'action': 'subscribed' })
else:
self.redirect('/module/community.forum/%s' % thread.url_path)
else:
auth = self.get_param('auth')
if not auth:
self.values['thread'] = thread
self.render('templates/module/community/community-forum-subscribe.html')
else:
if not self.auth():
return
thread.subscribers.remove(user.email)
thread.put()
self.remove_user_subscription(user, 'thread', thread.key().id())
if self.get_param('x'):
self.render_json({ 'action': 'unsubscribed' })
else:
self.redirect('/module/community.forum/%s' % thread.url_path)
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
import datetime
from google.appengine.ext import db
from handlers.AuthenticatedHandler import *
class CommunityForumDelete(AuthenticatedHandler):
def execute(self):
user = self.values['user']
if user.rol != 'admin':
self.forbidden()
return
if not self.auth():
return
thread = model.Thread.get(self.get_param('key'))
url = '/module/community.forum.list/' + thread.community.url_path
if not thread:
self.not_found()
return
if thread.parent_thread is not None:
message = self.get_param('message')
#decrement number of childs in the parent thread
thread.parent_thread.put()
#Delete child thread
thread.deletion_date = datetime.datetime.now()
thread.deletion_message = message
thread.put()
else:
#decrement threads in the community
community = thread.community
if community.activity:
value = 5 + (2 * thread.responses)
community.activity -= value
community.threads -=1
community.put()
#decrement thread in the app
app = model.Application().all().get()
app.threads -= 1
app.put()
memcache.delete('app')
#delete comments in this thread
childs = model.Thread.all().filter('parent_thread', thread)
db.delete(childs)
memcache.delete('index_threads')
thread.delete()
memcache.delete(str(thread.key().id()) + '_thread')
self.redirect(url)
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from google.appengine.ext import db
from handlers.BaseHandler import *
class CommunityForumList(BaseHandler):
def execute(self):
self.values['tab'] = '/module/community.list'
url_path = self.request.path.split('/', 3)[3]
community = model.Community.gql('WHERE url_path=:1', url_path).get()
if not community:
self.not_found()
return
self.values['community'] = community
self.values['joined'] = self.joined(community)
if community.all_users is None or community.all_users:
self.values['can_write'] = True
else:
self.values['can_write'] = self.can_write(community)
query = model.Thread.all().filter('community', community).filter('parent_thread', None)
threads = self.paging(query, 20, '-last_response_date', community.threads, ['-last_response_date'])
self.values['threads'] = threads
self.render('templates/module/community/community-forum-list.html') | Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from google.appengine.ext import db
from handlers.AuthenticatedHandler import *
class CommunityForumMove(AuthenticatedHandler):
def execute(self):
method = self.request.method
user = self.values['user']
if user.rol != 'admin':
self.forbidden()
return
if method == 'GET':
thread_key = self.get_param('thread_key')
thread = model.Thread.get(thread_key)
if thread is None:
self.not_found()
return
self.values['thread_key'] = thread.key
self.render('templates/module/community/community-forum-move.html')
return
elif self.auth():
thread_key = self.get_param('thread_key')
community_key = self.get_param('community_key')
thread = model.Thread.get(thread_key)
community = model.Community.get(community_key)
if community is None or thread is None:
self.values['thread_key'] = thread.key
self.values['message'] = "Community not exists."
self.render('templates/module/community/community-forum-move.html')
return
if community.title == thread.community.title:
self.values['thread_key'] = thread.key
self.values['message'] = "Source and target community are the same one."
self.render('templates/module/community/community-forum-move.html')
return
#decrement threads in previous community
community_orig = thread.community
community_orig.threads -= 1
community_orig.responses= thread.responses
value = 5 + (2 * thread.responses)
if community_orig.activity:
community_orig.activity -= value
#update comments
responses = model.Thread.all().filter('parent_thread', thread)
for response in responses:
response.community = community
response.community_title = community.title
response.community_url_path = community.url_path
response.put()
#change gorup in thread and desnormalizated fields
thread.community = community
thread.community_title = community.title
thread.community_url_path = community.url_path
#increment threads in actual community
community.threads += 1
community.responses += thread.responses
if community.activity:
community.activity += value
#save fields
community_orig.put()
thread.put()
community.put()
self.redirect('/module/community.forum/%s' % (thread.url_path))
return
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Carrasco <jose.carrasco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.api import memcache
from google.appengine.ext.webapp import template
from handlers.BaseHandler import *
from utilities.AppProperties import AppProperties
# Params
UPDATER_VERSION = "0.8"
def update():
app = model.Application.all().get()
if app is None:
initializeDb()
#self.response.out.write('App installed. Created user administrator. nickname="admin", password="1234". Please change the password.')
return
elif not app.session_seed:
import sha, random
app.session_seed = sha.new(str(random.random())).hexdigest()
app.put()
#self.response.out.write('Seed installed')
version = app.version
if version is None or version != UPDATER_VERSION:
update07to08()
#self.response.out.write ('updated to version 0.8')
# elif app.version == '0.8':
# update08to09()
# elif app.version == '0.9':
# update09to10()
return
def initializeDb():
app = model.Application.all().get()
if app is None:
app = model.Application()
app.name = 'vikuit-example'
app.subject = 'Social portal: lightweight and easy to install'
app.recaptcha_public_key = '6LdORAMAAAAAAL42zaVvAyYeoOowf4V85ETg0_h-'
app.recaptcha_private_key = '6LdORAMAAAAAAGS9WvIBg5d7kwOBNaNpqwKXllMQ'
app.theme = 'blackbook'
app.users = 0
app.communities = 0
app.articles = 0
app.threads = 0
app.url = "http://localhost:8080"
app.mail_subject_prefix = "[Vikuit]"
app.mail_sender = "admin.example@vikuit.com"
app.mail_footer = ""
app.max_results = 20
app.max_results_sublist = 20
import sha, random
app.session_seed = sha.new(str(random.random())).hexdigest()
app.version = UPDATER_VERSION
app.put()
user = model.UserData(nickname='admin',
email='admin.example@vikuit.com',
password='1:c07cbf8821d47575a471c1606a56b79e5f6e6a68',
language='en',
articles=0,
draft_articles=0,
messages=0,
draft_messages=0,
comments=0,
rating_count=0,
rating_total=0,
rating_average=0,
threads=0,
responses=0,
communities=0,
favourites=0,
public=False,
contacts=0,
rol='admin')
user.put()
parent_category = model.Category(title='General',
description='General category description',
articles = 0,
communities = 0)
parent_category.put()
category = model.Category(title='News',
description='News description',
articles = 0,
communities = 0)
category.parent_category = parent_category
category.put()
post = model.Mblog(author=user,
author_nickname=user.nickname,
content='Welcome to Vikuit!!',
responses=0)
post.put()
# update from 0.7 to 0.8 release
def update07to08():
app = model.Application.all().get()
app.theme = 'blackbook'
app.version = '0.8'
app.put()
memcache.delete('app')
AppProperties().updateJinjaEnv()
return
# update from 0.8 to 0.9 release
def update08to09():
app = model.Application.all().get()
app.version = '0.9'
app.put()
# update from 0.9 to 01 release
def update09to10():
app = model.Application.all().get()
app.version = '1.0'
app.put()
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
# (C) Copyright 2011 Jose Carrasco <jose.carrasco[a]vikuit.com>
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
import model
import logging
from google.appengine.api import memcache
from google.appengine.ext import webapp
class ImageDisplayer(webapp.RequestHandler):
def get(self):
cached = memcache.get(self.request.path)
params = self.request.path.split('/')
if params[2] == 'user':
user = model.UserData.gql('WHERE nickname=:1', params[4]).get()
self.display_image(user, params, cached, 'user128_1.png', 'user48_1.png')
elif params[2] == 'community':
community = model.Community.get_by_id(int(params[4]))
self.display_image(community, params, cached, 'community128.png', 'community48.png')
elif params[2] == 'gallery':
query = model.Image.gql('WHERE url_path=:1', '%s/%s' % (params[4], params[5]) )
image = query.get()
self.display_image(image, params, cached, 'unknown128.png', 'unknown48.png', False)
elif params[2] == 'application':
app = model.Application.all().get()
image = app.logo
self.display_image(image, params, cached, 'logo.gif', 'logo.gif', False)
else:
self.error(404)
return
def display_image(self, obj, params, cached, default_avatar, default_thumbnail, not_gallery=True):
if obj is None:
if not_gallery:
self.error(404)
else:
self.redirect('/static/images/%s' % default_thumbnail)
return
image = None
if cached:
image = self.write_image(cached)
else:
if params[3] == 'avatar':
image = obj.avatar
if not image:
self.redirect('/static/images/%s' % default_avatar)
return
elif params[3] == 'thumbnail':
image = obj.thumbnail
if not image:
self.redirect('/static/images/%s' % default_thumbnail)
return
elif params[3] == 'logo':
image = obj
if not image:
self.redirect('/static/images/%s' % default_thumbnail)
return
if not_gallery and (len(params) == 5 or not obj.image_version or int(params[5]) != obj.image_version):
if not obj.image_version:
obj.image_version = 1
obj.put()
newparams = params[:5]
newparams.append(str(obj.image_version))
self.redirect('/'.join(newparams))
return
# self.response.headers['Content-Type'] = 'text/plain'
# self.response.out.write('/'.join(params))
else:
if not cached:
memcache.add(self.request.path, image)
self.write_image(image)
def write_image(self, image):
self.response.headers['Content-Type'] = 'image/jpg'
self.response.headers['Cache-Control'] = 'public, max-age=31536000'
self.response.out.write(image)
def showImage(self, image, default):
if image:
self.write_image(image)
memcache.add(self.request.path, image)
else:
self.redirect('/static/images/%s' % default) | Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# (C) Copyright 2008 Juan Luis Belmonte <jlbelmonte at gmail dot com>
#
# This file is part of "debug_mode_on".
#
# "debug_mode_on" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "debug_mode_on" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "debug_mode_on". If not, see <http://www.gnu.org/licenses/>.
#
import re
#main method to apply all filters
def media_content(value):
if re.search('youtube',value):
value=youtube(value)
if re.search('vimeo', value):
value=vimeo(value)
# if re.search('slideshare', value):
# value=slideshare(value)
if re.search('veoh', value):
value=veoh(value)
if re.search('metacafe', value):
value=metacafe(value)
if re.search('video\.yahoo', value):
value=yahoovideo(value)
# if re.search('show\.zoho', value):
# value=sohoshow(value)
# if re.search('teachertube', value):
# value=teachertube(value)
return value
# specific methods for the different services
def youtube(text):
targets = re.findall('media=http://\S+.youtube.com/watch\?v=\S+;', text)
for i in targets:
match= re.match('(.*)watch\?v=(\S+);',i)
html = '<p><object width="425" height="344"><param name="movie" value="http://www.youtube.com/v/%s"&hl=en&fs=1"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/%s"=es&fs=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="344"></embed></object></p>' % ( match.community(2), match.community(2))
text=text.replace(i,html)
return text
def vimeo(text):
targets = re.findall('media=\S*vimeo.com/\S+;',text)
for i in targets:
match = re.match('(\S*)vimeo.com/(\S+)',i)
html='<p><object width="400" height="300"><param name="allowfullscreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="movie" value="http://vimeo.com/moogaloop.swf?clip_id=%s&server=vimeo.com&show_title=1&show_byline=1&show_portrait=0&color=&fullscreen=1" /><embed src="http://vimeo.com/moogaloop.swf?clip_id=%s&server=vimeo.com&show_title=1&show_byline=1&show_portrait=0&color=&fullscreen=1" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="400" height="300"></embed></object></p>' % ( match.community(2), match.community(2))
text=text.replace(i,html)
return text
def slideshare(text):
targets = re.findall('(media=\[.*\];)', text)
for i in targets:
match = re.search('id=(.*)&doc=(.*)&w=(.*)',i)
html = '<p><div style="width:425px;text-align:left" id="__ss_%s"><object style="margin:0px" width="%s" height="355"><param name="movie" value="http://static.slideshare.net/swf/ssplayer2.swf?doc=%s"/><param name="allowFullScreen" value="true"/><param name="allowScriptAccess" value="always"/><embed src="http://static.slideshare.net/swf/ssplayer2.swf?doc=%s" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="%s" height="355"/></object></div></p>' %(match.community(1),match.community(3),match.community(2),match.community(2),match.community(3))
text=text.replace(i,html)
return text
def metacafe(text):
targets = re.findall('media=\S+/watch/\d+/\S+/;', text)
for i in targets:
match = re.search('http://www.metacafe.com/watch/(\d+)/(\S+)/', i)
html = '<p><embed src="http://www.metacafe.com/fplayer/%s/%s.swf" width="400" height="345" wmode="transparent" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash"> </embed></p>' %(match.community(1), match.community(2))
text=text.replace(i,html)
return text
def veoh(text):
targets = re.findall('media=\S+veoh.com/videos/\S+;', text)
for i in targets:
match = re.search('http://www.veoh.com/videos/(\S+);',i)
html = '<p><embed src="http://www.veoh.com/veohplayer.swf?permalinkId=%s&id=anonymous&player=videodetailsembedded&videoAutoPlay=0" allowFullScreen="true" width="410" height="341" bgcolor="#FFFFFF" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer"></embed></p>' % match.community(1)
text = text.replace(i, html)
return text
def yahoovideo(text):
targets = re.findall('media=\S+video.yahoo.com/\S+/\d+\S+\d+;', text)
for i in targets:
match = re.search('video.yahoo.com/\S+/(\d+)/(\d+);', i)
html='<p><div><object width="512" height="322"><param name="movie" value="http://d.yimg.com/static.video.yahoo.com/yep/YV_YEP.swf?ver=2.2.30" /><param name="allowFullScreen" value="true" /><param name="AllowScriptAccess" VALUE="always" /><param name="bgcolor" value="#000000" /><param name="flashVars" value="id=%s&vid=%s&lang=en-us&intl=us&embed=1" /><embed src="http://d.yimg.com/static.video.yahoo.com/yep/YV_YEP.swf?ver=2.2.30" type="application/x-shockwave-flash" width="512" height="322" allowFullScreen="true" AllowScriptAccess="always" bgcolor="#000000" flashVars="id=%s&vid=%s&lang=en-us&intl=us&embed=1" ></embed></object></div></p>' % (match.community(2),match.community(1),match.community(2),match.community(2))
text = text.replace(i, html)
return text
def teachertube(text):
targets = re.findall('media=\S+/view_video.php\?viewkey=\S+;', text)
for i in targets:
match = re.search('viewkey=(\S+)',i)
url_atom='%3'
html='<embed src="http://www.teachertube.com/skin-p/mediaplayer.swf" width="425" height="350" type="application/x-shockwave-flash" allowfullscreen="true" menu="false" flashvars="height=350&width=425&file=http://www.teachertube.com/flvideo/64252.flv&location=http://www.teachertube.com/skin-p/mediaplayer.swf&logo=http://www.teachertube.com/images/greylogo.swf&searchlink=http://teachertube.com/search_result.php%sFsearch_id%sD&frontcolor=0xffffff&backcolor=0x000000&lightcolor=0xFF0000&screencolor=0xffffff&autostart=false&volume=80&overstretch=fit&link=http://www.teachertube.com/view_video.php?viewkey=%s&linkfromdisplay=true></embed>' % (url_atom, url_atom, match.community(1))
text = text.replace(i, text)
return text
def sohoshow(text):
targets = re.findall('media=\S+show.zoho.com/public/\S+;', text)
for i in targets:
match = re.search('show.zoho.com/public/(\S+)/(\S+);',i)
html='<p><embed height="335" width="450" name="Welcome3" style="border:1px solid #AABBCC" scrolling="no" src="http://show.zoho.com/embed?USER=%s&DOC=%s&IFRAME=yes" frameBorder="0"></embed></p>' % (match.community(1), match.community(2))
text = text.replace(i, text)
return text
def dummy(text):
return text
### skeleton
#def teacherstube(text):
# targets = re.findall('', text)
# for i in targets:
# match = re.search('',text)
# html=
# text = text.replace(i, text)
# return text
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# (C) Copyright 2008 Alberto Gimeno <gimenete at gmail dot com>
#
# This file is part of "debug_mode_on".
#
# "debug_mode_on" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "debug_mode_on" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "debug_mode_on". If not, see <http://www.gnu.org/licenses/>.
#
import model
import simplejson
from google.appengine.ext import webapp
class TaskQueue(webapp.RequestHandler):
def get(self):
self.response.headers['Content-Type'] = 'text/plain;charset=utf-8'
task = model.Task.all().order('-priority').get()
if not task:
self.response.out.write('No pending tasks')
return
data = simplejson.loads(task.data)
data = self.__class__.__dict__[task.task_type].__call__(self, data)
if data is None:
self.response.out.write('Task finished %s %s' % (task.task_type, task.data))
task.delete()
else:
task.data = simplejson.dumps(data)
task.put()
self.response.out.write('Task executed but not finished %s %s' % (task.task_type, task.data))
def delete_recommendations(self, data):
offset = data['offset']
recs = model.Recommendation.all().fetch(1, offset)
if len(recs) == 0:
return None
next = recs[0]
article_to = next.article_to
article_from = next.article_from
if article_from.draft or article_to.draft or article_from.deletion_date is not None or article_to.deletion_date is not None:
next.delete()
else:
data['offset'] += 1
return data
def update_recommendations(self, data):
offset = data['offset']
recs = model.Recommendation.all().fetch(1, offset)
if len(recs) == 0:
return None
next = recs[0]
article_to = next.article_to
article_from = next.article_from
self.calculate_recommendation(article_from, article_to)
data['offset'] += 1
return data
def begin_recommendations(self, data):
offset = data['offset']
articles = model.Article.all().filter('draft', False).filter('deletion_date', None).order('creation_date').fetch(1, offset)
print 'articles: %d' % len(articles)
if len(articles) == 0:
return None
next = articles[0]
data['offset'] += 1
t = model.Task(task_type='article_recommendation', priority=0, data=simplejson.dumps({'article': next.key().id(), 'offset': 0}))
t.put()
return data
def article_recommendation(self, data):
article = model.Article.get_by_id(data['article'])
if article.draft or article.deletion_date is not None:
return None
offset = data['offset']
articles = model.Article.all().filter('draft', False).filter('deletion_date', None).order('creation_date').fetch(1, offset)
if not articles:
return None
next = articles[0]
data['offset'] += 1
self.calculate_recommendation(next, article)
return data
def calculate_recommendation(self, next, article):
def distance(v1, v2):
all = []
all.extend(v1)
all.extend(v2)
return float(len(all) - len(set(all)))
def create_recommendation(article_from, article_to, value):
return model.Recommendation(article_from=article_from,
article_to=article_to,
value=value,
article_from_title=article_from.title,
article_to_title=article_to.title,
article_from_author_nickname=article_from.author_nickname,
article_to_author_nickname=article_to.author_nickname,
article_from_url_path=article_from.url_path,
article_to_url_path=article_to.url_path)
if next.key().id() == article.key().id():
return
r1 = model.Recommendation.all().filter('article_from', article).filter('article_to', next).get()
r2 = model.Recommendation.all().filter('article_from', next).filter('article_to', article).get()
diff = distance(article.tags, next.tags)
if diff > 0:
if not r1:
r1 = create_recommendation(article, next, diff)
else:
r1.value = diff
if not r2:
r2 = create_recommendation(next, article, diff)
else:
r2.value = diff
r1.put()
r2.put()
else:
if r1:
r1.delete()
if r2:
r2.delete()
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from handlers.BaseHandler import *
class Dispatcher(BaseHandler):
def execute(self):
referer = self.request.path.split('/', 1)[1]
# if referer.startswith('module'):
# referer = self.request.path.split('/',2)[2]
self.add_tag_cloud()
self.values['tab'] = self.request.path
self.render('templates/%s.html' % referer) | Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from handlers.BaseHandler import *
class AuthenticatedHandler(BaseHandler):
def pre_execute(self):
user = self.get_current_user()
#user = self.values['user']
if not user:
self.redirect(self.values['login'])
return
self.execute() | Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# (C) Copyright 2008 Alberto Gimeno <gimenete at gmail dot com>
#
# This file is part of "debug_mode_on".
#
# "debug_mode_on" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "debug_mode_on" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "debug_mode_on". If not, see <http://www.gnu.org/licenses/>.
#
from handlers.BaseHandler import *
class Static(BaseHandler):
def execute(self):
template = self.request.path.split('/', 2)[2]
self.render('templates/static/%s' % template) | Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# (C) Copyright 2008 Alberto Gimeno <gimenete at gmail dot com>
# (C) Copyright 2008 Ignacio Andreu <plunchete at gmail dot com>
# (C) Copyright 2008 Néstor Salceda <nestor.salceda at gmail dot com>
#
# This file is part of "debug_mode_on".
#
# "debug_mode_on" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "debug_mode_on" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "debug_mode_on". If not, see <http://www.gnu.org/licenses/>.
#
from handlers.BaseHandler import *
class Search(BaseHandler):
def execute(self):
q = self.get_param('q')
typ = self.get_param('t')
if typ == 'articles':
query = model.Article.all().filter('draft', False).filter('deletion_date', None).search(q)
self.values['articles'] = self.paging(query, 10)
self.add_tag_cloud()
elif typ == 'forums':
query = model.Thread.all().search(q)
threads = self.paging(query, 10)
# migration
for t in threads:
if not t.url_path:
t.url_path = t.parent_thread.url_path
t.put()
# end migration
self.values['threads'] = threads
else:
query = model.Community.all().search(q)
self.values['communities'] = self.paging(query, 10)
self.values['q'] = q
self.values['t'] = typ
self.render('templates/search.html')
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from handlers.MainPage import *
### MODULES ###
# Admin
from handlers.module.admin.Admin import *
from handlers.module.admin.AdminCategories import *
from handlers.module.admin.AdminCategoryEdit import *
from handlers.module.admin.AdminApplication import *
from handlers.module.admin.CommunityAddRelated import *
from handlers.module.admin.AdminUsers import *
from handlers.module.admin.AdminModules import *
from handlers.module.admin.AdminLookAndFeel import *
from handlers.module.admin.AdminGoogle import *
from handlers.module.admin.AdminMail import *
from handlers.module.admin.AdminCache import *
from handlers.module.admin.AdminStats import *
# Articles
from handlers.module.article.ArticleList import *
from handlers.module.article.ArticleEdit import *
from handlers.module.article.ArticleView import *
from handlers.module.article.ArticleVote import *
from handlers.module.article.ArticleDelete import *
from handlers.module.article.ArticleComment import *
from handlers.module.article.ArticleFavourite import *
from handlers.module.article.ArticleCommentSubscribe import *
from handlers.module.article.ArticleCommentDelete import *
from handlers.module.article.ArticleAddCommunities import *
from handlers.module.article.ArticleCommentEdit import *
from handlers.module.article.ArticleVisit import *
# Communities
from handlers.module.community.CommunityList import *
from handlers.module.community.CommunityEdit import *
from handlers.module.community.CommunityView import *
from handlers.module.community.CommunityMove import *
from handlers.module.community.CommunityDelete import *
# community forums
from handlers.module.community.CommunityForumList import *
from handlers.module.community.CommunityForumEdit import *
from handlers.module.community.CommunityForumView import *
from handlers.module.community.CommunityForumReply import *
from handlers.module.community.CommunityForumSubscribe import *
from handlers.module.community.CommunityForumDelete import *
from handlers.module.community.CommunityThreadEdit import *
from handlers.module.community.CommunityForumMove import *
from handlers.module.community.CommunityForumVisit import *
# community articles
from handlers.module.community.CommunityArticleList import *
from handlers.module.community.CommunityNewArticle import *
from handlers.module.community.CommunityArticleDelete import *
# community users
from handlers.module.community.CommunityUserList import *
from handlers.module.community.CommunityUserUnjoin import *
from handlers.module.community.CommunityUserJoin import *
# Users
from handlers.module.user.UserList import *
from handlers.module.user.UserView import *
from handlers.module.user.UserEdit import *
from handlers.module.user.UserArticles import *
from handlers.module.user.UserLogin import *
from handlers.module.user.UserCommunities import *
from handlers.module.user.UserLogout import *
from handlers.module.user.UserRegister import *
from handlers.module.user.UserChangePassword import *
from handlers.module.user.UserForgotPassword import *
from handlers.module.user.UserResetPassword import *
from handlers.module.user.UserDrafts import *
from handlers.module.user.UserContact import *
from handlers.module.user.UserFavourites import *
from handlers.module.user.UserContacts import *
from handlers.module.user.UserPromote import *
from handlers.module.user.UserEvents import *
from handlers.module.user.UserForums import *
# Blogging
from handlers.module.mblog.MBlogEdit import *
# Messages
from handlers.module.message.MessageEdit import *
from handlers.module.message.MessageSent import *
from handlers.module.message.MessageInbox import *
from handlers.module.message.MessageRead import *
from handlers.module.message.MessageDelete import *
### Common handlers / Other Handlers ###
# forums
from handlers.ForumList import *
#search
from handlers.SearchResult import *
# inviting contacts
from handlers.Invite import *
# feed RSS
from handlers.Feed import *
# images
from handlers.ImageDisplayer import *
from handlers.editor.ImageBrowser import *
from handlers.editor.ImageUploader import *
#Queue
from handlers.MailQueue import *
from handlers.TaskQueue import *
from handlers.Tag import *
from handlers.Search import *
from handlers.Dispatcher import *
from handlers.Initialization import *
from handlers.NotFound import *
from handlers.BaseRest import *
from handlers.Static import *
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Carrasco <jose.carrasco[a]vikuit.com>
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from handlers.BaseHandler import *
class Initialization(BaseHandler):
def get(self):
self.response.headers['Content-Type'] = 'text/plain'
app = model.Application.all().get()
if app is None:
populateDB()
self.response.out.write('App installed. Created user administrator. nickname="admin", password="1234". Please change the password.')
return
elif not app.session_seed:
import sha, random
app.session_seed = sha.new(str(random.random())).hexdigest()
app.put()
self.response.out.write('Seed installed')
return
p = int(self.request.get('p'))
key = self.request.get('key')
action = self.request.get('action')
if key:
community = model.Community.get(key)
if not community:
self.response.out.write('community not found')
return
offset = (p-1)*10
if action == 'gi':
i = self.community_articles(community, offset)
elif action == 'gu':
i = self.community_users(community, offset)
elif action == 'th':
i = self.threads(offset)
elif action == 'cc':
i = self.contacts(offset)
elif action == 'fv':
i = self.favourites(offset)
elif action == 'sg':
i = self.show_communities(offset)
return
elif action == 'ut':
i = self.update_threads(offset)
elif action == 'uis':
i = self.update_article_subscription(p-1)
self.response.out.write('Processed from %d to %d. %d updated. Action %s' % (p-1, i[0], i[1], action))
return
elif action == 'ugs':
i = self.update_community_subscription(community, offset)
elif action == 'uts':
i = self.update_thread_subscription(p-1)
self.response.out.write('Processed from %d to %d. %d updated. Action %s' % (p-1, i[0], i[1], action))
return
elif action == 'ugc':
i = self.update_community_counters(p-1)
self.response.out.write('Processed from %d to %d. %d updated. Action %s' % (p-1, i[0], i[1], action))
return
elif action == 'adus':
i = self.add_date_user_subscription(offset)
elif action == 'afg':
i = self.add_follower_community(offset)
elif action == 'afu':
i = self.add_follower_user(offset)
elif action == 'afi':
i = self.add_follower_article(offset)
elif action == 'aft':
i = self.add_follower_thread(offset)
else:
self.response.out.write('unknown action -%s-' % action)
return
self.response.out.write('Processed from %d to %d. %d updated. Action %s' % (offset, i[0], i[1], action))
def community_articles(self, community, offset):
i = offset
p = 0
for gi in model.CommunityArticle.all().filter('community', community).order('-creation_date').fetch(10, offset):
if not gi.community_title:
article = gi.article
community = gi.community
gi.article_author_nickname = article.author_nickname
gi.article_title = article.title
gi.article_url_path = article.url_path
gi.community_title = community.title
gi.community_url_path = community.url_path
gi.put()
p += 1
i+=1
return (i, p)
def community_users(self, community, offset):
i = offset
p = 0
for gu in model.CommunityUser.all().filter('community', community).order('-creation_date').fetch(10, offset):
if not gu.community_title:
user = gu.user
community = gu.community
gu.user_nickname = gu.user.nickname
gu.community_title = community.title
gu.community_url_path = community.url_path
gu.put()
p += 1
i+=1
return (i, p)
def threads(self, offset):
i = offset
p = 0
for th in model.Thread.all().order('-creation_date').fetch(10, offset):
if not th.community_title:
community = th.community
th.community_title = community.title
th.community_url_path = community.url_path
if not th.url_path:
th.url_path = th.parent_thread.url_path
th.put()
p += 1
i+=1
return (i, p)
def contacts(self, offset):
i = offset
p = 0
for cc in model.Contact.all().order('-creation_date').fetch(10, offset):
if not cc.user_from_nickname:
cc.user_from_nickname = cc.user_from.nickname
cc.user_to_nickname = cc.user_to.nickname
cc.put()
p += 1
i+=1
return (i, p)
def favourites(self, offset):
i = offset
p = 0
for fv in model.Favourite.all().order('-creation_date').fetch(10, offset):
if not fv.user_nickname:
article = fv.article
fv.article_author_nickname = article.author_nickname
fv.article_title = article.title
fv.article_url_path = article.url_path
fv.user_nickname = fv.user.nickname
fv.put()
p += 1
i+=1
return (i, p)
def show_communities(self, offset):
for g in model.Community.all().order('-creation_date').fetch(10, offset):
self.response.out.write("('%s', '%s', %d),\n" % (g.title, str(g.key()), g.members))
def update_threads(self, offset):
i = offset
p = 0
for th in model.Thread.all().filter('parent_thread', None).order('-creation_date').fetch(10, offset):
if th.views is None:
th.views = 0
th.put()
p += 1
i+=1
return (i, p)
def update_article_subscription(self, offset):
i = offset
p = 0
for article in model.Article.all().order('-creation_date').fetch(1, offset):
if article.subscribers:
for subscriber in article.subscribers:
user = model.UserData.all().filter('email', subscriber).get()
if not model.UserSubscription.all().filter('user', user).filter('subscription_type', 'article').filter('subscription_id', article.key().id()).get():
self.add_user_subscription(user, 'article', article.key().id())
p += 1
i+=1
return (i, p)
def update_community_subscription(self, community, offset):
i = offset
p = 0
for community_user in model.CommunityUser.all().filter('community', community).order('-creation_date').fetch(10, offset):
if not model.UserSubscription.all().filter('user', community_user.user).filter('subscription_type', 'community').filter('subscription_id', community.key().id()).get():
self.add_user_subscription(community_user.user, 'community', community.key().id())
p += 1
i += 1
return (i, p)
def update_thread_subscription(self, offset):
i = offset
p = 0
for thread in model.Thread.all().filter('parent_thread', None).order('-creation_date').fetch(1, offset):
if thread.subscribers:
for subscriber in thread.subscribers:
user = model.UserData.all().filter('email', subscriber).get()
if not model.UserSubscription.all().filter('user', user).filter('subscription_type', 'thread').filter('subscription_id', thread.key().id()).get():
self.add_user_subscription(user, 'thread', thread.key().id())
p += 1
i+=1
return (i, p)
def update_community_counters(self, offset):
i = offset
p = 0
for community in model.Community.all().order('-creation_date').fetch(1, offset):
users = model.CommunityUser.all().filter('community', community).count()
articles = model.CommunityArticle.all().filter('community', community).count()
community_threads = model.Thread.all().filter('community', community).filter('parent_thread', None)
threads = community_threads.count()
comments = 0
for thread in community_threads:
comments += model.Thread.all().filter('community', community).filter('parent_thread', thread).count()
if community.members != users or community.articles != articles or community.threads != threads or community.responses != comments:
community.members = users
community.articles = articles
community.threads = threads
community.responses = comments
p += 1
if not community.activity:
community.activity = 0
community.activity = (community.members * 1) + (community.threads * 5) + (community.articles * 15) + (community.responses * 2)
community.put()
i += 1
return (i, p)
def add_date_user_subscription(self, offset):
i = offset
p = 0
for user_subscription in model.UserSubscription.all().fetch(10, offset):
if user_subscription.creation_date is None:
user_subscription.creation_date = datetime.datetime.now()
user_subscription.put()
p += 1
i += 1
return (i, p)
def add_follower_community(self, offset):
i = offset
p = 0
for community_user in model.CommunityUser.all().fetch(10, offset):
if community_user.user_nickname is None:
self.desnormalizate_community_user(community_user)
self.add_follower(community=community_user, nickname=community_user.user_nickname)
p +=1
i += 1
return(i,p)
def add_follower_user(self, offset):
i = offset
p = 0
for cc in model.Contact.all().fetch(10, offset):
if cc.user_from_nickname is None:
self.desnormalizate_user_contact(cc)
self.add_follower(user=cc.user_to, nickname=cc.user_from_nickname)
p += 1
i += 1
return(i,p)
def add_follower_article(self, offset):
i = offset
p = 0
for article in model.Article.all().filter('deletion_date', None).filter('draft', False).fetch(10, offset):
self.add_follower(article=article, nickname=article.author_nickname)
p += 1
i += 1
return(i,p)
def add_follower_thread(self, offset):
i = offset
p = 0
for t in model.Thread.all().filter('parent_thread', None).fetch(10, offset):
self.add_follower(thread=t, nickname=t.author_nickname)
p += 1
i += 1
return(i, p)
def desnormalizate_community_user(self, gu):
user = gu.user
community = gu.community
gu.user_nickname = gu.user.nickname
gu.community_title = community.title
gu.community_url_path = community.url_path
gu.put()
def desnormalizate_user_contact(self, cc):
cc.user_from_nickname = cc.user_from.nickname
cc.user_to_nickname = cc.user_to.nickname
cc.put()
def populateDB():
app = model.Application.all().get()
if app is None:
app = model.Application()
app.name = 'vikuit-example'
app.subject = 'Social portal: lightweight and easy to install'
app.recaptcha_public_key = '6LdORAMAAAAAAL42zaVvAyYeoOowf4V85ETg0_h-'
app.recaptcha_private_key = '6LdORAMAAAAAAGS9WvIBg5d7kwOBNaNpqwKXllMQ'
app.theme = 'blackbook'
app.users = 0
app.communities = 0
app.articles = 0
app.threads = 0
app.url = "http://localhost:8080"
app.mail_subject_prefix = "[Vikuit]"
app.mail_sender = "admin.example@vikuit.com"
app.mail_footer = ""
app.max_results = 20
app.max_results_sublist = 20
import sha, random
app.session_seed = sha.new(str(random.random())).hexdigest()
app.put()
user = model.UserData(nickname='admin',
email='admin.example@vikuit.com',
password='1:c07cbf8821d47575a471c1606a56b79e5f6e6a68',
language='en',
articles=0,
draft_articles=0,
messages=0,
draft_messages=0,
comments=0,
rating_count=0,
rating_total=0,
rating_average=0,
threads=0,
responses=0,
communities=0,
favourites=0,
public=False,
contacts=0,
rol='admin')
user.put()
parent_category = model.Category(title='General',
description='General category description',
articles = 0,
communities = 0)
parent_category.put()
category = model.Category(title='News',
description='News description',
articles = 0,
communities = 0)
category.parent_category = parent_category
category.put()
post = model.Mblog(author=user,
author_nickname=user.nickname,
content='Welcome to Vikuit!!',
responses=0)
post.put()
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Carrasco <jose.carrasco[a]vikuit.com>
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from handlers.BaseHandler import *
class MainPage(BaseHandler):
def execute(self):
self.values['tab'] = '/'
# memcache.delete('index_articles')
# memcache.delete('index_communities')
# memcache.delete('index_threads')
self.values['articles'] = self.cache('index_articles', self.get_articles)
# self.values['communities'] = self.cache('index_communities', self.get_communities)
self.values['threads'] = self.cache('index_threads', self.get_threads)
self.add_tag_cloud()
# self.add_categories()
self.render('templates/index.html')
def get_articles(self):
return model.Article.all().filter('draft', False).filter('deletion_date', None).order('-creation_date').fetch(5)
# return self.render_chunk('templates/index-articles.html', {'articles': articles})
def get_communities(self):
return model.Community.all().order('-members').fetch(5)
# return self.render_chunk('templates/index-communities.html', {'communities': communities})
def get_threads(self):
return model.Thread.all().filter('parent_thread', None).order('-last_response_date').fetch(5)
# return self.render_chunk('templates/index-threads.html', {'threads': threads})
| Python |
# -*- coding: utf-8 -*-
"""
jinja2.runtime
~~~~~~~~~~~~~~
Runtime helpers.
:copyright: (c) 2010 by the Jinja Team.
:license: BSD.
"""
import sys
from itertools import chain, imap
from jinja2.nodes import EvalContext, _context_function_types
from jinja2.utils import Markup, partial, soft_unicode, escape, missing, \
concat, internalcode, next, object_type_repr
from jinja2.exceptions import UndefinedError, TemplateRuntimeError, \
TemplateNotFound
# these variables are exported to the template runtime
__all__ = ['LoopContext', 'TemplateReference', 'Macro', 'Markup',
'TemplateRuntimeError', 'missing', 'concat', 'escape',
'markup_join', 'unicode_join', 'to_string', 'identity',
'TemplateNotFound']
#: the name of the function that is used to convert something into
#: a string. 2to3 will adopt that automatically and the generated
#: code can take advantage of it.
to_string = unicode
#: the identity function. Useful for certain things in the environment
identity = lambda x: x
def markup_join(seq):
"""Concatenation that escapes if necessary and converts to unicode."""
buf = []
iterator = imap(soft_unicode, seq)
for arg in iterator:
buf.append(arg)
if hasattr(arg, '__html__'):
return Markup(u'').join(chain(buf, iterator))
return concat(buf)
def unicode_join(seq):
"""Simple args to unicode conversion and concatenation."""
return concat(imap(unicode, seq))
def new_context(environment, template_name, blocks, vars=None,
shared=None, globals=None, locals=None):
"""Internal helper to for context creation."""
if vars is None:
vars = {}
if shared:
parent = vars
else:
parent = dict(globals or (), **vars)
if locals:
# if the parent is shared a copy should be created because
# we don't want to modify the dict passed
if shared:
parent = dict(parent)
for key, value in locals.iteritems():
if key[:2] == 'l_' and value is not missing:
parent[key[2:]] = value
return Context(environment, parent, template_name, blocks)
class TemplateReference(object):
"""The `self` in templates."""
def __init__(self, context):
self.__context = context
def __getitem__(self, name):
blocks = self.__context.blocks[name]
wrap = self.__context.eval_ctx.autoescape and \
Markup or (lambda x: x)
return BlockReference(name, self.__context, blocks, 0)
def __repr__(self):
return '<%s %r>' % (
self.__class__.__name__,
self.__context.name
)
class Context(object):
"""The template context holds the variables of a template. It stores the
values passed to the template and also the names the template exports.
Creating instances is neither supported nor useful as it's created
automatically at various stages of the template evaluation and should not
be created by hand.
The context is immutable. Modifications on :attr:`parent` **must not**
happen and modifications on :attr:`vars` are allowed from generated
template code only. Template filters and global functions marked as
:func:`contextfunction`\s get the active context passed as first argument
and are allowed to access the context read-only.
The template context supports read only dict operations (`get`,
`keys`, `values`, `items`, `iterkeys`, `itervalues`, `iteritems`,
`__getitem__`, `__contains__`). Additionally there is a :meth:`resolve`
method that doesn't fail with a `KeyError` but returns an
:class:`Undefined` object for missing variables.
"""
__slots__ = ('parent', 'vars', 'environment', 'eval_ctx', 'exported_vars',
'name', 'blocks', '__weakref__')
def __init__(self, environment, parent, name, blocks):
self.parent = parent
self.vars = {}
self.environment = environment
self.eval_ctx = EvalContext(self.environment, name)
self.exported_vars = set()
self.name = name
# create the initial mapping of blocks. Whenever template inheritance
# takes place the runtime will update this mapping with the new blocks
# from the template.
self.blocks = dict((k, [v]) for k, v in blocks.iteritems())
def super(self, name, current):
"""Render a parent block."""
try:
blocks = self.blocks[name]
index = blocks.index(current) + 1
blocks[index]
except LookupError:
return self.environment.undefined('there is no parent block '
'called %r.' % name,
name='super')
return BlockReference(name, self, blocks, index)
def get(self, key, default=None):
"""Returns an item from the template context, if it doesn't exist
`default` is returned.
"""
try:
return self[key]
except KeyError:
return default
def resolve(self, key):
"""Looks up a variable like `__getitem__` or `get` but returns an
:class:`Undefined` object with the name of the name looked up.
"""
if key in self.vars:
return self.vars[key]
if key in self.parent:
return self.parent[key]
return self.environment.undefined(name=key)
def get_exported(self):
"""Get a new dict with the exported variables."""
return dict((k, self.vars[k]) for k in self.exported_vars)
def get_all(self):
"""Return a copy of the complete context as dict including the
exported variables.
"""
return dict(self.parent, **self.vars)
@internalcode
def call(__self, __obj, *args, **kwargs):
"""Call the callable with the arguments and keyword arguments
provided but inject the active context or environment as first
argument if the callable is a :func:`contextfunction` or
:func:`environmentfunction`.
"""
if __debug__:
__traceback_hide__ = True
if isinstance(__obj, _context_function_types):
if getattr(__obj, 'contextfunction', 0):
args = (__self,) + args
elif getattr(__obj, 'evalcontextfunction', 0):
args = (__self.eval_ctx,) + args
elif getattr(__obj, 'environmentfunction', 0):
args = (__self.environment,) + args
try:
return __obj(*args, **kwargs)
except StopIteration:
return __self.environment.undefined('value was undefined because '
'a callable raised a '
'StopIteration exception')
def derived(self, locals=None):
"""Internal helper function to create a derived context."""
context = new_context(self.environment, self.name, {},
self.parent, True, None, locals)
context.eval_ctx = self.eval_ctx
context.blocks.update((k, list(v)) for k, v in self.blocks.iteritems())
return context
def _all(meth):
proxy = lambda self: getattr(self.get_all(), meth)()
proxy.__doc__ = getattr(dict, meth).__doc__
proxy.__name__ = meth
return proxy
keys = _all('keys')
values = _all('values')
items = _all('items')
# not available on python 3
if hasattr(dict, 'iterkeys'):
iterkeys = _all('iterkeys')
itervalues = _all('itervalues')
iteritems = _all('iteritems')
del _all
def __contains__(self, name):
return name in self.vars or name in self.parent
def __getitem__(self, key):
"""Lookup a variable or raise `KeyError` if the variable is
undefined.
"""
item = self.resolve(key)
if isinstance(item, Undefined):
raise KeyError(key)
return item
def __repr__(self):
return '<%s %s of %r>' % (
self.__class__.__name__,
repr(self.get_all()),
self.name
)
# register the context as mapping if possible
try:
from collections import Mapping
Mapping.register(Context)
except ImportError:
pass
class BlockReference(object):
"""One block on a template reference."""
def __init__(self, name, context, stack, depth):
self.name = name
self._context = context
self._stack = stack
self._depth = depth
@property
def super(self):
"""Super the block."""
if self._depth + 1 >= len(self._stack):
return self._context.environment. \
undefined('there is no parent block called %r.' %
self.name, name='super')
return BlockReference(self.name, self._context, self._stack,
self._depth + 1)
@internalcode
def __call__(self):
rv = concat(self._stack[self._depth](self._context))
if self._context.eval_ctx.autoescape:
rv = Markup(rv)
return rv
class LoopContext(object):
"""A loop context for dynamic iteration."""
def __init__(self, iterable, recurse=None):
self._iterator = iter(iterable)
self._recurse = recurse
self.index0 = -1
# try to get the length of the iterable early. This must be done
# here because there are some broken iterators around where there
# __len__ is the number of iterations left (i'm looking at your
# listreverseiterator!).
try:
self._length = len(iterable)
except (TypeError, AttributeError):
self._length = None
def cycle(self, *args):
"""Cycles among the arguments with the current loop index."""
if not args:
raise TypeError('no items for cycling given')
return args[self.index0 % len(args)]
first = property(lambda x: x.index0 == 0)
last = property(lambda x: x.index0 + 1 == x.length)
index = property(lambda x: x.index0 + 1)
revindex = property(lambda x: x.length - x.index0)
revindex0 = property(lambda x: x.length - x.index)
def __len__(self):
return self.length
def __iter__(self):
return LoopContextIterator(self)
@internalcode
def loop(self, iterable):
if self._recurse is None:
raise TypeError('Tried to call non recursive loop. Maybe you '
"forgot the 'recursive' modifier.")
return self._recurse(iterable, self._recurse)
# a nifty trick to enhance the error message if someone tried to call
# the the loop without or with too many arguments.
__call__ = loop
del loop
@property
def length(self):
if self._length is None:
# if was not possible to get the length of the iterator when
# the loop context was created (ie: iterating over a generator)
# we have to convert the iterable into a sequence and use the
# length of that.
iterable = tuple(self._iterator)
self._iterator = iter(iterable)
self._length = len(iterable) + self.index0 + 1
return self._length
def __repr__(self):
return '<%s %r/%r>' % (
self.__class__.__name__,
self.index,
self.length
)
class LoopContextIterator(object):
"""The iterator for a loop context."""
__slots__ = ('context',)
def __init__(self, context):
self.context = context
def __iter__(self):
return self
def next(self):
ctx = self.context
ctx.index0 += 1
return next(ctx._iterator), ctx
class Macro(object):
"""Wraps a macro function."""
def __init__(self, environment, func, name, arguments, defaults,
catch_kwargs, catch_varargs, caller):
self._environment = environment
self._func = func
self._argument_count = len(arguments)
self.name = name
self.arguments = arguments
self.defaults = defaults
self.catch_kwargs = catch_kwargs
self.catch_varargs = catch_varargs
self.caller = caller
@internalcode
def __call__(self, *args, **kwargs):
# try to consume the positional arguments
arguments = list(args[:self._argument_count])
off = len(arguments)
# if the number of arguments consumed is not the number of
# arguments expected we start filling in keyword arguments
# and defaults.
if off != self._argument_count:
for idx, name in enumerate(self.arguments[len(arguments):]):
try:
value = kwargs.pop(name)
except KeyError:
try:
value = self.defaults[idx - self._argument_count + off]
except IndexError:
value = self._environment.undefined(
'parameter %r was not provided' % name, name=name)
arguments.append(value)
# it's important that the order of these arguments does not change
# if not also changed in the compiler's `function_scoping` method.
# the order is caller, keyword arguments, positional arguments!
if self.caller:
caller = kwargs.pop('caller', None)
if caller is None:
caller = self._environment.undefined('No caller defined',
name='caller')
arguments.append(caller)
if self.catch_kwargs:
arguments.append(kwargs)
elif kwargs:
raise TypeError('macro %r takes no keyword argument %r' %
(self.name, next(iter(kwargs))))
if self.catch_varargs:
arguments.append(args[self._argument_count:])
elif len(args) > self._argument_count:
raise TypeError('macro %r takes not more than %d argument(s)' %
(self.name, len(self.arguments)))
return self._func(*arguments)
def __repr__(self):
return '<%s %s>' % (
self.__class__.__name__,
self.name is None and 'anonymous' or repr(self.name)
)
class Undefined(object):
"""The default undefined type. This undefined type can be printed and
iterated over, but every other access will raise an :exc:`UndefinedError`:
>>> foo = Undefined(name='foo')
>>> str(foo)
''
>>> not foo
True
>>> foo + 42
Traceback (most recent call last):
...
UndefinedError: 'foo' is undefined
"""
__slots__ = ('_undefined_hint', '_undefined_obj', '_undefined_name',
'_undefined_exception')
def __init__(self, hint=None, obj=missing, name=None, exc=UndefinedError):
self._undefined_hint = hint
self._undefined_obj = obj
self._undefined_name = name
self._undefined_exception = exc
@internalcode
def _fail_with_undefined_error(self, *args, **kwargs):
"""Regular callback function for undefined objects that raises an
`UndefinedError` on call.
"""
if self._undefined_hint is None:
if self._undefined_obj is missing:
hint = '%r is undefined' % self._undefined_name
elif not isinstance(self._undefined_name, basestring):
hint = '%s has no element %r' % (
object_type_repr(self._undefined_obj),
self._undefined_name
)
else:
hint = '%r has no attribute %r' % (
object_type_repr(self._undefined_obj),
self._undefined_name
)
else:
hint = self._undefined_hint
raise self._undefined_exception(hint)
__add__ = __radd__ = __mul__ = __rmul__ = __div__ = __rdiv__ = \
__truediv__ = __rtruediv__ = __floordiv__ = __rfloordiv__ = \
__mod__ = __rmod__ = __pos__ = __neg__ = __call__ = \
__getattr__ = __getitem__ = __lt__ = __le__ = __gt__ = __ge__ = \
__int__ = __float__ = __complex__ = __pow__ = __rpow__ = \
_fail_with_undefined_error
def __str__(self):
return unicode(self).encode('utf-8')
# unicode goes after __str__ because we configured 2to3 to rename
# __unicode__ to __str__. because the 2to3 tree is not designed to
# remove nodes from it, we leave the above __str__ around and let
# it override at runtime.
def __unicode__(self):
return u''
def __len__(self):
return 0
def __iter__(self):
if 0:
yield None
def __nonzero__(self):
return False
def __repr__(self):
return 'Undefined'
class DebugUndefined(Undefined):
"""An undefined that returns the debug info when printed.
>>> foo = DebugUndefined(name='foo')
>>> str(foo)
'{{ foo }}'
>>> not foo
True
>>> foo + 42
Traceback (most recent call last):
...
UndefinedError: 'foo' is undefined
"""
__slots__ = ()
def __unicode__(self):
if self._undefined_hint is None:
if self._undefined_obj is missing:
return u'{{ %s }}' % self._undefined_name
return '{{ no such element: %s[%r] }}' % (
object_type_repr(self._undefined_obj),
self._undefined_name
)
return u'{{ undefined value printed: %s }}' % self._undefined_hint
class StrictUndefined(Undefined):
"""An undefined that barks on print and iteration as well as boolean
tests and all kinds of comparisons. In other words: you can do nothing
with it except checking if it's defined using the `defined` test.
>>> foo = StrictUndefined(name='foo')
>>> str(foo)
Traceback (most recent call last):
...
UndefinedError: 'foo' is undefined
>>> not foo
Traceback (most recent call last):
...
UndefinedError: 'foo' is undefined
>>> foo + 42
Traceback (most recent call last):
...
UndefinedError: 'foo' is undefined
"""
__slots__ = ()
__iter__ = __unicode__ = __str__ = __len__ = __nonzero__ = __eq__ = \
__ne__ = __bool__ = Undefined._fail_with_undefined_error
# remove remaining slots attributes, after the metaclass did the magic they
# are unneeded and irritating as they contain wrong data for the subclasses.
del Undefined.__slots__, DebugUndefined.__slots__, StrictUndefined.__slots__
| Python |
# -*- coding: utf-8 -*-
"""
jinja2.nodes
~~~~~~~~~~~~
This module implements additional nodes derived from the ast base node.
It also provides some node tree helper functions like `in_lineno` and
`get_nodes` used by the parser and translator in order to normalize
python and jinja nodes.
:copyright: (c) 2010 by the Jinja Team.
:license: BSD, see LICENSE for more details.
"""
import operator
from itertools import chain, izip
from collections import deque
from jinja2.utils import Markup, MethodType, FunctionType
#: the types we support for context functions
_context_function_types = (FunctionType, MethodType)
_binop_to_func = {
'*': operator.mul,
'/': operator.truediv,
'//': operator.floordiv,
'**': operator.pow,
'%': operator.mod,
'+': operator.add,
'-': operator.sub
}
_uaop_to_func = {
'not': operator.not_,
'+': operator.pos,
'-': operator.neg
}
_cmpop_to_func = {
'eq': operator.eq,
'ne': operator.ne,
'gt': operator.gt,
'gteq': operator.ge,
'lt': operator.lt,
'lteq': operator.le,
'in': lambda a, b: a in b,
'notin': lambda a, b: a not in b
}
class Impossible(Exception):
"""Raised if the node could not perform a requested action."""
class NodeType(type):
"""A metaclass for nodes that handles the field and attribute
inheritance. fields and attributes from the parent class are
automatically forwarded to the child."""
def __new__(cls, name, bases, d):
for attr in 'fields', 'attributes':
storage = []
storage.extend(getattr(bases[0], attr, ()))
storage.extend(d.get(attr, ()))
assert len(bases) == 1, 'multiple inheritance not allowed'
assert len(storage) == len(set(storage)), 'layout conflict'
d[attr] = tuple(storage)
d.setdefault('abstract', False)
return type.__new__(cls, name, bases, d)
class EvalContext(object):
"""Holds evaluation time information. Custom attributes can be attached
to it in extensions.
"""
def __init__(self, environment, template_name=None):
if callable(environment.autoescape):
self.autoescape = environment.autoescape(template_name)
else:
self.autoescape = environment.autoescape
self.volatile = False
def save(self):
return self.__dict__.copy()
def revert(self, old):
self.__dict__.clear()
self.__dict__.update(old)
def get_eval_context(node, ctx):
if ctx is None:
if node.environment is None:
raise RuntimeError('if no eval context is passed, the '
'node must have an attached '
'environment.')
return EvalContext(node.environment)
return ctx
class Node(object):
"""Baseclass for all Jinja2 nodes. There are a number of nodes available
of different types. There are three major types:
- :class:`Stmt`: statements
- :class:`Expr`: expressions
- :class:`Helper`: helper nodes
- :class:`Template`: the outermost wrapper node
All nodes have fields and attributes. Fields may be other nodes, lists,
or arbitrary values. Fields are passed to the constructor as regular
positional arguments, attributes as keyword arguments. Each node has
two attributes: `lineno` (the line number of the node) and `environment`.
The `environment` attribute is set at the end of the parsing process for
all nodes automatically.
"""
__metaclass__ = NodeType
fields = ()
attributes = ('lineno', 'environment')
abstract = True
def __init__(self, *fields, **attributes):
if self.abstract:
raise TypeError('abstract nodes are not instanciable')
if fields:
if len(fields) != len(self.fields):
if not self.fields:
raise TypeError('%r takes 0 arguments' %
self.__class__.__name__)
raise TypeError('%r takes 0 or %d argument%s' % (
self.__class__.__name__,
len(self.fields),
len(self.fields) != 1 and 's' or ''
))
for name, arg in izip(self.fields, fields):
setattr(self, name, arg)
for attr in self.attributes:
setattr(self, attr, attributes.pop(attr, None))
if attributes:
raise TypeError('unknown attribute %r' %
iter(attributes).next())
def iter_fields(self, exclude=None, only=None):
"""This method iterates over all fields that are defined and yields
``(key, value)`` tuples. Per default all fields are returned, but
it's possible to limit that to some fields by providing the `only`
parameter or to exclude some using the `exclude` parameter. Both
should be sets or tuples of field names.
"""
for name in self.fields:
if (exclude is only is None) or \
(exclude is not None and name not in exclude) or \
(only is not None and name in only):
try:
yield name, getattr(self, name)
except AttributeError:
pass
def iter_child_nodes(self, exclude=None, only=None):
"""Iterates over all direct child nodes of the node. This iterates
over all fields and yields the values of they are nodes. If the value
of a field is a list all the nodes in that list are returned.
"""
for field, item in self.iter_fields(exclude, only):
if isinstance(item, list):
for n in item:
if isinstance(n, Node):
yield n
elif isinstance(item, Node):
yield item
def find(self, node_type):
"""Find the first node of a given type. If no such node exists the
return value is `None`.
"""
for result in self.find_all(node_type):
return result
def find_all(self, node_type):
"""Find all the nodes of a given type. If the type is a tuple,
the check is performed for any of the tuple items.
"""
for child in self.iter_child_nodes():
if isinstance(child, node_type):
yield child
for result in child.find_all(node_type):
yield result
def set_ctx(self, ctx):
"""Reset the context of a node and all child nodes. Per default the
parser will all generate nodes that have a 'load' context as it's the
most common one. This method is used in the parser to set assignment
targets and other nodes to a store context.
"""
todo = deque([self])
while todo:
node = todo.popleft()
if 'ctx' in node.fields:
node.ctx = ctx
todo.extend(node.iter_child_nodes())
return self
def set_lineno(self, lineno, override=False):
"""Set the line numbers of the node and children."""
todo = deque([self])
while todo:
node = todo.popleft()
if 'lineno' in node.attributes:
if node.lineno is None or override:
node.lineno = lineno
todo.extend(node.iter_child_nodes())
return self
def set_environment(self, environment):
"""Set the environment for all nodes."""
todo = deque([self])
while todo:
node = todo.popleft()
node.environment = environment
todo.extend(node.iter_child_nodes())
return self
def __eq__(self, other):
return type(self) is type(other) and \
tuple(self.iter_fields()) == tuple(other.iter_fields())
def __ne__(self, other):
return not self.__eq__(other)
def __repr__(self):
return '%s(%s)' % (
self.__class__.__name__,
', '.join('%s=%r' % (arg, getattr(self, arg, None)) for
arg in self.fields)
)
class Stmt(Node):
"""Base node for all statements."""
abstract = True
class Helper(Node):
"""Nodes that exist in a specific context only."""
abstract = True
class Template(Node):
"""Node that represents a template. This must be the outermost node that
is passed to the compiler.
"""
fields = ('body',)
class Output(Stmt):
"""A node that holds multiple expressions which are then printed out.
This is used both for the `print` statement and the regular template data.
"""
fields = ('nodes',)
class Extends(Stmt):
"""Represents an extends statement."""
fields = ('template',)
class For(Stmt):
"""The for loop. `target` is the target for the iteration (usually a
:class:`Name` or :class:`Tuple`), `iter` the iterable. `body` is a list
of nodes that are used as loop-body, and `else_` a list of nodes for the
`else` block. If no else node exists it has to be an empty list.
For filtered nodes an expression can be stored as `test`, otherwise `None`.
"""
fields = ('target', 'iter', 'body', 'else_', 'test', 'recursive')
class If(Stmt):
"""If `test` is true, `body` is rendered, else `else_`."""
fields = ('test', 'body', 'else_')
class Macro(Stmt):
"""A macro definition. `name` is the name of the macro, `args` a list of
arguments and `defaults` a list of defaults if there are any. `body` is
a list of nodes for the macro body.
"""
fields = ('name', 'args', 'defaults', 'body')
class CallBlock(Stmt):
"""Like a macro without a name but a call instead. `call` is called with
the unnamed macro as `caller` argument this node holds.
"""
fields = ('call', 'args', 'defaults', 'body')
class FilterBlock(Stmt):
"""Node for filter sections."""
fields = ('body', 'filter')
class Block(Stmt):
"""A node that represents a block."""
fields = ('name', 'body', 'scoped')
class Include(Stmt):
"""A node that represents the include tag."""
fields = ('template', 'with_context', 'ignore_missing')
class Import(Stmt):
"""A node that represents the import tag."""
fields = ('template', 'target', 'with_context')
class FromImport(Stmt):
"""A node that represents the from import tag. It's important to not
pass unsafe names to the name attribute. The compiler translates the
attribute lookups directly into getattr calls and does *not* use the
subscript callback of the interface. As exported variables may not
start with double underscores (which the parser asserts) this is not a
problem for regular Jinja code, but if this node is used in an extension
extra care must be taken.
The list of names may contain tuples if aliases are wanted.
"""
fields = ('template', 'names', 'with_context')
class ExprStmt(Stmt):
"""A statement that evaluates an expression and discards the result."""
fields = ('node',)
class Assign(Stmt):
"""Assigns an expression to a target."""
fields = ('target', 'node')
class Expr(Node):
"""Baseclass for all expressions."""
abstract = True
def as_const(self, eval_ctx=None):
"""Return the value of the expression as constant or raise
:exc:`Impossible` if this was not possible.
An :class:`EvalContext` can be provided, if none is given
a default context is created which requires the nodes to have
an attached environment.
.. versionchanged:: 2.4
the `eval_ctx` parameter was added.
"""
raise Impossible()
def can_assign(self):
"""Check if it's possible to assign something to this node."""
return False
class BinExpr(Expr):
"""Baseclass for all binary expressions."""
fields = ('left', 'right')
operator = None
abstract = True
def as_const(self, eval_ctx=None):
eval_ctx = get_eval_context(self, eval_ctx)
f = _binop_to_func[self.operator]
try:
return f(self.left.as_const(eval_ctx), self.right.as_const(eval_ctx))
except:
raise Impossible()
class UnaryExpr(Expr):
"""Baseclass for all unary expressions."""
fields = ('node',)
operator = None
abstract = True
def as_const(self, eval_ctx=None):
eval_ctx = get_eval_context(self, eval_ctx)
f = _uaop_to_func[self.operator]
try:
return f(self.node.as_const(eval_ctx))
except:
raise Impossible()
class Name(Expr):
"""Looks up a name or stores a value in a name.
The `ctx` of the node can be one of the following values:
- `store`: store a value in the name
- `load`: load that name
- `param`: like `store` but if the name was defined as function parameter.
"""
fields = ('name', 'ctx')
def can_assign(self):
return self.name not in ('true', 'false', 'none',
'True', 'False', 'None')
class Literal(Expr):
"""Baseclass for literals."""
abstract = True
class Const(Literal):
"""All constant values. The parser will return this node for simple
constants such as ``42`` or ``"foo"`` but it can be used to store more
complex values such as lists too. Only constants with a safe
representation (objects where ``eval(repr(x)) == x`` is true).
"""
fields = ('value',)
def as_const(self, eval_ctx=None):
return self.value
@classmethod
def from_untrusted(cls, value, lineno=None, environment=None):
"""Return a const object if the value is representable as
constant value in the generated code, otherwise it will raise
an `Impossible` exception.
"""
from compiler import has_safe_repr
if not has_safe_repr(value):
raise Impossible()
return cls(value, lineno=lineno, environment=environment)
class TemplateData(Literal):
"""A constant template string."""
fields = ('data',)
def as_const(self, eval_ctx=None):
eval_ctx = get_eval_context(self, eval_ctx)
if eval_ctx.volatile:
raise Impossible()
if eval_ctx.autoescape:
return Markup(self.data)
return self.data
class Tuple(Literal):
"""For loop unpacking and some other things like multiple arguments
for subscripts. Like for :class:`Name` `ctx` specifies if the tuple
is used for loading the names or storing.
"""
fields = ('items', 'ctx')
def as_const(self, eval_ctx=None):
eval_ctx = get_eval_context(self, eval_ctx)
return tuple(x.as_const(eval_ctx) for x in self.items)
def can_assign(self):
for item in self.items:
if not item.can_assign():
return False
return True
class List(Literal):
"""Any list literal such as ``[1, 2, 3]``"""
fields = ('items',)
def as_const(self, eval_ctx=None):
eval_ctx = get_eval_context(self, eval_ctx)
return [x.as_const(eval_ctx) for x in self.items]
class Dict(Literal):
"""Any dict literal such as ``{1: 2, 3: 4}``. The items must be a list of
:class:`Pair` nodes.
"""
fields = ('items',)
def as_const(self, eval_ctx=None):
eval_ctx = get_eval_context(self, eval_ctx)
return dict(x.as_const(eval_ctx) for x in self.items)
class Pair(Helper):
"""A key, value pair for dicts."""
fields = ('key', 'value')
def as_const(self, eval_ctx=None):
eval_ctx = get_eval_context(self, eval_ctx)
return self.key.as_const(eval_ctx), self.value.as_const(eval_ctx)
class Keyword(Helper):
"""A key, value pair for keyword arguments where key is a string."""
fields = ('key', 'value')
def as_const(self, eval_ctx=None):
eval_ctx = get_eval_context(self, eval_ctx)
return self.key, self.value.as_const(eval_ctx)
class CondExpr(Expr):
"""A conditional expression (inline if expression). (``{{
foo if bar else baz }}``)
"""
fields = ('test', 'expr1', 'expr2')
def as_const(self, eval_ctx=None):
eval_ctx = get_eval_context(self, eval_ctx)
if self.test.as_const(eval_ctx):
return self.expr1.as_const(eval_ctx)
# if we evaluate to an undefined object, we better do that at runtime
if self.expr2 is None:
raise Impossible()
return self.expr2.as_const(eval_ctx)
class Filter(Expr):
"""This node applies a filter on an expression. `name` is the name of
the filter, the rest of the fields are the same as for :class:`Call`.
If the `node` of a filter is `None` the contents of the last buffer are
filtered. Buffers are created by macros and filter blocks.
"""
fields = ('node', 'name', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')
def as_const(self, eval_ctx=None):
eval_ctx = get_eval_context(self, eval_ctx)
if eval_ctx.volatile or self.node is None:
raise Impossible()
# we have to be careful here because we call filter_ below.
# if this variable would be called filter, 2to3 would wrap the
# call in a list beause it is assuming we are talking about the
# builtin filter function here which no longer returns a list in
# python 3. because of that, do not rename filter_ to filter!
filter_ = self.environment.filters.get(self.name)
if filter_ is None or getattr(filter_, 'contextfilter', False):
raise Impossible()
obj = self.node.as_const(eval_ctx)
args = [x.as_const(eval_ctx) for x in self.args]
if getattr(filter_, 'evalcontextfilter', False):
args.insert(0, eval_ctx)
elif getattr(filter_, 'environmentfilter', False):
args.insert(0, self.environment)
kwargs = dict(x.as_const(eval_ctx) for x in self.kwargs)
if self.dyn_args is not None:
try:
args.extend(self.dyn_args.as_const(eval_ctx))
except:
raise Impossible()
if self.dyn_kwargs is not None:
try:
kwargs.update(self.dyn_kwargs.as_const(eval_ctx))
except:
raise Impossible()
try:
return filter_(obj, *args, **kwargs)
except:
raise Impossible()
class Test(Expr):
"""Applies a test on an expression. `name` is the name of the test, the
rest of the fields are the same as for :class:`Call`.
"""
fields = ('node', 'name', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')
class Call(Expr):
"""Calls an expression. `args` is a list of arguments, `kwargs` a list
of keyword arguments (list of :class:`Keyword` nodes), and `dyn_args`
and `dyn_kwargs` has to be either `None` or a node that is used as
node for dynamic positional (``*args``) or keyword (``**kwargs``)
arguments.
"""
fields = ('node', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')
def as_const(self, eval_ctx=None):
eval_ctx = get_eval_context(self, eval_ctx)
if eval_ctx.volatile:
raise Impossible()
obj = self.node.as_const(eval_ctx)
# don't evaluate context functions
args = [x.as_const(eval_ctx) for x in self.args]
if isinstance(obj, _context_function_types):
if getattr(obj, 'contextfunction', False):
raise Impossible()
elif getattr(obj, 'evalcontextfunction', False):
args.insert(0, eval_ctx)
elif getattr(obj, 'environmentfunction', False):
args.insert(0, self.environment)
kwargs = dict(x.as_const(eval_ctx) for x in self.kwargs)
if self.dyn_args is not None:
try:
args.extend(self.dyn_args.as_const(eval_ctx))
except:
raise Impossible()
if self.dyn_kwargs is not None:
try:
kwargs.update(self.dyn_kwargs.as_const(eval_ctx))
except:
raise Impossible()
try:
return obj(*args, **kwargs)
except:
raise Impossible()
class Getitem(Expr):
"""Get an attribute or item from an expression and prefer the item."""
fields = ('node', 'arg', 'ctx')
def as_const(self, eval_ctx=None):
eval_ctx = get_eval_context(self, eval_ctx)
if self.ctx != 'load':
raise Impossible()
try:
return self.environment.getitem(self.node.as_const(eval_ctx),
self.arg.as_const(eval_ctx))
except:
raise Impossible()
def can_assign(self):
return False
class Getattr(Expr):
"""Get an attribute or item from an expression that is a ascii-only
bytestring and prefer the attribute.
"""
fields = ('node', 'attr', 'ctx')
def as_const(self, eval_ctx=None):
if self.ctx != 'load':
raise Impossible()
try:
eval_ctx = get_eval_context(self, eval_ctx)
return self.environment.getattr(self.node.as_const(eval_ctx),
self.attr)
except:
raise Impossible()
def can_assign(self):
return False
class Slice(Expr):
"""Represents a slice object. This must only be used as argument for
:class:`Subscript`.
"""
fields = ('start', 'stop', 'step')
def as_const(self, eval_ctx=None):
eval_ctx = get_eval_context(self, eval_ctx)
def const(obj):
if obj is None:
return None
return obj.as_const(eval_ctx)
return slice(const(self.start), const(self.stop), const(self.step))
class Concat(Expr):
"""Concatenates the list of expressions provided after converting them to
unicode.
"""
fields = ('nodes',)
def as_const(self, eval_ctx=None):
eval_ctx = get_eval_context(self, eval_ctx)
return ''.join(unicode(x.as_const(eval_ctx)) for x in self.nodes)
class Compare(Expr):
"""Compares an expression with some other expressions. `ops` must be a
list of :class:`Operand`\s.
"""
fields = ('expr', 'ops')
def as_const(self, eval_ctx=None):
eval_ctx = get_eval_context(self, eval_ctx)
result = value = self.expr.as_const(eval_ctx)
try:
for op in self.ops:
new_value = op.expr.as_const(eval_ctx)
result = _cmpop_to_func[op.op](value, new_value)
value = new_value
except:
raise Impossible()
return result
class Operand(Helper):
"""Holds an operator and an expression."""
fields = ('op', 'expr')
if __debug__:
Operand.__doc__ += '\nThe following operators are available: ' + \
', '.join(sorted('``%s``' % x for x in set(_binop_to_func) |
set(_uaop_to_func) | set(_cmpop_to_func)))
class Mul(BinExpr):
"""Multiplies the left with the right node."""
operator = '*'
class Div(BinExpr):
"""Divides the left by the right node."""
operator = '/'
class FloorDiv(BinExpr):
"""Divides the left by the right node and truncates conver the
result into an integer by truncating.
"""
operator = '//'
class Add(BinExpr):
"""Add the left to the right node."""
operator = '+'
class Sub(BinExpr):
"""Substract the right from the left node."""
operator = '-'
class Mod(BinExpr):
"""Left modulo right."""
operator = '%'
class Pow(BinExpr):
"""Left to the power of right."""
operator = '**'
class And(BinExpr):
"""Short circuited AND."""
operator = 'and'
def as_const(self, eval_ctx=None):
eval_ctx = get_eval_context(self, eval_ctx)
return self.left.as_const(eval_ctx) and self.right.as_const(eval_ctx)
class Or(BinExpr):
"""Short circuited OR."""
operator = 'or'
def as_const(self, eval_ctx=None):
eval_ctx = get_eval_context(self, eval_ctx)
return self.left.as_const(eval_ctx) or self.right.as_const(eval_ctx)
class Not(UnaryExpr):
"""Negate the expression."""
operator = 'not'
class Neg(UnaryExpr):
"""Make the expression negative."""
operator = '-'
class Pos(UnaryExpr):
"""Make the expression positive (noop for most expressions)"""
operator = '+'
# Helpers for extensions
class EnvironmentAttribute(Expr):
"""Loads an attribute from the environment object. This is useful for
extensions that want to call a callback stored on the environment.
"""
fields = ('name',)
class ExtensionAttribute(Expr):
"""Returns the attribute of an extension bound to the environment.
The identifier is the identifier of the :class:`Extension`.
This node is usually constructed by calling the
:meth:`~jinja2.ext.Extension.attr` method on an extension.
"""
fields = ('identifier', 'name')
class ImportedName(Expr):
"""If created with an import name the import name is returned on node
access. For example ``ImportedName('cgi.escape')`` returns the `escape`
function from the cgi module on evaluation. Imports are optimized by the
compiler so there is no need to assign them to local variables.
"""
fields = ('importname',)
class InternalName(Expr):
"""An internal name in the compiler. You cannot create these nodes
yourself but the parser provides a
:meth:`~jinja2.parser.Parser.free_identifier` method that creates
a new identifier for you. This identifier is not available from the
template and is not threated specially by the compiler.
"""
fields = ('name',)
def __init__(self):
raise TypeError('Can\'t create internal names. Use the '
'`free_identifier` method on a parser.')
class MarkSafe(Expr):
"""Mark the wrapped expression as safe (wrap it as `Markup`)."""
fields = ('expr',)
def as_const(self, eval_ctx=None):
eval_ctx = get_eval_context(self, eval_ctx)
return Markup(self.expr.as_const(eval_ctx))
class MarkSafeIfAutoescape(Expr):
"""Mark the wrapped expression as safe (wrap it as `Markup`) but
only if autoescaping is active.
.. versionadded:: 2.5
"""
fields = ('expr',)
def as_const(self, eval_ctx=None):
eval_ctx = get_eval_context(self, eval_ctx)
if eval_ctx.volatile:
raise Impossible()
expr = self.expr.as_const(eval_ctx)
if eval_ctx.autoescape:
return Markup(expr)
return expr
class ContextReference(Expr):
"""Returns the current template context. It can be used like a
:class:`Name` node, with a ``'load'`` ctx and will return the
current :class:`~jinja2.runtime.Context` object.
Here an example that assigns the current template name to a
variable named `foo`::
Assign(Name('foo', ctx='store'),
Getattr(ContextReference(), 'name'))
"""
class Continue(Stmt):
"""Continue a loop."""
class Break(Stmt):
"""Break a loop."""
class Scope(Stmt):
"""An artificial scope."""
fields = ('body',)
class EvalContextModifier(Stmt):
"""Modifies the eval context. For each option that should be modified,
a :class:`Keyword` has to be added to the :attr:`options` list.
Example to change the `autoescape` setting::
EvalContextModifier(options=[Keyword('autoescape', Const(True))])
"""
fields = ('options',)
class ScopedEvalContextModifier(EvalContextModifier):
"""Modifies the eval context and reverts it later. Works exactly like
:class:`EvalContextModifier` but will only modify the
:class:`~jinja2.nodes.EvalContext` for nodes in the :attr:`body`.
"""
fields = ('body',)
# make sure nobody creates custom nodes
def _failing_new(*args, **kwargs):
raise TypeError('can\'t create custom node types')
NodeType.__new__ = staticmethod(_failing_new); del _failing_new
| Python |
# -*- coding: utf-8 -*-
"""
jinja2.debug
~~~~~~~~~~~~
Implements the debug interface for Jinja. This module does some pretty
ugly stuff with the Python traceback system in order to achieve tracebacks
with correct line numbers, locals and contents.
:copyright: (c) 2010 by the Jinja Team.
:license: BSD, see LICENSE for more details.
"""
import sys
import traceback
from jinja2.utils import CodeType, missing, internal_code
from jinja2.exceptions import TemplateSyntaxError
# how does the raise helper look like?
try:
exec "raise TypeError, 'foo'"
except SyntaxError:
raise_helper = 'raise __jinja_exception__[1]'
except TypeError:
raise_helper = 'raise __jinja_exception__[0], __jinja_exception__[1]'
class TracebackFrameProxy(object):
"""Proxies a traceback frame."""
def __init__(self, tb):
self.tb = tb
def _set_tb_next(self, next):
if tb_set_next is not None:
tb_set_next(self.tb, next and next.tb or None)
self._tb_next = next
def _get_tb_next(self):
return self._tb_next
tb_next = property(_get_tb_next, _set_tb_next)
del _get_tb_next, _set_tb_next
@property
def is_jinja_frame(self):
return '__jinja_template__' in self.tb.tb_frame.f_globals
def __getattr__(self, name):
return getattr(self.tb, name)
class ProcessedTraceback(object):
"""Holds a Jinja preprocessed traceback for priting or reraising."""
def __init__(self, exc_type, exc_value, frames):
assert frames, 'no frames for this traceback?'
self.exc_type = exc_type
self.exc_value = exc_value
self.frames = frames
def chain_frames(self):
"""Chains the frames. Requires ctypes or the debugsupport extension."""
prev_tb = None
for tb in self.frames:
if prev_tb is not None:
prev_tb.tb_next = tb
prev_tb = tb
prev_tb.tb_next = None
def render_as_text(self, limit=None):
"""Return a string with the traceback."""
lines = traceback.format_exception(self.exc_type, self.exc_value,
self.frames[0], limit=limit)
return ''.join(lines).rstrip()
def render_as_html(self, full=False):
"""Return a unicode string with the traceback as rendered HTML."""
from jinja2.debugrenderer import render_traceback
return u'%s\n\n<!--\n%s\n-->' % (
render_traceback(self, full=full),
self.render_as_text().decode('utf-8', 'replace')
)
@property
def is_template_syntax_error(self):
"""`True` if this is a template syntax error."""
return isinstance(self.exc_value, TemplateSyntaxError)
@property
def exc_info(self):
"""Exception info tuple with a proxy around the frame objects."""
return self.exc_type, self.exc_value, self.frames[0]
@property
def standard_exc_info(self):
"""Standard python exc_info for re-raising"""
return self.exc_type, self.exc_value, self.frames[0].tb
def make_traceback(exc_info, source_hint=None):
"""Creates a processed traceback object from the exc_info."""
exc_type, exc_value, tb = exc_info
if isinstance(exc_value, TemplateSyntaxError):
exc_info = translate_syntax_error(exc_value, source_hint)
initial_skip = 0
else:
initial_skip = 1
return translate_exception(exc_info, initial_skip)
def translate_syntax_error(error, source=None):
"""Rewrites a syntax error to please traceback systems."""
error.source = source
error.translated = True
exc_info = (error.__class__, error, None)
filename = error.filename
if filename is None:
filename = '<unknown>'
return fake_exc_info(exc_info, filename, error.lineno)
def translate_exception(exc_info, initial_skip=0):
"""If passed an exc_info it will automatically rewrite the exceptions
all the way down to the correct line numbers and frames.
"""
tb = exc_info[2]
frames = []
# skip some internal frames if wanted
for x in xrange(initial_skip):
if tb is not None:
tb = tb.tb_next
initial_tb = tb
while tb is not None:
# skip frames decorated with @internalcode. These are internal
# calls we can't avoid and that are useless in template debugging
# output.
if tb.tb_frame.f_code in internal_code:
tb = tb.tb_next
continue
# save a reference to the next frame if we override the current
# one with a faked one.
next = tb.tb_next
# fake template exceptions
template = tb.tb_frame.f_globals.get('__jinja_template__')
if template is not None:
lineno = template.get_corresponding_lineno(tb.tb_lineno)
tb = fake_exc_info(exc_info[:2] + (tb,), template.filename,
lineno)[2]
frames.append(TracebackFrameProxy(tb))
tb = next
# if we don't have any exceptions in the frames left, we have to
# reraise it unchanged.
# XXX: can we backup here? when could this happen?
if not frames:
raise exc_info[0], exc_info[1], exc_info[2]
traceback = ProcessedTraceback(exc_info[0], exc_info[1], frames)
if tb_set_next is not None:
traceback.chain_frames()
return traceback
def fake_exc_info(exc_info, filename, lineno):
"""Helper for `translate_exception`."""
exc_type, exc_value, tb = exc_info
# figure the real context out
if tb is not None:
real_locals = tb.tb_frame.f_locals.copy()
ctx = real_locals.get('context')
if ctx:
locals = ctx.get_all()
else:
locals = {}
for name, value in real_locals.iteritems():
if name.startswith('l_') and value is not missing:
locals[name[2:]] = value
# if there is a local called __jinja_exception__, we get
# rid of it to not break the debug functionality.
locals.pop('__jinja_exception__', None)
else:
locals = {}
# assamble fake globals we need
globals = {
'__name__': filename,
'__file__': filename,
'__jinja_exception__': exc_info[:2],
# we don't want to keep the reference to the template around
# to not cause circular dependencies, but we mark it as Jinja
# frame for the ProcessedTraceback
'__jinja_template__': None
}
# and fake the exception
code = compile('\n' * (lineno - 1) + raise_helper, filename, 'exec')
# if it's possible, change the name of the code. This won't work
# on some python environments such as google appengine
try:
if tb is None:
location = 'template'
else:
function = tb.tb_frame.f_code.co_name
if function == 'root':
location = 'top-level template code'
elif function.startswith('block_'):
location = 'block "%s"' % function[6:]
else:
location = 'template'
code = CodeType(0, code.co_nlocals, code.co_stacksize,
code.co_flags, code.co_code, code.co_consts,
code.co_names, code.co_varnames, filename,
location, code.co_firstlineno,
code.co_lnotab, (), ())
except:
pass
# execute the code and catch the new traceback
try:
exec code in globals, locals
except:
exc_info = sys.exc_info()
new_tb = exc_info[2].tb_next
# return without this frame
return exc_info[:2] + (new_tb,)
def _init_ugly_crap():
"""This function implements a few ugly things so that we can patch the
traceback objects. The function returned allows resetting `tb_next` on
any python traceback object.
"""
import ctypes
from types import TracebackType
# figure out side of _Py_ssize_t
if hasattr(ctypes.pythonapi, 'Py_InitModule4_64'):
_Py_ssize_t = ctypes.c_int64
else:
_Py_ssize_t = ctypes.c_int
# regular python
class _PyObject(ctypes.Structure):
pass
_PyObject._fields_ = [
('ob_refcnt', _Py_ssize_t),
('ob_type', ctypes.POINTER(_PyObject))
]
# python with trace
if hasattr(sys, 'getobjects'):
class _PyObject(ctypes.Structure):
pass
_PyObject._fields_ = [
('_ob_next', ctypes.POINTER(_PyObject)),
('_ob_prev', ctypes.POINTER(_PyObject)),
('ob_refcnt', _Py_ssize_t),
('ob_type', ctypes.POINTER(_PyObject))
]
class _Traceback(_PyObject):
pass
_Traceback._fields_ = [
('tb_next', ctypes.POINTER(_Traceback)),
('tb_frame', ctypes.POINTER(_PyObject)),
('tb_lasti', ctypes.c_int),
('tb_lineno', ctypes.c_int)
]
def tb_set_next(tb, next):
"""Set the tb_next attribute of a traceback object."""
if not (isinstance(tb, TracebackType) and
(next is None or isinstance(next, TracebackType))):
raise TypeError('tb_set_next arguments must be traceback objects')
obj = _Traceback.from_address(id(tb))
if tb.tb_next is not None:
old = _Traceback.from_address(id(tb.tb_next))
old.ob_refcnt -= 1
if next is None:
obj.tb_next = ctypes.POINTER(_Traceback)()
else:
next = _Traceback.from_address(id(next))
next.ob_refcnt += 1
obj.tb_next = ctypes.pointer(next)
return tb_set_next
# try to get a tb_set_next implementation
try:
from jinja2._debugsupport import tb_set_next
except ImportError:
try:
tb_set_next = _init_ugly_crap()
except:
tb_set_next = None
del _init_ugly_crap
| Python |
# -*- coding: utf-8 -*-
"""
jinja2.compiler
~~~~~~~~~~~~~~~
Compiles nodes into python code.
:copyright: (c) 2010 by the Jinja Team.
:license: BSD, see LICENSE for more details.
"""
from cStringIO import StringIO
from itertools import chain
from copy import deepcopy
from jinja2 import nodes
from jinja2.nodes import EvalContext
from jinja2.visitor import NodeVisitor, NodeTransformer
from jinja2.exceptions import TemplateAssertionError
from jinja2.utils import Markup, concat, escape, is_python_keyword, next
operators = {
'eq': '==',
'ne': '!=',
'gt': '>',
'gteq': '>=',
'lt': '<',
'lteq': '<=',
'in': 'in',
'notin': 'not in'
}
try:
exec '(0 if 0 else 0)'
except SyntaxError:
have_condexpr = False
else:
have_condexpr = True
# what method to iterate over items do we want to use for dict iteration
# in generated code? on 2.x let's go with iteritems, on 3.x with items
if hasattr(dict, 'iteritems'):
dict_item_iter = 'iteritems'
else:
dict_item_iter = 'items'
# does if 0: dummy(x) get us x into the scope?
def unoptimize_before_dead_code():
x = 42
def f():
if 0: dummy(x)
return f
unoptimize_before_dead_code = bool(unoptimize_before_dead_code().func_closure)
def generate(node, environment, name, filename, stream=None,
defer_init=False):
"""Generate the python source for a node tree."""
if not isinstance(node, nodes.Template):
raise TypeError('Can\'t compile non template nodes')
generator = CodeGenerator(environment, name, filename, stream, defer_init)
generator.visit(node)
if stream is None:
return generator.stream.getvalue()
def has_safe_repr(value):
"""Does the node have a safe representation?"""
if value is None or value is NotImplemented or value is Ellipsis:
return True
if isinstance(value, (bool, int, long, float, complex, basestring,
xrange, Markup)):
return True
if isinstance(value, (tuple, list, set, frozenset)):
for item in value:
if not has_safe_repr(item):
return False
return True
elif isinstance(value, dict):
for key, value in value.iteritems():
if not has_safe_repr(key):
return False
if not has_safe_repr(value):
return False
return True
return False
def find_undeclared(nodes, names):
"""Check if the names passed are accessed undeclared. The return value
is a set of all the undeclared names from the sequence of names found.
"""
visitor = UndeclaredNameVisitor(names)
try:
for node in nodes:
visitor.visit(node)
except VisitorExit:
pass
return visitor.undeclared
class Identifiers(object):
"""Tracks the status of identifiers in frames."""
def __init__(self):
# variables that are known to be declared (probably from outer
# frames or because they are special for the frame)
self.declared = set()
# undeclared variables from outer scopes
self.outer_undeclared = set()
# names that are accessed without being explicitly declared by
# this one or any of the outer scopes. Names can appear both in
# declared and undeclared.
self.undeclared = set()
# names that are declared locally
self.declared_locally = set()
# names that are declared by parameters
self.declared_parameter = set()
def add_special(self, name):
"""Register a special name like `loop`."""
self.undeclared.discard(name)
self.declared.add(name)
def is_declared(self, name, local_only=False):
"""Check if a name is declared in this or an outer scope."""
if name in self.declared_locally or name in self.declared_parameter:
return True
if local_only:
return False
return name in self.declared
def copy(self):
return deepcopy(self)
class Frame(object):
"""Holds compile time information for us."""
def __init__(self, eval_ctx, parent=None):
self.eval_ctx = eval_ctx
self.identifiers = Identifiers()
# a toplevel frame is the root + soft frames such as if conditions.
self.toplevel = False
# the root frame is basically just the outermost frame, so no if
# conditions. This information is used to optimize inheritance
# situations.
self.rootlevel = False
# in some dynamic inheritance situations the compiler needs to add
# write tests around output statements.
self.require_output_check = parent and parent.require_output_check
# inside some tags we are using a buffer rather than yield statements.
# this for example affects {% filter %} or {% macro %}. If a frame
# is buffered this variable points to the name of the list used as
# buffer.
self.buffer = None
# the name of the block we're in, otherwise None.
self.block = parent and parent.block or None
# a set of actually assigned names
self.assigned_names = set()
# the parent of this frame
self.parent = parent
if parent is not None:
self.identifiers.declared.update(
parent.identifiers.declared |
parent.identifiers.declared_parameter |
parent.assigned_names
)
self.identifiers.outer_undeclared.update(
parent.identifiers.undeclared -
self.identifiers.declared
)
self.buffer = parent.buffer
def copy(self):
"""Create a copy of the current one."""
rv = object.__new__(self.__class__)
rv.__dict__.update(self.__dict__)
rv.identifiers = object.__new__(self.identifiers.__class__)
rv.identifiers.__dict__.update(self.identifiers.__dict__)
return rv
def inspect(self, nodes, hard_scope=False):
"""Walk the node and check for identifiers. If the scope is hard (eg:
enforce on a python level) overrides from outer scopes are tracked
differently.
"""
visitor = FrameIdentifierVisitor(self.identifiers, hard_scope)
for node in nodes:
visitor.visit(node)
def find_shadowed(self, extra=()):
"""Find all the shadowed names. extra is an iterable of variables
that may be defined with `add_special` which may occour scoped.
"""
i = self.identifiers
return (i.declared | i.outer_undeclared) & \
(i.declared_locally | i.declared_parameter) | \
set(x for x in extra if i.is_declared(x))
def inner(self):
"""Return an inner frame."""
return Frame(self.eval_ctx, self)
def soft(self):
"""Return a soft frame. A soft frame may not be modified as
standalone thing as it shares the resources with the frame it
was created of, but it's not a rootlevel frame any longer.
"""
rv = self.copy()
rv.rootlevel = False
return rv
__copy__ = copy
class VisitorExit(RuntimeError):
"""Exception used by the `UndeclaredNameVisitor` to signal a stop."""
class DependencyFinderVisitor(NodeVisitor):
"""A visitor that collects filter and test calls."""
def __init__(self):
self.filters = set()
self.tests = set()
def visit_Filter(self, node):
self.generic_visit(node)
self.filters.add(node.name)
def visit_Test(self, node):
self.generic_visit(node)
self.tests.add(node.name)
def visit_Block(self, node):
"""Stop visiting at blocks."""
class UndeclaredNameVisitor(NodeVisitor):
"""A visitor that checks if a name is accessed without being
declared. This is different from the frame visitor as it will
not stop at closure frames.
"""
def __init__(self, names):
self.names = set(names)
self.undeclared = set()
def visit_Name(self, node):
if node.ctx == 'load' and node.name in self.names:
self.undeclared.add(node.name)
if self.undeclared == self.names:
raise VisitorExit()
else:
self.names.discard(node.name)
def visit_Block(self, node):
"""Stop visiting a blocks."""
class FrameIdentifierVisitor(NodeVisitor):
"""A visitor for `Frame.inspect`."""
def __init__(self, identifiers, hard_scope):
self.identifiers = identifiers
self.hard_scope = hard_scope
def visit_Name(self, node):
"""All assignments to names go through this function."""
if node.ctx == 'store':
self.identifiers.declared_locally.add(node.name)
elif node.ctx == 'param':
self.identifiers.declared_parameter.add(node.name)
elif node.ctx == 'load' and not \
self.identifiers.is_declared(node.name, self.hard_scope):
self.identifiers.undeclared.add(node.name)
def visit_If(self, node):
self.visit(node.test)
real_identifiers = self.identifiers
old_names = real_identifiers.declared_locally | \
real_identifiers.declared_parameter
def inner_visit(nodes):
if not nodes:
return set()
self.identifiers = real_identifiers.copy()
for subnode in nodes:
self.visit(subnode)
rv = self.identifiers.declared_locally - old_names
# we have to remember the undeclared variables of this branch
# because we will have to pull them.
real_identifiers.undeclared.update(self.identifiers.undeclared)
self.identifiers = real_identifiers
return rv
body = inner_visit(node.body)
else_ = inner_visit(node.else_ or ())
# the differences between the two branches are also pulled as
# undeclared variables
real_identifiers.undeclared.update(body.symmetric_difference(else_) -
real_identifiers.declared)
# remember those that are declared.
real_identifiers.declared_locally.update(body | else_)
def visit_Macro(self, node):
self.identifiers.declared_locally.add(node.name)
def visit_Import(self, node):
self.generic_visit(node)
self.identifiers.declared_locally.add(node.target)
def visit_FromImport(self, node):
self.generic_visit(node)
for name in node.names:
if isinstance(name, tuple):
self.identifiers.declared_locally.add(name[1])
else:
self.identifiers.declared_locally.add(name)
def visit_Assign(self, node):
"""Visit assignments in the correct order."""
self.visit(node.node)
self.visit(node.target)
def visit_For(self, node):
"""Visiting stops at for blocks. However the block sequence
is visited as part of the outer scope.
"""
self.visit(node.iter)
def visit_CallBlock(self, node):
self.visit(node.call)
def visit_FilterBlock(self, node):
self.visit(node.filter)
def visit_Scope(self, node):
"""Stop visiting at scopes."""
def visit_Block(self, node):
"""Stop visiting at blocks."""
class CompilerExit(Exception):
"""Raised if the compiler encountered a situation where it just
doesn't make sense to further process the code. Any block that
raises such an exception is not further processed.
"""
class CodeGenerator(NodeVisitor):
def __init__(self, environment, name, filename, stream=None,
defer_init=False):
if stream is None:
stream = StringIO()
self.environment = environment
self.name = name
self.filename = filename
self.stream = stream
self.created_block_context = False
self.defer_init = defer_init
# aliases for imports
self.import_aliases = {}
# a registry for all blocks. Because blocks are moved out
# into the global python scope they are registered here
self.blocks = {}
# the number of extends statements so far
self.extends_so_far = 0
# some templates have a rootlevel extends. In this case we
# can safely assume that we're a child template and do some
# more optimizations.
self.has_known_extends = False
# the current line number
self.code_lineno = 1
# registry of all filters and tests (global, not block local)
self.tests = {}
self.filters = {}
# the debug information
self.debug_info = []
self._write_debug_info = None
# the number of new lines before the next write()
self._new_lines = 0
# the line number of the last written statement
self._last_line = 0
# true if nothing was written so far.
self._first_write = True
# used by the `temporary_identifier` method to get new
# unique, temporary identifier
self._last_identifier = 0
# the current indentation
self._indentation = 0
# -- Various compilation helpers
def fail(self, msg, lineno):
"""Fail with a :exc:`TemplateAssertionError`."""
raise TemplateAssertionError(msg, lineno, self.name, self.filename)
def temporary_identifier(self):
"""Get a new unique identifier."""
self._last_identifier += 1
return 't_%d' % self._last_identifier
def buffer(self, frame):
"""Enable buffering for the frame from that point onwards."""
frame.buffer = self.temporary_identifier()
self.writeline('%s = []' % frame.buffer)
def return_buffer_contents(self, frame):
"""Return the buffer contents of the frame."""
if frame.eval_ctx.volatile:
self.writeline('if context.eval_ctx.autoescape:')
self.indent()
self.writeline('return Markup(concat(%s))' % frame.buffer)
self.outdent()
self.writeline('else:')
self.indent()
self.writeline('return concat(%s)' % frame.buffer)
self.outdent()
elif frame.eval_ctx.autoescape:
self.writeline('return Markup(concat(%s))' % frame.buffer)
else:
self.writeline('return concat(%s)' % frame.buffer)
def indent(self):
"""Indent by one."""
self._indentation += 1
def outdent(self, step=1):
"""Outdent by step."""
self._indentation -= step
def start_write(self, frame, node=None):
"""Yield or write into the frame buffer."""
if frame.buffer is None:
self.writeline('yield ', node)
else:
self.writeline('%s.append(' % frame.buffer, node)
def end_write(self, frame):
"""End the writing process started by `start_write`."""
if frame.buffer is not None:
self.write(')')
def simple_write(self, s, frame, node=None):
"""Simple shortcut for start_write + write + end_write."""
self.start_write(frame, node)
self.write(s)
self.end_write(frame)
def blockvisit(self, nodes, frame):
"""Visit a list of nodes as block in a frame. If the current frame
is no buffer a dummy ``if 0: yield None`` is written automatically
unless the force_generator parameter is set to False.
"""
if frame.buffer is None:
self.writeline('if 0: yield None')
else:
self.writeline('pass')
try:
for node in nodes:
self.visit(node, frame)
except CompilerExit:
pass
def write(self, x):
"""Write a string into the output stream."""
if self._new_lines:
if not self._first_write:
self.stream.write('\n' * self._new_lines)
self.code_lineno += self._new_lines
if self._write_debug_info is not None:
self.debug_info.append((self._write_debug_info,
self.code_lineno))
self._write_debug_info = None
self._first_write = False
self.stream.write(' ' * self._indentation)
self._new_lines = 0
self.stream.write(x)
def writeline(self, x, node=None, extra=0):
"""Combination of newline and write."""
self.newline(node, extra)
self.write(x)
def newline(self, node=None, extra=0):
"""Add one or more newlines before the next write."""
self._new_lines = max(self._new_lines, 1 + extra)
if node is not None and node.lineno != self._last_line:
self._write_debug_info = node.lineno
self._last_line = node.lineno
def signature(self, node, frame, extra_kwargs=None):
"""Writes a function call to the stream for the current node.
A leading comma is added automatically. The extra keyword
arguments may not include python keywords otherwise a syntax
error could occour. The extra keyword arguments should be given
as python dict.
"""
# if any of the given keyword arguments is a python keyword
# we have to make sure that no invalid call is created.
kwarg_workaround = False
for kwarg in chain((x.key for x in node.kwargs), extra_kwargs or ()):
if is_python_keyword(kwarg):
kwarg_workaround = True
break
for arg in node.args:
self.write(', ')
self.visit(arg, frame)
if not kwarg_workaround:
for kwarg in node.kwargs:
self.write(', ')
self.visit(kwarg, frame)
if extra_kwargs is not None:
for key, value in extra_kwargs.iteritems():
self.write(', %s=%s' % (key, value))
if node.dyn_args:
self.write(', *')
self.visit(node.dyn_args, frame)
if kwarg_workaround:
if node.dyn_kwargs is not None:
self.write(', **dict({')
else:
self.write(', **{')
for kwarg in node.kwargs:
self.write('%r: ' % kwarg.key)
self.visit(kwarg.value, frame)
self.write(', ')
if extra_kwargs is not None:
for key, value in extra_kwargs.iteritems():
self.write('%r: %s, ' % (key, value))
if node.dyn_kwargs is not None:
self.write('}, **')
self.visit(node.dyn_kwargs, frame)
self.write(')')
else:
self.write('}')
elif node.dyn_kwargs is not None:
self.write(', **')
self.visit(node.dyn_kwargs, frame)
def pull_locals(self, frame):
"""Pull all the references identifiers into the local scope."""
for name in frame.identifiers.undeclared:
self.writeline('l_%s = context.resolve(%r)' % (name, name))
def pull_dependencies(self, nodes):
"""Pull all the dependencies."""
visitor = DependencyFinderVisitor()
for node in nodes:
visitor.visit(node)
for dependency in 'filters', 'tests':
mapping = getattr(self, dependency)
for name in getattr(visitor, dependency):
if name not in mapping:
mapping[name] = self.temporary_identifier()
self.writeline('%s = environment.%s[%r]' %
(mapping[name], dependency, name))
def unoptimize_scope(self, frame):
"""Disable Python optimizations for the frame."""
# XXX: this is not that nice but it has no real overhead. It
# mainly works because python finds the locals before dead code
# is removed. If that breaks we have to add a dummy function
# that just accepts the arguments and does nothing.
if frame.identifiers.declared:
self.writeline('%sdummy(%s)' % (
unoptimize_before_dead_code and 'if 0: ' or '',
', '.join('l_' + name for name in frame.identifiers.declared)
))
def push_scope(self, frame, extra_vars=()):
"""This function returns all the shadowed variables in a dict
in the form name: alias and will write the required assignments
into the current scope. No indentation takes place.
This also predefines locally declared variables from the loop
body because under some circumstances it may be the case that
`extra_vars` is passed to `Frame.find_shadowed`.
"""
aliases = {}
for name in frame.find_shadowed(extra_vars):
aliases[name] = ident = self.temporary_identifier()
self.writeline('%s = l_%s' % (ident, name))
to_declare = set()
for name in frame.identifiers.declared_locally:
if name not in aliases:
to_declare.add('l_' + name)
if to_declare:
self.writeline(' = '.join(to_declare) + ' = missing')
return aliases
def pop_scope(self, aliases, frame):
"""Restore all aliases and delete unused variables."""
for name, alias in aliases.iteritems():
self.writeline('l_%s = %s' % (name, alias))
to_delete = set()
for name in frame.identifiers.declared_locally:
if name not in aliases:
to_delete.add('l_' + name)
if to_delete:
# we cannot use the del statement here because enclosed
# scopes can trigger a SyntaxError:
# a = 42; b = lambda: a; del a
self.writeline(' = '.join(to_delete) + ' = missing')
def function_scoping(self, node, frame, children=None,
find_special=True):
"""In Jinja a few statements require the help of anonymous
functions. Those are currently macros and call blocks and in
the future also recursive loops. As there is currently
technical limitation that doesn't allow reading and writing a
variable in a scope where the initial value is coming from an
outer scope, this function tries to fall back with a common
error message. Additionally the frame passed is modified so
that the argumetns are collected and callers are looked up.
This will return the modified frame.
"""
# we have to iterate twice over it, make sure that works
if children is None:
children = node.iter_child_nodes()
children = list(children)
func_frame = frame.inner()
func_frame.inspect(children, hard_scope=True)
# variables that are undeclared (accessed before declaration) and
# declared locally *and* part of an outside scope raise a template
# assertion error. Reason: we can't generate reasonable code from
# it without aliasing all the variables.
# this could be fixed in Python 3 where we have the nonlocal
# keyword or if we switch to bytecode generation
overriden_closure_vars = (
func_frame.identifiers.undeclared &
func_frame.identifiers.declared &
(func_frame.identifiers.declared_locally |
func_frame.identifiers.declared_parameter)
)
if overriden_closure_vars:
self.fail('It\'s not possible to set and access variables '
'derived from an outer scope! (affects: %s)' %
', '.join(sorted(overriden_closure_vars)), node.lineno)
# remove variables from a closure from the frame's undeclared
# identifiers.
func_frame.identifiers.undeclared -= (
func_frame.identifiers.undeclared &
func_frame.identifiers.declared
)
# no special variables for this scope, abort early
if not find_special:
return func_frame
func_frame.accesses_kwargs = False
func_frame.accesses_varargs = False
func_frame.accesses_caller = False
func_frame.arguments = args = ['l_' + x.name for x in node.args]
undeclared = find_undeclared(children, ('caller', 'kwargs', 'varargs'))
if 'caller' in undeclared:
func_frame.accesses_caller = True
func_frame.identifiers.add_special('caller')
args.append('l_caller')
if 'kwargs' in undeclared:
func_frame.accesses_kwargs = True
func_frame.identifiers.add_special('kwargs')
args.append('l_kwargs')
if 'varargs' in undeclared:
func_frame.accesses_varargs = True
func_frame.identifiers.add_special('varargs')
args.append('l_varargs')
return func_frame
def macro_body(self, node, frame, children=None):
"""Dump the function def of a macro or call block."""
frame = self.function_scoping(node, frame, children)
# macros are delayed, they never require output checks
frame.require_output_check = False
args = frame.arguments
# XXX: this is an ugly fix for the loop nesting bug
# (tests.test_old_bugs.test_loop_call_bug). This works around
# a identifier nesting problem we have in general. It's just more
# likely to happen in loops which is why we work around it. The
# real solution would be "nonlocal" all the identifiers that are
# leaking into a new python frame and might be used both unassigned
# and assigned.
if 'loop' in frame.identifiers.declared:
args = args + ['l_loop=l_loop']
self.writeline('def macro(%s):' % ', '.join(args), node)
self.indent()
self.buffer(frame)
self.pull_locals(frame)
self.blockvisit(node.body, frame)
self.return_buffer_contents(frame)
self.outdent()
return frame
def macro_def(self, node, frame):
"""Dump the macro definition for the def created by macro_body."""
arg_tuple = ', '.join(repr(x.name) for x in node.args)
name = getattr(node, 'name', None)
if len(node.args) == 1:
arg_tuple += ','
self.write('Macro(environment, macro, %r, (%s), (' %
(name, arg_tuple))
for arg in node.defaults:
self.visit(arg, frame)
self.write(', ')
self.write('), %r, %r, %r)' % (
bool(frame.accesses_kwargs),
bool(frame.accesses_varargs),
bool(frame.accesses_caller)
))
def position(self, node):
"""Return a human readable position for the node."""
rv = 'line %d' % node.lineno
if self.name is not None:
rv += ' in ' + repr(self.name)
return rv
# -- Statement Visitors
def visit_Template(self, node, frame=None):
assert frame is None, 'no root frame allowed'
eval_ctx = EvalContext(self.environment, self.name)
from jinja2.runtime import __all__ as exported
self.writeline('from __future__ import division')
self.writeline('from jinja2.runtime import ' + ', '.join(exported))
if not unoptimize_before_dead_code:
self.writeline('dummy = lambda *x: None')
# if we want a deferred initialization we cannot move the
# environment into a local name
envenv = not self.defer_init and ', environment=environment' or ''
# do we have an extends tag at all? If not, we can save some
# overhead by just not processing any inheritance code.
have_extends = node.find(nodes.Extends) is not None
# find all blocks
for block in node.find_all(nodes.Block):
if block.name in self.blocks:
self.fail('block %r defined twice' % block.name, block.lineno)
self.blocks[block.name] = block
# find all imports and import them
for import_ in node.find_all(nodes.ImportedName):
if import_.importname not in self.import_aliases:
imp = import_.importname
self.import_aliases[imp] = alias = self.temporary_identifier()
if '.' in imp:
module, obj = imp.rsplit('.', 1)
self.writeline('from %s import %s as %s' %
(module, obj, alias))
else:
self.writeline('import %s as %s' % (imp, alias))
# add the load name
self.writeline('name = %r' % self.name)
# generate the root render function.
self.writeline('def root(context%s):' % envenv, extra=1)
# process the root
frame = Frame(eval_ctx)
frame.inspect(node.body)
frame.toplevel = frame.rootlevel = True
frame.require_output_check = have_extends and not self.has_known_extends
self.indent()
if have_extends:
self.writeline('parent_template = None')
if 'self' in find_undeclared(node.body, ('self',)):
frame.identifiers.add_special('self')
self.writeline('l_self = TemplateReference(context)')
self.pull_locals(frame)
self.pull_dependencies(node.body)
self.blockvisit(node.body, frame)
self.outdent()
# make sure that the parent root is called.
if have_extends:
if not self.has_known_extends:
self.indent()
self.writeline('if parent_template is not None:')
self.indent()
self.writeline('for event in parent_template.'
'root_render_func(context):')
self.indent()
self.writeline('yield event')
self.outdent(2 + (not self.has_known_extends))
# at this point we now have the blocks collected and can visit them too.
for name, block in self.blocks.iteritems():
block_frame = Frame(eval_ctx)
block_frame.inspect(block.body)
block_frame.block = name
self.writeline('def block_%s(context%s):' % (name, envenv),
block, 1)
self.indent()
undeclared = find_undeclared(block.body, ('self', 'super'))
if 'self' in undeclared:
block_frame.identifiers.add_special('self')
self.writeline('l_self = TemplateReference(context)')
if 'super' in undeclared:
block_frame.identifiers.add_special('super')
self.writeline('l_super = context.super(%r, '
'block_%s)' % (name, name))
self.pull_locals(block_frame)
self.pull_dependencies(block.body)
self.blockvisit(block.body, block_frame)
self.outdent()
self.writeline('blocks = {%s}' % ', '.join('%r: block_%s' % (x, x)
for x in self.blocks),
extra=1)
# add a function that returns the debug info
self.writeline('debug_info = %r' % '&'.join('%s=%s' % x for x
in self.debug_info))
def visit_Block(self, node, frame):
"""Call a block and register it for the template."""
level = 1
if frame.toplevel:
# if we know that we are a child template, there is no need to
# check if we are one
if self.has_known_extends:
return
if self.extends_so_far > 0:
self.writeline('if parent_template is None:')
self.indent()
level += 1
context = node.scoped and 'context.derived(locals())' or 'context'
self.writeline('for event in context.blocks[%r][0](%s):' % (
node.name, context), node)
self.indent()
self.simple_write('event', frame)
self.outdent(level)
def visit_Extends(self, node, frame):
"""Calls the extender."""
if not frame.toplevel:
self.fail('cannot use extend from a non top-level scope',
node.lineno)
# if the number of extends statements in general is zero so
# far, we don't have to add a check if something extended
# the template before this one.
if self.extends_so_far > 0:
# if we have a known extends we just add a template runtime
# error into the generated code. We could catch that at compile
# time too, but i welcome it not to confuse users by throwing the
# same error at different times just "because we can".
if not self.has_known_extends:
self.writeline('if parent_template is not None:')
self.indent()
self.writeline('raise TemplateRuntimeError(%r)' %
'extended multiple times')
self.outdent()
# if we have a known extends already we don't need that code here
# as we know that the template execution will end here.
if self.has_known_extends:
raise CompilerExit()
self.writeline('parent_template = environment.get_template(', node)
self.visit(node.template, frame)
self.write(', %r)' % self.name)
self.writeline('for name, parent_block in parent_template.'
'blocks.%s():' % dict_item_iter)
self.indent()
self.writeline('context.blocks.setdefault(name, []).'
'append(parent_block)')
self.outdent()
# if this extends statement was in the root level we can take
# advantage of that information and simplify the generated code
# in the top level from this point onwards
if frame.rootlevel:
self.has_known_extends = True
# and now we have one more
self.extends_so_far += 1
def visit_Include(self, node, frame):
"""Handles includes."""
if node.with_context:
self.unoptimize_scope(frame)
if node.ignore_missing:
self.writeline('try:')
self.indent()
func_name = 'get_or_select_template'
if isinstance(node.template, nodes.Const):
if isinstance(node.template.value, basestring):
func_name = 'get_template'
elif isinstance(node.template.value, (tuple, list)):
func_name = 'select_template'
elif isinstance(node.template, (nodes.Tuple, nodes.List)):
func_name = 'select_template'
self.writeline('template = environment.%s(' % func_name, node)
self.visit(node.template, frame)
self.write(', %r)' % self.name)
if node.ignore_missing:
self.outdent()
self.writeline('except TemplateNotFound:')
self.indent()
self.writeline('pass')
self.outdent()
self.writeline('else:')
self.indent()
if node.with_context:
self.writeline('for event in template.root_render_func('
'template.new_context(context.parent, True, '
'locals())):')
else:
self.writeline('for event in template.module._body_stream:')
self.indent()
self.simple_write('event', frame)
self.outdent()
if node.ignore_missing:
self.outdent()
def visit_Import(self, node, frame):
"""Visit regular imports."""
if node.with_context:
self.unoptimize_scope(frame)
self.writeline('l_%s = ' % node.target, node)
if frame.toplevel:
self.write('context.vars[%r] = ' % node.target)
self.write('environment.get_template(')
self.visit(node.template, frame)
self.write(', %r).' % self.name)
if node.with_context:
self.write('make_module(context.parent, True, locals())')
else:
self.write('module')
if frame.toplevel and not node.target.startswith('_'):
self.writeline('context.exported_vars.discard(%r)' % node.target)
frame.assigned_names.add(node.target)
def visit_FromImport(self, node, frame):
"""Visit named imports."""
self.newline(node)
self.write('included_template = environment.get_template(')
self.visit(node.template, frame)
self.write(', %r).' % self.name)
if node.with_context:
self.write('make_module(context.parent, True)')
else:
self.write('module')
var_names = []
discarded_names = []
for name in node.names:
if isinstance(name, tuple):
name, alias = name
else:
alias = name
self.writeline('l_%s = getattr(included_template, '
'%r, missing)' % (alias, name))
self.writeline('if l_%s is missing:' % alias)
self.indent()
self.writeline('l_%s = environment.undefined(%r %% '
'included_template.__name__, '
'name=%r)' %
(alias, 'the template %%r (imported on %s) does '
'not export the requested name %s' % (
self.position(node),
repr(name)
), name))
self.outdent()
if frame.toplevel:
var_names.append(alias)
if not alias.startswith('_'):
discarded_names.append(alias)
frame.assigned_names.add(alias)
if var_names:
if len(var_names) == 1:
name = var_names[0]
self.writeline('context.vars[%r] = l_%s' % (name, name))
else:
self.writeline('context.vars.update({%s})' % ', '.join(
'%r: l_%s' % (name, name) for name in var_names
))
if discarded_names:
if len(discarded_names) == 1:
self.writeline('context.exported_vars.discard(%r)' %
discarded_names[0])
else:
self.writeline('context.exported_vars.difference_'
'update((%s))' % ', '.join(map(repr, discarded_names)))
def visit_For(self, node, frame):
# when calculating the nodes for the inner frame we have to exclude
# the iterator contents from it
children = node.iter_child_nodes(exclude=('iter',))
if node.recursive:
loop_frame = self.function_scoping(node, frame, children,
find_special=False)
else:
loop_frame = frame.inner()
loop_frame.inspect(children)
# try to figure out if we have an extended loop. An extended loop
# is necessary if the loop is in recursive mode if the special loop
# variable is accessed in the body.
extended_loop = node.recursive or 'loop' in \
find_undeclared(node.iter_child_nodes(
only=('body',)), ('loop',))
# if we don't have an recursive loop we have to find the shadowed
# variables at that point. Because loops can be nested but the loop
# variable is a special one we have to enforce aliasing for it.
if not node.recursive:
aliases = self.push_scope(loop_frame, ('loop',))
# otherwise we set up a buffer and add a function def
else:
self.writeline('def loop(reciter, loop_render_func):', node)
self.indent()
self.buffer(loop_frame)
aliases = {}
# make sure the loop variable is a special one and raise a template
# assertion error if a loop tries to write to loop
if extended_loop:
loop_frame.identifiers.add_special('loop')
for name in node.find_all(nodes.Name):
if name.ctx == 'store' and name.name == 'loop':
self.fail('Can\'t assign to special loop variable '
'in for-loop target', name.lineno)
self.pull_locals(loop_frame)
if node.else_:
iteration_indicator = self.temporary_identifier()
self.writeline('%s = 1' % iteration_indicator)
# Create a fake parent loop if the else or test section of a
# loop is accessing the special loop variable and no parent loop
# exists.
if 'loop' not in aliases and 'loop' in find_undeclared(
node.iter_child_nodes(only=('else_', 'test')), ('loop',)):
self.writeline("l_loop = environment.undefined(%r, name='loop')" %
("'loop' is undefined. the filter section of a loop as well "
"as the else block doesn't have access to the special 'loop'"
" variable of the current loop. Because there is no parent "
"loop it's undefined. Happened in loop on %s" %
self.position(node)))
self.writeline('for ', node)
self.visit(node.target, loop_frame)
self.write(extended_loop and ', l_loop in LoopContext(' or ' in ')
# if we have an extened loop and a node test, we filter in the
# "outer frame".
if extended_loop and node.test is not None:
self.write('(')
self.visit(node.target, loop_frame)
self.write(' for ')
self.visit(node.target, loop_frame)
self.write(' in ')
if node.recursive:
self.write('reciter')
else:
self.visit(node.iter, loop_frame)
self.write(' if (')
test_frame = loop_frame.copy()
self.visit(node.test, test_frame)
self.write('))')
elif node.recursive:
self.write('reciter')
else:
self.visit(node.iter, loop_frame)
if node.recursive:
self.write(', recurse=loop_render_func):')
else:
self.write(extended_loop and '):' or ':')
# tests in not extended loops become a continue
if not extended_loop and node.test is not None:
self.indent()
self.writeline('if not ')
self.visit(node.test, loop_frame)
self.write(':')
self.indent()
self.writeline('continue')
self.outdent(2)
self.indent()
self.blockvisit(node.body, loop_frame)
if node.else_:
self.writeline('%s = 0' % iteration_indicator)
self.outdent()
if node.else_:
self.writeline('if %s:' % iteration_indicator)
self.indent()
self.blockvisit(node.else_, loop_frame)
self.outdent()
# reset the aliases if there are any.
if not node.recursive:
self.pop_scope(aliases, loop_frame)
# if the node was recursive we have to return the buffer contents
# and start the iteration code
if node.recursive:
self.return_buffer_contents(loop_frame)
self.outdent()
self.start_write(frame, node)
self.write('loop(')
self.visit(node.iter, frame)
self.write(', loop)')
self.end_write(frame)
def visit_If(self, node, frame):
if_frame = frame.soft()
self.writeline('if ', node)
self.visit(node.test, if_frame)
self.write(':')
self.indent()
self.blockvisit(node.body, if_frame)
self.outdent()
if node.else_:
self.writeline('else:')
self.indent()
self.blockvisit(node.else_, if_frame)
self.outdent()
def visit_Macro(self, node, frame):
macro_frame = self.macro_body(node, frame)
self.newline()
if frame.toplevel:
if not node.name.startswith('_'):
self.write('context.exported_vars.add(%r)' % node.name)
self.writeline('context.vars[%r] = ' % node.name)
self.write('l_%s = ' % node.name)
self.macro_def(node, macro_frame)
frame.assigned_names.add(node.name)
def visit_CallBlock(self, node, frame):
children = node.iter_child_nodes(exclude=('call',))
call_frame = self.macro_body(node, frame, children)
self.writeline('caller = ')
self.macro_def(node, call_frame)
self.start_write(frame, node)
self.visit_Call(node.call, call_frame, forward_caller=True)
self.end_write(frame)
def visit_FilterBlock(self, node, frame):
filter_frame = frame.inner()
filter_frame.inspect(node.iter_child_nodes())
aliases = self.push_scope(filter_frame)
self.pull_locals(filter_frame)
self.buffer(filter_frame)
self.blockvisit(node.body, filter_frame)
self.start_write(frame, node)
self.visit_Filter(node.filter, filter_frame)
self.end_write(frame)
self.pop_scope(aliases, filter_frame)
def visit_ExprStmt(self, node, frame):
self.newline(node)
self.visit(node.node, frame)
def visit_Output(self, node, frame):
# if we have a known extends statement, we don't output anything
# if we are in a require_output_check section
if self.has_known_extends and frame.require_output_check:
return
if self.environment.finalize:
finalize = lambda x: unicode(self.environment.finalize(x))
else:
finalize = unicode
# if we are inside a frame that requires output checking, we do so
outdent_later = False
if frame.require_output_check:
self.writeline('if parent_template is None:')
self.indent()
outdent_later = True
# try to evaluate as many chunks as possible into a static
# string at compile time.
body = []
for child in node.nodes:
try:
const = child.as_const(frame.eval_ctx)
except nodes.Impossible:
body.append(child)
continue
# the frame can't be volatile here, becaus otherwise the
# as_const() function would raise an Impossible exception
# at that point.
try:
if frame.eval_ctx.autoescape:
if hasattr(const, '__html__'):
const = const.__html__()
else:
const = escape(const)
const = finalize(const)
except:
# if something goes wrong here we evaluate the node
# at runtime for easier debugging
body.append(child)
continue
if body and isinstance(body[-1], list):
body[-1].append(const)
else:
body.append([const])
# if we have less than 3 nodes or a buffer we yield or extend/append
if len(body) < 3 or frame.buffer is not None:
if frame.buffer is not None:
# for one item we append, for more we extend
if len(body) == 1:
self.writeline('%s.append(' % frame.buffer)
else:
self.writeline('%s.extend((' % frame.buffer)
self.indent()
for item in body:
if isinstance(item, list):
val = repr(concat(item))
if frame.buffer is None:
self.writeline('yield ' + val)
else:
self.writeline(val + ', ')
else:
if frame.buffer is None:
self.writeline('yield ', item)
else:
self.newline(item)
close = 1
if frame.eval_ctx.volatile:
self.write('(context.eval_ctx.autoescape and'
' escape or to_string)(')
elif frame.eval_ctx.autoescape:
self.write('escape(')
else:
self.write('to_string(')
if self.environment.finalize is not None:
self.write('environment.finalize(')
close += 1
self.visit(item, frame)
self.write(')' * close)
if frame.buffer is not None:
self.write(', ')
if frame.buffer is not None:
# close the open parentheses
self.outdent()
self.writeline(len(body) == 1 and ')' or '))')
# otherwise we create a format string as this is faster in that case
else:
format = []
arguments = []
for item in body:
if isinstance(item, list):
format.append(concat(item).replace('%', '%%'))
else:
format.append('%s')
arguments.append(item)
self.writeline('yield ')
self.write(repr(concat(format)) + ' % (')
idx = -1
self.indent()
for argument in arguments:
self.newline(argument)
close = 0
if frame.eval_ctx.volatile:
self.write('(context.eval_ctx.autoescape and'
' escape or to_string)(')
close += 1
elif frame.eval_ctx.autoescape:
self.write('escape(')
close += 1
if self.environment.finalize is not None:
self.write('environment.finalize(')
close += 1
self.visit(argument, frame)
self.write(')' * close + ', ')
self.outdent()
self.writeline(')')
if outdent_later:
self.outdent()
def visit_Assign(self, node, frame):
self.newline(node)
# toplevel assignments however go into the local namespace and
# the current template's context. We create a copy of the frame
# here and add a set so that the Name visitor can add the assigned
# names here.
if frame.toplevel:
assignment_frame = frame.copy()
assignment_frame.toplevel_assignments = set()
else:
assignment_frame = frame
self.visit(node.target, assignment_frame)
self.write(' = ')
self.visit(node.node, frame)
# make sure toplevel assignments are added to the context.
if frame.toplevel:
public_names = [x for x in assignment_frame.toplevel_assignments
if not x.startswith('_')]
if len(assignment_frame.toplevel_assignments) == 1:
name = next(iter(assignment_frame.toplevel_assignments))
self.writeline('context.vars[%r] = l_%s' % (name, name))
else:
self.writeline('context.vars.update({')
for idx, name in enumerate(assignment_frame.toplevel_assignments):
if idx:
self.write(', ')
self.write('%r: l_%s' % (name, name))
self.write('})')
if public_names:
if len(public_names) == 1:
self.writeline('context.exported_vars.add(%r)' %
public_names[0])
else:
self.writeline('context.exported_vars.update((%s))' %
', '.join(map(repr, public_names)))
# -- Expression Visitors
def visit_Name(self, node, frame):
if node.ctx == 'store' and frame.toplevel:
frame.toplevel_assignments.add(node.name)
self.write('l_' + node.name)
frame.assigned_names.add(node.name)
def visit_Const(self, node, frame):
val = node.value
if isinstance(val, float):
self.write(str(val))
else:
self.write(repr(val))
def visit_TemplateData(self, node, frame):
try:
self.write(repr(node.as_const(frame.eval_ctx)))
except nodes.Impossible:
self.write('(context.eval_ctx.autoescape and Markup or identity)(%r)'
% node.data)
def visit_Tuple(self, node, frame):
self.write('(')
idx = -1
for idx, item in enumerate(node.items):
if idx:
self.write(', ')
self.visit(item, frame)
self.write(idx == 0 and ',)' or ')')
def visit_List(self, node, frame):
self.write('[')
for idx, item in enumerate(node.items):
if idx:
self.write(', ')
self.visit(item, frame)
self.write(']')
def visit_Dict(self, node, frame):
self.write('{')
for idx, item in enumerate(node.items):
if idx:
self.write(', ')
self.visit(item.key, frame)
self.write(': ')
self.visit(item.value, frame)
self.write('}')
def binop(operator):
def visitor(self, node, frame):
self.write('(')
self.visit(node.left, frame)
self.write(' %s ' % operator)
self.visit(node.right, frame)
self.write(')')
return visitor
def uaop(operator):
def visitor(self, node, frame):
self.write('(' + operator)
self.visit(node.node, frame)
self.write(')')
return visitor
visit_Add = binop('+')
visit_Sub = binop('-')
visit_Mul = binop('*')
visit_Div = binop('/')
visit_FloorDiv = binop('//')
visit_Pow = binop('**')
visit_Mod = binop('%')
visit_And = binop('and')
visit_Or = binop('or')
visit_Pos = uaop('+')
visit_Neg = uaop('-')
visit_Not = uaop('not ')
del binop, uaop
def visit_Concat(self, node, frame):
if frame.eval_ctx.volatile:
func_name = '(context.eval_ctx.volatile and' \
' markup_join or unicode_join)'
elif frame.eval_ctx.autoescape:
func_name = 'markup_join'
else:
func_name = 'unicode_join'
self.write('%s((' % func_name)
for arg in node.nodes:
self.visit(arg, frame)
self.write(', ')
self.write('))')
def visit_Compare(self, node, frame):
self.visit(node.expr, frame)
for op in node.ops:
self.visit(op, frame)
def visit_Operand(self, node, frame):
self.write(' %s ' % operators[node.op])
self.visit(node.expr, frame)
def visit_Getattr(self, node, frame):
self.write('environment.getattr(')
self.visit(node.node, frame)
self.write(', %r)' % node.attr)
def visit_Getitem(self, node, frame):
# slices bypass the environment getitem method.
if isinstance(node.arg, nodes.Slice):
self.visit(node.node, frame)
self.write('[')
self.visit(node.arg, frame)
self.write(']')
else:
self.write('environment.getitem(')
self.visit(node.node, frame)
self.write(', ')
self.visit(node.arg, frame)
self.write(')')
def visit_Slice(self, node, frame):
if node.start is not None:
self.visit(node.start, frame)
self.write(':')
if node.stop is not None:
self.visit(node.stop, frame)
if node.step is not None:
self.write(':')
self.visit(node.step, frame)
def visit_Filter(self, node, frame):
self.write(self.filters[node.name] + '(')
func = self.environment.filters.get(node.name)
if func is None:
self.fail('no filter named %r' % node.name, node.lineno)
if getattr(func, 'contextfilter', False):
self.write('context, ')
elif getattr(func, 'evalcontextfilter', False):
self.write('context.eval_ctx, ')
elif getattr(func, 'environmentfilter', False):
self.write('environment, ')
# if the filter node is None we are inside a filter block
# and want to write to the current buffer
if node.node is not None:
self.visit(node.node, frame)
elif frame.eval_ctx.volatile:
self.write('(context.eval_ctx.autoescape and'
' Markup(concat(%s)) or concat(%s))' %
(frame.buffer, frame.buffer))
elif frame.eval_ctx.autoescape:
self.write('Markup(concat(%s))' % frame.buffer)
else:
self.write('concat(%s)' % frame.buffer)
self.signature(node, frame)
self.write(')')
def visit_Test(self, node, frame):
self.write(self.tests[node.name] + '(')
if node.name not in self.environment.tests:
self.fail('no test named %r' % node.name, node.lineno)
self.visit(node.node, frame)
self.signature(node, frame)
self.write(')')
def visit_CondExpr(self, node, frame):
def write_expr2():
if node.expr2 is not None:
return self.visit(node.expr2, frame)
self.write('environment.undefined(%r)' % ('the inline if-'
'expression on %s evaluated to false and '
'no else section was defined.' % self.position(node)))
if not have_condexpr:
self.write('((')
self.visit(node.test, frame)
self.write(') and (')
self.visit(node.expr1, frame)
self.write(',) or (')
write_expr2()
self.write(',))[0]')
else:
self.write('(')
self.visit(node.expr1, frame)
self.write(' if ')
self.visit(node.test, frame)
self.write(' else ')
write_expr2()
self.write(')')
def visit_Call(self, node, frame, forward_caller=False):
if self.environment.sandboxed:
self.write('environment.call(context, ')
else:
self.write('context.call(')
self.visit(node.node, frame)
extra_kwargs = forward_caller and {'caller': 'caller'} or None
self.signature(node, frame, extra_kwargs)
self.write(')')
def visit_Keyword(self, node, frame):
self.write(node.key + '=')
self.visit(node.value, frame)
# -- Unused nodes for extensions
def visit_MarkSafe(self, node, frame):
self.write('Markup(')
self.visit(node.expr, frame)
self.write(')')
def visit_MarkSafeIfAutoescape(self, node, frame):
self.write('(context.eval_ctx.autoescape and Markup or identity)(')
self.visit(node.expr, frame)
self.write(')')
def visit_EnvironmentAttribute(self, node, frame):
self.write('environment.' + node.name)
def visit_ExtensionAttribute(self, node, frame):
self.write('environment.extensions[%r].%s' % (node.identifier, node.name))
def visit_ImportedName(self, node, frame):
self.write(self.import_aliases[node.importname])
def visit_InternalName(self, node, frame):
self.write(node.name)
def visit_ContextReference(self, node, frame):
self.write('context')
def visit_Continue(self, node, frame):
self.writeline('continue', node)
def visit_Break(self, node, frame):
self.writeline('break', node)
def visit_Scope(self, node, frame):
scope_frame = frame.inner()
scope_frame.inspect(node.iter_child_nodes())
aliases = self.push_scope(scope_frame)
self.pull_locals(scope_frame)
self.blockvisit(node.body, scope_frame)
self.pop_scope(aliases, scope_frame)
def visit_EvalContextModifier(self, node, frame):
for keyword in node.options:
self.writeline('context.eval_ctx.%s = ' % keyword.key)
self.visit(keyword.value, frame)
try:
val = keyword.value.as_const(frame.eval_ctx)
except nodes.Impossible:
frame.eval_ctx.volatile = True
else:
setattr(frame.eval_ctx, keyword.key, val)
def visit_ScopedEvalContextModifier(self, node, frame):
old_ctx_name = self.temporary_identifier()
safed_ctx = frame.eval_ctx.save()
self.writeline('%s = context.eval_ctx.save()' % old_ctx_name)
self.visit_EvalContextModifier(node, frame)
for child in node.body:
self.visit(child, frame)
frame.eval_ctx.revert(safed_ctx)
self.writeline('context.eval_ctx.revert(%s)' % old_ctx_name)
| Python |
# -*- coding: utf-8 -*-
"""
jinja2.optimizer
~~~~~~~~~~~~~~~~
The jinja optimizer is currently trying to constant fold a few expressions
and modify the AST in place so that it should be easier to evaluate it.
Because the AST does not contain all the scoping information and the
compiler has to find that out, we cannot do all the optimizations we
want. For example loop unrolling doesn't work because unrolled loops would
have a different scoping.
The solution would be a second syntax tree that has the scoping rules stored.
:copyright: (c) 2010 by the Jinja Team.
:license: BSD.
"""
from jinja2 import nodes
from jinja2.visitor import NodeTransformer
def optimize(node, environment):
"""The context hint can be used to perform an static optimization
based on the context given."""
optimizer = Optimizer(environment)
return optimizer.visit(node)
class Optimizer(NodeTransformer):
def __init__(self, environment):
self.environment = environment
def visit_If(self, node):
"""Eliminate dead code."""
# do not optimize ifs that have a block inside so that it doesn't
# break super().
if node.find(nodes.Block) is not None:
return self.generic_visit(node)
try:
val = self.visit(node.test).as_const()
except nodes.Impossible:
return self.generic_visit(node)
if val:
body = node.body
else:
body = node.else_
result = []
for node in body:
result.extend(self.visit_list(node))
return result
def fold(self, node):
"""Do constant folding."""
node = self.generic_visit(node)
try:
return nodes.Const.from_untrusted(node.as_const(),
lineno=node.lineno,
environment=self.environment)
except nodes.Impossible:
return node
visit_Add = visit_Sub = visit_Mul = visit_Div = visit_FloorDiv = \
visit_Pow = visit_Mod = visit_And = visit_Or = visit_Pos = visit_Neg = \
visit_Not = visit_Compare = visit_Getitem = visit_Getattr = visit_Call = \
visit_Filter = visit_Test = visit_CondExpr = fold
del fold
| Python |
# -*- coding: utf-8 -*-
"""
jinja2.utils
~~~~~~~~~~~~
Utility functions.
:copyright: (c) 2010 by the Jinja Team.
:license: BSD, see LICENSE for more details.
"""
import re
import sys
import errno
try:
from thread import allocate_lock
except ImportError:
from dummy_thread import allocate_lock
from collections import deque
from itertools import imap
_word_split_re = re.compile(r'(\s+)')
_punctuation_re = re.compile(
'^(?P<lead>(?:%s)*)(?P<middle>.*?)(?P<trail>(?:%s)*)$' % (
'|'.join(imap(re.escape, ('(', '<', '<'))),
'|'.join(imap(re.escape, ('.', ',', ')', '>', '\n', '>')))
)
)
_simple_email_re = re.compile(r'^\S+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+$')
_striptags_re = re.compile(r'(<!--.*?-->|<[^>]*>)')
_entity_re = re.compile(r'&([^;]+);')
_letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
_digits = '0123456789'
# special singleton representing missing values for the runtime
missing = type('MissingType', (), {'__repr__': lambda x: 'missing'})()
# internal code
internal_code = set()
# concatenate a list of strings and convert them to unicode.
# unfortunately there is a bug in python 2.4 and lower that causes
# unicode.join trash the traceback.
_concat = u''.join
try:
def _test_gen_bug():
raise TypeError(_test_gen_bug)
yield None
_concat(_test_gen_bug())
except TypeError, _error:
if not _error.args or _error.args[0] is not _test_gen_bug:
def concat(gen):
try:
return _concat(list(gen))
except:
# this hack is needed so that the current frame
# does not show up in the traceback.
exc_type, exc_value, tb = sys.exc_info()
raise exc_type, exc_value, tb.tb_next
else:
concat = _concat
del _test_gen_bug, _error
# for python 2.x we create outselves a next() function that does the
# basics without exception catching.
try:
next = next
except NameError:
def next(x):
return x.next()
# if this python version is unable to deal with unicode filenames
# when passed to encode we let this function encode it properly.
# This is used in a couple of places. As far as Jinja is concerned
# filenames are unicode *or* bytestrings in 2.x and unicode only in
# 3.x because compile cannot handle bytes
if sys.version_info < (3, 0):
def _encode_filename(filename):
if isinstance(filename, unicode):
return filename.encode('utf-8')
return filename
else:
def _encode_filename(filename):
assert filename is None or isinstance(filename, str), \
'filenames must be strings'
return filename
from keyword import iskeyword as is_python_keyword
# common types. These do exist in the special types module too which however
# does not exist in IronPython out of the box. Also that way we don't have
# to deal with implementation specific stuff here
class _C(object):
def method(self): pass
def _func():
yield None
FunctionType = type(_func)
GeneratorType = type(_func())
MethodType = type(_C.method)
CodeType = type(_C.method.func_code)
try:
raise TypeError()
except TypeError:
_tb = sys.exc_info()[2]
TracebackType = type(_tb)
FrameType = type(_tb.tb_frame)
del _C, _tb, _func
def contextfunction(f):
"""This decorator can be used to mark a function or method context callable.
A context callable is passed the active :class:`Context` as first argument when
called from the template. This is useful if a function wants to get access
to the context or functions provided on the context object. For example
a function that returns a sorted list of template variables the current
template exports could look like this::
@contextfunction
def get_exported_names(context):
return sorted(context.exported_vars)
"""
f.contextfunction = True
return f
def evalcontextfunction(f):
"""This decoraotr can be used to mark a function or method as an eval
context callable. This is similar to the :func:`contextfunction`
but instead of passing the context, an evaluation context object is
passed. For more information about the eval context, see
:ref:`eval-context`.
.. versionadded:: 2.4
"""
f.evalcontextfunction = True
return f
def environmentfunction(f):
"""This decorator can be used to mark a function or method as environment
callable. This decorator works exactly like the :func:`contextfunction`
decorator just that the first argument is the active :class:`Environment`
and not context.
"""
f.environmentfunction = True
return f
def internalcode(f):
"""Marks the function as internally used"""
internal_code.add(f.func_code)
return f
def is_undefined(obj):
"""Check if the object passed is undefined. This does nothing more than
performing an instance check against :class:`Undefined` but looks nicer.
This can be used for custom filters or tests that want to react to
undefined variables. For example a custom default filter can look like
this::
def default(var, default=''):
if is_undefined(var):
return default
return var
"""
from jinja2.runtime import Undefined
return isinstance(obj, Undefined)
def consume(iterable):
"""Consumes an iterable without doing anything with it."""
for event in iterable:
pass
def clear_caches():
"""Jinja2 keeps internal caches for environments and lexers. These are
used so that Jinja2 doesn't have to recreate environments and lexers all
the time. Normally you don't have to care about that but if you are
messuring memory consumption you may want to clean the caches.
"""
from jinja2.environment import _spontaneous_environments
from jinja2.lexer import _lexer_cache
_spontaneous_environments.clear()
_lexer_cache.clear()
def import_string(import_name, silent=False):
"""Imports an object based on a string. This use useful if you want to
use import paths as endpoints or something similar. An import path can
be specified either in dotted notation (``xml.sax.saxutils.escape``)
or with a colon as object delimiter (``xml.sax.saxutils:escape``).
If the `silent` is True the return value will be `None` if the import
fails.
:return: imported object
"""
try:
if ':' in import_name:
module, obj = import_name.split(':', 1)
elif '.' in import_name:
items = import_name.split('.')
module = '.'.join(items[:-1])
obj = items[-1]
else:
return __import__(import_name)
return getattr(__import__(module, None, None, [obj]), obj)
except (ImportError, AttributeError):
if not silent:
raise
def open_if_exists(filename, mode='rb'):
"""Returns a file descriptor for the filename if that file exists,
otherwise `None`.
"""
try:
return open(filename, mode)
except IOError, e:
if e.errno not in (errno.ENOENT, errno.EISDIR):
raise
def object_type_repr(obj):
"""Returns the name of the object's type. For some recognized
singletons the name of the object is returned instead. (For
example for `None` and `Ellipsis`).
"""
if obj is None:
return 'None'
elif obj is Ellipsis:
return 'Ellipsis'
# __builtin__ in 2.x, builtins in 3.x
if obj.__class__.__module__ in ('__builtin__', 'builtins'):
name = obj.__class__.__name__
else:
name = obj.__class__.__module__ + '.' + obj.__class__.__name__
return '%s object' % name
def pformat(obj, verbose=False):
"""Prettyprint an object. Either use the `pretty` library or the
builtin `pprint`.
"""
try:
from pretty import pretty
return pretty(obj, verbose=verbose)
except ImportError:
from pprint import pformat
return pformat(obj)
def urlize(text, trim_url_limit=None, nofollow=False):
"""Converts any URLs in text into clickable links. Works on http://,
https:// and www. links. Links can have trailing punctuation (periods,
commas, close-parens) and leading punctuation (opening parens) and
it'll still do the right thing.
If trim_url_limit is not None, the URLs in link text will be limited
to trim_url_limit characters.
If nofollow is True, the URLs in link text will get a rel="nofollow"
attribute.
"""
trim_url = lambda x, limit=trim_url_limit: limit is not None \
and (x[:limit] + (len(x) >=limit and '...'
or '')) or x
words = _word_split_re.split(unicode(escape(text)))
nofollow_attr = nofollow and ' rel="nofollow"' or ''
for i, word in enumerate(words):
match = _punctuation_re.match(word)
if match:
lead, middle, trail = match.groups()
if middle.startswith('www.') or (
'@' not in middle and
not middle.startswith('http://') and
len(middle) > 0 and
middle[0] in _letters + _digits and (
middle.endswith('.org') or
middle.endswith('.net') or
middle.endswith('.com')
)):
middle = '<a href="http://%s"%s>%s</a>' % (middle,
nofollow_attr, trim_url(middle))
if middle.startswith('http://') or \
middle.startswith('https://'):
middle = '<a href="%s"%s>%s</a>' % (middle,
nofollow_attr, trim_url(middle))
if '@' in middle and not middle.startswith('www.') and \
not ':' in middle and _simple_email_re.match(middle):
middle = '<a href="mailto:%s">%s</a>' % (middle, middle)
if lead + middle + trail != word:
words[i] = lead + middle + trail
return u''.join(words)
def generate_lorem_ipsum(n=5, html=True, min=20, max=100):
"""Generate some lorem impsum for the template."""
from jinja2.constants import LOREM_IPSUM_WORDS
from random import choice, randrange
words = LOREM_IPSUM_WORDS.split()
result = []
for _ in xrange(n):
next_capitalized = True
last_comma = last_fullstop = 0
word = None
last = None
p = []
# each paragraph contains out of 20 to 100 words.
for idx, _ in enumerate(xrange(randrange(min, max))):
while True:
word = choice(words)
if word != last:
last = word
break
if next_capitalized:
word = word.capitalize()
next_capitalized = False
# add commas
if idx - randrange(3, 8) > last_comma:
last_comma = idx
last_fullstop += 2
word += ','
# add end of sentences
if idx - randrange(10, 20) > last_fullstop:
last_comma = last_fullstop = idx
word += '.'
next_capitalized = True
p.append(word)
# ensure that the paragraph ends with a dot.
p = u' '.join(p)
if p.endswith(','):
p = p[:-1] + '.'
elif not p.endswith('.'):
p += '.'
result.append(p)
if not html:
return u'\n\n'.join(result)
return Markup(u'\n'.join(u'<p>%s</p>' % escape(x) for x in result))
class LRUCache(object):
"""A simple LRU Cache implementation."""
# this is fast for small capacities (something below 1000) but doesn't
# scale. But as long as it's only used as storage for templates this
# won't do any harm.
def __init__(self, capacity):
self.capacity = capacity
self._mapping = {}
self._queue = deque()
self._postinit()
def _postinit(self):
# alias all queue methods for faster lookup
self._popleft = self._queue.popleft
self._pop = self._queue.pop
if hasattr(self._queue, 'remove'):
self._remove = self._queue.remove
self._wlock = allocate_lock()
self._append = self._queue.append
def _remove(self, obj):
"""Python 2.4 compatibility."""
for idx, item in enumerate(self._queue):
if item == obj:
del self._queue[idx]
break
def __getstate__(self):
return {
'capacity': self.capacity,
'_mapping': self._mapping,
'_queue': self._queue
}
def __setstate__(self, d):
self.__dict__.update(d)
self._postinit()
def __getnewargs__(self):
return (self.capacity,)
def copy(self):
"""Return an shallow copy of the instance."""
rv = self.__class__(self.capacity)
rv._mapping.update(self._mapping)
rv._queue = deque(self._queue)
return rv
def get(self, key, default=None):
"""Return an item from the cache dict or `default`"""
try:
return self[key]
except KeyError:
return default
def setdefault(self, key, default=None):
"""Set `default` if the key is not in the cache otherwise
leave unchanged. Return the value of this key.
"""
try:
return self[key]
except KeyError:
self[key] = default
return default
def clear(self):
"""Clear the cache."""
self._wlock.acquire()
try:
self._mapping.clear()
self._queue.clear()
finally:
self._wlock.release()
def __contains__(self, key):
"""Check if a key exists in this cache."""
return key in self._mapping
def __len__(self):
"""Return the current size of the cache."""
return len(self._mapping)
def __repr__(self):
return '<%s %r>' % (
self.__class__.__name__,
self._mapping
)
def __getitem__(self, key):
"""Get an item from the cache. Moves the item up so that it has the
highest priority then.
Raise an `KeyError` if it does not exist.
"""
rv = self._mapping[key]
if self._queue[-1] != key:
try:
self._remove(key)
except ValueError:
# if something removed the key from the container
# when we read, ignore the ValueError that we would
# get otherwise.
pass
self._append(key)
return rv
def __setitem__(self, key, value):
"""Sets the value for an item. Moves the item up so that it
has the highest priority then.
"""
self._wlock.acquire()
try:
if key in self._mapping:
try:
self._remove(key)
except ValueError:
# __getitem__ is not locked, it might happen
pass
elif len(self._mapping) == self.capacity:
del self._mapping[self._popleft()]
self._append(key)
self._mapping[key] = value
finally:
self._wlock.release()
def __delitem__(self, key):
"""Remove an item from the cache dict.
Raise an `KeyError` if it does not exist.
"""
self._wlock.acquire()
try:
del self._mapping[key]
try:
self._remove(key)
except ValueError:
# __getitem__ is not locked, it might happen
pass
finally:
self._wlock.release()
def items(self):
"""Return a list of items."""
result = [(key, self._mapping[key]) for key in list(self._queue)]
result.reverse()
return result
def iteritems(self):
"""Iterate over all items."""
return iter(self.items())
def values(self):
"""Return a list of all values."""
return [x[1] for x in self.items()]
def itervalue(self):
"""Iterate over all values."""
return iter(self.values())
def keys(self):
"""Return a list of all keys ordered by most recent usage."""
return list(self)
def iterkeys(self):
"""Iterate over all keys in the cache dict, ordered by
the most recent usage.
"""
return reversed(tuple(self._queue))
__iter__ = iterkeys
def __reversed__(self):
"""Iterate over the values in the cache dict, oldest items
coming first.
"""
return iter(tuple(self._queue))
__copy__ = copy
# register the LRU cache as mutable mapping if possible
try:
from collections import MutableMapping
MutableMapping.register(LRUCache)
except ImportError:
pass
class Cycler(object):
"""A cycle helper for templates."""
def __init__(self, *items):
if not items:
raise RuntimeError('at least one item has to be provided')
self.items = items
self.reset()
def reset(self):
"""Resets the cycle."""
self.pos = 0
@property
def current(self):
"""Returns the current item."""
return self.items[self.pos]
def next(self):
"""Goes one item ahead and returns it."""
rv = self.current
self.pos = (self.pos + 1) % len(self.items)
return rv
class Joiner(object):
"""A joining helper for templates."""
def __init__(self, sep=u', '):
self.sep = sep
self.used = False
def __call__(self):
if not self.used:
self.used = True
return u''
return self.sep
# try markupsafe first, if that fails go with Jinja2's bundled version
# of markupsafe. Markupsafe was previously Jinja2's implementation of
# the Markup object but was moved into a separate package in a patchleve
# release
try:
from markupsafe import Markup, escape, soft_unicode
except ImportError:
from jinja2._markupsafe import Markup, escape, soft_unicode
# partials
try:
from functools import partial
except ImportError:
class partial(object):
def __init__(self, _func, *args, **kwargs):
self._func = _func
self._args = args
self._kwargs = kwargs
def __call__(self, *args, **kwargs):
kwargs.update(self._kwargs)
return self._func(*(self._args + args), **kwargs)
| Python |
Subsets and Splits
SQL Console for ajibawa-2023/Python-Code-Large
Provides a useful breakdown of language distribution in the training data, showing which languages have the most samples and helping identify potential imbalances across different language groups.