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.
9 from django import template
10 from django.template import Node, Variable
11 from django.utils.encoding import smart_str
12 from django.core.cache import get_cache
13 from django.core.urlresolvers import reverse
14 from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
15 from django.db.models import Q
16 from django.conf import settings
17 from django.template.defaultfilters import stringfilter
18 from django.utils.translation import ugettext as _
20 from catalogue import forms
21 from catalogue.utils import split_tags
22 from catalogue.models import Book, Fragment, Tag
24 register = template.Library()
27 class RegistrationForm(UserCreationForm):
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)
33 class LoginForm(AuthenticationForm):
35 "Returns this form rendered as HTML <li>s -- excluding the <ul></ul>."
36 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)
49 return '%s%s' % (text[0].upper(), text[1:])
55 def simple_title(tags):
58 title.append("%s: %s" % (_(tag.category), tag.name))
59 return capfirst(', '.join(title))
63 def book_title(book, html_links=False):
64 return book.pretty_title(html_links)
68 def book_title_html(book):
69 return book_title(book, html_links=True)
73 def title_from_tags(tags):
77 result[tag.category] = tag
80 # TODO: Remove this after adding flection mechanism
81 return simple_title(tags)
83 class Flection(object):
84 def get_case(self, name, flection):
88 self = split_tags(tags)
92 # Specjalny przypadek oglądania wszystkich lektur na danej półce
93 if len(self) == 1 and 'set' in self:
94 return u'Półka %s' % self['set']
96 # Specjalny przypadek "Twórczość w pozytywizmie", wtedy gdy tylko epoka
97 # jest wybrana przez użytkownika
98 if 'epoch' in self and len(self) == 1:
99 text = u'Twórczość w %s' % flection.get_case(unicode(self['epoch']), u'miejscownik')
100 return capfirst(text)
102 # Specjalny przypadek "Dramat w twórczości Sofoklesa", wtedy gdy podane
103 # są tylko rodzaj literacki i autor
104 if 'kind' in self and 'author' in self and len(self) == 2:
105 text = u'%s w twórczości %s' % (unicode(self['kind']),
106 flection.get_case(unicode(self['author']), u'dopełniacz'))
107 return capfirst(text)
109 # Przypadki ogólniejsze
111 title += u'Motyw %s' % unicode(self['theme'])
115 title += u' w %s' % flection.get_case(unicode(self['genre']), u'miejscownik')
117 title += unicode(self['genre'])
119 if 'kind' in self or 'author' in self or 'epoch' in self:
120 if 'genre' in self or 'theme' in self:
122 title += u' w %s ' % flection.get_case(unicode(self['kind']), u'miejscownik')
124 title += u' w twórczości '
126 title += u'%s ' % unicode(self.get('kind', u'twórczość'))
129 title += flection.get_case(unicode(self['author']), u'dopełniacz')
130 elif 'epoch' in self:
131 title += flection.get_case(unicode(self['epoch']), u'dopełniacz')
133 return capfirst(title)
137 def book_tree(book_list, books_by_parent):
138 text = "".join("<li><a href='%s'>%s</a>%s</li>" % (
139 book.get_absolute_url(), book.title, book_tree(books_by_parent.get(book, ()), books_by_parent)
140 ) for book in book_list)
143 return "<ol>%s</ol>" % text
148 def book_tree_texml(book_list, books_by_parent, depth=1):
150 <cmd name='hspace'><parm>%(depth)dem</parm></cmd>%(title)s
151 <spec cat='align' /><cmd name="note"><parm>%(audiences)s</parm></cmd>
152 <spec cat='align' /><cmd name="note"><parm>%(audiobook)s</parm></cmd>
158 "audiences": ", ".join(book.audiences_pl()),
159 "audiobook": "audiobook" if book.has_media('mp3') else "",
160 "children": book_tree_texml(books_by_parent.get(book.id, ()), books_by_parent, depth + 1)
161 } for book in book_list)
165 def all_editors(extra_info):
167 if 'editors' in extra_info:
168 editors += extra_info['editors']
169 if 'technical_editors' in extra_info:
170 editors += extra_info['technical_editors']
171 # support for extra_info-s from librarian<1.2
172 if 'editor' in extra_info:
173 editors.append(extra_info['editor'])
174 if 'technical_editor' in extra_info:
175 editors.append(extra_info['technical_editor'])
177 ' '.join(p.strip() for p in person.rsplit(',', 1)[::-1])
178 for person in sorted(set(editors)))
182 def user_creation_form():
183 return RegistrationForm(prefix='registration').as_ul()
187 def authentication_form():
188 return LoginForm(prefix='login').as_ul()
192 def catalogue_url(parser, token):
193 bits = token.split_contents()
200 tags_to_remove.append(bit[1:])
202 tags_to_add.append(bit)
204 return CatalogueURLNode(tags_to_add, tags_to_remove)
207 class CatalogueURLNode(Node):
208 def __init__(self, tags_to_add, tags_to_remove):
209 self.tags_to_add = [Variable(tag) for tag in tags_to_add]
210 self.tags_to_remove = [Variable(tag) for tag in tags_to_remove]
212 def render(self, context):
216 for tag_variable in self.tags_to_add:
217 tag = tag_variable.resolve(context)
218 if isinstance(tag, (list, dict)):
219 tags_to_add += [t for t in tag]
221 tags_to_add.append(tag)
223 for tag_variable in self.tags_to_remove:
224 tag = tag_variable.resolve(context)
226 tags_to_remove += [t for t in tag]
228 tags_to_remove.append(tag)
230 tag_slugs = [tag.url_chunk for tag in tags_to_add]
231 for tag in tags_to_remove:
233 tag_slugs.remove(tag.url_chunk)
237 if len(tag_slugs) > 0:
238 return reverse('tagged_object_list', kwargs={'tags': '/'.join(tag_slugs)})
240 return reverse('main_page')
243 @register.inclusion_tag('catalogue/latest_blog_posts.html')
244 def latest_blog_posts(feed_url, posts_to_show=5):
246 feed = feedparser.parse(str(feed_url))
248 for i in range(posts_to_show):
249 pub_date = feed['entries'][i].updated_parsed
250 published = datetime.date(pub_date[0], pub_date[1], pub_date[2] )
252 'title': feed['entries'][i].title,
253 'summary': feed['entries'][i].summary,
254 'link': feed['entries'][i].link,
257 return {'posts': posts}
262 @register.inclusion_tag('catalogue/tag_list.html')
263 def tag_list(tags, choices=None):
270 @register.inclusion_tag('catalogue/inline_tag_list.html')
271 def inline_tag_list(tags, choices=None):
279 @register.inclusion_tag('catalogue/book_info.html')
284 @register.inclusion_tag('catalogue/book_wide.html', takes_context=True)
285 def book_wide(context, book):
286 theme_counter = book.theme_counter
287 book_themes = Tag.objects.filter(pk__in=theme_counter.keys())
288 for tag in book_themes:
289 tag.count = theme_counter[tag.pk]
290 extra_info = book.get_extra_info_value()
291 hide_about = extra_info.get('about', '').startswith('http://wiki.wolnepodreczniki.pl')
295 'main_link': reverse('book_text', args=[book.slug]),
296 'related': book.related_info(),
297 'extra_info': book.get_extra_info_value(),
298 'hide_about': hide_about,
299 'themes': book_themes,
300 'custom_pdf_form': forms.CustomPDFForm(),
301 'request': context.get('request'),
305 @register.inclusion_tag('catalogue/book_short.html', takes_context=True)
306 def book_short(context, book):
309 'main_link': book.get_absolute_url(),
310 'related': book.related_info(),
311 'request': context.get('request'),
315 @register.inclusion_tag('catalogue/book_mini_box.html')
319 'related': book.related_info(),
323 @register.inclusion_tag('catalogue/work-list.html', takes_context=True)
324 def work_list(context, object_list):
325 request = context.get('request')
327 object_type = type(object_list[0]).__name__
331 @register.inclusion_tag('catalogue/fragment_promo.html')
332 def fragment_promo(arg=None):
334 fragments = Fragment.objects.all().order_by('?')
335 fragment = fragments[0] if fragments.exists() else None
336 elif isinstance(arg, Book):
337 fragment = arg.choose_fragment()
339 fragments = Fragment.tagged.with_all(arg).order_by('?')
340 fragment = fragments[0] if fragments.exists() else None
343 'fragment': fragment,
347 @register.inclusion_tag('catalogue/related_books.html')
348 def related_books(book, limit=6):
349 related = list(Book.objects.filter(
350 common_slug=book.common_slug).exclude(pk=book.pk)[:limit])
351 limit -= len(related)
353 related += Book.tagged.related_to(book,
354 Book.objects.exclude(common_slug=book.common_slug),
355 ignore_by_tag=book.book_tag())[:limit]
362 def tag_url(category, slug):
363 return reverse('catalogue.views.tagged_object_list', args=[
364 '/'.join((Tag.categories_dict[category], slug))
370 def removewholetags(value, tags):
371 """Removes a space separated list of [X]HTML tags from the output.
373 FIXME: It makes the assumption the removed tags aren't nested.
376 tags = [re.escape(tag) for tag in tags.split()]
377 tags_re = u'(%s)' % u'|'.join(tags)
378 tag_re = re.compile(ur'<%s[^>]*>.*?</\s*\1\s*>' % tags_re, re.U)
379 value = tag_re.sub(u'', value)