1 from datetime import datetime
6 from django.conf import settings
7 from django.core.urlresolvers import reverse
8 from django import http
9 from django.http import Http404, HttpResponseForbidden
10 from django.middleware.gzip import GZipMiddleware
11 from django.utils.decorators import decorator_from_middleware
12 from django.utils.encoding import smart_unicode
13 from django.utils.formats import localize
14 from django.utils.translation import ugettext as _
15 from django.views.decorators.http import require_POST, require_GET
16 from django.shortcuts import get_object_or_404, render
17 from django.utils import simplejson
19 from catalogue.models import Book, Chunk, Template
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")
36 def get_history(chunk):
38 for change in chunk.history():
40 "version": change.revision,
41 "description": change.description,
42 "author": change.author_str(),
43 "date": localize(change.created_at),
44 "publishable": _("Publishable") + "\n" if change.publishable else "",
45 "tag": ',\n'.join(unicode(tag) for tag in change.tags.all()),
46 "published": _("Published") + ": " + \
47 localize(change.publish_log.order_by('-book_record__timestamp')[0].book_record.timestamp) \
48 if change.publish_log.exists() else "",
54 def editor(request, slug, chunk=None, template_name='wiki/bootstrap.html'):
56 chunk = Chunk.get(slug, chunk)
57 except Chunk.MultipleObjectsReturned:
60 except Chunk.DoesNotExist:
63 book = Book.objects.get(slug=slug)
64 except Book.DoesNotExist:
65 return http.HttpResponseRedirect(reverse("catalogue_create_missing", args=[slug]))
68 if not chunk.book.accessible(request):
69 return HttpResponseForbidden("Not authorized.")
71 access_time = datetime.now()
72 last_books = request.session.get("wiki_last_books", {})
73 last_books[slug, chunk.slug] = {
75 'title': chunk.pretty_name(),
78 if len(last_books) > MAX_LAST_DOCS:
79 oldest_key = min(last_books, key=lambda x: last_books[x]['time'])
80 del last_books[oldest_key]
81 request.session['wiki_last_books'] = last_books
83 save_form = forms.DocumentTextSaveForm(user=request.user, prefix="textsave")
84 return render(request, template_name, {
85 'serialized_document_data': simplejson.dumps({
86 'document': chunk.materialize(),
87 'document_id': chunk.id,
88 'title': chunk.book.title,
89 'history': get_history(chunk),
90 'version': chunk.revision(),
91 'stage': chunk.stage.name if chunk.stage else None,
92 'assignment': chunk.user.username if chunk.user else None
94 'serialized_templates': simplejson.dumps([
95 {'id': t.id, 'name': t.name, 'content': t.content} for t in Template.objects.filter(is_partial=True)
98 "text_save": save_form,
99 "text_revert": forms.DocumentTextRevertForm(prefix="textrevert")
101 'tags': list(save_form.fields['stage_completed'].choices),
102 'can_pubmark': request.user.has_perm('catalogue.can_pubmark'),
107 def editor_readonly(request, slug, chunk=None, template_name='wiki/document_details_readonly.html'):
109 chunk = Chunk.get(slug, chunk)
110 revision = request.GET['revision']
111 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist, KeyError):
113 if not chunk.book.accessible(request):
114 return HttpResponseForbidden("Not authorized.")
116 access_time = datetime.now()
117 last_books = request.session.get("wiki_last_books", {})
118 last_books[slug, chunk.slug] = {
120 'title': chunk.book.title,
123 if len(last_books) > MAX_LAST_DOCS:
124 oldest_key = min(last_books, key=lambda x: last_books[x]['time'])
125 del last_books[oldest_key]
126 request.session['wiki_last_books'] = last_books
128 return render(request, template_name, {
130 'revision': revision,
132 'REDMINE_URL': settings.REDMINE_URL,
137 @decorator_from_middleware(GZipMiddleware)
138 def text(request, chunk_id):
139 doc = get_object_or_404(Chunk, pk=chunk_id)
140 if not doc.book.accessible(request):
141 return HttpResponseForbidden("Not authorized.")
143 if request.method == 'POST':
144 form = forms.DocumentTextSaveForm(request.POST, user=request.user, prefix="textsave")
146 if request.user.is_authenticated():
147 author = request.user
150 text = form.cleaned_data['text']
151 parent_revision = form.cleaned_data['parent_revision']
152 if parent_revision is not None:
153 parent = doc.at_revision(parent_revision)
156 stage = form.cleaned_data['stage_completed']
157 tags = [stage] if stage else []
158 publishable = (form.cleaned_data['publishable'] and
159 request.user.has_perm('catalogue.can_pubmark'))
160 doc.commit(author=author,
163 description=form.cleaned_data['comment'],
165 author_name=form.cleaned_data['author_name'],
166 author_email=form.cleaned_data['author_email'],
167 publishable=publishable,
169 revision = doc.revision()
170 return JSONResponse({
171 'text': doc.materialize() if parent_revision != revision else None,
173 'stage': doc.stage.name if doc.stage else None,
174 'assignment': doc.user.username if doc.user else None
177 return JSONFormInvalid(form)
179 revision = request.GET.get("revision", None)
182 revision = int(revision)
183 except (ValueError, TypeError):
184 revision = doc.revision()
186 if revision is not None:
187 text = doc.at_revision(revision).materialize()
191 return JSONResponse({
194 'revision': revision,
200 def revert(request, chunk_id):
201 form = forms.DocumentTextRevertForm(request.POST, prefix="textrevert")
203 doc = get_object_or_404(Chunk, pk=chunk_id)
204 if not doc.book.accessible(request):
205 return HttpResponseForbidden("Not authorized.")
207 revision = form.cleaned_data['revision']
209 comment = form.cleaned_data['comment']
210 comment += "\n#revert to %s" % revision
212 if request.user.is_authenticated():
213 author = request.user
217 before = doc.revision()
218 logger.info("Reverting %s to %s", chunk_id, revision)
219 doc.at_revision(revision).revert(author=author, description=comment)
221 return JSONResponse({
222 'document': doc.materialize() if before != doc.revision() else None,
223 'version': doc.revision(),
226 return JSONFormInvalid(form)
230 def gallery(request, directory):
233 smart_unicode(settings.MEDIA_URL),
234 smart_unicode(settings.IMAGE_DIR),
235 smart_unicode(directory)))
237 base_dir = os.path.join(
238 smart_unicode(settings.MEDIA_ROOT),
239 smart_unicode(settings.IMAGE_DIR),
240 smart_unicode(directory))
242 def map_to_url(filename):
243 return urllib.quote("%s/%s" % (base_url, smart_unicode(filename)))
245 def is_image(filename):
246 return os.path.splitext(f)[1].lower() in (u'.jpg', u'.jpeg', u'.png')
248 images = [map_to_url(f) for f in map(smart_unicode, os.listdir(base_dir)) if is_image(f)]
251 if not request.user.is_authenticated():
252 return HttpResponseForbidden("Not authorized.")
254 return JSONResponse(images)
255 except (IndexError, OSError):
256 logger.exception("Unable to fetch gallery")
261 def diff(request, chunk_id):
262 revA = int(request.GET.get('from', 0))
263 revB = int(request.GET.get('to', 0))
266 revA, revB = revB, revA
271 doc = get_object_or_404(Chunk, pk=chunk_id)
272 if not doc.book.accessible(request):
273 return HttpResponseForbidden("Not authorized.")
275 # allow diff from the beginning
277 docA = doc.at_revision(revA).materialize()
280 docB = doc.at_revision(revB).materialize()
282 return http.HttpResponse(nice_diff.html_diff_table(docA.splitlines(),
283 docB.splitlines(), context=3))
287 def revision(request, chunk_id):
288 doc = get_object_or_404(Chunk, pk=chunk_id)
289 if not doc.book.accessible(request):
290 return HttpResponseForbidden("Not authorized.")
291 return http.HttpResponse(str(doc.revision()))
295 def history(request, chunk_id):
297 doc = get_object_or_404(Chunk, pk=chunk_id)
298 if not doc.book.accessible(request):
299 return HttpResponseForbidden("Not authorized.")
301 return JSONResponse(get_history(doc))
305 @ajax_require_permission('catalogue.can_pubmark')
306 def pubmark(request, chunk_id):
307 form = forms.DocumentPubmarkForm(request.POST, prefix="pubmark")
309 doc = get_object_or_404(Chunk, pk=chunk_id)
310 if not doc.book.accessible(request):
311 return HttpResponseForbidden("Not authorized.")
313 revision = form.cleaned_data['revision']
314 publishable = form.cleaned_data['publishable']
315 change = doc.at_revision(revision)
316 if publishable != change.publishable:
317 change.set_publishable(publishable)
318 return JSONResponse({"message": _("Revision marked")})
320 return JSONResponse({"message": _("Nothing changed")})
322 return JSONFormInvalid(form)
326 prefix = request.GET.get('q', '')
327 return http.HttpResponse('\n'.join([str(t) for t in Theme.objects.filter(name__istartswith=prefix)]))