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.
8 from django import template
9 from django.template import Node, Variable
10 from django.utils.encoding import smart_str
11 from django.core.urlresolvers import reverse
12 from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
13 from django.db.models import Q
14 from django.conf import settings
15 from django.utils.translation import ugettext as _
17 from catalogue.forms import SearchForm
20 register = template.Library()
23 class RegistrationForm(UserCreationForm):
25 "Returns this form rendered as HTML <li>s -- excluding the <ul></ul>."
26 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)
29 class LoginForm(AuthenticationForm):
31 "Returns this form rendered as HTML <li>s -- excluding the <ul></ul>."
32 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)
45 return '%s%s' % (text[0].upper(), text[1:])
51 def simple_title(tags):
54 title.append("%s: %s" % (_(tag.category), tag.name))
55 return capfirst(', '.join(title))
59 def book_title(book, html_links=False):
60 return book.pretty_title(html_links)
64 def book_title_html(book):
65 return book_title(book, html_links=True)
69 def title_from_tags(tags):
73 result[tag.category] = tag
76 # TODO: Remove this after adding flection mechanism
77 return simple_title(tags)
79 class Flection(object):
80 def get_case(self, name, flection):
84 self = split_tags(tags)
88 # Specjalny przypadek oglądania wszystkich lektur na danej półce
89 if len(self) == 1 and 'set' in self:
90 return u'Półka %s' % self['set']
92 # Specjalny przypadek "Twórczość w pozytywizmie", wtedy gdy tylko epoka
93 # jest wybrana przez użytkownika
94 if 'epoch' in self and len(self) == 1:
95 text = u'Twórczość w %s' % flection.get_case(unicode(self['epoch']), u'miejscownik')
98 # Specjalny przypadek "Dramat w twórczości Sofoklesa", wtedy gdy podane
99 # są tylko rodzaj literacki i autor
100 if 'kind' in self and 'author' in self and len(self) == 2:
101 text = u'%s w twórczości %s' % (unicode(self['kind']),
102 flection.get_case(unicode(self['author']), u'dopełniacz'))
103 return capfirst(text)
105 # Przypadki ogólniejsze
107 title += u'Motyw %s' % unicode(self['theme'])
111 title += u' w %s' % flection.get_case(unicode(self['genre']), u'miejscownik')
113 title += unicode(self['genre'])
115 if 'kind' in self or 'author' in self or 'epoch' in self:
116 if 'genre' in self or 'theme' in self:
118 title += u' w %s ' % flection.get_case(unicode(self['kind']), u'miejscownik')
120 title += u' w twórczości '
122 title += u'%s ' % unicode(self.get('kind', u'twórczość'))
125 title += flection.get_case(unicode(self['author']), u'dopełniacz')
126 elif 'epoch' in self:
127 title += flection.get_case(unicode(self['epoch']), u'dopełniacz')
129 return capfirst(title)
133 def book_tree(book_list, books_by_parent):
134 text = "".join("<li><a href='%s'>%s</a>%s</li>" % (
135 book.get_absolute_url(), book.title, book_tree(books_by_parent.get(book, ()), books_by_parent)
136 ) for book in book_list)
139 return "<ol>%s</ol>" % text
144 def book_tree_texml(book_list, books_by_parent, depth=1):
146 <cmd name='hspace'><parm>%(depth)dem</parm></cmd>%(title)s
147 <spec cat='align' /><cmd name="note"><parm>%(audiences)s</parm></cmd>
148 <spec cat='align' /><cmd name="note"><parm>%(audiobook)s</parm></cmd>
154 "audiences": ", ".join(book.audiences_pl()),
155 "audiobook": "audiobook" if book.has_media('mp3') else "",
156 "children": book_tree_texml(books_by_parent.get(book.id, ()), books_by_parent, depth + 1)
157 } for book in book_list)
161 def all_editors(extra_info):
163 if 'editors' in extra_info:
164 editors += extra_info['editors']
165 if 'technical_editors' in extra_info:
166 editors += extra_info['technical_editors']
167 # support for extra_info-s from librarian<1.2
168 if 'editor' in extra_info:
169 editors.append(extra_info['editor'])
170 if 'technical_editor' in extra_info:
171 editors.append(extra_info['technical_editor'])
173 ' '.join(p.strip() for p in person.rsplit(',', 1)[::-1])
174 for person in sorted(set(editors)))
178 def user_creation_form():
179 return RegistrationForm(prefix='registration').as_ul()
183 def authentication_form():
184 return LoginForm(prefix='login').as_ul()
187 @register.inclusion_tag('catalogue/search_form.html')
189 return {"form": SearchForm()}
191 @register.inclusion_tag('catalogue/breadcrumbs.html')
192 def breadcrumbs(tags, search_form=True):
193 context = {'tag_list': tags}
195 max_tag_list = settings.MAX_TAG_LIST
196 except AttributeError:
198 if search_form and (max_tag_list == -1 or len(tags) < max_tag_list):
199 context['search_form'] = SearchForm(tags=tags)
204 def catalogue_url(parser, token):
205 bits = token.split_contents()
212 tags_to_remove.append(bit[1:])
214 tags_to_add.append(bit)
216 return CatalogueURLNode(tags_to_add, tags_to_remove)
219 class CatalogueURLNode(Node):
220 def __init__(self, tags_to_add, tags_to_remove):
221 self.tags_to_add = [Variable(tag) for tag in tags_to_add]
222 self.tags_to_remove = [Variable(tag) for tag in tags_to_remove]
224 def render(self, context):
228 for tag_variable in self.tags_to_add:
229 tag = tag_variable.resolve(context)
230 if isinstance(tag, (list, dict)):
231 tags_to_add += [t for t in tag]
233 tags_to_add.append(tag)
235 for tag_variable in self.tags_to_remove:
236 tag = tag_variable.resolve(context)
238 tags_to_remove += [t for t in tag]
240 tags_to_remove.append(tag)
242 tag_slugs = [tag.url_chunk for tag in tags_to_add]
243 for tag in tags_to_remove:
245 tag_slugs.remove(tag.url_chunk)
249 if len(tag_slugs) > 0:
250 return reverse('tagged_object_list', kwargs={'tags': '/'.join(tag_slugs)})
252 return reverse('main_page')
255 @register.inclusion_tag('catalogue/latest_blog_posts.html')
256 def latest_blog_posts(feed_url, posts_to_show=5):
258 feed = feedparser.parse(str(feed_url))
260 for i in range(posts_to_show):
261 pub_date = feed['entries'][i].updated_parsed
262 published = datetime.date(pub_date[0], pub_date[1], pub_date[2] )
264 'title': feed['entries'][i].title,
265 'summary': feed['entries'][i].summary,
266 'link': feed['entries'][i].link,
269 return {'posts': posts}
274 @register.inclusion_tag('catalogue/tag_list.html')
275 def tag_list(tags, choices=None):
283 @register.inclusion_tag('catalogue/book_info.html')