1 # -*- coding: utf-8 -*-
2 from datetime import datetime
5 from time import mktime
8 from django.conf import settings
9 from django.core.urlresolvers import reverse
10 from django import http
11 from django.http import Http404, HttpResponseForbidden
12 from django.middleware.gzip import GZipMiddleware
13 from django.utils.decorators import decorator_from_middleware
14 from django.utils.encoding import smart_unicode
15 from django.utils.formats import localize
16 from django.utils.translation import ugettext as _
17 from django.views.decorators.http import require_POST, require_GET
18 from django.shortcuts import get_object_or_404, render
20 from catalogue.models import Book, Chunk
22 from wiki import forms
23 from wiki.helpers import (JSONResponse, JSONFormInvalid, JSONServerError,
24 ajax_require_permission)
25 from wiki.models import Theme
28 # Quick hack around caching problems, TODO: use ETags
30 from django.views.decorators.cache import never_cache
32 logger = logging.getLogger("fnp.wiki")
38 def editor(request, slug, chunk=None, template_name='wiki/document_details.html'):
40 chunk = Chunk.get(slug, chunk)
41 except Chunk.MultipleObjectsReturned:
44 except Chunk.DoesNotExist:
47 book = Book.objects.get(slug=slug)
48 except Book.DoesNotExist:
49 return http.HttpResponseRedirect(reverse("catalogue_create_missing", args=[slug]))
52 if not chunk.book.accessible(request):
53 return HttpResponseForbidden("Not authorized.")
55 access_time = datetime.now()
56 last_books = request.session.get("wiki_last_books", {})
57 last_books[reverse(editor, args=[chunk.book.slug, chunk.slug])] = {
58 'time': mktime(access_time.timetuple()),
59 'title': chunk.pretty_name(),
62 if len(last_books) > MAX_LAST_DOCS:
63 oldest_key = min(last_books, key=lambda x: last_books[x]['time'])
64 del last_books[oldest_key]
65 request.session['wiki_last_books'] = last_books
67 return render(request, template_name, {
70 "text_save": forms.DocumentTextSaveForm(user=request.user, prefix="textsave"),
71 "text_revert": forms.DocumentTextRevertForm(prefix="textrevert"),
72 "pubmark": forms.DocumentPubmarkForm(prefix="pubmark"),
74 'can_pubmark': request.user.has_perm('catalogue.can_pubmark'),
75 'REDMINE_URL': settings.REDMINE_URL,
80 def editor_readonly(request, slug, chunk=None, template_name='wiki/document_details_readonly.html'):
82 chunk = Chunk.get(slug, chunk)
83 revision = request.GET['revision']
84 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist, KeyError):
86 if not chunk.book.accessible(request):
87 return HttpResponseForbidden("Not authorized.")
89 access_time = datetime.now()
90 last_books = request.session.get("wiki_last_books", {})
91 last_books[slug, chunk.slug] = {
92 'time': mktime(access_time.timetuple()),
93 'title': chunk.book.title,
96 if len(last_books) > MAX_LAST_DOCS:
97 oldest_key = min(last_books, key=lambda x: last_books[x]['time'])
98 del last_books[oldest_key]
99 request.session['wiki_last_books'] = last_books
101 return render(request, template_name, {
103 'revision': revision,
105 'REDMINE_URL': settings.REDMINE_URL,
110 @decorator_from_middleware(GZipMiddleware)
111 def text(request, chunk_id):
112 doc = get_object_or_404(Chunk, pk=chunk_id)
113 if not doc.book.accessible(request):
114 return HttpResponseForbidden("Not authorized.")
116 if request.method == 'POST':
117 form = forms.DocumentTextSaveForm(request.POST, user=request.user, prefix="textsave")
119 if request.user.is_authenticated():
120 author = request.user
123 text = form.cleaned_data['text']
124 parent_revision = form.cleaned_data['parent_revision']
125 if parent_revision is not None:
126 parent = doc.at_revision(parent_revision)
129 stage = form.cleaned_data['stage_completed']
130 tags = [stage] if stage else []
131 publishable = (form.cleaned_data['publishable'] and
132 request.user.has_perm('catalogue.can_pubmark'))
133 doc.commit(author=author,
136 description=form.cleaned_data['comment'],
138 author_name=form.cleaned_data['author_name'],
139 author_email=form.cleaned_data['author_email'],
140 publishable=publishable,
142 revision = doc.revision()
143 return JSONResponse({
144 'text': doc.materialize() if parent_revision != revision else None,
146 'revision': revision,
149 return JSONFormInvalid(form)
151 revision = request.GET.get("revision", None)
154 revision = int(revision)
155 except (ValueError, TypeError):
156 revision = doc.revision()
158 if revision is not None:
159 text = doc.at_revision(revision).materialize()
163 return JSONResponse({
166 'revision': revision,
172 def revert(request, chunk_id):
173 form = forms.DocumentTextRevertForm(request.POST, prefix="textrevert")
175 doc = get_object_or_404(Chunk, pk=chunk_id)
176 if not doc.book.accessible(request):
177 return HttpResponseForbidden("Not authorized.")
179 revision = form.cleaned_data['revision']
181 comment = form.cleaned_data['comment']
182 comment += "\n#revert to %s" % revision
184 if request.user.is_authenticated():
185 author = request.user
189 before = doc.revision()
190 logger.info("Reverting %s to %s", chunk_id, revision)
191 doc.at_revision(revision).revert(author=author, description=comment)
193 return JSONResponse({
194 'text': doc.materialize() if before != doc.revision() else None,
196 'revision': doc.revision(),
199 return JSONFormInvalid(form)
203 def gallery(request, directory):
206 smart_unicode(settings.MEDIA_URL),
207 smart_unicode(settings.IMAGE_DIR),
208 smart_unicode(directory)))
210 base_dir = os.path.join(
211 smart_unicode(settings.MEDIA_ROOT),
212 smart_unicode(settings.IMAGE_DIR),
213 smart_unicode(directory))
215 def map_to_url(filename):
216 return urllib.quote(("%s/%s" % (base_url, smart_unicode(filename))).encode('utf-8'))
218 def is_image(filename):
219 return os.path.splitext(filename)[1].lower() in (u'.jpg', u'.jpeg', u'.png')
221 images = [map_to_url(f) for f in map(smart_unicode, os.listdir(base_dir)) if is_image(f)]
224 books = Book.objects.filter(gallery=directory)
226 if not all(book.public for book in books) and not request.user.is_authenticated():
227 return HttpResponseForbidden("Not authorized.")
229 return JSONResponse(images)
230 except (IndexError, OSError):
231 logger.exception("Unable to fetch gallery")
236 def diff(request, chunk_id):
237 revA = int(request.GET.get('from', 0))
238 revB = int(request.GET.get('to', 0))
241 revA, revB = revB, revA
246 doc = get_object_or_404(Chunk, pk=chunk_id)
247 if not doc.book.accessible(request):
248 return HttpResponseForbidden("Not authorized.")
250 # allow diff from the beginning
252 docA = doc.at_revision(revA).materialize()
255 docB = doc.at_revision(revB).materialize()
257 return http.HttpResponse(nice_diff.html_diff_table(docA.splitlines(),
258 docB.splitlines(), context=3))
262 def revision(request, chunk_id):
263 doc = get_object_or_404(Chunk, pk=chunk_id)
264 if not doc.book.accessible(request):
265 return HttpResponseForbidden("Not authorized.")
266 return http.HttpResponse(str(doc.revision()))
270 def history(request, chunk_id):
272 doc = get_object_or_404(Chunk, pk=chunk_id)
273 if not doc.book.accessible(request):
274 return HttpResponseForbidden("Not authorized.")
277 for change in doc.history().reverse():
279 "version": change.revision,
280 "description": change.description,
281 "author": change.author_str(),
282 "date": localize(change.created_at),
283 "publishable": _("Publishable") + "\n" if change.publishable else "",
284 "tag": ',\n'.join(unicode(tag) for tag in change.tags.all()),
285 "published": _("Published") + ": " + \
286 localize(change.publish_log.order_by('-book_record__timestamp')[0].book_record.timestamp) \
287 if change.publish_log.exists() else "",
289 return JSONResponse(changes)
293 @ajax_require_permission('catalogue.can_pubmark')
294 def pubmark(request, chunk_id):
295 form = forms.DocumentPubmarkForm(request.POST, prefix="pubmark")
297 doc = get_object_or_404(Chunk, pk=chunk_id)
298 if not doc.book.accessible(request):
299 return HttpResponseForbidden("Not authorized.")
301 revision = form.cleaned_data['revision']
302 publishable = form.cleaned_data['publishable']
303 change = doc.at_revision(revision)
304 if publishable != change.publishable:
305 change.set_publishable(publishable)
306 return JSONResponse({"message": _("Revision marked")})
308 return JSONResponse({"message": _("Nothing changed")})
310 return JSONFormInvalid(form)
314 prefix = request.GET.get('q', '')
315 return http.HttpResponse('\n'.join([str(t) for t in Theme.objects.filter(name__istartswith=prefix)]))