use html5 placeholder and hide labels,
[wolnelektury.git] / apps / catalogue / templatetags / catalogue_tags.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 import datetime
6 import feedparser
7
8 from django import template
9 from django.template import Node, Variable, Template, Context
10 from django.core.urlresolvers import reverse
11 from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
12 from django.utils.translation import ugettext as _
13
14 from catalogue import forms
15 from catalogue.utils import split_tags
16 from catalogue.models import Book, Fragment, Tag
17
18 register = template.Library()
19
20
21 class RegistrationForm(UserCreationForm):
22     def as_ul(self):
23         "Returns this form rendered as HTML <li>s -- excluding the <ul></ul>."
24         return self._html_output(u'<li>%(errors)s%(label)s %(field)s<span class="help-text">%(help_text)s</span></li>', u'<li>%s</li>', '</li>', u' %s', False)
25
26
27 class LoginForm(AuthenticationForm):
28     def as_ul(self):
29         "Returns this form rendered as HTML <li>s -- excluding the <ul></ul>."
30         return self._html_output(u'<li>%(errors)s%(label)s %(field)s<span class="help-text">%(help_text)s</span></li>', u'<li>%s</li>', '</li>', u' %s', False)
31
32
33 def iterable(obj):
34     try:
35         iter(obj)
36         return True
37     except TypeError:
38         return False
39
40
41 def capfirst(text):
42     try:
43         return '%s%s' % (text[0].upper(), text[1:])
44     except IndexError:
45         return ''
46
47
48 @register.simple_tag
49 def html_title_from_tags(tags):
50     if len(tags) < 2:
51         return title_from_tags(tags)
52     template = Template("{{ category }}: <a href='{{ tag.get_absolute_url }}'>{{ tag.name }}</a>")
53     return capfirst(",<br/>".join(
54         template.render(Context({'tag': tag, 'category': _(tag.category)})) for tag in tags))
55     
56
57
58 def simple_title(tags):
59     title = []
60     for tag in tags:
61         title.append("%s: %s" % (_(tag.category), tag.name))
62     return capfirst(', '.join(title))
63
64
65 @register.simple_tag
66 def book_title(book, html_links=False):
67     return book.pretty_title(html_links)
68
69
70 @register.simple_tag
71 def book_title_html(book):
72     return book_title(book, html_links=True)
73
74
75 @register.simple_tag
76 def title_from_tags(tags):
77     def split_tags(tags):
78         result = {}
79         for tag in tags:
80             result[tag.category] = tag
81         return result
82
83     # TODO: Remove this after adding flection mechanism
84     return simple_title(tags)
85
86     class Flection(object):
87         def get_case(self, name, flection):
88             return name
89     flection = Flection()
90
91     self = split_tags(tags)
92
93     title = u''
94
95     # Specjalny przypadek oglądania wszystkich lektur na danej półce
96     if len(self) == 1 and 'set' in self:
97         return u'Półka %s' % self['set']
98
99     # Specjalny przypadek "Twórczość w pozytywizmie", wtedy gdy tylko epoka
100     # jest wybrana przez użytkownika
101     if 'epoch' in self and len(self) == 1:
102         text = u'Twórczość w %s' % flection.get_case(unicode(self['epoch']), u'miejscownik')
103         return capfirst(text)
104
105     # Specjalny przypadek "Dramat w twórczości Sofoklesa", wtedy gdy podane
106     # są tylko rodzaj literacki i autor
107     if 'kind' in self and 'author' in self and len(self) == 2:
108         text = u'%s w twórczości %s' % (unicode(self['kind']),
109             flection.get_case(unicode(self['author']), u'dopełniacz'))
110         return capfirst(text)
111
112     # Przypadki ogólniejsze
113     if 'theme' in self:
114         title += u'Motyw %s' % unicode(self['theme'])
115
116     if 'genre' in self:
117         if 'theme' in self:
118             title += u' w %s' % flection.get_case(unicode(self['genre']), u'miejscownik')
119         else:
120             title += unicode(self['genre'])
121
122     if 'kind' in self or 'author' in self or 'epoch' in self:
123         if 'genre' in self or 'theme' in self:
124             if 'kind' in self:
125                 title += u' w %s ' % flection.get_case(unicode(self['kind']), u'miejscownik')
126             else:
127                 title += u' w twórczości '
128         else:
129             title += u'%s ' % unicode(self.get('kind', u'twórczość'))
130
131     if 'author' in self:
132         title += flection.get_case(unicode(self['author']), u'dopełniacz')
133     elif 'epoch' in self:
134         title += flection.get_case(unicode(self['epoch']), u'dopełniacz')
135
136     return capfirst(title)
137
138
139 @register.simple_tag
140 def book_tree(book_list, books_by_parent):
141     text = "".join("<li><a href='%s'>%s</a>%s</li>" % (
142         book.get_absolute_url(), book.title, book_tree(books_by_parent.get(book, ()), books_by_parent)
143         ) for book in book_list)
144
145     if text:
146         return "<ol>%s</ol>" % text
147     else:
148         return ''
149
150 @register.simple_tag
151 def book_tree_texml(book_list, books_by_parent, depth=1):
152     return "".join("""
153             <cmd name='hspace'><parm>%(depth)dem</parm></cmd>%(title)s
154             <spec cat='align' /><cmd name="note"><parm>%(audiences)s</parm></cmd>
155             <spec cat='align' /><cmd name="note"><parm>%(audiobook)s</parm></cmd>
156             <ctrl ch='\\' />
157             %(children)s
158             """ % {
159                 "depth": depth,
160                 "title": book.title, 
161                 "audiences": ", ".join(book.audiences_pl()),
162                 "audiobook": "audiobook" if book.has_media('mp3') else "",
163                 "children": book_tree_texml(books_by_parent.get(book.id, ()), books_by_parent, depth + 1)
164             } for book in book_list)
165
166
167 @register.simple_tag
168 def all_editors(extra_info):
169     editors = []
170     if 'editors' in extra_info:
171         editors += extra_info['editors']
172     if 'technical_editors' in extra_info:
173         editors += extra_info['technical_editors']
174     # support for extra_info-s from librarian<1.2
175     if 'editor' in extra_info:
176         editors.append(extra_info['editor'])
177     if 'technical_editor' in extra_info:
178         editors.append(extra_info['technical_editor'])
179     return ', '.join(
180                      ' '.join(p.strip() for p in person.rsplit(',', 1)[::-1])
181                      for person in sorted(set(editors)))
182
183
184 @register.simple_tag
185 def user_creation_form():
186     return RegistrationForm(prefix='registration').as_ul()
187
188
189 @register.simple_tag
190 def authentication_form():
191     return LoginForm(prefix='login').as_ul()
192
193
194 @register.tag
195 def catalogue_url(parser, token):
196     bits = token.split_contents()
197     tag_name = bits[0]
198
199     tags_to_add = []
200     tags_to_remove = []
201     for bit in bits[1:]:
202         if bit[0] == '-':
203             tags_to_remove.append(bit[1:])
204         else:
205             tags_to_add.append(bit)
206
207     return CatalogueURLNode(tags_to_add, tags_to_remove)
208
209
210 class CatalogueURLNode(Node):
211     def __init__(self, tags_to_add, tags_to_remove):
212         self.tags_to_add = [Variable(tag) for tag in tags_to_add]
213         self.tags_to_remove = [Variable(tag) for tag in tags_to_remove]
214
215     def render(self, context):
216         tags_to_add = []
217         tags_to_remove = []
218
219         for tag_variable in self.tags_to_add:
220             tag = tag_variable.resolve(context)
221             if isinstance(tag, (list, dict)):
222                 tags_to_add += [t for t in tag]
223             else:
224                 tags_to_add.append(tag)
225
226         for tag_variable in self.tags_to_remove:
227             tag = tag_variable.resolve(context)
228             if iterable(tag):
229                 tags_to_remove += [t for t in tag]
230             else:
231                 tags_to_remove.append(tag)
232
233         tag_slugs = [tag.url_chunk for tag in tags_to_add]
234         for tag in tags_to_remove:
235             try:
236                 tag_slugs.remove(tag.url_chunk)
237             except KeyError:
238                 pass
239
240         if len(tag_slugs) > 0:
241             return reverse('tagged_object_list', kwargs={'tags': '/'.join(tag_slugs)})
242         else:
243             return reverse('main_page')
244
245
246 @register.inclusion_tag('catalogue/latest_blog_posts.html')
247 def latest_blog_posts(feed_url, posts_to_show=5):
248     try:
249         feed = feedparser.parse(str(feed_url))
250         posts = []
251         for i in range(posts_to_show):
252             pub_date = feed['entries'][i].updated_parsed
253             published = datetime.date(pub_date[0], pub_date[1], pub_date[2] )
254             posts.append({
255                 'title': feed['entries'][i].title,
256                 'summary': feed['entries'][i].summary,
257                 'link': feed['entries'][i].link,
258                 'date': published,
259                 })
260         return {'posts': posts}
261     except:
262         return {'posts': []}
263
264
265 @register.inclusion_tag('catalogue/tag_list.html')
266 def tag_list(tags, choices=None):
267     if choices is None:
268         choices = []
269     if len(tags) == 1:
270         one_tag = tags[0]
271     return locals()
272
273 @register.inclusion_tag('catalogue/inline_tag_list.html')
274 def inline_tag_list(tags, choices=None):
275     if choices is None:
276         choices = []
277     if len(tags) == 1:
278         one_tag = tags[0]
279     return locals()
280
281
282 @register.inclusion_tag('catalogue/book_info.html')
283 def book_info(book):
284     return locals()
285
286
287 @register.inclusion_tag('catalogue/book_wide.html', takes_context=True)
288 def book_wide(context, book):
289     theme_counter = book.theme_counter
290     book_themes = Tag.objects.filter(pk__in=theme_counter.keys())
291     for tag in book_themes:
292         tag.count = theme_counter[tag.pk]
293     extra_info = book.get_extra_info_value()
294     hide_about = extra_info.get('about', '').startswith('http://wiki.wolnepodreczniki.pl')
295
296     return {
297         'book': book,
298         'main_link': reverse('book_text', args=[book.slug]),
299         'related': book.related_info(),
300         'extra_info': book.get_extra_info_value(),
301         'hide_about': hide_about,
302         'themes': book_themes,
303         'custom_pdf_form': forms.CustomPDFForm(),
304         'request': context.get('request'),
305     }
306
307
308 @register.inclusion_tag('catalogue/book_short.html', takes_context=True)
309 def book_short(context, book):
310     return {
311         'book': book,
312         'main_link': book.get_absolute_url(),
313         'related': book.related_info(),
314         'request': context.get('request'),
315     }
316
317
318 @register.inclusion_tag('catalogue/book_mini_box.html')
319 def book_mini(book):
320     return {
321         'book': book,
322         'related': book.related_info(),
323     }
324
325
326 @register.inclusion_tag('catalogue/work-list.html', takes_context=True)
327 def work_list(context, object_list):
328     request = context.get('request')
329     if object_list:
330         object_type = type(object_list[0]).__name__
331     return locals()
332
333
334 @register.inclusion_tag('catalogue/fragment_promo.html')
335 def fragment_promo(arg=None):
336     if arg is None:
337         fragments = Fragment.objects.all().order_by('?')
338         fragment = fragments[0] if fragments.exists() else None
339     elif isinstance(arg, Book):
340         fragment = arg.choose_fragment()
341     else:
342         fragments = Fragment.tagged.with_all(arg).order_by('?')
343         fragment = fragments[0] if fragments.exists() else None
344
345     return {
346         'fragment': fragment,
347     }
348
349
350 @register.inclusion_tag('catalogue/related_books.html')
351 def related_books(book, limit=6):
352     related = list(Book.objects.filter(
353         common_slug=book.common_slug).exclude(pk=book.pk)[:limit])
354     limit -= len(related)
355     if limit:
356         related += Book.tagged.related_to(book,
357                 Book.objects.exclude(common_slug=book.common_slug),
358                 ignore_by_tag=book.book_tag())[:limit]
359     return {
360         'books': related,
361     }
362
363
364 @register.inclusion_tag('catalogue/menu.html')
365 def catalogue_menu():
366     tags = Tag.objects.filter(
367             category__in=('author', 'epoch', 'genre', 'kind', 'theme')
368         ).exclude(book_count=0)
369     return split_tags(tags)
370     
371
372
373 @register.simple_tag
374 def tag_url(category, slug):
375     return reverse('catalogue.views.tagged_object_list', args=[
376         '/'.join((Tag.categories_dict[category], slug))
377     ])