20518e88543116c2261ae8d61da00afbf20d79bb
[wolnelektury.git] / apps / catalogue / views.py
1 # -*- coding: utf-8 -*-
2 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
3 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
4 #
5 from collections import OrderedDict
6 import re
7
8 from django.conf import settings
9 from django.template import RequestContext
10 from django.template.loader import render_to_string
11 from django.shortcuts import render_to_response, get_object_or_404, render
12 from django.http import HttpResponse, HttpResponseRedirect, Http404, HttpResponsePermanentRedirect, JsonResponse
13 from django.core.urlresolvers import reverse
14 from django.db.models import Q
15 from django.contrib.auth.decorators import login_required, user_passes_test
16 from django.utils.http import urlquote_plus
17 from django.utils import translation
18 from django.utils.translation import ugettext as _, ugettext_lazy
19
20 from ajaxable.utils import AjaxableFormView
21 from pdcounter import models as pdcounter_models
22 from pdcounter import views as pdcounter_views
23 from picture.models import Picture, PictureArea
24 from picture.views import picture_list_thumb
25 from ssify import ssi_included, ssi_expect, SsiVariable as V
26 from suggest.forms import PublishingSuggestForm
27 from catalogue import forms
28 from catalogue.helpers import get_top_level_related_tags
29 from catalogue import models
30 from catalogue.utils import split_tags, MultiQuerySet, SortedMultiQuerySet
31 from catalogue.templatetags.catalogue_tags import tag_list, collection_list
32
33 staff_required = user_passes_test(lambda user: user.is_staff)
34
35
36 def catalogue(request, as_json=False):
37     common_categories = ('author',)
38     split_categories = ('epoch', 'genre', 'kind')
39
40     categories = split_tags(
41         get_top_level_related_tags(categories=common_categories),
42         models.Tag.objects.usage_for_model(
43             models.Fragment, counts=True).filter(category='theme'),
44         models.Tag.objects.usage_for_model(
45             Picture, counts=True).filter(category__in=common_categories),
46         models.Tag.objects.usage_for_model(
47             PictureArea, counts=True).filter(
48             category='theme')
49     )
50     book_categories = split_tags(
51         get_top_level_related_tags(categories=split_categories)
52         )
53     picture_categories = split_tags(
54         models.Tag.objects.usage_for_model(
55             Picture, counts=True).filter(
56             category__in=split_categories),
57         )
58
59     collections = models.Collection.objects.all()
60
61     def render_tag_list(tags):
62         return render_to_string('catalogue/tag_list.html', tag_list(tags))
63
64     def render_split(with_books, with_pictures):
65         ctx = {}
66         if with_books:
67             ctx['books'] = render_tag_list(with_books)
68         if with_pictures:
69             ctx['pictures'] = render_tag_list(with_pictures)
70         return render_to_string('catalogue/tag_list_split.html', ctx)
71
72     output = {}
73     output['theme'] = render_tag_list(categories.get('theme', []))
74     for category in common_categories:
75         output[category] = render_tag_list(categories.get(category, []))
76     for category in split_categories:
77         output[category] = render_split(
78             book_categories.get(category, []),
79             picture_categories.get(category, []))
80
81     output['collections'] = render_to_string(
82         'catalogue/collection_list.html', collection_list(collections))
83     if as_json:
84         return JsonResponse(output)
85     else:
86         return render_to_response('catalogue/catalogue.html', locals(),
87             context_instance=RequestContext(request))
88
89
90 @ssi_included
91 def catalogue_json(request):
92     return catalogue(request, True)
93
94
95 def book_list(request, filter=None, get_filter=None,
96         template_name='catalogue/book_list.html',
97         nav_template_name='catalogue/snippets/book_list_nav.html',
98         list_template_name='catalogue/snippets/book_list.html',
99         context=None,
100         ):
101     """ generates a listing of all books, optionally filtered with a test function """
102     if get_filter:
103         filter = get_filter()
104     books_by_author, orphans, books_by_parent = models.Book.book_list(filter)
105     books_nav = OrderedDict()
106     for tag in books_by_author:
107         if books_by_author[tag]:
108             books_nav.setdefault(tag.sort_key[0], []).append(tag)
109     rendered_nav = render_to_string(nav_template_name, locals())
110     rendered_book_list = render_to_string(list_template_name, locals())
111     return render_to_response(template_name, locals(),
112         context_instance=RequestContext(request))
113
114
115 def audiobook_list(request):
116     return book_list(request, Q(media__type='mp3') | Q(media__type='ogg'),
117                      template_name='catalogue/audiobook_list.html',
118                      list_template_name='catalogue/snippets/audiobook_list.html',
119                      )
120
121
122 def daisy_list(request):
123     return book_list(request, Q(media__type='daisy'),
124                      template_name='catalogue/daisy_list.html',
125                      )
126
127
128 def collection(request, slug):
129     coll = get_object_or_404(models.Collection, slug=slug)
130     if coll.kind == 'book':
131         view = book_list
132         tmpl = "catalogue/collection.html"
133     elif coll.kind == 'picture':
134         view = picture_list_thumb
135         tmpl = "picture/collection.html"
136     else:
137         raise ValueError('How do I show this kind of collection? %s' % coll.kind)
138     return view(request, get_filter=coll.get_query,
139                      template_name=tmpl,
140                      context={'collection': coll})
141
142
143 def differentiate_tags(request, tags, ambiguous_slugs):
144     beginning = '/'.join(tag.url_chunk for tag in tags)
145     unparsed = '/'.join(ambiguous_slugs[1:])
146     options = []
147     for tag in models.Tag.objects.filter(slug=ambiguous_slugs[0]):
148         options.append({
149             'url_args': '/'.join((beginning, tag.url_chunk, unparsed)).strip('/'),
150             'tags': [tag]
151         })
152     return render_to_response('catalogue/differentiate_tags.html',
153                 {'tags': tags, 'options': options, 'unparsed': ambiguous_slugs[1:]},
154                 context_instance=RequestContext(request))
155
156
157 # TODO: Rewrite this hellish piece of code which tries to do everything
158 def tagged_object_list(request, tags=''):
159     # preliminary tests and conditions
160     try:
161         tags = models.Tag.get_tag_list(tags)
162     except models.Tag.DoesNotExist:
163         # Perhaps the user is asking about an author in Public Domain
164         # counter (they are not represented in tags)
165         chunks = tags.split('/')
166         if len(chunks) == 2 and chunks[0] == 'autor':
167             return pdcounter_views.author_detail(request, chunks[1])
168         else:
169             raise Http404
170     except models.Tag.MultipleObjectsReturned, e:
171         # Ask the user to disambiguate
172         return differentiate_tags(request, e.tags, e.ambiguous_slugs)
173     except models.Tag.UrlDeprecationWarning, e:
174         return HttpResponsePermanentRedirect(reverse('tagged_object_list', args=['/'.join(tag.url_chunk for tag in e.tags)]))
175
176     try:
177         if len(tags) > settings.MAX_TAG_LIST:
178             raise Http404
179     except AttributeError:
180         pass
181
182     # beginning of digestion
183     theme_is_set = [tag for tag in tags if tag.category == 'theme']
184     shelf_is_set = [tag for tag in tags if tag.category == 'set']
185     only_shelf = shelf_is_set and len(tags) == 1
186     only_my_shelf = only_shelf and request.user.is_authenticated() and request.user == tags[0].user
187     tags_pks = [tag.pk for tag in tags]
188
189     objects = None
190
191     if theme_is_set:
192         shelf_tags = [tag for tag in tags if tag.category == 'set']
193         fragment_tags = [tag for tag in tags if tag.category != 'set']
194         fragments = models.Fragment.tagged.with_all(fragment_tags)
195         areas = PictureArea.tagged.with_all(fragment_tags)
196
197         if shelf_tags:
198             books = models.Book.tagged.with_all(shelf_tags).order_by()
199             fragments = fragments.filter(Q(book__in=books) | Q(book__ancestor__in=books))
200             areas = PictureArea.objects.none()
201
202         categories = split_tags(
203             models.Tag.objects.usage_for_queryset(fragments, counts=True
204                 ).exclude(pk__in=tags_pks),
205             models.Tag.objects.usage_for_queryset(areas, counts=True
206                 ).exclude(pk__in=tags_pks)
207             )
208
209         # we want the Pictures to go first
210         objects = MultiQuerySet(areas, fragments)
211     else:
212         all_books = models.Book.tagged.with_all(tags)
213         if shelf_is_set:
214             books = all_books.order_by('sort_key_author', 'title')
215             pictures = Picture.objects.none()
216             related_book_tags = models.Tag.objects.usage_for_queryset(
217                 books, counts=True).exclude(
218                 category='set').exclude(pk__in=tags_pks)
219         else:
220             books = models.Book.tagged_top_level(tags).order_by(
221                 'sort_key_author', 'title')
222             pictures = Picture.tagged.with_all(tags).order_by(
223                 'sort_key_author', 'title')
224             related_book_tags = get_top_level_related_tags(tags)
225
226         fragments = models.Fragment.objects.filter(book__in=all_books)
227         areas = PictureArea.objects.filter(picture__in=pictures)
228
229         categories = split_tags(
230             related_book_tags,
231             models.Tag.objects.usage_for_queryset(
232                 pictures, counts=True).exclude(pk__in=tags_pks),
233             models.Tag.objects.usage_for_queryset(
234                 fragments, counts=True).filter(
235                 category='theme').exclude(pk__in=tags_pks),
236             models.Tag.objects.usage_for_queryset(
237                 areas, counts=True).filter(
238                 category__in=('theme', 'thing')).exclude(
239                 pk__in=tags_pks),
240         )
241
242         objects = SortedMultiQuerySet(pictures, books,
243             order_by=('sort_key_author', 'title'))
244
245     return render_to_response('catalogue/tagged_object_list.html',
246         {
247             'object_list': objects,
248             'categories': categories,
249             'only_shelf': only_shelf,
250             'only_my_shelf': only_my_shelf,
251             'formats_form': forms.DownloadFormatsForm(),
252             'tags': tags,
253             'tags_ids': tags_pks,
254             'theme_is_set': theme_is_set,
255         },
256         context_instance=RequestContext(request))
257
258
259 def book_fragments(request, slug, theme_slug):
260     book = get_object_or_404(models.Book, slug=slug)
261     theme = get_object_or_404(models.Tag, slug=theme_slug, category='theme')
262     fragments = models.Fragment.tagged.with_all([theme]).filter(
263         Q(book=book) | Q(book__ancestor=book))
264
265     return render_to_response('catalogue/book_fragments.html', locals(),
266         context_instance=RequestContext(request))
267
268
269 def book_detail(request, slug):
270     try:
271         book = models.Book.objects.get(slug=slug)
272     except models.Book.DoesNotExist:
273         return pdcounter_views.book_stub_detail(request, slug)
274
275     book_children = book.children.all().order_by('parent_number', 'sort_key')
276     return render_to_response('catalogue/book_detail.html', locals(),
277         context_instance=RequestContext(request))
278
279
280 def player(request, slug):
281     book = get_object_or_404(models.Book, slug=slug)
282     if not book.has_media('mp3'):
283         raise Http404
284
285     ogg_files = {}
286     for m in book.media.filter(type='ogg').order_by().iterator():
287         ogg_files[m.name] = m
288
289     audiobooks = []
290     have_oggs = True
291     projects = set()
292     for mp3 in book.media.filter(type='mp3').iterator():
293         # ogg files are always from the same project
294         meta = mp3.extra_info
295         project = meta.get('project')
296         if not project:
297             # temporary fallback
298             project = u'CzytamySłuchając'
299
300         projects.add((project, meta.get('funded_by', '')))
301
302         media = {'mp3': mp3}
303
304         ogg = ogg_files.get(mp3.name)
305         if ogg:
306             media['ogg'] = ogg
307         else:
308             have_oggs = False
309         audiobooks.append(media)
310
311     projects = sorted(projects)
312
313     extra_info = book.extra_info
314
315     return render_to_response('catalogue/player.html', locals(),
316         context_instance=RequestContext(request))
317
318
319 def book_text(request, slug):
320     book = get_object_or_404(models.Book, slug=slug)
321
322     if not book.has_html_file():
323         raise Http404
324     return render_to_response('catalogue/book_text.html', locals(),
325         context_instance=RequestContext(request))
326
327
328 # ==========
329 # = Search =
330 # ==========
331
332 def _no_diacritics_regexp(query):
333     """ returns a regexp for searching for a query without diacritics
334
335     should be locale-aware """
336     names = {
337         u'a':u'aąĄ', u'c':u'cćĆ', u'e':u'eęĘ', u'l': u'lłŁ', u'n':u'nńŃ', u'o':u'oóÓ', u's':u'sśŚ', u'z':u'zźżŹŻ',
338         u'ą':u'ąĄ', u'ć':u'ćĆ', u'ę':u'ęĘ', u'ł': u'łŁ', u'ń':u'ńŃ', u'ó':u'óÓ', u'ś':u'śŚ', u'ź':u'źŹ', u'ż':u'żŻ'
339         }
340     def repl(m):
341         l = m.group()
342         return u"(%s)" % '|'.join(names[l])
343     return re.sub(u'[%s]' % (u''.join(names.keys())), repl, query)
344
345 def unicode_re_escape(query):
346     """ Unicode-friendly version of re.escape """
347     return re.sub(r'(?u)(\W)', r'\\\1', query)
348
349 def _word_starts_with(name, prefix):
350     """returns a Q object getting models having `name` contain a word
351     starting with `prefix`
352
353     We define word characters as alphanumeric and underscore, like in JS.
354
355     Works for MySQL, PostgreSQL, Oracle.
356     For SQLite, _sqlite* version is substituted for this.
357     """
358     kwargs = {}
359
360     prefix = _no_diacritics_regexp(unicode_re_escape(prefix))
361     # can't use [[:<:]] (word start),
362     # but we want both `xy` and `(xy` to catch `(xyz)`
363     kwargs['%s__iregex' % name] = u"(^|[^[:alnum:]_])%s" % prefix
364
365     return Q(**kwargs)
366
367
368 def _word_starts_with_regexp(prefix):
369     prefix = _no_diacritics_regexp(unicode_re_escape(prefix))
370     return ur"(^|(?<=[^\wąćęłńóśźżĄĆĘŁŃÓŚŹŻ]))%s" % prefix
371
372
373 def _sqlite_word_starts_with(name, prefix):
374     """ version of _word_starts_with for SQLite
375
376     SQLite in Django uses Python re module
377     """
378     kwargs = {}
379     kwargs['%s__iregex' % name] = _word_starts_with_regexp(prefix)
380     return Q(**kwargs)
381
382
383 if hasattr(settings, 'DATABASES'):
384     if settings.DATABASES['default']['ENGINE'] == 'django.db.backends.sqlite3':
385         _word_starts_with = _sqlite_word_starts_with
386 elif settings.DATABASE_ENGINE == 'sqlite3':
387     _word_starts_with = _sqlite_word_starts_with
388
389
390 class App():
391     def __init__(self, name, view):
392         self.name = name
393         self._view = view
394         self.lower = name.lower()
395         self.category = 'application'
396     def view(self):
397         return reverse(*self._view)
398
399 _apps = (
400     App(u'Leśmianator', (u'lesmianator', )),
401     )
402
403
404 def _tags_starting_with(prefix, user=None):
405     prefix = prefix.lower()
406     # PD counter
407     book_stubs = pdcounter_models.BookStub.objects.filter(_word_starts_with('title', prefix))
408     authors = pdcounter_models.Author.objects.filter(_word_starts_with('name', prefix))
409
410     books = models.Book.objects.filter(_word_starts_with('title', prefix))
411     tags = models.Tag.objects.filter(_word_starts_with('name', prefix))
412     if user and user.is_authenticated():
413         tags = tags.filter(~Q(category='set') | Q(user=user))
414     else:
415         tags = tags.exclude(category='set')
416
417     prefix_regexp = re.compile(_word_starts_with_regexp(prefix))
418     return list(books) + list(tags) + [app for app in _apps if prefix_regexp.search(app.lower)] + list(book_stubs) + list(authors)
419
420
421 def _get_result_link(match, tag_list):
422     if isinstance(match, models.Tag):
423         return reverse('catalogue.views.tagged_object_list',
424             kwargs={'tags': '/'.join(tag.url_chunk for tag in tag_list + [match])}
425         )
426     elif isinstance(match, App):
427         return match.view()
428     else:
429         return match.get_absolute_url()
430
431
432 def _get_result_type(match):
433     if isinstance(match, models.Book) or isinstance(match, pdcounter_models.BookStub):
434         match_type = 'book'
435     else:
436         match_type = match.category
437     return match_type
438
439
440 def books_starting_with(prefix):
441     prefix = prefix.lower()
442     return models.Book.objects.filter(_word_starts_with('title', prefix))
443
444
445 def find_best_matches(query, user=None):
446     """ Finds a models.Book, Tag, models.BookStub or Author best matching a query.
447
448     Returns a with:
449       - zero elements when nothing is found,
450       - one element when a best result is found,
451       - more then one element on multiple exact matches
452
453     Raises a ValueError on too short a query.
454     """
455
456     query = query.lower()
457     if len(query) < 2:
458         raise ValueError("query must have at least two characters")
459
460     result = tuple(_tags_starting_with(query, user))
461     # remove pdcounter stuff
462     book_titles = set(match.pretty_title().lower() for match in result
463                       if isinstance(match, models.Book))
464     authors = set(match.name.lower() for match in result
465                   if isinstance(match, models.Tag) and match.category == 'author')
466     result = tuple(res for res in result if not (
467                  (isinstance(res, pdcounter_models.BookStub) and res.pretty_title().lower() in book_titles)
468                  or (isinstance(res, pdcounter_models.Author) and res.name.lower() in authors)
469              ))
470
471     exact_matches = tuple(res for res in result if res.name.lower() == query)
472     if exact_matches:
473         return exact_matches
474     else:
475         return tuple(result)[:1]
476
477
478 def search(request):
479     tags = request.GET.get('tags', '')
480     prefix = request.GET.get('q', '')
481
482     try:
483         tag_list = models.Tag.get_tag_list(tags)
484     except:
485         tag_list = []
486
487     try:
488         result = find_best_matches(prefix, request.user)
489     except ValueError:
490         return render_to_response('catalogue/search_too_short.html', {'tags':tag_list, 'prefix':prefix},
491             context_instance=RequestContext(request))
492
493     if len(result) == 1:
494         return HttpResponseRedirect(_get_result_link(result[0], tag_list))
495     elif len(result) > 1:
496         return render_to_response('catalogue/search_multiple_hits.html',
497             {'tags':tag_list, 'prefix':prefix, 'results':((x, _get_result_link(x, tag_list), _get_result_type(x)) for x in result)},
498             context_instance=RequestContext(request))
499     else:
500         form = PublishingSuggestForm(initial={"books": prefix + ", "})
501         return render_to_response('catalogue/search_no_hits.html',
502             {'tags':tag_list, 'prefix':prefix, "pubsuggest_form": form},
503             context_instance=RequestContext(request))
504
505
506 def tags_starting_with(request):
507     prefix = request.GET.get('q', '')
508     # Prefix must have at least 2 characters
509     if len(prefix) < 2:
510         return HttpResponse('')
511     tags_list = []
512     result = ""
513     for tag in _tags_starting_with(prefix, request.user):
514         if not tag.name in tags_list:
515             result += "\n" + tag.name
516             tags_list.append(tag.name)
517     return HttpResponse(result)
518
519 def json_tags_starting_with(request, callback=None):
520     # Callback for JSONP
521     prefix = request.GET.get('q', '')
522     callback = request.GET.get('callback', '')
523     # Prefix must have at least 2 characters
524     if len(prefix) < 2:
525         return HttpResponse('')
526     tags_list = []
527     for tag in _tags_starting_with(prefix, request.user):
528         if not tag.name in tags_list:
529             tags_list.append(tag.name)
530     if request.GET.get('mozhint', ''):
531         result = [prefix, tags_list]
532     else:
533         result = {"matches": tags_list}
534     response = JsonResponse(result, safe=False)
535     if callback:
536         response.content = callback + "(" + response.content + ");"
537     return response
538
539
540 # =========
541 # = Admin =
542 # =========
543 @login_required
544 @staff_required
545 def import_book(request):
546     """docstring for import_book"""
547     book_import_form = forms.BookImportForm(request.POST, request.FILES)
548     if book_import_form.is_valid():
549         try:
550             book_import_form.save()
551         except:
552             import sys
553             import pprint
554             import traceback
555             info = sys.exc_info()
556             exception = pprint.pformat(info[1])
557             tb = '\n'.join(traceback.format_tb(info[2]))
558             return HttpResponse(_("An error occurred: %(exception)s\n\n%(tb)s") % {'exception':exception, 'tb':tb}, mimetype='text/plain')
559         return HttpResponse(_("Book imported successfully"))
560     else:
561         return HttpResponse(_("Error importing file: %r") % book_import_form.errors)
562
563
564 # info views for API
565
566 def book_info(request, id, lang='pl'):
567     book = get_object_or_404(models.Book, id=id)
568     # set language by hand
569     translation.activate(lang)
570     return render_to_response('catalogue/book_info.html', locals(),
571         context_instance=RequestContext(request))
572
573
574 def tag_info(request, id):
575     tag = get_object_or_404(models.Tag, id=id)
576     return HttpResponse(tag.description)
577
578
579 def download_zip(request, format, slug=None):
580     url = None
581     if format in models.Book.ebook_formats:
582         url = models.Book.zip_format(format)
583     elif format in ('mp3', 'ogg') and slug is not None:
584         book = get_object_or_404(models.Book, slug=slug)
585         url = book.zip_audiobooks(format)
586     else:
587         raise Http404('No format specified for zip package')
588     return HttpResponseRedirect(urlquote_plus(settings.MEDIA_URL + url, safe='/?='))
589
590
591 class CustomPDFFormView(AjaxableFormView):
592     form_class = forms.CustomPDFForm
593     title = ugettext_lazy('Download custom PDF')
594     submit = ugettext_lazy('Download')
595     honeypot = True
596
597     def __call__(self, *args, **kwargs):
598         if settings.NO_CUSTOM_PDF:
599             raise Http404('Custom PDF is disabled')
600         return super(CustomPDFFormView, self).__call__(*args, **kwargs)
601
602     def form_args(self, request, obj):
603         """Override to parse view args and give additional args to the form."""
604         return (obj,), {}
605
606     def get_object(self, request, slug, *args, **kwargs):
607         return get_object_or_404(models.Book, slug=slug)
608
609     def context_description(self, request, obj):
610         return obj.pretty_title()
611
612
613 ####
614 # Includes
615 ####
616
617
618 @ssi_included
619 def book_mini(request, pk, with_link=True):
620     book = get_object_or_404(models.Book, pk=pk)
621     author_str = ", ".join(tag.name
622         for tag in book.tags.filter(category='author'))
623     return render(request, 'catalogue/book_mini_box.html', {
624         'book': book,
625         'author_str': author_str,
626         'with_link': with_link,
627         'show_lang': book.language_code() != settings.LANGUAGE_CODE,
628     })
629
630
631 @ssi_included(get_ssi_vars=lambda pk: (lambda ipk: (
632         ('ssify.get_csrf_token',),
633         ('social_tags.likes_book', (ipk,)),
634         ('social_tags.book_shelf_tags', (ipk,)),
635     ))(ssi_expect(pk, int)))
636 def book_short(request, pk):
637     book = get_object_or_404(models.Book, pk=pk)
638     stage_note, stage_note_url = book.stage_note()
639
640     return render(request, 'catalogue/book_short.html', {
641         'book': book,
642         'has_audio': book.has_media('mp3'),
643         'main_link': book.get_absolute_url(),
644         'parents': book.parents(),
645         'tags': split_tags(book.tags.exclude(category__in=('set', 'theme'))),
646         'show_lang': book.language_code() != settings.LANGUAGE_CODE,
647         'stage_note': stage_note,
648         'stage_note_url': stage_note_url,
649     })
650
651
652 @ssi_included(get_ssi_vars=lambda pk: book_short.get_ssi_vars(pk) +
653     (lambda ipk: (
654         ('social_tags.choose_cite', [ipk]),
655         ('catalogue_tags.choose_fragment', [ipk], {
656             'unless': V('social_tags.choose_cite', [ipk])}),
657     ))(ssi_expect(pk, int)))
658 def book_wide(request, pk):
659     book = get_object_or_404(models.Book, pk=pk)
660     stage_note, stage_note_url = book.stage_note()
661     extra_info = book.extra_info
662
663     return render(request, 'catalogue/book_wide.html', {
664         'book': book,
665         'has_audio': book.has_media('mp3'),
666         'parents': book.parents(),
667         'tags': split_tags(book.tags.exclude(category__in=('set', 'theme'))),
668         'show_lang': book.language_code() != settings.LANGUAGE_CODE,
669         'stage_note': stage_note,
670         'stage_note_url': stage_note_url,
671
672         'main_link': reverse('book_text', args=[book.slug]) if book.html_file else None,
673         'extra_info': extra_info,
674         'hide_about': extra_info.get('about', '').startswith('http://wiki.wolnepodreczniki.pl'),
675         'themes': book.related_themes(),
676     })
677
678
679 @ssi_included
680 def fragment_short(request, pk):
681     fragment = get_object_or_404(models.Fragment, pk=pk)
682     return render(request, 'catalogue/fragment_short.html',
683         {'fragment': fragment})
684
685
686 @ssi_included
687 def fragment_promo(request, pk):
688     fragment = get_object_or_404(models.Fragment, pk=pk)
689     return render(request, 'catalogue/fragment_promo.html', {
690         'fragment': fragment
691     })