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.utils import split_tags
21 from catalogue.models import Book, Fragment
23 register = template.Library()
26 class RegistrationForm(UserCreationForm):
28 "Returns this form rendered as HTML <li>s -- excluding the <ul></ul>."
29 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)
32 class LoginForm(AuthenticationForm):
34 "Returns this form rendered as HTML <li>s -- excluding the <ul></ul>."
35 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)
48 return '%s%s' % (text[0].upper(), text[1:])
54 def simple_title(tags):
57 title.append("%s: %s" % (_(tag.category), tag.name))
58 return capfirst(', '.join(title))
62 def book_title(book, html_links=False):
63 return book.pretty_title(html_links)
67 def book_title_html(book):
68 return book_title(book, html_links=True)
72 def title_from_tags(tags):
76 result[tag.category] = tag
79 # TODO: Remove this after adding flection mechanism
80 return simple_title(tags)
82 class Flection(object):
83 def get_case(self, name, flection):
87 self = split_tags(tags)
91 # Specjalny przypadek oglądania wszystkich lektur na danej półce
92 if len(self) == 1 and 'set' in self:
93 return u'Półka %s' % self['set']
95 # Specjalny przypadek "Twórczość w pozytywizmie", wtedy gdy tylko epoka
96 # jest wybrana przez użytkownika
97 if 'epoch' in self and len(self) == 1:
98 text = u'Twórczość w %s' % flection.get_case(unicode(self['epoch']), u'miejscownik')
101 # Specjalny przypadek "Dramat w twórczości Sofoklesa", wtedy gdy podane
102 # są tylko rodzaj literacki i autor
103 if 'kind' in self and 'author' in self and len(self) == 2:
104 text = u'%s w twórczości %s' % (unicode(self['kind']),
105 flection.get_case(unicode(self['author']), u'dopełniacz'))
106 return capfirst(text)
108 # Przypadki ogólniejsze
110 title += u'Motyw %s' % unicode(self['theme'])
114 title += u' w %s' % flection.get_case(unicode(self['genre']), u'miejscownik')
116 title += unicode(self['genre'])
118 if 'kind' in self or 'author' in self or 'epoch' in self:
119 if 'genre' in self or 'theme' in self:
121 title += u' w %s ' % flection.get_case(unicode(self['kind']), u'miejscownik')
123 title += u' w twórczości '
125 title += u'%s ' % unicode(self.get('kind', u'twórczość'))
128 title += flection.get_case(unicode(self['author']), u'dopełniacz')
129 elif 'epoch' in self:
130 title += flection.get_case(unicode(self['epoch']), u'dopełniacz')
132 return capfirst(title)
136 def book_tree(book_list, books_by_parent):
137 text = "".join("<li><a href='%s'>%s</a>%s</li>" % (
138 book.get_absolute_url(), book.title, book_tree(books_by_parent.get(book, ()), books_by_parent)
139 ) for book in book_list)
142 return "<ol>%s</ol>" % text
147 def book_tree_texml(book_list, books_by_parent, depth=1):
149 <cmd name='hspace'><parm>%(depth)dem</parm></cmd>%(title)s
150 <spec cat='align' /><cmd name="note"><parm>%(audiences)s</parm></cmd>
151 <spec cat='align' /><cmd name="note"><parm>%(audiobook)s</parm></cmd>
157 "audiences": ", ".join(book.audiences_pl()),
158 "audiobook": "audiobook" if book.has_media('mp3') else "",
159 "children": book_tree_texml(books_by_parent.get(book.id, ()), books_by_parent, depth + 1)
160 } for book in book_list)
164 def all_editors(extra_info):
166 if 'editors' in extra_info:
167 editors += extra_info['editors']
168 if 'technical_editors' in extra_info:
169 editors += extra_info['technical_editors']
170 # support for extra_info-s from librarian<1.2
171 if 'editor' in extra_info:
172 editors.append(extra_info['editor'])
173 if 'technical_editor' in extra_info:
174 editors.append(extra_info['technical_editor'])
176 ' '.join(p.strip() for p in person.rsplit(',', 1)[::-1])
177 for person in sorted(set(editors)))
181 def user_creation_form():
182 return RegistrationForm(prefix='registration').as_ul()
186 def authentication_form():
187 return LoginForm(prefix='login').as_ul()
191 def catalogue_url(parser, token):
192 bits = token.split_contents()
199 tags_to_remove.append(bit[1:])
201 tags_to_add.append(bit)
203 return CatalogueURLNode(tags_to_add, tags_to_remove)
206 class CatalogueURLNode(Node):
207 def __init__(self, tags_to_add, tags_to_remove):
208 self.tags_to_add = [Variable(tag) for tag in tags_to_add]
209 self.tags_to_remove = [Variable(tag) for tag in tags_to_remove]
211 def render(self, context):
215 for tag_variable in self.tags_to_add:
216 tag = tag_variable.resolve(context)
217 if isinstance(tag, (list, dict)):
218 tags_to_add += [t for t in tag]
220 tags_to_add.append(tag)
222 for tag_variable in self.tags_to_remove:
223 tag = tag_variable.resolve(context)
225 tags_to_remove += [t for t in tag]
227 tags_to_remove.append(tag)
229 tag_slugs = [tag.url_chunk for tag in tags_to_add]
230 for tag in tags_to_remove:
232 tag_slugs.remove(tag.url_chunk)
236 if len(tag_slugs) > 0:
237 return reverse('tagged_object_list', kwargs={'tags': '/'.join(tag_slugs)})
239 return reverse('main_page')
242 @register.inclusion_tag('catalogue/latest_blog_posts.html')
243 def latest_blog_posts(feed_url, posts_to_show=5):
245 feed = feedparser.parse(str(feed_url))
247 for i in range(posts_to_show):
248 pub_date = feed['entries'][i].updated_parsed
249 published = datetime.date(pub_date[0], pub_date[1], pub_date[2] )
251 'title': feed['entries'][i].title,
252 'summary': feed['entries'][i].summary,
253 'link': feed['entries'][i].link,
256 return {'posts': posts}
261 @register.inclusion_tag('catalogue/tag_list.html')
262 def tag_list(tags, choices=None):
269 @register.inclusion_tag('catalogue/inline_tag_list.html')
270 def inline_tag_list(tags, choices=None):
278 @register.inclusion_tag('catalogue/book_info.html')
283 @register.inclusion_tag('catalogue/book_wide.html', takes_context=True)
284 def book_wide(context, book):
286 # files generated during publication
287 for ebook_format in book.ebook_formats:
288 if book.has_media(ebook_format):
289 formats[ebook_format] = book.get_media(ebook_format)
292 'related': book.related_info(),
295 'extra_info': book.get_extra_info_value(),
296 'request': context.get('request'),
297 'fragment': book.choose_fragment(),
301 @register.inclusion_tag('catalogue/book_short.html', takes_context=True)
302 def book_short(context, book):
304 'related': book.related_info(),
306 'request': context.get('request'),
310 @register.inclusion_tag('catalogue/book_mini_box.html')
313 'related': book.related_info(),
318 @register.inclusion_tag('catalogue/work-list.html', takes_context=True)
319 def work_list(context, object_list):
320 request = context.get('request')
322 object_type = type(object_list[0]).__name__
326 @register.inclusion_tag('catalogue/fragment_promo.html')
327 def fragment_promo(arg=None):
329 fragments = Fragment.objects.all().order_by('?')
330 fragment = fragments[0] if fragments.exists() else None
331 elif isinstance(arg, Book):
332 fragment = arg.choose_fragment()
334 fragments = Fragment.tagged.with_all(arg).order_by('?')
335 fragment = fragments[0] if fragments.exists() else None
338 'fragment': fragment,
342 @register.inclusion_tag('catalogue/related_books.html')
343 def related_books(book, limit=6):
344 related = list(Book.objects.filter(
345 common_slug=book.common_slug).exclude(pk=book.pk)[:limit])
346 limit -= len(related)
348 related += Book.tagged.related_to(book,
349 Book.objects.exclude(common_slug=book.common_slug),
350 ignore_by_tag=book.book_tag())[:limit]
358 def removewholetags(value, tags):
359 """Removes a space separated list of [X]HTML tags from the output.
361 FIXME: It makes the assumption the removed tags aren't nested.
364 tags = [re.escape(tag) for tag in tags.split()]
365 tags_re = u'(%s)' % u'|'.join(tags)
366 tag_re = re.compile(ur'<%s[^>]*>.*?</\s*\1\s*>' % tags_re, re.U)
367 value = tag_re.sub(u'', value)