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 _
18 register = template.Library()
21 class RegistrationForm(UserCreationForm):
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)
27 class LoginForm(AuthenticationForm):
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)
43 return '%s%s' % (text[0].upper(), text[1:])
49 def simple_title(tags):
52 title.append("%s: %s" % (_(tag.category), tag.name))
53 return capfirst(', '.join(title))
57 def book_title(book, html_links=False):
58 return book.pretty_title(html_links)
62 def book_title_html(book):
63 return book_title(book, html_links=True)
67 def title_from_tags(tags):
71 result[tag.category] = tag
74 # TODO: Remove this after adding flection mechanism
75 return simple_title(tags)
77 class Flection(object):
78 def get_case(self, name, flection):
82 self = split_tags(tags)
86 # Specjalny przypadek oglądania wszystkich lektur na danej półce
87 if len(self) == 1 and 'set' in self:
88 return u'Półka %s' % self['set']
90 # Specjalny przypadek "Twórczość w pozytywizmie", wtedy gdy tylko epoka
91 # jest wybrana przez użytkownika
92 if 'epoch' in self and len(self) == 1:
93 text = u'Twórczość w %s' % flection.get_case(unicode(self['epoch']), u'miejscownik')
96 # Specjalny przypadek "Dramat w twórczości Sofoklesa", wtedy gdy podane
97 # są tylko rodzaj literacki i autor
98 if 'kind' in self and 'author' in self and len(self) == 2:
99 text = u'%s w twórczości %s' % (unicode(self['kind']),
100 flection.get_case(unicode(self['author']), u'dopełniacz'))
101 return capfirst(text)
103 # Przypadki ogólniejsze
105 title += u'Motyw %s' % unicode(self['theme'])
109 title += u' w %s' % flection.get_case(unicode(self['genre']), u'miejscownik')
111 title += unicode(self['genre'])
113 if 'kind' in self or 'author' in self or 'epoch' in self:
114 if 'genre' in self or 'theme' in self:
116 title += u' w %s ' % flection.get_case(unicode(self['kind']), u'miejscownik')
118 title += u' w twórczości '
120 title += u'%s ' % unicode(self.get('kind', u'twórczość'))
123 title += flection.get_case(unicode(self['author']), u'dopełniacz')
124 elif 'epoch' in self:
125 title += flection.get_case(unicode(self['epoch']), u'dopełniacz')
127 return capfirst(title)
131 def book_tree(book_list, books_by_parent):
132 text = "".join("<li><a href='%s'>%s</a>%s</li>" % (
133 book.get_absolute_url(), book.title, book_tree(books_by_parent.get(book, ()), books_by_parent)
134 ) for book in book_list)
137 return "<ol>%s</ol>" % text
143 def person_name(person):
144 return ' '.join(p.strip() for p in person.split(',')[::-1])
148 def user_creation_form():
149 return RegistrationForm(prefix='registration').as_ul()
153 def authentication_form():
154 return LoginForm(prefix='login').as_ul()
157 @register.inclusion_tag('catalogue/breadcrumbs.html')
158 def breadcrumbs(tags, search_form=True):
159 from catalogue.forms import SearchForm
160 context = {'tag_list': tags}
162 max_tag_list = settings.MAX_TAG_LIST
163 except AttributeError:
165 if search_form and (max_tag_list == -1 or len(tags) < max_tag_list):
166 context['search_form'] = SearchForm(tags=tags)
171 def catalogue_url(parser, token):
172 bits = token.split_contents()
179 tags_to_remove.append(bit[1:])
181 tags_to_add.append(bit)
183 return CatalogueURLNode(tags_to_add, tags_to_remove)
186 class CatalogueURLNode(Node):
187 def __init__(self, tags_to_add, tags_to_remove):
188 self.tags_to_add = [Variable(tag) for tag in tags_to_add]
189 self.tags_to_remove = [Variable(tag) for tag in tags_to_remove]
191 def render(self, context):
195 for tag_variable in self.tags_to_add:
196 tag = tag_variable.resolve(context)
197 if isinstance(tag, (list, dict)):
198 tags_to_add += [t for t in tag]
200 tags_to_add.append(tag)
202 for tag_variable in self.tags_to_remove:
203 tag = tag_variable.resolve(context)
205 tags_to_remove += [t for t in tag]
207 tags_to_remove.append(tag)
209 tag_slugs = [tag.url_chunk for tag in tags_to_add]
210 for tag in tags_to_remove:
212 tag_slugs.remove(tag.url_chunk)
216 if len(tag_slugs) > 0:
217 return reverse('tagged_object_list', kwargs={'tags': '/'.join(tag_slugs)})
219 return reverse('main_page')
222 @register.inclusion_tag('catalogue/latest_blog_posts.html')
223 def latest_blog_posts(feed_url, posts_to_show=5):
225 feed = feedparser.parse(str(feed_url))
227 for i in range(posts_to_show):
228 pub_date = feed['entries'][i].updated_parsed
229 published = datetime.date(pub_date[0], pub_date[1], pub_date[2] )
231 'title': feed['entries'][i].title,
232 'summary': feed['entries'][i].summary,
233 'link': feed['entries'][i].link,
236 return {'posts': posts}
241 @register.inclusion_tag('catalogue/tag_list.html')
242 def tag_list(tags, choices=None):
250 @register.inclusion_tag('catalogue/folded_tag_list.html')
251 def folded_tag_list(tags, choices=None):
252 tags = [tag for tag in tags if tag.count]
255 some_tags_hidden = False
256 tag_count = len(tags)
261 shown_tags = [tag for tag in tags if tag.main_page]
262 if tag_count > len(shown_tags):
263 some_tags_hidden = True