1 from datetime import datetime
4 from time import mktime
7 from django.conf import settings
8 from django.core.urlresolvers import reverse
9 from django import http
10 from django.http import Http404, HttpResponseForbidden
11 from django.middleware.gzip import GZipMiddleware
12 from django.utils.decorators import decorator_from_middleware
13 from django.utils.encoding import smart_unicode
14 from django.utils.formats import localize
15 from django.utils.translation import ugettext as _
16 from django.views.decorators.http import require_POST, require_GET
17 from django.shortcuts import get_object_or_404, render
19 from catalogue.models import Book, Chunk
21 from wiki import forms
22 from wiki.helpers import (JSONResponse, JSONFormInvalid, JSONServerError,
23 ajax_require_permission)
24 from wiki.models import Theme
27 # Quick hack around caching problems, TODO: use ETags
29 from django.views.decorators.cache import never_cache
31 logger = logging.getLogger("fnp.wiki")
37 def editor(request, slug, chunk=None, template_name='wiki/document_details.html'):
39 chunk = Chunk.get(slug, chunk)
40 except Chunk.MultipleObjectsReturned:
43 except Chunk.DoesNotExist:
46 book = Book.objects.get(slug=slug)
47 except Book.DoesNotExist:
48 return http.HttpResponseRedirect(reverse("catalogue_create_missing", args=[slug]))
51 if not chunk.book.accessible(request):
52 return HttpResponseForbidden("Not authorized.")
54 access_time = datetime.now()
55 last_books = request.session.get("wiki_last_books", {})
56 last_books[reverse(editor, args=[chunk.book.slug, chunk.slug])] = {
57 'time': mktime(access_time.timetuple()),
58 'title': chunk.pretty_name(),
61 if len(last_books) > MAX_LAST_DOCS:
62 oldest_key = min(last_books, key=lambda x: last_books[x]['time'])
63 del last_books[oldest_key]
64 request.session['wiki_last_books'] = last_books
66 return render(request, template_name, {
69 "text_save": forms.DocumentTextSaveForm(user=request.user, prefix="textsave"),
70 "text_revert": forms.DocumentTextRevertForm(prefix="textrevert"),
71 "pubmark": forms.DocumentPubmarkForm(prefix="pubmark"),
73 'can_pubmark': request.user.has_perm('catalogue.can_pubmark'),
74 'REDMINE_URL': settings.REDMINE_URL,
79 def editor_readonly(request, slug, chunk=None, template_name='wiki/document_details_readonly.html'):
81 chunk = Chunk.get(slug, chunk)
82 revision = request.GET['revision']
83 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist, KeyError):
85 if not chunk.book.accessible(request):
86 return HttpResponseForbidden("Not authorized.")
88 access_time = datetime.now()
89 last_books = request.session.get("wiki_last_books", {})
90 last_books[slug, chunk.slug] = {
91 'time': mktime(access_time.timetuple()),
92 'title': chunk.book.title,
95 if len(last_books) > MAX_LAST_DOCS:
96 oldest_key = min(last_books, key=lambda x: last_books[x]['time'])
97 del last_books[oldest_key]
98 request.session['wiki_last_books'] = last_books
100 return render(request, template_name, {
102 'revision': revision,
104 'REDMINE_URL': settings.REDMINE_URL,
109 @decorator_from_middleware(GZipMiddleware)
110 def text(request, chunk_id):
111 doc = get_object_or_404(Chunk, pk=chunk_id)
112 if not doc.book.accessible(request):
113 return HttpResponseForbidden("Not authorized.")
115 if request.method == 'POST':
116 form = forms.DocumentTextSaveForm(request.POST, user=request.user, prefix="textsave")
118 if request.user.is_authenticated():
119 author = request.user
122 text = form.cleaned_data['text']
123 parent_revision = form.cleaned_data['parent_revision']
124 if parent_revision is not None:
125 parent = doc.at_revision(parent_revision)
128 stage = form.cleaned_data['stage_completed']
129 tags = [stage] if stage else []
130 publishable = (form.cleaned_data['publishable'] and
131 request.user.has_perm('catalogue.can_pubmark'))
132 doc.commit(author=author,
135 description=form.cleaned_data['comment'],
137 author_name=form.cleaned_data['author_name'],
138 author_email=form.cleaned_data['author_email'],
139 publishable=publishable,
141 revision = doc.revision()
142 return JSONResponse({
143 'text': doc.materialize() if parent_revision != revision else None,
145 'revision': revision,
148 return JSONFormInvalid(form)
150 revision = request.GET.get("revision", None)
153 revision = int(revision)
154 except (ValueError, TypeError):
155 revision = doc.revision()
157 if revision is not None:
158 text = doc.at_revision(revision).materialize()
162 return JSONResponse({
165 'revision': revision,
171 def revert(request, chunk_id):
172 form = forms.DocumentTextRevertForm(request.POST, prefix="textrevert")
174 doc = get_object_or_404(Chunk, pk=chunk_id)
175 if not doc.book.accessible(request):
176 return HttpResponseForbidden("Not authorized.")
178 revision = form.cleaned_data['revision']
180 comment = form.cleaned_data['comment']
181 comment += "\n#revert to %s" % revision
183 if request.user.is_authenticated():
184 author = request.user
188 before = doc.revision()
189 logger.info("Reverting %s to %s", chunk_id, revision)
190 doc.at_revision(revision).revert(author=author, description=comment)
192 return JSONResponse({
193 'text': doc.materialize() if before != doc.revision() else None,
195 'revision': doc.revision(),
198 return JSONFormInvalid(form)
202 def gallery(request, directory):
205 smart_unicode(settings.MEDIA_URL),
206 smart_unicode(settings.IMAGE_DIR),
207 smart_unicode(directory)))
209 base_dir = os.path.join(
210 smart_unicode(settings.MEDIA_ROOT),
211 smart_unicode(settings.IMAGE_DIR),
212 smart_unicode(directory))
214 def map_to_url(filename):
215 return urllib.quote("%s/%s" % (base_url, smart_unicode(filename)))
217 def is_image(filename):
218 return os.path.splitext(f)[1].lower() in (u'.jpg', u'.jpeg', u'.png')
220 images = [map_to_url(f) for f in map(smart_unicode, os.listdir(base_dir)) if is_image(f)]
223 if not request.user.is_authenticated():
224 return HttpResponseForbidden("Not authorized.")
226 return JSONResponse(images)
227 except (IndexError, OSError):
228 logger.exception("Unable to fetch gallery")
233 def diff(request, chunk_id):
234 revA = int(request.GET.get('from', 0))
235 revB = int(request.GET.get('to', 0))
238 revA, revB = revB, revA
243 doc = get_object_or_404(Chunk, pk=chunk_id)
244 if not doc.book.accessible(request):
245 return HttpResponseForbidden("Not authorized.")
247 # allow diff from the beginning
249 docA = doc.at_revision(revA).materialize()
252 docB = doc.at_revision(revB).materialize()
254 return http.HttpResponse(nice_diff.html_diff_table(docA.splitlines(),
255 docB.splitlines(), context=3))
259 def revision(request, chunk_id):
260 doc = get_object_or_404(Chunk, pk=chunk_id)
261 if not doc.book.accessible(request):
262 return HttpResponseForbidden("Not authorized.")
263 return http.HttpResponse(str(doc.revision()))
267 def history(request, chunk_id):
269 doc = get_object_or_404(Chunk, pk=chunk_id)
270 if not doc.book.accessible(request):
271 return HttpResponseForbidden("Not authorized.")
274 for change in doc.history().reverse():
276 "version": change.revision,
277 "description": change.description,
278 "author": change.author_str(),
279 "date": localize(change.created_at),
280 "publishable": _("Publishable") + "\n" if change.publishable else "",
281 "tag": ',\n'.join(unicode(tag) for tag in change.tags.all()),
282 "published": _("Published") + ": " + \
283 localize(change.publish_log.order_by('-book_record__timestamp')[0].book_record.timestamp) \
284 if change.publish_log.exists() else "",
286 return JSONResponse(changes)
290 @ajax_require_permission('catalogue.can_pubmark')
291 def pubmark(request, chunk_id):
292 form = forms.DocumentPubmarkForm(request.POST, prefix="pubmark")
294 doc = get_object_or_404(Chunk, pk=chunk_id)
295 if not doc.book.accessible(request):
296 return HttpResponseForbidden("Not authorized.")
298 revision = form.cleaned_data['revision']
299 publishable = form.cleaned_data['publishable']
300 change = doc.at_revision(revision)
301 if publishable != change.publishable:
302 change.set_publishable(publishable)
303 return JSONResponse({"message": _("Revision marked")})
305 return JSONResponse({"message": _("Nothing changed")})
307 return JSONFormInvalid(form)
311 prefix = request.GET.get('q', '')
312 return http.HttpResponse('\n'.join([str(t) for t in Theme.objects.filter(name__istartswith=prefix)]))