def homepage(request): os, flavor = os_detect(request.META['HTTP_USER_AGENT']) flavor = '_' + flavor if flavor else '' latest_download = cache.get('homepage_latest_download_%s%s' % (os, flavor)) if latest_download == None: latest_download = get_object_or_None(Release.objects.select_related(), platform__name='%s%s' % (os, flavor)) cache.set('homepage_latest_download_%s%s' % (os, flavor), latest_download, 86400) news_forum_id = get_config('NEWS_FORUM', 1) news = cache.get('homepage_news') if news == None: news = list(Post.objects.filter(topic__forum=news_forum_id, topic__first_post__id=F('id')).order_by('-created_at'). \ select_related()[:get_config('NEWS_ITEMS_ON_HOMEPAGE', 5)]) cache.set('homepage_news', news) journal_forum_id = get_config('JOURNAL_FORUM', 2) journal = cache.get('homepage_journal') if journal == None: journal = list(Post.objects.filter(topic__forum=journal_forum_id, topic__first_post__id=F('id')).order_by('-created_at'). \ select_related()[:get_config('JOURNAL_ITEMS_ON_HOMEPAGE', 5)]) cache.set('homepage_journal', journal) return {'news': news, 'journal': journal, 'forum_id': news_forum_id, 'latest_download': latest_download}
def resend_activation_key(request, user_id): user = get_object_or_404(User, pk=user_id) activation = get_object_or_None(ActivationKey, user=user) if not activation == None: # Cleaning database from unused objects activation.delete() if request.method == 'POST': form = ResendActivationKeyForm(request.POST) if not form.cleaned_data['email'] == user.email: messages.error(request, "E-mail address sent by you doesn't match \ with address used to register this account.") return redirect(reverse('home')) if form.is_valid(): t = loader.get_template('accounts/email/email_activation.html') ak = ActivationKey(user=user) ak.save() webmaster_email = get_config('WEBMASTER_EMAIL', '*****@*****.**') site_name = get_config('SITE_NAME', 'Trinitee application') c = Context({'new_user': user, 'activation_key': ak.key, 'webmaster_email': webmaster_email, 'site_name': site_name, 'server_name': request.get_host()}) send_mail("E-mail activation at %s" % site_name, t.render(c), get_config('MAILER_ADDRESS', '*****@*****.**'), [email], fail_silently=False) messages.success(request, "An email has been sent \ to the specified address with instructions on how to activate \ your new account. If it doesn't arrive you can contact the forum \ administrator at %s" % webmaster_email) return redirect(reverse('home')) else: form = ResendActivationKeyForm() return {'form': form}
def save(self, *args, **kwargs): if get_config('ENABLE_BBCODE', False): markup = postmarkup.create(annotate_links=False, use_pygments=get_config('BBCODE_USE_PYGMENTS', False)) self.content_html = markup(self.content) else: self.content_html = self.content super(Post, self).save(*args, **kwargs)
def items(self): journal_forum_id = get_config('JOURNAL_FORUM', 2) entries = cache.get('homepage_journal') if entries == None: entries = list(Post.objects.filter(topic__forum=journal_forum_id, topic__first_post__id=F('id')).order_by('-created_at') \ .select_related()[:get_config('NEWS_ITEMS_ON_HOMEPAGE', 5)]) cache.set('homepage_journal', entries) return entries
def items(self): news_forum_id = get_config('NEWS_FORUM', 1) news = cache.get('homepage_news') if news == None: news = list(Post.objects.filter(topic__forum=news_forum_id, topic__first_post__id=F('id')).order_by('-created_at'). \ select_related()[:get_config('NEWS_ITEMS_ON_HOMEPAGE', 5)]) cache.set('homepage_news', news) return news
def journal(request): journal_forum_id = get_config('JOURNAL_FORUM', 2) journal = cache.get('homepage_journal') if journal == None: journal = list(Post.objects.filter(topic__forum=journal_forum_id, topic__first_post__id=F('id')).order_by('-created_at'). \ select_related()[:get_config('JOURNAL_ITEMS_ON_HOMEPAGE', 5)]) cache.set('homepage_journal', journal) return {'journal': journal}
def save(self, *args, **kwargs): cache.delete('misc_drawboard') if get_config('ENABLE_BBCODE', False): markup = postmarkup.create(annotate_links=False, use_pygments=get_config('BBCODE_USE_PYGMENTS', False)) self.content_html = markup(self.content) else: self.content_html = self.content super(Drawboard, self).save(*args, **kwargs) cache.set('misc_drawboard', self)
def save(self, *args, **kwargs): if not self.user.is_superuser: is_staff_group = self.group.is_staff_group if self.group else False self.user.is_staff = is_staff_group if get_config('ENABLE_BBCODE', False): markup = postmarkup.create(annotate_links=False, use_pygments=get_config('BBCODE_USE_PYGMENTS', False)) self.signature_html = markup(self.signature) self.about_html = markup(self.about) else: self.signature_html = self.signature self.about_html = markup(self.about) super(UserProfile, self).save(*args, **kwargs)
def process_request(self, request): if not get_config('MAINTENANCE_MODE', False): return if request.path in ['/user/login/', '/user/logout/'] \ or 'static' in request.path: return if hasattr(request, 'user') \ and (request.user.is_staff or request.user.is_superuser): return resp = render_to_response('503.html', {'message': get_config('MAINTENANCE_MESSAGE', None)}, context_instance=RequestContext(request)) resp.status_code = 503 return resp
def items(self): reports = cache.get('admin_forums_feed_reports') if reports == None: reports = list(Report.objects \ .filter(status=None)[:get_config('FEED_ITEMS', 50)]) cache.set('admin_forums_feed_reports', reports) return reports
def post_permalink(request, post_id): post = get_object_or_404(Post, pk=post_id) older_posts = Post.objects.filter(topic__pk=post.topic.id, created_at__lt=post.created_at).count() page = int(math.ceil((float(older_posts) + 1.0) / get_config('POSTS_PER_PAGE', 25))) return redirect(post.topic.get_absolute_url() + '?page=%s#post-%s' % (page, post.id))
def clean_avatar(self): avatar = self.cleaned_data.get('avatar') delete = self.cleaned_data.get('delete') if not avatar or delete: return avatar else: w, h = get_image_dimensions(avatar) max_w = get_config('AVATAR_MAX_WIDTH', 60) max_h = get_config('AVATAR_MAX_HEIGTH', 60) # TODO add max file size if w > max_w: raise forms.ValidationError("The image is %i pixel wide. " "It's supposed to be %ipx" % (w, max_h)) if h > max_h: raise forms.ValidationError("The image is %i pixel high. " "It's supposed to be %ipx" % (h, max_h)) return avatar
def items(self, item): posts = cache.get('forums_feed_topic_%s' % item) if posts == None: posts = list(Post.objects.filter(topic=item) \ .order_by('-created_at') \ .select_related()[:get_config('FEED_ITEMS', 50)]) cache.set('forums_feed_topic_%s' % item, posts) return posts
def items(self): posts = cache.get('forums_feed_topics') if posts == None: posts = list(Post.objects.filter(topic__first_post__id=F('id')) \ .order_by('-created_at') \ .select_related()[:get_config('FEED_ITEMS', 50)]) cache.set('forums_feed_topics', posts) return posts
def user_timezone(dt, user): """ Converts the given datetime to the given User's timezone, if they have one set in their forum profile. Adapted from http://www.djangosnippets.org/snippets/183/ """ tz = get_config('TIME_ZONE', 'UTC') if user.is_authenticated(): if user.profile.timezone: tz = user.profile.timezone try: result = dt.astimezone(pytz.timezone(tz)) except ValueError: # The datetime was stored without timezone info, so use the # timezone configured in settings. result = dt.replace(tzinfo=pytz.timezone(get_config('TIME_ZONE', 'UTC'))) \ .astimezone(pytz.timezone(tz)) return result
def process_view(self, request, view_func, *view_args, **view_kwargs): if not get_config('MAINTENANCE_MODE', False): return if 'static' in request.path or '__debug__' in request.path: return if hasattr(request, 'user') \ and (request.user.is_staff or request.user.is_superuser): messages.warning(request, "Site is currently running under" " maintenance mode, please turn it off" " after finishing your work.")
def render(self, name, value, attrs=None): if value is None: icon = 'unknown' elif value: icon = 'yes' elif not value: icon = 'no' else: raise ValueError('NullBooleanROWidget can be used with boolean and None values only.') return mark_safe(u'<img src="%simg/admin/icon-%s.gif" />' % \ (get_config('ADMIN_MEDIA_PREFIX', '/static/admin/'), icon))
def post_warning_save(instance, **kwargs): warn_count = sum(Warn.objects.filter(user=instance.user) \ .values_list('weight', flat=True)) firstban_count = get_config('WARNINGS_TO_FIRSTBAN', 4) permban_count = get_config('WARNINGS_TO_PERMBAN', 5) if warn_count >= permban_count: ban = Ban(created_by=instance.created_by, banned_user=instance.user, expires_at=False, comment="AUTO PERMANENT ban, sorry." "Here's last warning comment:\n%s" % instance.comment) ban.save() elif warn_count >= firstban_count: ban = Ban(created_by=instance.created_by, banned_user=instance.user, expires_at=datetime.datetime.now()+datetime.timedelta(days=7), comment="AUTO ban, sorry." "Here's last warning comment:\n%s" % instance.comment) ban.save() else: StoredNotification(user=instance.user, message="You have been warned (weight: %s) by %s.<br />Reason: %s" "<br />Additional comment:<br />%s<br /><br />" "You have %s warnings. You are on the way to destruction, " "make your time." % (instance.weight, instance.warned_by, instance.reason, instance.comment, warn_count), level=40)
def post_post_save(instance, **kwargs): post = instance topic = post.topic forum = topic.forum if kwargs['created']: if topic.post_count == 0: topic.first_post = post topic.last_post = post topic.post_count = topic.get_post_count() forum.last_post = post forum.post_count = forum.get_post_count() profile = post.author.profile profile.post_count = profile.get_post_count() profile.save(force_update=True) topic.save(force_update=True) forum.save(force_update=True) cache.delete('forums_count_posts') if forum.id == get_config('NEWS_FORUM', 1): cache.delete('homepage_news') if forum.id == get_config('JOURNAL_FORUM', 2): cache.delete('homepage_journal') cache.delete('forums_topics_%s' % forum.id) cache.delete('forums_posts_%s' % topic.id) cache.delete('forums_latest_topics')
def register(request): # ref: comment to accounts.views.login_ if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] email = form.cleaned_data['email'] user = User(username=username, email=email, is_active=False) user.set_password(password) if not get_config('ACTIVATION_REQUIRED', False): user.is_active = True user.save() messages.success(request, "Thank you for registering." " You can now log in.") else: if not get_config('EMAIL_HOST', False) \ or not get_config('EMAIL_PORT', False) \ or not get_config('EMAIL_HOST_USER', False) \ or not get_config('EMAIL_HOST_PASSWORD', False): raise ImproperlyConfigured("You must configure mailer.") user.save() ak = ActivationKey(user=user) ak.save() t = loader.get_template('accounts/email/email_activation.html') webmaster_email = get_config('WEBMASTER_EMAIL', '*****@*****.**') site_name = get_config('SITE_NAME', 'Trinitee application') c = Context({'new_user': user, 'activation_key': ak.key, 'webmaster_email': webmaster_email, 'site_name': site_name, 'server_name': request.get_host()}) send_mail("E-mail activation at %s" % site_name, t.render(c), get_config('MAILER_ADDRESS', '*****@*****.**'), [email]) messages.success(request, "Thank you for registering." " An email has been sent to the specified address with" " instructions on how to activate your new account." " If it doesn't arrive you can contact the forum" " administrator at %s" % webmaster_email) return redirect(reverse('accounts.views.login')) else: form = RegistrationForm() return {'form': form}
def save(self, *args, **kwargs): self.key = User.objects.make_random_password() # OK, not really a password self.expires_at = datetime.datetime.now() + \ datetime.timedelta(days=get_config('ACTIVATION_KEY_EXPIRY_TIME', 7)) super(ActivationKey, self).save(*args, **kwargs)
(":D", "big_smile.png"), (":|", "neutral.png"), (":(", "sad.png"), (";)", "wink.png"), (":p", "tongue.png"), (":P", "tongue.png"), (":o", "yikes.png"), (":O", "yikes.png"), (":/", "hmm.png"), (":lol:", "lol.png"), (":mad:", "mad.png"), (":cool:", "cool.png"), (":rolleyes:", "roll.png"), ) SMILEYS_URL = get_config("SMILEYS_URL", "%ssmileys/" % settings.MEDIA_URL) SMILEYS_LIST = get_config("SMILEYS_LIST", smileys_default_list) RE_SMILEYS_LIST = [(re.compile(re.escape(smiley[0])), smiley[0], smiley[1]) for smiley in SMILEYS_LIST] RE_SMILEYS_SAFE = re.compile(r"(<.+?>)|(https?://[\w\.#$%]+)|(\S+?@(\S\+?.)+\S{2,3})") def replace_smileys(content, autoescape=None): esc = autoescape and conditional_escape or (lambda x: x) for smiley, name, image in RE_SMILEYS_LIST: safe_things = re.findall(RE_SMILEYS_SAFE, content) content_safe = re.sub(RE_SMILEYS_SAFE, "#~", content) if smiley.search(content_safe): smiley_html = '<img class="%s" src="%s" alt="%s" />' % ("smiley", os.path.join(SMILEYS_URL, image), name)
def validate_signature(value): max_lines = get_config('SIGNATURE_MAX_LINES', False) if not max_lines: return if len(value.split("\n")) > max_lines: raise ValidationError("Signature has more than %d lines." % max_lines)
def __init__(self, **kwargs): self.columns = 3 Dashboard.__init__(self, **kwargs) self.children.append(DrawboardModule( title="Drawboard", css_classes=['collapse', 'open'], )) self.children.append(modules.AppList( title="Users", include_list=('django.contrib.auth', 'accounts'), css_classes=['collapse', 'open'], )) self.children.append(modules.AppList( title="Forums", include_list=('forums', ), css_classes=['collapse', 'open'], )) self.children.append(modules.AppList( title="Flatpages", include_list=('utilities.superflatpages', ), css_classes=['collapse', 'open'], )) self.children.append(modules.AppList( title="Downloads", include_list=('downloads', ), css_classes=['collapse', 'open'], )) self.children.append(modules.AppList( title="Bans", include_list=('misc', ), css_classes=['collapse', 'open'], )) self.children.append(modules.AppList( title="Sites", include_list=('django.contrib.sites', ), css_classes=['collapse', 'closed'], )) # append a recent actions module self.children.append(modules.RecentActions( column=2, title=_('Recent Actions'), limit=10, )) # append a feed module # self.children.append(modules.Feed( # column=2, # title=_('Latest Django News'), # feed_url='http://www.djangoproject.com/rss/weblog/', # limit=5 # )) self.children.append(modules.LinkList( column=3, title=_('Quick actions'), children=[ { 'title': _('Add new Teeworlds version'), 'url': reverse('admin:downloads_version_add'), }, { 'title': _('Post new news item'), 'url': reverse('admin:forums_topic_add') + '?forum=%s' % get_config('NEWS_FORUM', 1), }, { 'title': _('Post new developer\'s entry'), 'url': reverse('admin:forums_topic_add') + '?forum=%s' % get_config('JOURNAL_FORUM', 2), }, ], )) self.children.append(modules.LinkList( column=3, title=_('Quick links'), children=[ { 'title': _('Return to site'), 'url': '/', }, { 'title': _('Change password'), 'url': reverse('admin:password_change'), }, { 'title': _('Log out'), 'url': reverse('admin:logout') }, ], ))
def title(self, item): return "Latest posts in topic \"%s\" - %s" % (item.title, get_config('SITE_NAME', "Trinitee"))
def title(self, item): return "Latest posts in forum \"%s\" - %s" % (item.name, get_config('SITE_NAME', "Trinitee"))
def title(self, item): return "Latest posts of user \"%s\" - %s" % (item.username, get_config('SITE_NAME', "Trinitee"))