Fixes #2167
[redakcja.git] / apps / wiki / views.py
1 from datetime import datetime
2 import os
3 import logging
4
5 from django.conf import settings
6 from django.core.urlresolvers import reverse
7 from django import http
8 from django.http import Http404, HttpResponseForbidden
9 from django.middleware.gzip import GZipMiddleware
10 from django.utils.decorators import decorator_from_middleware
11 from django.utils.encoding import smart_unicode
12 from django.utils.formats import localize
13 from django.utils.translation import ugettext as _
14 from django.views.decorators.http import require_POST, require_GET
15 from django.shortcuts import get_object_or_404, render
16
17 from catalogue.models import Book, Chunk
18 import nice_diff
19 from wiki import forms
20 from wiki.helpers import (JSONResponse, JSONFormInvalid, JSONServerError,
21                 ajax_require_permission)
22 from wiki.models import Theme
23
24 #
25 # Quick hack around caching problems, TODO: use ETags
26 #
27 from django.views.decorators.cache import never_cache
28
29 logger = logging.getLogger("fnp.wiki")
30
31 MAX_LAST_DOCS = 10
32
33
34 @never_cache
35 def editor(request, slug, chunk=None, template_name='wiki/document_details.html'):
36     try:
37         chunk = Chunk.get(slug, chunk)
38     except Chunk.MultipleObjectsReturned:
39         # TODO: choice page
40         raise Http404
41     except Chunk.DoesNotExist:
42         if chunk is None:
43             try:
44                 book = Book.objects.get(slug=slug)
45             except Book.DoesNotExist:
46                 return http.HttpResponseRedirect(reverse("catalogue_create_missing", args=[slug]))
47         else:
48             raise Http404
49     if not chunk.book.accessible(request):
50         return HttpResponseForbidden("Not authorized.")
51
52     access_time = datetime.now()
53     last_books = request.session.get("wiki_last_books", {})
54     last_books[slug, chunk.slug] = {
55         'time': access_time,
56         'title': chunk.pretty_name(),
57         }
58
59     if len(last_books) > MAX_LAST_DOCS:
60         oldest_key = min(last_books, key=lambda x: last_books[x]['time'])
61         del last_books[oldest_key]
62     request.session['wiki_last_books'] = last_books
63
64     return render(request, template_name, {
65         'chunk': chunk,
66         'forms': {
67             "text_save": forms.DocumentTextSaveForm(user=request.user, prefix="textsave"),
68             "text_revert": forms.DocumentTextRevertForm(prefix="textrevert"),
69             "pubmark": forms.DocumentPubmarkForm(prefix="pubmark"),
70         },
71         'can_pubmark': request.user.has_perm('catalogue.can_pubmark'),
72         'REDMINE_URL': settings.REDMINE_URL,
73     })
74
75
76 @require_GET
77 def editor_readonly(request, slug, chunk=None, template_name='wiki/document_details_readonly.html'):
78     try:
79         chunk = Chunk.get(slug, chunk)
80         revision = request.GET['revision']
81     except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist, KeyError):
82         raise Http404
83     if not chunk.book.accessible(request):
84         return HttpResponseForbidden("Not authorized.")
85
86     access_time = datetime.now()
87     last_books = request.session.get("wiki_last_books", {})
88     last_books[slug, chunk.slug] = {
89         'time': access_time,
90         'title': chunk.book.title,
91         }
92
93     if len(last_books) > MAX_LAST_DOCS:
94         oldest_key = min(last_books, key=lambda x: last_books[x]['time'])
95         del last_books[oldest_key]
96     request.session['wiki_last_books'] = last_books
97
98     return render(request, template_name, {
99         'chunk': chunk,
100         'revision': revision,
101         'readonly': True,
102         'REDMINE_URL': settings.REDMINE_URL,
103     })
104
105
106 @never_cache
107 @decorator_from_middleware(GZipMiddleware)
108 def text(request, chunk_id):
109     doc = get_object_or_404(Chunk, pk=chunk_id)
110     if not doc.book.accessible(request):
111         return HttpResponseForbidden("Not authorized.")
112
113     if request.method == 'POST':
114         form = forms.DocumentTextSaveForm(request.POST, user=request.user, prefix="textsave")
115         if form.is_valid():
116             if request.user.is_authenticated():
117                 author = request.user
118             else:
119                 author = None
120             text = form.cleaned_data['text']
121             parent_revision = form.cleaned_data['parent_revision']
122             if parent_revision is not None:
123                 parent = doc.at_revision(parent_revision)
124             else:
125                 parent = None
126             stage = form.cleaned_data['stage_completed']
127             tags = [stage] if stage else []
128             publishable = (form.cleaned_data['publishable'] and
129                     request.user.has_perm('catalogue.can_pubmark'))
130             doc.commit(author=author,
131                        text=text,
132                        parent=parent,
133                        description=form.cleaned_data['comment'],
134                        tags=tags,
135                        author_name=form.cleaned_data['author_name'],
136                        author_email=form.cleaned_data['author_email'],
137                        publishable=publishable,
138                        )
139             revision = doc.revision()
140             return JSONResponse({
141                 'text': doc.materialize() if parent_revision != revision else None,
142                 'meta': {},
143                 'revision': revision,
144             })
145         else:
146             return JSONFormInvalid(form)
147     else:
148         revision = request.GET.get("revision", None)
149         
150         try:
151             revision = int(revision)
152         except (ValueError, TypeError):
153             revision = doc.revision()
154
155         if revision is not None:
156             text = doc.at_revision(revision).materialize()
157         else:
158             text = ''
159
160         return JSONResponse({
161             'text': text,
162             'meta': {},
163             'revision': revision,
164         })
165
166
167 @never_cache
168 @require_POST
169 def revert(request, chunk_id):
170     form = forms.DocumentTextRevertForm(request.POST, prefix="textrevert")
171     if form.is_valid():
172         doc = get_object_or_404(Chunk, pk=chunk_id)
173         if not doc.book.accessible(request):
174             return HttpResponseForbidden("Not authorized.")
175
176         revision = form.cleaned_data['revision']
177
178         comment = form.cleaned_data['comment']
179         comment += "\n#revert to %s" % revision
180
181         if request.user.is_authenticated():
182             author = request.user
183         else:
184             author = None
185
186         before = doc.revision()
187         logger.info("Reverting %s to %s", chunk_id, revision)
188         doc.at_revision(revision).revert(author=author, description=comment)
189
190         return JSONResponse({
191             'text': doc.materialize() if before != doc.revision() else None,
192             'meta': {},
193             'revision': doc.revision(),
194         })
195     else:
196         return JSONFormInvalid(form)
197
198
199 @never_cache
200 def gallery(request, directory):
201     try:
202         base_url = ''.join((
203                         smart_unicode(settings.MEDIA_URL),
204                         smart_unicode(settings.IMAGE_DIR),
205                         smart_unicode(directory)))
206
207         base_dir = os.path.join(
208                     smart_unicode(settings.MEDIA_ROOT),
209                     smart_unicode(settings.IMAGE_DIR),
210                     smart_unicode(directory))
211
212         def map_to_url(filename):
213             return "%s/%s" % (base_url, smart_unicode(filename))
214
215         def is_image(filename):
216             return os.path.splitext(f)[1].lower() in (u'.jpg', u'.jpeg', u'.png')
217
218         images = [map_to_url(f) for f in map(smart_unicode, os.listdir(base_dir)) if is_image(f)]
219         images.sort()
220
221         if not request.user.is_authenticated():
222             return HttpResponseForbidden("Not authorized.")
223
224         return JSONResponse(images)
225     except (IndexError, OSError):
226         logger.exception("Unable to fetch gallery")
227         raise http.Http404
228
229
230 @never_cache
231 def diff(request, chunk_id):
232     revA = int(request.GET.get('from', 0))
233     revB = int(request.GET.get('to', 0))
234
235     if revA > revB:
236         revA, revB = revB, revA
237
238     if revB == 0:
239         revB = None
240
241     doc = get_object_or_404(Chunk, pk=chunk_id)
242     if not doc.book.accessible(request):
243         return HttpResponseForbidden("Not authorized.")
244
245     # allow diff from the beginning
246     if revA:
247         docA = doc.at_revision(revA).materialize()
248     else:
249         docA = ""
250     docB = doc.at_revision(revB).materialize()
251
252     return http.HttpResponse(nice_diff.html_diff_table(docA.splitlines(),
253                                          docB.splitlines(), context=3))
254
255
256 @never_cache
257 def revision(request, chunk_id):
258     doc = get_object_or_404(Chunk, pk=chunk_id)
259     if not doc.book.accessible(request):
260         return HttpResponseForbidden("Not authorized.")
261     return http.HttpResponse(str(doc.revision()))
262
263
264 @never_cache
265 def history(request, chunk_id):
266     # TODO: pagination
267     doc = get_object_or_404(Chunk, pk=chunk_id)
268     if not doc.book.accessible(request):
269         return HttpResponseForbidden("Not authorized.")
270
271     changes = []
272     for change in doc.history().reverse():
273         changes.append({
274                 "version": change.revision,
275                 "description": change.description,
276                 "author": change.author_str(),
277                 "date": localize(change.created_at),
278                 "publishable": _("Publishable") + "\n" if change.publishable else "",
279                 "tag": ',\n'.join(unicode(tag) for tag in change.tags.all()),
280             })
281     return JSONResponse(changes)
282
283
284 @require_POST
285 @ajax_require_permission('catalogue.can_pubmark')
286 def pubmark(request, chunk_id):
287     form = forms.DocumentPubmarkForm(request.POST, prefix="pubmark")
288     if form.is_valid():
289         doc = get_object_or_404(Chunk, pk=chunk_id)
290         if not doc.book.accessible(request):
291             return HttpResponseForbidden("Not authorized.")
292
293         revision = form.cleaned_data['revision']
294         publishable = form.cleaned_data['publishable']
295         change = doc.at_revision(revision)
296         if publishable != change.publishable:
297             change.set_publishable(publishable)
298             return JSONResponse({"message": _("Revision marked")})
299         else:
300             return JSONResponse({"message": _("Nothing changed")})
301     else:
302         return JSONFormInvalid(form)
303
304
305 def themes(request):
306     prefix = request.GET.get('q', '')
307     return http.HttpResponse('\n'.join([str(t) for t in Theme.objects.filter(name__istartswith=prefix)]))