def sph_showavatar(user): profile = None try: profile = CommunityUserProfile.objects.get(user=user, ) except CommunityUserProfile.DoesNotExist: pass avatar = None avatar_width = None avatar_height = None if not profile or not profile.avatar: avatar = get_sph_setting('community_avatar_default') log.error("got default photo: %s", avatar) if not avatar: return '' avatar_width = get_sph_setting('community_avatar_default_width') avatar_height = get_sph_setting('community_avatar_default_height') else: avatar = profile.avatar.url avatar_width = profile.avatar_width avatar_height = profile.avatar_height log.info("avatar: %s", avatar) return '<img src="%s" width="%dpx" height="%dpx" alt="%s" class="sph_avatar"></img>' % ( avatar, avatar_width, avatar_height, _(u'Users photo'))
def community_advprofile_edit_init_form(sender, instance, signal, *args, **kwargs): user = instance.user try: profile = CommunityUserProfile.objects.get(user=user, ) except CommunityUserProfile.DoesNotExist: profile = CommunityUserProfile(user=user, ) if profile.avatar: instance.fields[ 'community_advprofile_avatar_remove'] = djangoforms.BooleanField( label=_(u'Delete avatar'), required=False) max_width = get_sph_setting('community_avatar_max_width') max_height = get_sph_setting('community_avatar_max_height') instance.fields['community_advprofile_avatar'] = djangoforms.ImageField( label=_(u'Avatar'), help_text=_( u'Avatar with maximum size of %(max_width)sx%(max_height)s' % { 'max_width': max_width, 'max_height': max_height }), required=False, ) instance.clean_community_advprofile_avatar = lambda: clean_community_advprofile_avatar( instance)
def sph_showavatar(user, maxwidth = None): profile = None try: profile = CommunityUserProfile.objects.get( user = user, ) except CommunityUserProfile.DoesNotExist: pass avatar = None avatar_width = None avatar_height = None if not profile or not profile.avatar: avatar = get_sph_setting( 'community_avatar_default' ) log.error("got default avatar: %s", avatar) if not avatar: return '' avatar_width = get_sph_setting( 'community_avatar_default_width' ) avatar_height = get_sph_setting( 'community_avatar_default_height' ) else: avatar = profile.avatar.url avatar_width = profile.avatar_width avatar_height = profile.avatar_height if maxwidth is not None and maxwidth < avatar_width: avatar_height = round(float(avatar_height) * (float(maxwidth) / avatar_width)) avatar_width = maxwidth log.info("avatar: %s", avatar) return '<img src="%s" width="%dpx" height="%dpx" alt="%s" class="sph_avatar"></img>' % (avatar, avatar_width, avatar_height, _(u'Users avatar'))
def sph_markdown(value, arg='', oldmd=None, extra_macros={}): try: from sphene.contrib.libs.markdown import markdown except ImportError: if settings.DEBUG: raise template.TemplateSyntaxError, "Error in {% markdown %} filter: The Python markdown library isn't installed." return value else: safe_mode = arg == 'safe' macros = { 'helloWorld': SimpleHelloWorldMacro(), 'news': NewsMacro(), 'newsrss': NewsRSSLinkMacro(), 'include': IncludeMacro(), 'includetemplate': IncludeTemplateMacro(), } macros.update(extra_macros), md = markdown.Markdown(value, extensions = [ 'footnotes', 'wikilink', 'macros', 'toc' ], extension_configs = { 'wikilink': [ ], 'macros': [ ( 'macros', macros ) ], 'toc': { 'include_header_one_in_toc': True, }, }, safe_mode = safe_mode, ) md.number_headings = get_sph_setting('markdown_number_headings', True) md.top_heading_level = get_sph_setting('markdown_top_heading_level', 1) if oldmd and hasattr(oldmd,'header_numbers'): md.header_numbers = oldmd.header_numbers ret = md.toString() if hasattr(md, 'tocDiv'): sphdata = get_current_sphdata() sphdata['toc'] = mark_safe( md.tocDiv.toxml() ) return ret
def sph_publicemailaddress(value): if get_sph_setting('community_email_anonymous_require_captcha'): # as a security constraint we don't return the public email # address if the user is not logged in. if not get_current_user().is_authenticated(): validated = get_current_request().session.get( 'sph_email_captcha_validated', 0) # if the timeout is reached or the captcha was never entered # provide a link for the user to enter the captcha. if validated < time() - get_sph_setting( 'community_email_anonymous_require_captcha_timeout'): return mark_safe('<a href="%s">%s</a>' % (sph_reverse('sph_reveal_emailaddress', (), { 'user_id': value.id, }), ugettext('Reveal this emailaddress'))) if get_sph_setting('community_email_show_only_public'): try: return CommunityUserProfile.objects.get( user=value, ).public_emailaddress except CommunityUserProfile.DoesNotExist: pass return '' try: profile = CommunityUserProfile.objects.get(user=value, ) except CommunityUserProfile.DoesNotExist: return "n/a" #value.email return profile.public_emailaddress or value.email
def community_advprofile_display(sender, signal, request, user, **kwargs): try: profile = CommunityUserProfile.objects.get(user=user) except CommunityUserProfile.DoesNotExist: return None avatar = None avatar_width = None avatar_height = None if not profile.avatar: default_avatar = get_sph_setting("community_avatar_default") if not default_avatar: return None avatar = default_avatar avatar_width = get_sph_setting("community_avatar_default_width") avatar_height = get_sph_setting("community_avatar_default_height") else: avatar = profile.avatar.url avatar_width = profile.avatar_width avatar_height = profile.avatar_height ret = "" ret = '<tr><th>%s</th><td><img src="%s" width="%dpx" height="%dpx" alt="%s"></img></td></tr>' % ( _(u"Avatar"), avatar, avatar_width, avatar_height, _(u"Users avatar"), ) return ret
def _get_markup_choices(): choices = [] classes = {} enabled_markup = get_sph_setting('board_markup_enabled', ('bbcode',)) custom_markup = get_sph_setting('board_custom_markup', {}) for en in enabled_markup: try: renderclass = AVAILABLE_MARKUP[en] except KeyError: try: renderer = custom_markup[en] except KeyError: raise exceptions.ImproperlyConfigured( _(u"Custom renderer '%(renderer)s' needs a matching Render \ Class entry in your sphene settings 'board_custom_markup'") \ % {'renderer': en}) renderclass = get_method_by_name(renderer) classes[en] = renderclass choices.append((en, renderclass.label)) return tuple(choices), classes
def clean_community_advprofile_avatar(self): f = self.cleaned_data['community_advprofile_avatar'] if f is None: return f # Verify file size .. size = len(self.cleaned_data['community_advprofile_avatar']) max_size = get_sph_setting( 'community_avatar_max_size' ) if size > max_size: raise djangoforms.ValidationError( _(u"Max upload filesize of %(max_size)d bytes exceeded. (Your file had %(size)d bytes)") % {'max_size':max_size, 'size':size} ) from PIL import Image from cStringIO import StringIO try: # Verify image dimensions .. image = Image.open(f) width = image.size[0] height = image.size[1] f.seek(-f.tell()) max_width = get_sph_setting( 'community_avatar_max_width' ) max_height = get_sph_setting( 'community_avatar_max_height' ) if width > max_width or height > max_height: raise djangoforms.ValidationError( "Max size of %dx%d exceeded (Your upload was %dx%d)" % (max_width, max_height, width, height) ) except IOError: raise ValidationError( _(u"Uploaded an invalid image.") ) return f
def sph_publicemailaddress(value): if get_sph_setting('community_email_anonymous_require_captcha'): # as a security constraint we don't return the public email # address if the user is not logged in. if not get_current_user().is_authenticated: validated = get_current_request().session.get('sph_email_captcha_validated', 0) # if the timeout is reached or the captcha was never entered # provide a link for the user to enter the captcha. if validated < time() - get_sph_setting('community_email_anonymous_require_captcha_timeout'): return mark_safe('<a href="%s">%s</a>' % ( sph_reverse('sph_reveal_emailaddress', kwargs={'user_id': value.id, }), _('Reveal this emailaddress'))) if get_sph_setting('community_email_show_only_public'): try: return CommunityUserProfile.objects.get(user=value, ).public_emailaddress except CommunityUserProfile.DoesNotExist: pass return '' try: profile = CommunityUserProfile.objects.get(user=value, ) except CommunityUserProfile.DoesNotExist: return "n/a" # value.email return profile.public_emailaddress or value.email
def _get_markup_choices(): choices = [] classes = {} enabled_markup = get_sph_setting('board_markup_enabled', ('bbcode', )) custom_markup = get_sph_setting('board_custom_markup', {}) for en in enabled_markup: try: renderclass = AVAILABLE_MARKUP[en] except KeyError: try: renderer = custom_markup[en] except KeyError: raise exceptions.ImproperlyConfigured( _(u"Custom renderer '%(renderer)s' needs a matching Render \ Class entry in your sphene settings 'board_custom_markup'" )\ % {'renderer': en}) renderclass = get_method_by_name(renderer) classes[en] = renderclass choices.append((en, renderclass.label)) return tuple(choices), classes
def community_advprofile_display(sender, signal, request, user, **kwargs): try: profile = CommunityUserProfile.objects.get(user=user, ) except CommunityUserProfile.DoesNotExist: return None avatar = None avatar_width = None avatar_height = None if not profile.avatar: default_avatar = get_sph_setting('community_avatar_default') if not default_avatar: return None avatar = default_avatar avatar_width = get_sph_setting('community_avatar_default_width') avatar_height = get_sph_setting('community_avatar_default_height') else: avatar = profile.avatar.url avatar_width = profile.avatar_width avatar_height = profile.avatar_height ret = '<tr><th>%s</th><td><img src="%s" width="%dpx" height="%dpx" alt="%s"></img></td></tr>' % ( _(u'Avatar'), avatar, avatar_width, avatar_height, _(u'Users avatar')) return ret
def attachmentEdit(request, group, snipName, attachmentId=None): """Importing ModelForm""" from django.forms import ModelForm """ Class necessary for the Modelform """ class AttachmentFormNew(ModelForm): class Meta: model = WikiAttachment attachment = None if attachmentId is None: AttachmentForm = AttachmentFormNew() else: attachment = WikiAttachment.objects.get(id=attachmentId) AttachmentForm = AttachmentFormNew(instance=attachment) if attachment: if not attachment.snip.has_edit_permission(): raise PermissionDenied() if 'delete' in request.GET and request.GET['delete'] == '1': attachment.delete() messages.success(request, message=ugettext("Successfully deleted attachment.")) return HttpResponseRedirect( attachment.snip.get_absolute_attachmenturl()) AttachmentForm.base_fields['fileupload'].widget = widgets.FileInput() if request.method == 'POST': if get_sph_setting('django096compatibility'): reqdata = request.POST.copy() reqdata.update(request.FILES) form = AttachmentForm(reqdata) else: form = AttachmentFormNew(request.POST, request.FILES) if form.is_valid(): attachment = form.save(commit=False) snip = WikiSnip.objects.get(name__exact=snipName, group=group) attachment.snip = snip attachment.uploader = request.user if get_sph_setting('django096compatibility'): attachment.save_fileupload_file( reqdata['fileupload']['filename'], reqdata['fileupload']['content']) attachment.save() return HttpResponseRedirect(snip.get_absolute_attachmenturl()) else: form = AttachmentFormNew(instance=attachment) return render_to_response('sphene/sphwiki/editAttachment.html', { 'form': form, 'snipName': snipName, }, context_instance=RequestContext(request))
def attachmentEdit(request, group, snipName, attachmentId = None): """Importing ModelForm""" from django.forms import ModelForm """ Class necessary for the Modelform """ class AttachmentFormNew(ModelForm): class Meta: model = WikiAttachment attachment = None if attachmentId is None: AttachmentForm = AttachmentFormNew() else: attachment = WikiAttachment.objects.get(id=attachmentId) AttachmentForm = AttachmentFormNew(instance=attachment) if attachment: if not attachment.snip.has_edit_permission(): raise PermissionDenied() if 'delete' in request.GET and request.GET['delete'] == '1': attachment.delete() messages.success(request, message = ugettext("Successfully deleted attachment.") ) return HttpResponseRedirect( attachment.snip.get_absolute_attachmenturl() ) AttachmentForm.base_fields['fileupload'].widget = widgets.FileInput() if request.method == 'POST': if get_sph_setting( 'django096compatibility' ): reqdata = request.POST.copy() reqdata.update(request.FILES) form = AttachmentForm(reqdata) else: form = AttachmentFormNew(request.POST, request.FILES) if form.is_valid(): attachment = form.save(commit=False) snip = WikiSnip.objects.get( name__exact = snipName, group = group ) attachment.snip = snip attachment.uploader = request.user if get_sph_setting( 'django096compatibility' ): attachment.save_fileupload_file( reqdata['fileupload']['filename'], reqdata['fileupload']['content'] ) attachment.save() return HttpResponseRedirect( snip.get_absolute_attachmenturl() ) else: form = AttachmentFormNew(instance=attachment) return render_to_response( 'sphene/sphwiki/editAttachment.html', { 'form': form, 'snipName' : snipName, }, context_instance = RequestContext(request) )
def pdf_get_cachefile(self): """ Returns the pathname to the cache file for this wiki snip. """ if not get_sph_setting("wiki_pdf_generation", False) or not self.pdf_enabled(): raise Exception("PDF Generation not enabled by configuration.") cachedir = get_sph_setting("wiki_pdf_generation_cachedir", "/tmp/sct_pdf") if not os.path.isdir(cachedir): os.mkdir(cachedir) filename = re.sub("[^A-Za-z0-9]", "_", self.name) cachefile = os.path.join(cachedir, "%s_%d.pdf" % (filename, self.id)) return cachefile
def is_spammer(user_id): from sphene.sphboard.models import UserPostCount user = User.objects.get(pk=user_id) if user.username in get_sph_setting('board_no_limits_users'): return False apply_spammer_limits = False try: upc = UserPostCount.objects.get_post_count(user, get_current_group()) except User.DoesNotExist: upc = 0 if upc < get_sph_setting('board_signature_required_post_count'): apply_spammer_limits = True return apply_spammer_limits
def community_advprofile_edit_init_form(sender, instance, signal, *args, **kwargs): user = instance.user try: profile = CommunityUserProfile.objects.get( user = user, ) except CommunityUserProfile.DoesNotExist: profile = CommunityUserProfile( user = user, ) if profile.avatar: instance.fields['community_advprofile_avatar_remove'] = djangoforms.BooleanField( label = _(u'Delete avatar'), required = False ) max_width = get_sph_setting( 'community_avatar_max_width' ) max_height = get_sph_setting( 'community_avatar_max_height' ) instance.fields['community_advprofile_avatar'] = djangoforms.ImageField( label = _(u'Avatar'), help_text = _(u'Avatar with maximum size of %(max_width)sx%(max_height)s' % { 'max_width': max_width, 'max_height': max_height }), required = False, ) instance.clean_community_advprofile_avatar = lambda : clean_community_advprofile_avatar(instance)
def clean_community_advprofile_avatar(self): f = self.cleaned_data['community_advprofile_avatar'] if f is None: return f # Verify file size .. size = len(self.cleaned_data['community_advprofile_avatar']) max_size = get_sph_setting('community_avatar_max_size') if size > max_size: raise djangoforms.ValidationError( _(u"Max upload filesize of %(max_size)d bytes exceeded. (Your file had %(size)d bytes)" ) % { 'max_size': max_size, 'size': size }) try: from PIL import Image except ImportError: import Image try: # Verify image dimensions .. image = Image.open(f) format = image.format width = image.size[0] height = image.size[1] f.seek(-f.tell()) max_width = get_sph_setting('community_avatar_max_width') max_height = get_sph_setting('community_avatar_max_height') if width > max_width or height > max_height: # Instead of creating a validation error, simply resize the image. image.thumbnail((max_width, max_height), Image.ANTIALIAS) from tempfile import NamedTemporaryFile from django.core.files.base import File import os tmpfile = NamedTemporaryFile() image.save(tmpfile, format=format) f = File(tmpfile, f.name) # raise djangoforms.ValidationError( "Max size of %dx%d exceeded (Your upload was %dx%d)" % (max_width, max_height, width, height) ) except IOError as e: print(e) raise djangoforms.ValidationError(_(u"Uploaded an invalid image.")) return f
def showThread(request, thread_id, group=None, slug=None): thread = get_object_or_404(Post.objects, pk=thread_id) if not thread.category.has_view_permission(request.user): raise PermissionDenied() thread.viewed(request.session, request.user) sphdata = get_current_sphdata() if sphdata != None: sphdata['subtitle'] = thread.subject category_type = thread.category.get_category_type() template_name = category_type.get_show_thread_template() res = object_list( request=request, #queryset = Post.objects.filter( Q( pk = thread_id ) | Q( thread = thread ) ).order_by('postdate'), queryset=thread.get_all_posts().order_by('postdate'), allow_empty=True, template_name=template_name, extra_context={ 'thread': thread, 'allowPosting': thread.allowPosting(request.user), 'postSubject': 'Re: ' + thread.subject, 'category_type': category_type, }, template_object_name='post', paginate_by=get_sph_setting('board_post_paging'), ) res.sph_lastmodified = thread.get_latest_post().postdate return res
def move_post_2(request, group, post_id, category_id): """ Display threads in category (category_id) where the post can be moved to """ post = Post.objects.get(pk=post_id) if not post.allow_moving_post(): raise PermissionDenied() thread = post.get_thread() category = Category.objects.get(pk=category_id) thread_list = category.get_thread_list().exclude( root_post=thread.pk).order_by('-thread_latest_postdate') res = object_list(request=request, queryset=thread_list, allow_empty=True, template_name="sphene/sphboard/move_post_2.html", extra_context={ 'post': post, 'category': category }, template_object_name='thread', paginate_by=get_sph_setting('board_post_paging')) return res
class WikiAttachment(models.Model): snip = models.ForeignKey(WikiSnip, editable=False) uploader = models.ForeignKey(User, editable=False) uploaded = models.DateTimeField(editable=False) fileupload = models.FileField( ugettext_lazy('fileupload'), upload_to=get_sph_setting('wiki_attachments_upload_to')) description = models.TextField(ugettext_lazy('description'), blank=True) def get_absolute_editurl(self): return ('sphene.sphwiki.views.attachmentEdit', (), { 'groupName': self.snip.group.name, 'snipName': self.snip.name, 'attachmentId': self.id }) get_absolute_editurl = sphpermalink(get_absolute_editurl) def save(self, force_insert=False, force_update=False): self.uploaded = datetime.today() super(WikiAttachment, self).save(force_insert=force_insert, force_update=force_update) def __unicode__(self): return self.fileupload.name
def showThread(request, thread_id, group = None): thread = get_object_or_404(Post.objects, pk = thread_id ) if not thread.category.has_view_permission(request.user): raise PermissionDenied() thread.viewed( request.session, request.user ) sphdata = get_current_sphdata() if sphdata != None: sphdata['subtitle'] = thread.subject category_type = thread.category.get_category_type() template_name = category_type.get_show_thread_template() res = object_list( request = request, #queryset = Post.objects.filter( Q( pk = thread_id ) | Q( thread = thread ) ).order_by('postdate'), queryset = thread.get_all_posts().order_by('postdate'), allow_empty = True, template_name = template_name, extra_context = { 'thread': thread, 'allowPosting': thread.allowPosting( request.user ), 'postSubject': 'Re: ' + thread.subject, 'category_type': category_type, }, template_object_name = 'post', paginate_by = get_sph_setting( 'board_post_paging' ), ) res.sph_lastmodified = thread.get_latest_post().postdate return res
def move_post_2(request, group, post_id, category_id): """ Display threads in category (category_id) where the post can be moved to """ post_obj = Post.objects.get(pk=post_id) if not post_obj.allow_moving_post(): raise PermissionDenied() thread = post_obj.get_thread() category = Category.objects.get(pk=category_id) thread_list = category.get_thread_list().exclude( root_post=thread.pk).order_by('-thread_latest_postdate') paginator = Paginator(thread_list, get_sph_setting('board_post_paging'), allow_empty_first_page=True) page = request.GET.get('page') page_obj = paginator.get_page(page) # res = object_list(request=request, # queryset=thread_list, # allow_empty=True, # template_name="sphene/sphboard/move_post_2.html", # extra_context={'post': post_obj, # 'category': category}, # template_object_name='thread', # paginate_by=get_sph_setting('board_post_paging') # ) return render(request, 'sphene/sphboard/move_post_2.html', { 'post': post_obj, 'category': category, 'thread_list': page_obj, })
def pdf_get_cachefile(self): """ Returns the pathname to the cache file for this wiki snip. """ if not get_sph_setting('wiki_pdf_generation', False) or not self.pdf_enabled(): raise Exception('PDF Generation not enabled by configuration.') cachedir = get_sph_setting('wiki_pdf_generation_cachedir', '/tmp/sct_pdf') if not os.path.isdir(cachedir): os.mkdir(cachedir) filename = re.sub("[^A-Za-z0-9]", "_", self.name) cachefile = os.path.join(cachedir, '%s_%d.pdf' % (filename, self.id)) return cachefile
def clean_community_advprofile_avatar(self): f = self.cleaned_data['community_advprofile_avatar'] if f is None: return f # Verify file size .. size = len(self.cleaned_data['community_advprofile_avatar']) max_size = get_sph_setting('community_avatar_max_size') if size > max_size: raise djangoforms.ValidationError( _(u"Max upload filesize of %(max_size)d bytes exceeded. (Your file had %(size)d bytes)") % { 'max_size': max_size, 'size': size}) try: from PIL import Image except ImportError: import Image try: # Verify image dimensions .. image = Image.open(f) format = image.format width = image.size[0] height = image.size[1] f.seek(-f.tell()) max_width = get_sph_setting('community_avatar_max_width') max_height = get_sph_setting('community_avatar_max_height') if width > max_width or height > max_height: # Instead of creating a validation error, simply resize the image. image.thumbnail((max_width, max_height), Image.ANTIALIAS) from tempfile import NamedTemporaryFile from django.core.files.base import File import os tmpfile = NamedTemporaryFile() image.save(tmpfile, format=format) f = File(tmpfile, f.name) # raise djangoforms.ValidationError( "Max size of %dx%d exceeded (Your upload was %dx%d)" % (max_width, max_height, width, height) ) except IOError as e: print(e) raise djangoforms.ValidationError(_(u"Uploaded an invalid image.")) return f
def sphboard_default_notify_me(user): try: profile = BoardUserProfile.objects.get(user = user) if profile.default_notifyme_value is False: return False except BoardUserProfile.DoesNotExist: pass return get_sph_setting( 'board_default_notifyme' )
def handle_wikilinks_match(matchgroups): if matchgroups.get('urls'): # We matched a HTML link .. simply return the whole html code. return {'label': matchgroups.get('urls')} if matchgroups.get('escape'): # CamelCase expresion was escaped ... return {'label': matchgroups.get('wholeexpression')} snipname = matchgroups.get('camelcase') or matchgroups.get('snipname') label = matchgroups.get('sniplabel') or snipname.replace('_', ' ') cssclass = 'sph_wikilink' try: snip = WikiSnip.objects.get( group=get_current_group(), name=snipname, ) href = snip.get_absolute_url() except WikiSnip.DoesNotExist: try: snip = WikiSnip( group=get_current_group(), name=snipname, ) except TypeError: log.error('No group found when getting wikilinks. Ignoring.') return {'label': label} if not snip.has_edit_permission() \ and get_sph_setting('wiki_links_nonexistent_show_only_privileged'): return { 'label': label, } href = snip.get_absolute_editurl() cssclass += ' sph_nonexistent' if get_sph_setting('wiki_links_nonexistent_prefix'): label = "create:" + label return { 'href': href, 'label': label, 'class': cssclass, }
def sph_showavatar(user, maxwidth=None): profile = None try: profile = CommunityUserProfile.objects.get(user=user, ) except CommunityUserProfile.DoesNotExist: pass avatar = None avatar_width = None avatar_height = None get_avatar = get_sph_setting('community_user_get_avatar') if get_avatar is not None: avatarinfo = get_avatar(user) if avatarinfo is not None: avatar = avatarinfo['url'] avatar_width = avatarinfo['width'] avatar_height = avatarinfo['height'] if avatar is None: if not profile or not profile.avatar: avatar = get_sph_setting('community_avatar_default') log.debug("got default avatar: %s", avatar) if not avatar: return '' avatar_width = get_sph_setting('community_avatar_default_width') avatar_height = get_sph_setting('community_avatar_default_height') else: avatar = profile.avatar.url avatar_width = profile.avatar_width avatar_height = profile.avatar_height if maxwidth is not None and maxwidth < avatar_width: avatar_height = round( float(avatar_height) * (float(maxwidth) / avatar_width)) avatar_width = maxwidth log.info("avatar: %s", avatar) return format_html( '<img src="{}" width="{}px" height="{}px" alt="{}" class="sph_avatar"></img>', avatar, avatar_width, avatar_height, _(u'Users avatar'))
def sph_markdown(value, arg='', oldmd=None, extra_macros={}): try: from sphene.contrib.libs.markdown import markdown except ImportError: if settings.DEBUG: raise ( template.TemplateSyntaxError, "Error in {% markdown %} filter: The Python markdown library isn't installed." ) return value else: safe_mode = arg == 'safe' macros = { 'helloWorld': SimpleHelloWorldMacro(), 'news': NewsMacro(), 'newsrss': NewsRSSLinkMacro(), 'include': IncludeMacro(), 'includetemplate': IncludeTemplateMacro(), } macros.update(extra_macros), md = markdown.Markdown( value, extensions=['footnotes', 'wikilink', 'macros', 'toc'], extension_configs={ 'wikilink': [], 'macros': [('macros', macros)], 'toc': { 'include_header_one_in_toc': True, }, }, safe_mode=safe_mode, ) md.number_headings = get_sph_setting('markdown_number_headings', True) md.top_heading_level = get_sph_setting('markdown_top_heading_level', 1) if oldmd and hasattr(oldmd, 'header_numbers'): md.header_numbers = oldmd.header_numbers ret = md.toString() if hasattr(md, 'tocDiv'): sphdata = get_current_sphdata() sphdata['toc'] = mark_safe(md.tocDiv.toxml()) return ret
def sph_showavatar(user, maxwidth=None): profile = None try: profile = CommunityUserProfile.objects.get(user=user, ) except CommunityUserProfile.DoesNotExist: pass avatar = None avatar_width = None avatar_height = None get_avatar = get_sph_setting('community_user_get_avatar') if get_avatar is not None: avatarinfo = get_avatar(user) if avatarinfo is not None: avatar = avatarinfo['url'] avatar_width = avatarinfo['width'] avatar_height = avatarinfo['height'] if avatar is None: if not profile or not profile.avatar: avatar = get_sph_setting('community_avatar_default') log.debug("got default avatar: %s", avatar) if not avatar: return '' avatar_width = get_sph_setting('community_avatar_default_width') avatar_height = get_sph_setting('community_avatar_default_height') else: avatar = profile.avatar.url avatar_width = profile.avatar_width avatar_height = profile.avatar_height if maxwidth is not None and maxwidth < avatar_width: avatar_height = round(float(avatar_height) * (float(maxwidth) / avatar_width)) avatar_width = maxwidth log.info("avatar: %s", avatar) return format_html( '<img src="{}" width="{}px" height="{}px" alt="{}" class="sph_avatar"></img>', avatar, avatar_width, avatar_height, _(u'Users avatar'))
def render_node_xhtml(self, node): if len(node.children) == 0: return '' if not node.parameter is None: url = node.parameter.strip() else: url = node.children[0].text.strip() linktext = node.render_children_xhtml() #node.children[0].text.strip() if len(url) == 0: return '' else: post_link = get_sph_setting('board_post_link') return post_link % {'url':escape(url), 'text':linktext}
def get_paged_objects(objects, page): paginator = Paginator(objects, get_sph_setting('blog_post_paging')) try: page = int(page) except ValueError: page = 1 try: paged_objects = paginator.page(page) except (EmptyPage, InvalidPage): paged_objects = paginator.page(paginator.num_pages) return paged_objects
def pdf_generate(self): """ Generates the PDF for this snip and stores it into cachedir. """ cachefile = self.pdf_get_cachefile() xmlfile = cachefile + ".xhtml" snip_rendered_body = str(self.render()) # TODO do this in the model ? like the board post body ? sctpath = hasattr(settings, "LIB_PATH") and settings.LIB_PATH or "." # static_filepath = get_sph_setting( 'wiki_pdf_generation_static_filepath', os.path.join(sctpath, '..', 'static', 'sphene') ) static_filepath = settings.MEDIA_ROOT snip_rendered_body = snip_rendered_body.replace( '<img src="%(media_url)s' % {"media_url": settings.STATIC_URL}, '<img src="%s/' % static_filepath ) import codecs xmlout = codecs.open(xmlfile, mode="w", encoding="utf-8") xmlout.write( """ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>%(title)s</title> </head> <body> <div id="header" class="pdf"> <div class="label">%(title)s</div> </div> <div id="footer" class="pdf"> Page <pdf:pagenumber /> </div> """ % {"title": self.title or self.name} ) xmlout.write(snip_rendered_body) xmlout.write( """ </body> </html> """ ) xmlout.close() command = get_sph_setting("wiki_pdf_generation_command") os.system(command % {"srcfile": xmlfile, "destfile": cachefile}) if not os.path.isfile(cachefile): raise Exception("Error while generating PDF.")
def handle_wikilinks_match(matchgroups): if matchgroups.get('urls'): # We matched a HTML link .. simply return the whole html code. return { 'label': matchgroups.get('urls') } if matchgroups.get('escape'): # CamelCase expresion was escaped ... return { 'label': matchgroups.get('wholeexpression') } snipname = matchgroups.get('camelcase') or matchgroups.get('snipname') label = matchgroups.get('sniplabel') or snipname.replace('_', ' ') cssclass = 'sph_wikilink' try: snip = WikiSnip.objects.get( group = get_current_group(), name = snipname, ) href = snip.get_absolute_url() except WikiSnip.DoesNotExist: try: snip = WikiSnip( group = get_current_group(), name = snipname, ) except TypeError: log.error('No group found when getting wikilinks. Ignoring.') return { 'label' : label} if not snip.has_edit_permission() \ and get_sph_setting('wiki_links_nonexistent_show_only_privileged'): return { 'label': label, } href = snip.get_absolute_editurl() cssclass += ' sph_nonexistent' if get_sph_setting( 'wiki_links_nonexistent_prefix' ): label = "create:"+label return { 'href': href, 'label': label, 'class': cssclass, }
def ready(self): from sphene.community.sphutils import get_sph_setting from sphene.community import sphsettings jsincludes = get_sph_setting( 'community_jsincludes', []) # jquery is already added by the community application. #jsincludes.append(settings.STATIC_URL + 'sphene/community/jquery-1.2.3.min.js') jsincludes.append(settings.STATIC_URL + 'sphene/community/jquery.dimensions.js') jsincludes.append(settings.STATIC_URL + 'sphene/community/ui.mouse.js') #jsincludes.append(settings.STATIC_URL + 'sphene/community/ui.draggable.js') jsincludes.append(settings.STATIC_URL + 'sphene/community/ui.droppable.js') jsincludes.append(settings.STATIC_URL + 'sphene/community/ui.sortable.js') jsincludes.append(settings.STATIC_URL + 'sphene/sphblockframework/blocksorting.js') sphsettings.set_sph_setting( 'community_jsincludes', jsincludes )
def render_node_xhtml(self, node): if len(node.children) == 0: return '' if not node.parameter is None: url = node.parameter.strip() else: url = node.children[0].text.strip() linktext = node.render_children_xhtml( ) # node.children[0].text.strip() if len(url) == 0: return '' else: post_link = get_sph_setting('board_post_link') return post_link % {'url': escape(url), 'text': linktext}
def pdf_generate(self): """ Generates the PDF for this snip and stores it into cachedir. """ cachefile = self.pdf_get_cachefile() xmlfile = cachefile + '.xhtml' snip_rendered_body = str(self.render( )) # TODO do this in the model ? like the board post body ? sctpath = hasattr(settings, 'LIB_PATH') and settings.LIB_PATH or '.' #static_filepath = get_sph_setting( 'wiki_pdf_generation_static_filepath', os.path.join(sctpath, '..', 'static', 'sphene') ) static_filepath = settings.MEDIA_ROOT snip_rendered_body = snip_rendered_body.replace( '<img src="%(media_url)s' % \ { 'media_url': settings.STATIC_URL }, '<img src="%s/' % static_filepath ) import codecs xmlout = codecs.open(xmlfile, mode='w', encoding='utf-8') xmlout.write(''' <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>%(title)s</title> </head> <body> <div id="header" class="pdf"> <div class="label">%(title)s</div> </div> <div id="footer" class="pdf"> Page <pdf:pagenumber /> </div> ''' % {'title': self.title or self.name}) xmlout.write(snip_rendered_body) xmlout.write(''' </body> </html> ''') xmlout.close() command = get_sph_setting('wiki_pdf_generation_command') os.system(command % { 'srcfile': xmlfile, 'destfile': cachefile, }) if not os.path.isfile(cachefile): raise Exception('Error while generating PDF.')
def pdf_enabled(self): """ Checks if PDF generation is 1. enabled and 2. the current user has permission. (E.g. setting 'wiki_pdf_generation' to 'loggedin' would only allow loggedin users to view PDF versions.) This method is ment to be used in templates. """ setting = get_sph_setting("wiki_pdf_generation") if setting == True: return True if setting == "loggedin": return get_current_user() and get_current_user().is_authenticated() if setting == "staff": return get_current_user() and get_current_user().is_authenticated() and get_current_user().is_staff return False
def pdf_enabled(self): """ Checks if PDF generation is 1. enabled and 2. the current user has permission. (E.g. setting 'wiki_pdf_generation' to 'loggedin' would only allow loggedin users to view PDF versions.) This method is ment to be used in templates. """ setting = get_sph_setting('wiki_pdf_generation') if setting == True: return True if setting == 'loggedin': return get_current_user() and get_current_user().is_authenticated() if setting == 'staff': return get_current_user() and get_current_user().is_authenticated( ) and get_current_user().is_staff return False
def pdf_generate(self): """ Generates the PDF for this snip and stores it into cachedir. """ cachefile = self.pdf_get_cachefile() xmlfile = cachefile + '.xhtml' snip_rendered_body = str(self.render()) # TODO do this in the model ? like the board post body ? sctpath = hasattr(settings, 'LIB_PATH') and settings.LIB_PATH or '.' static_filepath = settings.MEDIA_ROOT snip_rendered_body = snip_rendered_body.replace( '<img src="%(media_url)s' % { 'media_url': settings.STATIC_URL }, '<img src="%s/' % static_filepath) import codecs xmlout = codecs.open(xmlfile, mode='w', encoding='utf-8') xmlout.write(''' <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>%(title)s</title> </head> <body> <div id="header" class="pdf"> <div class="label">%(title)s</div> </div> <div id="footer" class="pdf"> Page <pdf:pagenumber /> </div> ''' % {'title': self.title or self.name}) xmlout.write(snip_rendered_body) xmlout.write(''' </body> </html> ''') xmlout.close() command = get_sph_setting('wiki_pdf_generation_command') os.system(command % {'srcfile': xmlfile, 'destfile': cachefile, }) if not os.path.isfile(cachefile): raise Exception('Error while generating PDF.')
def move_post_2(request, group, post_id, category_id): """ Display threads in category (category_id) where the post can be moved to """ post = Post.objects.get(pk=post_id) if not post.allow_moving_post(): raise PermissionDenied() thread = post.get_thread() category = Category.objects.get(pk=category_id) thread_list = category.get_thread_list().exclude(root_post=thread.pk).order_by('-thread_latest_postdate') res = object_list(request = request, queryset = thread_list, allow_empty = True, template_name = "sphene/sphboard/move_post_2.html", extra_context = {'post': post, 'category':category}, template_object_name = 'thread', paginate_by = get_sph_setting('board_post_paging') ) return res
class ThreadListView(ListView): paginate_by = get_sph_setting('board_post_paging') def __init__(self, **kwargs): super().__init__(**kwargs) self.thread: Post = None def get(self, request, group=None, thread_id=None, **kwargs): assert group self.thread = thread = get_object_or_404(Post.objects, pk=thread_id) if not thread.category.has_view_permission(request.user): raise PermissionDenied() thread.viewed(request.session, request.user) sphdata = get_current_sphdata() if sphdata is not None: sphdata['subtitle'] = thread.subject category_type = thread.category.get_category_type() self.template_name = category_type.get_show_thread_template() return super().get(request, **kwargs) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) return { **context, 'thread': self.thread, 'allowPosting': self.thread.allowPosting(self.request.user), 'postSubject': 'Re: ' + self.thread.subject, 'category_type': self.thread.category.get_category_type(), } def get_queryset(self): return self.thread.get_all_posts().order_by('postdate')
## e.g. [email], [member], the rendering of [quote=person] ## 3) 'Missing' tags - [img] - but should be easy to add ## 4) Mostly it works on one-to-one correspondance between ## 'bbtags' and xhtml tags, but with some added constraints to force ## extra elements to be inserted to comply with XHTML, and ## use some tricks to relax the nesting constraints, such ## as some elements being context sensitive in the render phase import re #### CCIW specific imports ##### #from zilbo.common.text.utils import get_member_link, obfuscate_email #from cciw.apps.cciw.settings import CCIW_MEDIA_ROOT from sphene.community.sphutils import render_blockquote, get_sph_setting from django.conf import settings EMOTICONS_ROOT = get_sph_setting('board_emoticons_root') ##### UTILITY FUNCTIONS ##### def get_member_link( member ): return member def obfuscate_email( email ): return email def escape(html): "Returns the given HTML with ampersands, quotes and carets encoded" if not isinstance(html, basestring): html = str(html) return html.replace('&', '&').replace('<', '<') \ .replace('>', '>').replace('"', '"')
from django.conf import settings from sphene.community import sphsettings from sphene.community.sphutils import get_sph_setting jsincludes = get_sph_setting('community_jsincludes', []) # jquery is already added by the community application. #jsincludes.append(settings.STATIC_URL + 'sphene/community/jquery-1.2.3.min.js') jsincludes.append(settings.STATIC_URL + 'sphene/community/jquery.dimensions.js') jsincludes.append(settings.STATIC_URL + 'sphene/community/ui.mouse.js') #jsincludes.append(settings.STATIC_URL + 'sphene/community/ui.draggable.js') jsincludes.append(settings.STATIC_URL + 'sphene/community/ui.droppable.js') jsincludes.append(settings.STATIC_URL + 'sphene/community/ui.sortable.js') jsincludes.append(settings.STATIC_URL + 'sphene/sphblockframework/blocksorting.js') sphsettings.set_sph_setting('community_jsincludes', jsincludes)
return get_sph_setting( 'board_default_notifyme' ) def authorinfo_cachekey(user_id, group_id = None, language_code = None): if group_id is None: group_id = get_current_group().id if language_code is None: language_code = getattr(get_current_request(), 'LANGUAGE_CODE', '') return '%s_sphboard_authorinfo_%s_%s_%s' % \ (settings.CACHE_MIDDLEWARE_KEY_PREFIX, str(group_id), str(user_id), language_code) @cache_inclusion_tag(register, 'sphene/sphboard/_post_authorinfo.html', cache_key_func=authorinfo_cachekey, cache_time = get_sph_setting( 'board_authorinfo_cache_timeout' )) def sphboard_post_authorinfo(user_id): if user_id is None: user = None else: user = User.objects.get(pk = user_id) return {'author': user, 'STATIC_URL': settings.STATIC_URL, 'post_count': UserPostCount.objects.get_post_count(user, get_current_group())} def clear_cache_all_languages(user_id, group_id): from django.conf import settings if not hasattr(settings, 'LANGUAGES'): return
class PermissionDenied(Exception): pass # We can't import it as 'forms' because we've got a package called 'forms' .. how smart. from django import forms as djangoforms from django.conf import settings from sphene.community.forms import EditProfileForm, Separator from sphene.community.signals import profile_edit_init_form, profile_edit_save_form, profile_display from sphene.community.sphutils import get_sph_setting from sphene.community.models import CommunityUserProfile from sphene.community import sphsettings from django.utils.translation import ugettext as _ from django.utils.translation import ugettext_lazy jsincludes = get_sph_setting("community_jsincludes", []) jsincludes.append(settings.MEDIA_URL + "sphene/community/jquery-1.2.3.min.js") jsincludes.append(settings.MEDIA_URL + "sphene/community/jquery.autocomplete.js") sphsettings.set_sph_setting("community_jsincludes", jsincludes) #### # # Source code for adding an avatar .. (advanced community profile) # def clean_community_advprofile_avatar(self): f = self.cleaned_data["community_advprofile_avatar"] if f is None: return f
def post(request, group = None, category_id = None, post_id = None, thread_id = None): if 'type' in request.REQUEST and request.REQUEST['type'] == 'preview': previewpost = Post( body = request.REQUEST['body'], markup = request.REQUEST.get('markup', None), ) return HttpResponse( unicode(previewpost.body_escaped()) ) post = None thread = None category = None context = { } if post_id is None and 'post_id' in request.REQUEST: # if no post_id is given take it from the request. post_id = request.REQUEST['post_id'] if post_id: try: post = Post.allobjects.get( pk = post_id ) except Post.DoesNotExist: raise Http404 if not post.allowEditing(): raise PermissionDenied() thread = post.thread if 'thread' in request.REQUEST: thread_id = request.REQUEST['thread'] if thread_id: try: thread = Post.allobjects.get( pk = thread_id ) except Post.DoesNotExist: raise Http404 category = thread.category context['thread'] = thread if not thread.allowPosting( request.user ): raise PermissionDenied() else: category = get_object_or_404(Category, pk = category_id) if not category.allowPostThread( request.user ): raise PermissionDenied() context['category'] = category category_type = category.get_category_type() MyPostForm = PostForm if category_type is not None: MyPostForm = category_type.get_post_form_class(thread, post) attachmentForm = None allow_attachments = get_sph_setting('board_allow_attachments') if request.method == 'POST': postForm = MyPostForm(request.POST) postForm.init_for_category_type(category_type, post) pollForm = PostPollForm(request.POST) create_post = True if allow_attachments: attachmentForm = PostAttachmentForm(request.POST, request.FILES, prefix = 'attachment') if 'cmd_addfile' in request.POST: create_post = False if attachmentForm.is_valid(): attachment = attachmentForm.save(commit = False) if attachment.fileupload: # Only save attachments if there was an upload... # If the form is valid, store the attachment if not post: # if there is no post yet.. we need to create a draft post = Post( category = category, author = request.user, thread = thread, is_hidden = 1, ) post.set_new( True ) post.save() # Reference the post and save the attachment attachment.post = post attachment.save() if create_post \ and postForm.is_valid() \ and ('createpoll' not in request.POST \ or pollForm.is_valid()): data = postForm.cleaned_data if post: newpost = post newpost.subject = data['subject'] newpost.body = data['body'] # make post visible newpost.is_hidden = 0 if not post.is_new() and category_type.append_edit_message_to_post(post): newpost.body += "\n\n" + _(u'--- Last Edited by %(username)s at %(edit_date)s ---') % {'username':get_user_displayname( request.user ), 'edit_date':format_date( datetime.today())} else: user = request.user.is_authenticated() and request.user or None newpost = Post( category = category, subject = data['subject'], body = data['body'], author = user, thread = thread, ) if 'markup' in data: newpost.markup = data['markup'] elif len( POST_MARKUP_CHOICES ) == 1: newpost.markup = POST_MARKUP_CHOICES[0][0] newpost.save() category_type.save_post( newpost, data ) # Creating monitor if request.POST.get( 'addmonitor', False ): newpost.toggle_monitor() if 'createpoll' in request.POST and request.POST['createpoll'] == '1': newpost.set_poll( True ); newpost.save() # Creating poll... polldata = pollForm.cleaned_data newpoll = Poll( post = newpost, question = polldata['question'], choices_per_user = polldata['choicesPerUser']) newpoll.save() choices = polldata['answers'].splitlines() i=0 for choice in choices: pollchoice = PollChoice( poll = newpoll, choice = choice, count = 0, sortorder = i) i+=1 pollchoice.save() if request.user.is_authenticated(): request.user.message_set.create( message = ugettext(u'Vote created successfully.') ) if request.user.is_authenticated(): if post: request.user.message_set.create( message = ugettext(u'Post edited successfully.') ) else: request.user.message_set.create( message = ugettext(u'Post created successfully.') ) if thread == None: thread = newpost return HttpResponseRedirect( newpost.get_absolute_url() ) else: postForm = MyPostForm( ) postForm.init_for_category_type(category_type, post) pollForm = PostPollForm() if allow_attachments: attachmentForm = PostAttachmentForm(prefix = 'attachment') if post: postForm.fields['subject'].initial = post.subject postForm.fields['body'].initial = post.body if 'markup' in postForm.fields: postForm.fields['markup'].initial = post.markup context['post'] = post context['thread'] = post.thread or post elif 'quote' in request.REQUEST: quotepost = Post.objects.get( pk = request.REQUEST['quote'] ) postForm.fields['subject'].initial = 'Re: %s' % thread.subject if quotepost.author == None: username = '******' else: username = quotepost.author.username postForm.fields['body'].initial = '[quote=%s;%s]\n%s\n[/quote]\n' % (username, quotepost.id, quotepost.body) elif thread: postForm.fields['subject'].initial = 'Re: %s' % thread.subject context['form'] = postForm # Only allow polls if this is a new _thread_ (not a reply) if (not thread and not post) or (post and post.is_new() and post.thread is None): context['pollform'] = pollForm context['attachmentForm'] = attachmentForm if 'createpoll' in request.REQUEST: context['createpoll'] = request.REQUEST['createpoll'] res = render_to_response( "sphene/sphboard/post.html", context, context_instance = RequestContext(request) ) # Maybe the user is in the 'edit' form, which should not be cached. res.sph_lastmodified = True return res
import re from sphene.sphwiki.models import WikiSnip from sphene.community.sphutils import get_sph_setting from sphene.community.middleware import get_current_group import logging log = logging.getLogger('wikilink_utils') # We don't want to match anything in HTML link tags.. so we exclude them completely. WIKILINK_RE = r'''((?P<urls><a .*?>.*?</a)|(?P<escape>\\|\b)?(?P<wholeexpression>(((?P<camelcase>([A-Z]+[a-z-_0-9]+){2,})\b)|\[(?P<snipname>[A-Za-z-_/0-9]+)(\|(?P<sniplabel>.+?))?\])))''' WIKILINK_RE = get_sph_setting('wikilink_regexp', WIKILINK_RE) WIKILINK_RE_COMPILED = re.compile(WIKILINK_RE) def get_wikilink_regex_pattern(): return WIKILINK_RE def get_wikilink_regex(): return WIKILINK_RE_COMPILED def handle_wikilinks_match(matchgroups): if matchgroups.get('urls'): # We matched a HTML link .. simply return the whole html code. return {'label': matchgroups.get('urls')} if matchgroups.get('escape'): # CamelCase expresion was escaped ... return {'label': matchgroups.get('wholeexpression')}
def render(self, text, apply_spammer_limits=False): if get_sph_setting('board_auto_wiki_link_enabled', True): from sphene.sphwiki import wikilink_utils return wikilink_utils.render_wikilinks(bbcode.bb2xhtml(text)) else: return bbcode.bb2xhtml(text, apply_spammer_limits=apply_spammer_limits)
def enable_wysiwyg_editor(): # we want the bbcode WYSIWYG editor only if 'bbcode' is the only # choice. return len( POST_MARKUP_CHOICES ) == 1 and \ POST_MARKUP_CHOICES[0][0] == 'bbcode' and \ get_sph_setting('board_wysiwyg')
from django.utils.encoding import force_unicode class PermissionDenied(Exception): pass # We can't import it as 'forms' because we've got a package called 'forms' .. how smart. from django import forms as djangoforms from django.conf import settings from sphene.community.forms import EditProfileForm from sphene.community.signals import profile_edit_init_form, profile_edit_save_form, profile_display from sphene.community.sphutils import get_sph_setting from sphene.community.models import CommunityUserProfile from sphene.community import sphsettings from django.utils.translation import ugettext as _ jsincludes = get_sph_setting( 'community_jsincludes', []) jsincludes.append(settings.STATIC_URL + 'sphene/community/jquery-1.7.2.min.js') jsincludes.append(settings.STATIC_URL + 'sphene/community/jquery.autocomplete.js') sphsettings.set_sph_setting( 'community_jsincludes', jsincludes ) #### # # Source code for adding an avatar .. (advanced community profile) # def clean_community_advprofile_avatar(self): f = self.cleaned_data['community_advprofile_avatar'] if f is None: return f # Verify file size ..
def post(request, group=None, category_id=None, post_id=None, thread_id=None): """ View method to allow users to: - create new threads (post_id and thread_id is None) - reply to threads (post_id is None) - edit posts (post_id is the post which should be edited, thread_id is None) post_id and thread_id can either be passed in by URL (named parameters to this method) or by request.REQUEST parameters. """ if "type" in request.REQUEST and request.REQUEST["type"] == "preview": # If user just wants a preview, simply create a dummy post so it can be rendered. previewpost = Post(body=request.REQUEST["body"], markup=request.REQUEST.get("markup", None)) return HttpResponse(unicode(previewpost.body_escaped())) # All available objects should be loaded from the _id variables. post = None thread = None category = None context = { "bbcodewysiwyg": enable_wysiwyg_editor() or (get_sph_setting("board_wysiwyg_testing") and request.REQUEST.get("wysiwyg", False)) } if post_id is None and "post_id" in request.REQUEST: # if no post_id is given take it from the request. post_id = request.REQUEST["post_id"] if post_id is not None: # User wants to edit a post .. try: post = Post.allobjects.get(pk=post_id) except Post.DoesNotExist: raise Http404 if not post.allowEditing(): raise PermissionDenied() thread = post.thread category = post.category else: # User wants to create a new post (thread or reply) if "thread" in request.REQUEST: thread_id = request.REQUEST["thread"] if thread_id is not None: # User is posting (replying) to a thread. try: thread = Post.allobjects.get(pk=thread_id) except Post.DoesNotExist: raise Http404 category = thread.category if not thread.allowPosting(request.user): raise PermissionDenied() else: # User is creating a new thread. category = get_object_or_404(Category, pk=category_id) if not category.allowPostThread(request.user): raise PermissionDenied() context["thread"] = thread context["category"] = category category_type = category.get_category_type() MyPostForm = PostForm if category_type is not None: MyPostForm = category_type.get_post_form_class(thread, post) attachmentForm = None allow_attachments = get_sph_setting("board_allow_attachments") if request.method == "POST": postForm = MyPostForm(request.POST) postForm.init_for_category_type(category_type, post) pollForm = PostPollForm(request.POST) create_post = True if allow_attachments: attachmentForm = PostAttachmentForm(request.POST, request.FILES, prefix="attachment") if "cmd_addfile" in request.POST: create_post = False if attachmentForm.is_valid(): attachment = attachmentForm.save(commit=False) if attachment.fileupload: # Only save attachments if there was an upload... # If the form is valid, store the attachment if not post: # if there is no post yet.. we need to create a draft post = Post(category=category, author=request.user, thread=thread, is_hidden=1) post.set_new(True) post.save() # Reference the post and save the attachment attachment.post = post attachment.save() if create_post and postForm.is_valid() and ("createpoll" not in request.POST or pollForm.is_valid()): data = postForm.cleaned_data if post: newpost = post newpost.subject = data["subject"] newpost.body = data["body"] # make post visible newpost.is_hidden = 0 if not post.is_new() and category_type.append_edit_message_to_post(post): newpost.body += "\n\n" + _(u"--- Last Edited by %(username)s at %(edit_date)s ---") % { "username": get_user_displayname(request.user), "edit_date": format_date(datetime.today()), } else: user = request.user.is_authenticated() and request.user or None newpost = Post( category=category, subject=data["subject"], body=data["body"], author=user, thread=thread ) if "markup" in data: newpost.markup = data["markup"] elif len(POST_MARKUP_CHOICES) == 1: newpost.markup = POST_MARKUP_CHOICES[0][0] newpost.save(additional_data=data) # category_type.save_post( newpost, data ) # Creating monitor if request.POST.get("addmonitor", False): newpost.toggle_monitor() if "createpoll" in request.POST and request.POST["createpoll"] == "1": newpost.set_poll(True) newpost.save() # Creating poll... polldata = pollForm.cleaned_data newpoll = Poll(post=newpost, question=polldata["question"], choices_per_user=polldata["choicesPerUser"]) newpoll.save() choices = polldata["answers"].splitlines() i = 0 for choice in choices: pollchoice = PollChoice(poll=newpoll, choice=choice, count=0, sortorder=i) i += 1 pollchoice.save() if request.user.is_authenticated(): request.user.message_set.create(message=ugettext(u"Vote created successfully.")) if request.user.is_authenticated(): if post: request.user.message_set.create(message=ugettext(u"Post edited successfully.")) else: request.user.message_set.create(message=ugettext(u"Post created successfully.")) if thread == None: thread = newpost return HttpResponseRedirect(newpost.get_absolute_url()) else: postForm = MyPostForm() postForm.init_for_category_type(category_type, post) pollForm = PostPollForm() if allow_attachments: attachmentForm = PostAttachmentForm(prefix="attachment") if post: postForm.fields["subject"].initial = post.subject postForm.fields["body"].initial = post.body if "markup" in postForm.fields: postForm.fields["markup"].initial = post.markup context["post"] = post context["thread"] = post.thread or post elif "quote" in request.REQUEST: quotepost = Post.objects.get(pk=request.REQUEST["quote"]) postForm.fields["subject"].initial = "Re: %s" % thread.subject if quotepost.author == None: username = "******" else: username = quotepost.author.username postForm.fields["body"].initial = "[quote=%s;%s]\n%s\n[/quote]\n" % (username, quotepost.id, quotepost.body) elif thread: postForm.fields["subject"].initial = "Re: %s" % thread.subject context["form"] = postForm # Only allow polls if this is a new _thread_ (not a reply) if (not thread and not post) or (post and post.is_new() and post.thread is None): context["pollform"] = pollForm context["attachmentForm"] = attachmentForm if "createpoll" in request.REQUEST: context["createpoll"] = request.REQUEST["createpoll"] res = render_to_response("sphene/sphboard/post.html", context, context_instance=RequestContext(request)) # Maybe the user is in the 'edit' form, which should not be cached. res.sph_lastmodified = True return res
def render(self, text): if get_sph_setting('board_auto_wiki_link_enabled', True): return wikilink_utils.render_wikilinks(bbcode.bb2xhtml(text)) else: return bbcode.bb2xhtml(text)
def post(request, group=None, category_id=None, post_id=None, thread_id=None): """ View method to allow users to: - create new threads (post_id and thread_id is None) - reply to threads (post_id is None) - edit posts (post_id is the post which should be edited, thread_id is None) post_id and thread_id can either be passed in by URL (named parameters to this method) or by request.REQUEST parameters. """ if 'type' in request.REQUEST and request.REQUEST['type'] == 'preview': # If user just wants a preview, simply create a dummy post so it can be rendered. previewpost = Post( body=request.REQUEST['body'], markup=request.REQUEST.get('markup', None), ) return HttpResponse(unicode(previewpost.body_escaped())) # All available objects should be loaded from the _id variables. post_obj = None thread = None category = None context = { 'bbcodewysiwyg': enable_wysiwyg_editor() \ or (get_sph_setting('board_wysiwyg_testing') \ and request.REQUEST.get('wysiwyg', False)) } if post_id is None and 'post_id' in request.REQUEST: # if no post_id is given take it from the request. post_id = request.REQUEST['post_id'] if post_id is not None: # User wants to edit a post .. try: post_obj = Post.allobjects.get(pk=post_id) except Post.DoesNotExist: raise Http404 if not post_obj.allowEditing(): raise PermissionDenied() thread = post_obj.thread category = post_obj.category else: # User wants to create a new post (thread or reply) if 'thread' in request.REQUEST: thread_id = request.REQUEST['thread'] if thread_id is not None: # User is posting (replying) to a thread. try: thread = Post.allobjects.get(pk=thread_id) except Post.DoesNotExist: raise Http404 category = thread.category if not thread.allowPosting(request.user): raise PermissionDenied() else: # User is creating a new thread. category = get_object_or_404(Category, pk=category_id) if not category.allowPostThread(request.user): raise PermissionDenied() context['thread'] = thread context['category'] = category category_type = category.get_category_type() MyPostForm = PostForm if category_type is not None: MyPostForm = category_type.get_post_form_class(thread, post_obj) allow_attachments = get_sph_setting('board_allow_attachments') allowedattachments = 0 if allow_attachments: allowedattachments = 1 # bool is a subclass of int (hehe) if isinstance(allow_attachments, int) and type(allow_attachments) != bool: allowedattachments = allow_attachments PostAttachmentFormSet = modelformset_factory(PostAttachment, form=PostAttachmentForm, fields=('fileupload', ), can_delete=True, max_num=allowedattachments) post_attachment_qs = PostAttachment.objects.none() if post_obj: post_attachment_qs = post_obj.attachments.all() if request.method == 'POST': postForm = MyPostForm(request.POST) postForm.init_for_category_type(category_type, post_obj) pollForm = PostPollForm(request.POST) create_post = True if allowedattachments and 'cmd_addfile' in request.POST: create_post = False post_attachment_formset = PostAttachmentFormSet( request.POST, request.FILES, queryset=post_attachment_qs, prefix='attachment') if post_attachment_formset.is_valid(): instances = post_attachment_formset.save(commit=False) for attachment in instances: if not post_obj: # if there is no post yet.. we need to create a draft post_obj = Post( category=category, author=request.user, thread=thread, is_hidden=1, ) post_obj.set_new(True) post_obj.save() # Reference the post and save the attachment attachment.post = post_obj attachment.save() if create_post \ and postForm.is_valid() \ and ('createpoll' not in request.POST \ or pollForm.is_valid()): data = postForm.cleaned_data if post_obj: newpost = post_obj newpost.subject = data['subject'] newpost.body = data['body'] # make post visible newpost.is_hidden = 0 if not post_obj.is_new( ) and category_type.append_edit_message_to_post(post_obj): newpost.body += "\n\n" + _( u'--- Last Edited by %(username)s at %(edit_date)s ---' ) % { 'username': get_user_displayname(request.user), 'edit_date': format_date(timezone.now()) } else: user = request.user.is_authenticated() and request.user or None newpost = Post( category=category, subject=data['subject'], body=data['body'], author=user, thread=thread, ) if 'markup' in data: newpost.markup = data['markup'] elif len(POST_MARKUP_CHOICES) == 1: newpost.markup = POST_MARKUP_CHOICES[0][0] newpost.save(additional_data=data) #category_type.save_post( newpost, data ) # Creating monitor if request.POST.get('addmonitor', False): newpost.toggle_monitor() if 'createpoll' in request.POST and request.POST[ 'createpoll'] == '1': newpost.set_poll(True) newpost.save() # Creating poll... polldata = pollForm.cleaned_data newpoll = Poll(post=newpost, question=polldata['question'], choices_per_user=polldata['choicesPerUser']) newpoll.save() choices = polldata['answers'].splitlines() i = 0 for choice in choices: pollchoice = PollChoice(poll=newpoll, choice=choice, count=0, sortorder=i) i += 1 pollchoice.save() if request.user.is_authenticated(): messages.success( request, message=ugettext(u'Vote created successfully.')) if request.user.is_authenticated(): if post_obj: messages.success( request, message=ugettext(u'Post edited successfully.')) else: messages.success( request, message=ugettext(u'Post created successfully.')) if thread == None: thread = newpost return HttpResponseRedirect(newpost.get_absolute_url()) else: postForm = MyPostForm() postForm.init_for_category_type(category_type, post_obj) pollForm = PostPollForm() post_attachment_formset = PostAttachmentFormSet( queryset=post_attachment_qs, prefix='attachment') if post_obj: postForm.fields['subject'].initial = post_obj.subject postForm.fields['body'].initial = post_obj.body if 'markup' in postForm.fields: postForm.fields['markup'].initial = post_obj.markup context['post'] = post_obj context['thread'] = post_obj.thread or post_obj elif 'quote' in request.REQUEST: quotepost = get_object_or_404(Post, pk=request.REQUEST['quote']) postForm.fields['subject'].initial = 'Re: %s' % thread.subject if quotepost.author == None: username = '******' else: username = quotepost.author.username postForm.fields['body'].initial = '[quote=%s;%s]\n%s\n[/quote]\n' % ( username, quotepost.id, quotepost.body) elif thread: postForm.fields['subject'].initial = 'Re: %s' % thread.subject context['form'] = postForm # Only allow polls if this is a new _thread_ (not a reply) if (not thread and not post_obj) or (post_obj and post_obj.is_new() and post_obj.thread is None): context['pollform'] = pollForm context['post_attachment_formset'] = post_attachment_formset if 'createpoll' in request.REQUEST: context['createpoll'] = request.REQUEST['createpoll'] res = render_to_response("sphene/sphboard/post.html", context, context_instance=RequestContext(request)) # Maybe the user is in the 'edit' form, which should not be cached. res.sph_lastmodified = True return res