1 from datetime import datetime
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.views.generic.simple import direct_to_template
16 from django.shortcuts import get_object_or_404
18 from catalogue.models import Book, Chunk
20 from wiki import forms
21 from wiki.helpers import (JSONResponse, JSONFormInvalid, JSONServerError,
22 ajax_require_permission)
23 from wiki.models import Theme
26 # Quick hack around caching problems, TODO: use ETags
28 from django.views.decorators.cache import never_cache
30 logger = logging.getLogger("fnp.wiki")
36 def editor(request, slug, chunk=None, template_name='wiki/document_details.html'):
38 chunk = Chunk.get(slug, chunk)
39 except Chunk.MultipleObjectsReturned:
42 except Chunk.DoesNotExist:
45 book = Book.objects.get(slug=slug)
46 except Book.DoesNotExist:
47 return http.HttpResponseRedirect(reverse("catalogue_create_missing", args=[slug]))
50 if not chunk.book.accessible(request):
51 return HttpResponseForbidden("Not authorized.")
53 access_time = datetime.now()
54 last_books = request.session.get("wiki_last_books", {})
55 last_books[slug, chunk.slug] = {
57 'title': chunk.pretty_name(),
60 if len(last_books) > MAX_LAST_DOCS:
61 oldest_key = min(last_books, key=lambda x: last_books[x]['time'])
62 del last_books[oldest_key]
63 request.session['wiki_last_books'] = last_books
65 return direct_to_template(request, template_name, extra_context={
68 "text_save": forms.DocumentTextSaveForm(user=request.user, prefix="textsave"),
69 "text_revert": forms.DocumentTextRevertForm(prefix="textrevert"),
70 "pubmark": forms.DocumentPubmarkForm(prefix="pubmark"),
72 'can_pubmark': request.user.has_perm('catalogue.can_pubmark'),
73 'REDMINE_URL': settings.REDMINE_URL,
78 def editor_readonly(request, slug, chunk=None, template_name='wiki/document_details_readonly.html'):
80 chunk = Chunk.get(slug, chunk)
81 revision = request.GET['revision']
82 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist, KeyError):
84 if not chunk.book.accessible(request):
85 return HttpResponseForbidden("Not authorized.")
87 access_time = datetime.now()
88 last_books = request.session.get("wiki_last_books", {})
89 last_books[slug, chunk.slug] = {
91 'title': chunk.book.title,
94 if len(last_books) > MAX_LAST_DOCS:
95 oldest_key = min(last_books, key=lambda x: last_books[x]['time'])
96 del last_books[oldest_key]
97 request.session['wiki_last_books'] = last_books
99 return direct_to_template(request, template_name, extra_context={
101 'revision': revision,
103 'REDMINE_URL': settings.REDMINE_URL,
108 @decorator_from_middleware(GZipMiddleware)
109 def text(request, chunk_id):
110 doc = get_object_or_404(Chunk, pk=chunk_id)
111 if not doc.book.accessible(request):
112 return HttpResponseForbidden("Not authorized.")
114 if request.method == 'POST':
115 form = forms.DocumentTextSaveForm(request.POST, user=request.user, prefix="textsave")
117 if request.user.is_authenticated():
118 author = request.user
121 text = form.cleaned_data['text']
122 parent_revision = form.cleaned_data['parent_revision']
123 if parent_revision is not None:
124 parent = doc.at_revision(parent_revision)
127 stage = form.cleaned_data['stage_completed']
128 tags = [stage] if stage else []
129 publishable = (form.cleaned_data['publishable'] and
130 request.user.has_perm('catalogue.can_pubmark'))
131 doc.commit(author=author,
134 description=form.cleaned_data['comment'],
136 author_name=form.cleaned_data['author_name'],
137 author_email=form.cleaned_data['author_email'],
138 publishable=publishable,
140 revision = doc.revision()
141 return JSONResponse({
142 'text': doc.materialize() if parent_revision != revision else None,
144 'revision': revision,
147 return JSONFormInvalid(form)
149 revision = request.GET.get("revision", None)
152 revision = int(revision)
153 except (ValueError, TypeError):
154 revision = doc.revision()
156 if revision is not None:
157 text = doc.at_revision(revision).materialize()
161 return JSONResponse({
164 'revision': revision,
170 def revert(request, chunk_id):
171 form = forms.DocumentTextRevertForm(request.POST, prefix="textrevert")
173 doc = get_object_or_404(Chunk, pk=chunk_id)
174 if not doc.book.accessible(request):
175 return HttpResponseForbidden("Not authorized.")
177 revision = form.cleaned_data['revision']
179 comment = form.cleaned_data['comment']
180 comment += "\n#revert to %s" % revision
182 if request.user.is_authenticated():
183 author = request.user
187 before = doc.revision()
188 logger.info("Reverting %s to %s", chunk_id, revision)
189 doc.at_revision(revision).revert(author=author, description=comment)
191 return JSONResponse({
192 'text': doc.materialize() if before != doc.revision() else None,
194 'revision': doc.revision(),
197 return JSONFormInvalid(form)
201 def gallery(request, directory):
204 smart_unicode(settings.MEDIA_URL),
205 smart_unicode(settings.FILEBROWSER_DIRECTORY),
206 smart_unicode(directory)))
208 base_dir = os.path.join(
209 smart_unicode(settings.MEDIA_ROOT),
210 smart_unicode(settings.FILEBROWSER_DIRECTORY),
211 smart_unicode(directory))
213 def map_to_url(filename):
214 return "%s/%s" % (base_url, smart_unicode(filename))
216 def is_image(filename):
217 return os.path.splitext(f)[1].lower() in (u'.jpg', u'.jpeg', u'.png')
219 images = [map_to_url(f) for f in map(smart_unicode, os.listdir(base_dir)) if is_image(f)]
222 if not request.user.is_authenticated():
223 return HttpResponseForbidden("Not authorized.")
225 return JSONResponse(images)
226 except (IndexError, OSError):
227 logger.exception("Unable to fetch gallery")
232 def diff(request, chunk_id):
233 revA = int(request.GET.get('from', 0))
234 revB = int(request.GET.get('to', 0))
237 revA, revB = revB, revA
242 doc = get_object_or_404(Chunk, pk=chunk_id)
243 if not doc.book.accessible(request):
244 return HttpResponseForbidden("Not authorized.")
246 # allow diff from the beginning
248 docA = doc.at_revision(revA).materialize()
251 docB = doc.at_revision(revB).materialize()
253 return http.HttpResponse(nice_diff.html_diff_table(docA.splitlines(),
254 docB.splitlines(), context=3))
258 def revision(request, chunk_id):
259 doc = get_object_or_404(Chunk, pk=chunk_id)
260 if not doc.book.accessible(request):
261 return HttpResponseForbidden("Not authorized.")
262 return http.HttpResponse(str(doc.revision()))
266 def history(request, chunk_id):
268 doc = get_object_or_404(Chunk, pk=chunk_id)
269 if not doc.book.accessible(request):
270 return HttpResponseForbidden("Not authorized.")
273 for change in doc.history().reverse():
275 "version": change.revision,
276 "description": change.description,
277 "author": change.author_str(),
278 "date": localize(change.created_at),
279 "publishable": _("Publishable") + "\n" if change.publishable else "",
280 "tag": ',\n'.join(unicode(tag) for tag in change.tags.all()),
282 return JSONResponse(changes)
286 @ajax_require_permission('catalogue.can_pubmark')
287 def pubmark(request, chunk_id):
288 form = forms.DocumentPubmarkForm(request.POST, prefix="pubmark")
290 doc = get_object_or_404(Chunk, pk=chunk_id)
291 if not doc.book.accessible(request):
292 return HttpResponseForbidden("Not authorized.")
294 revision = form.cleaned_data['revision']
295 publishable = form.cleaned_data['publishable']
296 change = doc.at_revision(revision)
297 if publishable != change.publishable:
298 change.set_publishable(publishable)
299 return JSONResponse({"message": _("Revision marked")})
301 return JSONResponse({"message": _("Nothing changed")})
303 return JSONFormInvalid(form)
307 prefix = request.GET.get('q', '')
308 return http.HttpResponse('\n'.join([str(t) for t in Theme.objects.filter(name__istartswith=prefix)]))