# -*- coding: utf-8 -*- import os from datetime import datetime, date, time from django.shortcuts import render from django.contrib.auth import authenticate, login, logout from django.http import HttpResponseRedirect, HttpResponse, Http404 from django.contrib.auth.decorators import login_required from django.views.decorators.csrf import csrf_exempt from django.forms.models import inlineformset_factory from django.core import mail from django.core.mail import EmailMultiAlternatives from dynastie.models import * from dynastie.forms import * from django.template.defaultfilters import register from django.template import Variable, VariableDoesNotExist @register.filter def hash(object, attr): pseudo_context = { 'object' : object } try: value = Variable('object.%s' % attr).resolve(pseudo_context) except VariableDoesNotExist: value = None return value def have_I_right(request, blog_id=None, post_id=None, must_be_superuser=False): b = None p = None if must_be_superuser and not request.user.is_superuser: raise Http404 if not post_id is None: p = Post.objects.get(pk=post_id) if p is None: raise Http404 blog_id = p.blog.id if not blog_id is None: if not request.user.is_superuser: b = Blog.objects.filter(pk=blog_id).filter(writers=request.user.id) if len(b) == 0: raise Http404 b = b[0] else: b = Blog.objects.get(pk=post.blog.id) if b is None: raise Http404 return (b, p) def index(request): if request.user.is_authenticated(): return HttpResponseRedirect('/blog') login_failed = False if 'login' in request.POST: user = authenticate(username=request.POST['login'], password=request.POST['password']) if user is None: login_failed = True else: login(request, user) if 'next' in request.GET: return HttpResponseRedirect(request.GET['next']) else: return HttpResponseRedirect('/blog') c = {'auth_key': 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA',\ 'login_failed' : login_failed} return render(request, 'templates/login.html', c) def disconnect(request): logout(request) c = {'auth_key': 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA',\ 'login_failed' : False} return HttpResponseRedirect('/') @login_required def user(request): users = User.objects.all() c = {'users' : users} return render(request, 'templates/user.html', c) @login_required def add_user(request): if not request.user.is_superuser: return HttpResponseRedirect('/user') if request.method == 'POST': # If the form has been submitted... if 'add' in request.POST: form = UserForm(request.POST) # A form bound to the POST data if form.is_valid(): # All validation rules pass form = form.save() user = User.objects.get(pk=form.id) user.set_password(request.POST['password']) user.save() # Process the data in form.cleaned_data # ... return HttpResponseRedirect('/user') # Redirect after POST else: return HttpResponseRedirect('/user') # Redirect after POST else: form = UserForm() # An unbound form return render(request, 'add_user.html', { 'form': form, }) @login_required def edit_user(request, user_id): user = User.objects.get(pk=user_id) if user is None: raise Http404 edited = False if request.method == 'POST': # If the form has been submitted... if int(user_id) != int(request.user.id) and (not request.user.is_superuser): return HttpResponseRedirect('/user/' + str(user_id)) if 'edit' in request.POST: form = UserForm(request.POST, instance=user, initial={'password':''}) # A form bound to the POST data if form.is_valid(): # All validation rules pass form.save() if request.POST['password'] != '': user.set_password(request.POST['password']) user.save() edited = True else: if 'delete' in request.POST and request.user.is_superuser: User.objects.get(pk=user_id).delete() return HttpResponseRedirect('/user') if 'cancel' in request.POST: return HttpResponseRedirect('/user') else: form = UserForm(instance=user, initial={'password':''}) # An unbound form c = {'user_to_edit' : user, 'form' : form, 'edited' : edited} return render(request, 'templates/edit_user.html', c) @login_required def category(request, blog_id): b = have_I_right(request, blog_id) categories = Category.objects.filter(blog_id=blog_id) c = {'categories' : categories} return render(request, 'templates/category.html', c) @login_required def add_category(request, blog_id): b = have_I_right(request, blog_id)[0] if request.method == 'POST': # If the form has been submitted... if 'add' in request.POST: form = CategoryForm(request.POST) # A form bound to the POST data form.blog = b if form.is_valid(): # All validation rules pass form = form.save() # Process the data in form.cleaned_data # ... return HttpResponseRedirect('/category/' + str(b.id)) else: return HttpResponseRedirect('/category/' + str(b.id)) else: form = CategoryForm() # An unbound form return render(request, 'add_category.html', { 'form': form, }) @login_required def edit_category(request, category_id): category = Category.objects.get(pk=category_id) if category is None: raise Http404 b = have_I_right(request, category.blog.id)[0] if request.method == 'POST': # If the form has been submitted... if 'cancel' in request.POST: return HttpResponseRedirect('/category' + str(b.id)) if 'edit' in request.POST: name = category.name form = CategoryForm(request.POST, instance=category) # A form bound to the POST data if form.is_valid(): # All validation rules pass if request.POST['name'] != name: category.remove() form.save() return HttpResponseRedirect('/category/' + str(b.id)) else: form = CategoryForm(instance=category) # An unbound form c = {'category' : category, 'form' : form} return render(request, 'templates/edit_category.html', c) @login_required def delete_category(request, category_id): category = Category.objects.get(pk=category_id) if category is None: raise Http404 b = have_I_right(request, category.blog.id)[0] category.remove() category.delete() return HttpResponseRedirect('/category/' + str(b.id)) @login_required def blog(request): if request.user.is_superuser: b = Blog.objects.all() else: b = Blog.objects.filter(writers=request.user.id) c = {'blogs' : b} return render(request, 'templates/blog.html', c) @login_required def add_blog(request): if not request.user.is_superuser: return HttpResponseRedirect('/blog') if request.method == 'POST': # If the form has been submitted... if 'add' in request.POST: form = BlogForm(request.POST) # A form bound to the POST data if form.is_valid(): # All validation rules pass form = form.save() form.create() return HttpResponseRedirect('/blog') # Redirect after POST else: return HttpResponseRedirect('/blog') # Redirect after POST else: form = BlogForm() # An unbound form return render(request, 'add_blog.html', { 'form': form, }) @login_required def view_blog(request, blog_id): if not request.user.is_superuser: b = Blog.objects.filter(id=blog_id).filter(writers=request.user.id) else: b = Blog.objects.get(pk=blog_id) if b is None: raise Http404 posts = Post.objects.filter(blog=b).order_by('-creation_date') b = Blog.objects.get(pk=blog_id) form = BlogForm(instance=b) comments = Comment.objects.all() dict_comments = {} for comment in comments: key = comment.post.id if not key in dict_comments: dict_comments[key] = 1 else: dict_comments[key] = dict_comments[key] + 1 c = {'blog' : b, 'posts' : posts, 'form' : form, 'comments' : dict_comments} return render(request, 'templates/view_blog.html', c) @login_required def edit_blog(request, blog_id): if not request.user.is_superuser: return HttpResponseRedirect('/blog/' + str(blog_id)) b = Blog.objects.get(pk=blog_id) if b is None: raise Http404 if request.method == 'POST': # If the form has been submitted... if 'edit' in request.POST: form = BlogForm(request.POST, instance=b) # A form bound to the POST data if form.is_valid(): # All validation rules pass form.save() else: if 'delete' in request.POST: b = Blog.objects.get(pk=blog_id) b.delete() return HttpResponseRedirect('/blog') else: form = BlogForm(instance=b) # An unbound form posts = Post.objects.filter(blog=b).order_by('-creation_date') c = {'blog' : b, 'posts' : posts, 'form' : form} return render(request, 'templates/view_blog.html', c) @login_required def add_post(request, blog_id): (b,) = have_I_right(request, blog_id) if request.method == 'POST': # If the form has been submitted... if 'add' in request.POST: post = Post(blog=Blog.objects.get(pk=blog_id), author=User.objects.get(pk=request.user.id), creation_date=datetime.now(), modification_date=datetime.now()) content = request.POST['content'] # del request.POST['content'] form = PostForm(request.POST, instance=post) # A form bound to the POST data if form.is_valid(): # All validation rules pass form = form.save() form.createPost(content) # Process the data in form.cleaned_data # ... return HttpResponseRedirect('/blog/' + blog_id) # Redirect after POST else: return HttpResponseRedirect('/blog/' + blog_id) # Redirect after POST else: form = PostForm() # An unbound form return render(request, 'add_post.html', { 'form': form, 'blog_id' : blog_id }) @login_required def edit_post(request, post_id): (b, post) = have_I_right(request, None, post_id) post = Post.objects.get(pk=post_id) title = post.title blog_id = b.id if request.method == 'POST': # If the form has been submitted... if 'edit' in request.POST: post.modification_date = datetime.now() form = PostForm(request.POST, instance=post) # A form bound to the POST data if form.is_valid(): # All validation rules pass if title != request.POST['title']: post.remove() form.save() post.createPost(request.POST['content']) # Process the data in form.cleaned_data # ... return HttpResponseRedirect('/blog/' + str(blog_id)) # Redirect after POST else: if 'cancel' in request.POST: return HttpResponseRedirect('/blog/' + str(blog_id)) # Redirect after POST else: form = PostForm(instance=post) # An unbound form b.create_paths() filename = b.src_path + '/_post/' + str(post.pk) if os.path.exists(filename): f = open(filename, 'rb') content = f.read() f.close() else: content = 'Empty post' comments = Comment.objects.filter(post=post).order_by('date') comment_list = [] for comment in comments: comment_list.append(comment) return render(request, 'edit_post.html', { 'form': form, 'post_id' : post_id, 'content' : content, 'blog_id' : blog_id, 'comments' : comment_list }) @login_required def delete_post(request, post_id): (b, post) = have_I_right(request, None, post_id) blog_id = b.id post.delete() return HttpResponseRedirect('/blog/' + str(blog_id)) @login_required def generate(request, blog_id): (b, post) = have_I_right(request, blog_id) b.create_paths() report = b.generate() posts = Post.objects.filter(blog=b).order_by('-creation_date') b = Blog.objects.get(pk=blog_id) form = BlogForm(instance=b) comments = Comment.objects.all() dict_comments = {} for comment in comments: key = comment.post.id if not key in dict_comments: dict_comments[key] = 1 else: dict_comments[key] = dict_comments[key] + 1 c = {'blog' : b, 'posts' : posts, 'form' : form, 'report': report, 'comments' : dict_comments} return render(request, 'templates/generate.html', c) @login_required def preview(request, blog_id): from dynastie.generators import post values = {'title' : request.POST['title'], \ 'author' : request.user.first_name + ' ' + request.user.last_name, \ 'content' : request.POST['content'] } (b, ) = have_I_right(request, blog_id) b.create_paths() engine = globals()['post'] for name, obj in inspect.getmembers(engine): if inspect.isclass(obj) and obj.__module__.startswith("dynastie.generators") \ and obj.__module__.endswith("post"): e = obj() content = e.preview(b.src_path, values) break output = b.output_path path = output + '/preview.html' if os.path.exists(path): os.unlink(path) f = open(path, 'wb') f.write(content) f.close() c = {'content' : content} return HttpResponseRedirect('http://' + b.name + '/preview.html') # return HttpResponseRedirect('http://' + 'localhost:8080' + '/preview.html') def _tinymcelist(request, b, year, month): ret = 'var tinyMCEImageList = new Array(' b.create_paths() if month < 10: suffix = '/images/' + str(year) + '/0' + str(month) else: suffix = '/images/' + str(year) + '/' + str(month) path = b.src_path + '/' + suffix # url = 'http://' + 'localhost:8080' + '/' + suffix + '/' url = 'http://' + b.name + '/' + suffix + '/' if os.path.exists(path): files = '' for p in os.listdir(path): files += '["' + p + '", "' + url + p + '"],' # Remove last comma if len(files) != 0: ret += files[:-1] ret += ');' return ret @login_required def tinymcelist_add(request, blog_id): now = datetime.now() year = now.year month = now.month try: (b, ) = have_I_right(request, blog_id) except Http404: return HttpResponse('', content_type='application/x-javascript') ret = _tinymcelist(request, b, year, month) return HttpResponse(ret, content_type='application/x-javascript') @login_required def tinymcelist_edit(request, post_id): try: (b, post) = have_I_right(request, None, post_id) except Http404: return HttpResponse('', content_type='application/x-javascript') year = post.creation_date.year() month = post.creation_date.month() ret = _tinymcelist(request, b, year, month) return HttpResponse(ret, content_type='application/x-javascript') @csrf_exempt def add_comment(request, post_id, parent_id): from dynastie.generators import post ref = request.META['HTTP_REFERER'] post = Post.objects.get(pk=post_id) if post is None: print 'no post' return HttpResponseRedirect(ref) blog = Blog.objects.get(pk=post.blog_id) if blog is None: print 'no blog ' + str(post.blog.id) return HttpResponseRedirect(ref) parent_id = int(parent_id) if parent_id != 0: parentComment = Comment.objects.get(pk=parent_id) if parentComment is None: return HttpResponseRedirect(ref) else: parentComment = None if request.POST['author'] == '' or request.POST['the_comment'] == '': print 'Error on author or the_comment' return HttpResponseRedirect(ref) comment = Comment(post=post, parent=parentComment, date=datetime.now(), author=request.POST['author'],\ email=request.POST['email'], the_comment=request.POST['the_comment'], ip=request.META['REMOTE_ADDR']) comment.save() engine = globals()['post'] blog.create_paths() post_list = [post] for name, obj in inspect.getmembers(engine): if inspect.isclass(obj) and obj.__module__.startswith("dynastie.generators") \ and obj.__module__.endswith("post"): e = obj() content = e._generate(blog, blog.src_path, blog.output_path, post_list) break # Send emails emails = {} comments = Comment.objects.filter(post=post).order_by('date') comment_index = str(len(comments)) for comment in comments: email = comment.email if email != '' and email != request.POST['email'] and not email in emails: emails[email] = comment.author if len(emails) > 0: connection = mail.get_connection(fail_silently=True) connection.open() messages = [] subject = '[%s] Nouveau commentaire pour l\'article "%s"' % (blog.name, post.title) for email,author in emails.items(): text_body = u'Bonjour %s,\n\nUn nouveau commentaire a été posté pour l\'article "%s".\n\n' % (author, post.title) text_body += u'Pour le consulter, rendez vous sur http://%s%s/#comment_%s\n\n----------------\n\n' % (blog.name, post.getPath(), comment_index) text_body += comment.the_comment text_body += '\n' html_body = u'' html_body += u'Bonjour %s,

Un nouveau commentaire a été posté pour l\'article "%s".

' % (author, post.title) html_body = html_body + u'Pour le consulter, rendez vous sur http://%s%s#comment_%s

----------------
'  % (blog.name, post.getPath(), comment_index, blog.name, post.getPath(), comment_index)
            c = comment.the_comment
            # Avoid script injection
            c = c.replace('
', '<pre>')
            c = c.replace('
', '</pre>') html_body += c + '
' html_body += '' msg = EmailMultiAlternatives(subject, text_body, 'no-reply@%s' % blog.name , [email]) msg.attach_alternative(html_body, "text/html") messages.append(msg) connection.send_messages(messages) connection.close() response = HttpResponseRedirect(ref) response.set_cookie('author', request.POST['author'], domain=blog.name, secure=True, httponly=False); if request.POST['email'] != '': response.set_cookie('email', request.POST['email'], domain=blog.name, secure=True, httponly=False); return response @login_required def edit_comment(request, comment_id): comment = Comment.objects.get(pk=comment_id) if comment is None: return Http404 (b, post) = have_I_right(request, None, comment.post_id) post_id = comment.post_id if request.method == 'POST': # If the form has been submitted... if 'edit' in request.POST: form = CommentForm(request.POST, instance=comment) # A form bound to the POST data if form.is_valid(): # All validation rules pass form = form.save() # Process the data in form.cleaned_data # ... return HttpResponseRedirect('/post/edit/' + str(post_id)) else: return HttpResponseRedirect('/post/edit/' + str(post_id)) else: form = CommentForm(instance=comment) # An unbound form return render(request, 'edit_comment.html', { 'form': form, 'comment':comment }) @login_required def delete_comment(request, comment_id): comment = Comment.objects.get(pk=comment_id) if comment is None: return Http404 (b, post) = have_I_right(request, None, comment.post_id) post_id = comment.post_id childs = Comment.objects.filter(parent=comment.id) try: parent = comment.parent except: parent = None for child in childs: child.parent = parent child.save() comment.delete() return HttpResponseRedirect('/post/edit/' + str(post_id))