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
18 from django.contrib.auth.decorators import login_required
20 from catalogue.models import Book, Chunk, Template
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")
37 def get_history(chunk):
39 for change in chunk.history():
41 "version": change.revision,
42 "description": change.description,
43 "author": change.author_str(),
44 "date": localize(change.created_at),
45 "publishable": _("Publishable") + "\n" if change.publishable else "",
46 "tag": ',\n'.join(unicode(tag) for tag in change.tags.all()),
47 "published": _("Published") + ": " + \
48 localize(change.publish_log.order_by('-book_record__timestamp')[0].book_record.timestamp) \
49 if change.publish_log.exists() else "",
56 def editor(request, slug, chunk=None, template_name='wiki/bootstrap.html'):
58 chunk = Chunk.get(slug, chunk)
59 except Chunk.MultipleObjectsReturned:
62 except Chunk.DoesNotExist:
65 book = Book.objects.get(slug=slug)
66 except Book.DoesNotExist:
67 return http.HttpResponseRedirect(reverse("catalogue_create_missing", args=[slug]))
70 if not chunk.book.accessible(request):
71 return HttpResponseForbidden("Not authorized.")
73 access_time = datetime.now()
74 last_books = request.session.get("wiki_last_books", {})
75 last_books[slug, chunk.slug] = {
77 'title': chunk.pretty_name(),
80 if len(last_books) > MAX_LAST_DOCS:
81 oldest_key = min(last_books, key=lambda x: last_books[x]['time'])
82 del last_books[oldest_key]
83 request.session['wiki_last_books'] = last_books
85 save_form = forms.DocumentTextSaveForm(user=request.user, prefix="textsave")
86 return render(request, template_name, {
87 'serialized_document_data': simplejson.dumps({
88 'document': chunk.materialize(),
89 'document_id': chunk.id,
90 'title': chunk.book.title,
91 'history': get_history(chunk),
92 'version': chunk.revision(),
93 'stage': chunk.stage.name if chunk.stage else None,
94 'assignment': chunk.user.username if chunk.user else None
96 'serialized_templates': simplejson.dumps([
97 {'id': t.id, 'name': t.name, 'content': t.content} for t in Template.objects.filter(is_partial=True)
100 "text_save": save_form,
101 "text_revert": forms.DocumentTextRevertForm(prefix="textrevert")
103 'tags': list(save_form.fields['stage_completed'].choices),
104 'can_pubmark': request.user.has_perm('catalogue.can_pubmark'),
105 'slug': chunk.book.slug
110 def editor_readonly(request, slug, chunk=None, template_name='wiki/document_details_readonly.html'):
112 chunk = Chunk.get(slug, chunk)
113 revision = request.GET['revision']
114 except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist, KeyError):
116 if not chunk.book.accessible(request):
117 return HttpResponseForbidden("Not authorized.")
119 access_time = datetime.now()
120 last_books = request.session.get("wiki_last_books", {})
121 last_books[slug, chunk.slug] = {
123 'title': chunk.book.title,
126 if len(last_books) > MAX_LAST_DOCS:
127 oldest_key = min(last_books, key=lambda x: last_books[x]['time'])
128 del last_books[oldest_key]
129 request.session['wiki_last_books'] = last_books
131 return render(request, template_name, {
133 'revision': revision,
135 'REDMINE_URL': settings.REDMINE_URL,
140 @decorator_from_middleware(GZipMiddleware)
141 def text(request, chunk_id):
142 doc = get_object_or_404(Chunk, pk=chunk_id)
143 if not doc.book.accessible(request):
144 return HttpResponseForbidden("Not authorized.")
146 if request.method == 'POST':
147 form = forms.DocumentTextSaveForm(request.POST, user=request.user, prefix="textsave")
149 if request.user.is_authenticated():
150 author = request.user
153 text = form.cleaned_data['text']
154 parent_revision = form.cleaned_data['parent_revision']
155 if parent_revision is not None:
156 parent = doc.at_revision(parent_revision)
159 stage = form.cleaned_data['stage_completed']
160 tags = [stage] if stage else []
161 publishable = (form.cleaned_data['publishable'] and
162 request.user.has_perm('catalogue.can_pubmark'))
163 doc.commit(author=author,
166 description=form.cleaned_data['comment'],
168 author_name=form.cleaned_data['author_name'],
169 author_email=form.cleaned_data['author_email'],
170 publishable=publishable,
172 revision = doc.revision()
173 return JSONResponse({
174 'text': doc.materialize() if parent_revision != revision else None,
176 'stage': doc.stage.name if doc.stage else None,
177 'assignment': doc.user.username if doc.user else None
180 return JSONFormInvalid(form)
182 revision = request.GET.get("revision", None)
185 revision = int(revision)
186 except (ValueError, TypeError):
187 revision = doc.revision()
189 if revision is not None:
190 text = doc.at_revision(revision).materialize()
194 return JSONResponse({
197 'revision': revision,
203 def revert(request, chunk_id):
204 form = forms.DocumentTextRevertForm(request.POST, prefix="textrevert")
206 doc = get_object_or_404(Chunk, pk=chunk_id)
207 if not doc.book.accessible(request):
208 return HttpResponseForbidden("Not authorized.")
210 revision = form.cleaned_data['revision']
212 comment = form.cleaned_data['comment']
213 comment += "\n#revert to %s" % revision
215 if request.user.is_authenticated():
216 author = request.user
220 before = doc.revision()
221 logger.info("Reverting %s to %s", chunk_id, revision)
222 doc.at_revision(revision).revert(author=author, description=comment)
224 return JSONResponse({
225 'document': doc.materialize() if before != doc.revision() else None,
226 'version': doc.revision(),
229 return JSONFormInvalid(form)
233 def gallery(request, directory):
236 smart_unicode(settings.MEDIA_URL),
237 smart_unicode(settings.IMAGE_DIR),
238 smart_unicode(directory)))
240 base_dir = os.path.join(
241 smart_unicode(settings.MEDIA_ROOT),
242 smart_unicode(settings.IMAGE_DIR),
243 smart_unicode(directory))
245 def map_to_url(filename):
246 return urllib.quote("%s/%s" % (base_url, smart_unicode(filename)))
248 def is_image(filename):
249 return os.path.splitext(f)[1].lower() in (u'.jpg', u'.jpeg', u'.png')
251 images = [map_to_url(f) for f in map(smart_unicode, os.listdir(base_dir)) if is_image(f)]
254 if not request.user.is_authenticated():
255 return HttpResponseForbidden("Not authorized.")
257 return JSONResponse(images)
258 except (IndexError, OSError):
259 logger.exception("Unable to fetch gallery")
264 def diff(request, chunk_id):
265 revA = int(request.GET.get('from', 0))
266 revB = int(request.GET.get('to', 0))
269 revA, revB = revB, revA
274 doc = get_object_or_404(Chunk, pk=chunk_id)
275 if not doc.book.accessible(request):
276 return HttpResponseForbidden("Not authorized.")
278 # allow diff from the beginning
280 docA = doc.at_revision(revA).materialize()
283 docB = doc.at_revision(revB).materialize()
285 return http.HttpResponse(nice_diff.html_diff_table(docA.splitlines(),
286 docB.splitlines(), context=3))
290 def revision(request, chunk_id):
291 doc = get_object_or_404(Chunk, pk=chunk_id)
292 if not doc.book.accessible(request):
293 return HttpResponseForbidden("Not authorized.")
294 return http.HttpResponse(str(doc.revision()))
298 def history(request, chunk_id):
300 doc = get_object_or_404(Chunk, pk=chunk_id)
301 if not doc.book.accessible(request):
302 return HttpResponseForbidden("Not authorized.")
304 return JSONResponse(get_history(doc))
308 @ajax_require_permission('catalogue.can_pubmark')
309 def pubmark(request, chunk_id):
310 form = forms.DocumentPubmarkForm(request.POST, prefix="pubmark")
312 doc = get_object_or_404(Chunk, pk=chunk_id)
313 if not doc.book.accessible(request):
314 return HttpResponseForbidden("Not authorized.")
316 revision = form.cleaned_data['revision']
317 publishable = form.cleaned_data['publishable']
318 change = doc.at_revision(revision)
319 if publishable != change.publishable:
320 change.set_publishable(publishable)
321 return JSONResponse({"message": _("Revision marked")})
323 return JSONResponse({"message": _("Nothing changed")})
325 return JSONFormInvalid(form)
329 prefix = request.GET.get('q', '')
330 return http.HttpResponse('\n'.join([str(t) for t in Theme.objects.filter(name__istartswith=prefix)]))