[FIX] website_blog: order archives by date desc
[odoo/odoo.git] / addons / website_blog / controllers / main.py
1 # -*- coding: utf-8 -*-
2
3 import datetime
4 import werkzeug
5
6 from openerp import tools
7 from openerp.addons.web import http
8 from openerp.addons.web.http import request
9 from openerp.addons.website.models.website import slug
10 from openerp.osv.orm import browse_record
11 from openerp.tools.translate import _
12 from openerp import SUPERUSER_ID
13 from openerp.tools import html2plaintext
14
15
16 class QueryURL(object):
17     def __init__(self, path='', path_args=None, **args):
18         self.path = path
19         self.args = args
20         self.path_args = set(path_args or [])
21
22     def __call__(self, path=None, path_args=None, **kw):
23         path = path or self.path
24         for k, v in self.args.items():
25             kw.setdefault(k, v)
26         path_args = set(path_args or []).union(self.path_args)
27         paths, fragments = [], []
28         for key, value in kw.items():
29             if value and key in path_args:
30                 if isinstance(value, browse_record):
31                     paths.append((key, slug(value)))
32                 else:
33                     paths.append((key, value))
34             elif value:
35                 if isinstance(value, list) or isinstance(value, set):
36                     fragments.append(werkzeug.url_encode([(key, item) for item in value]))
37                 else:
38                     fragments.append(werkzeug.url_encode([(key, value)]))
39         for key, value in paths:
40             path += '/' + key + '/%s' % value
41         if fragments:
42             path += '?' + '&'.join(fragments)
43         return path
44
45
46 class WebsiteBlog(http.Controller):
47     _blog_post_per_page = 20
48     _post_comment_per_page = 10
49
50     def nav_list(self):
51         blog_post_obj = request.registry['blog.post']
52         groups = blog_post_obj.read_group(
53             request.cr, request.uid, [], ['name', 'create_date'],
54             groupby="create_date", orderby="create_date desc", context=request.context)
55         for group in groups:
56             begin_date = datetime.datetime.strptime(group['__domain'][0][2], tools.DEFAULT_SERVER_DATETIME_FORMAT).date()
57             end_date = datetime.datetime.strptime(group['__domain'][1][2], tools.DEFAULT_SERVER_DATETIME_FORMAT).date()
58             group['date_begin'] = '%s' % datetime.date.strftime(begin_date, tools.DEFAULT_SERVER_DATE_FORMAT)
59             group['date_end'] = '%s' % datetime.date.strftime(end_date, tools.DEFAULT_SERVER_DATE_FORMAT)
60         return groups
61
62     @http.route([
63         '/blog',
64         '/blog/page/<int:page>',
65     ], type='http', auth="public", website=True, multilang=True)
66     def blogs(self, page=1, **post):
67         cr, uid, context = request.cr, request.uid, request.context
68         blog_obj = request.registry['blog.post']
69         total = blog_obj.search(cr, uid, [], count=True, context=context)
70         pager = request.website.pager(
71             url='/blog',
72             total=total,
73             page=page,
74             step=self._blog_post_per_page,
75         )
76         post_ids = blog_obj.search(cr, uid, [], offset=(page-1)*self._blog_post_per_page, limit=self._blog_post_per_page, context=context)
77         posts = blog_obj.browse(cr, uid, post_ids, context=context)
78         blog_url = QueryURL('', ['blog', 'tag'])
79         return request.website.render("website_blog.latest_blogs", {
80             'posts': posts,
81             'pager': pager,
82             'blog_url': blog_url,
83         })
84
85     @http.route([
86         '/blog/<model("blog.blog"):blog>',
87         '/blog/<model("blog.blog"):blog>/page/<int:page>',
88         '/blog/<model("blog.blog"):blog>/tag/<model("blog.tag"):tag>',
89         '/blog/<model("blog.blog"):blog>/tag/<model("blog.tag"):tag>/page/<int:page>',
90     ], type='http', auth="public", website=True, multilang=True)
91     def blog(self, blog=None, tag=None, page=1, **opt):
92         """ Prepare all values to display the blog.
93
94         :return dict values: values for the templates, containing
95
96          - 'blog': current blog
97          - 'blogs': all blogs for navigation
98          - 'pager': pager of posts
99          - 'tag': current tag
100          - 'tags': all tags, for navigation
101          - 'nav_list': a dict [year][month] for archives navigation
102          - 'date': date_begin optional parameter, used in archives navigation
103          - 'blog_url': help object to create URLs
104         """
105         date_begin, date_end = opt.get('date_begin'), opt.get('date_end')
106
107         cr, uid, context = request.cr, request.uid, request.context
108         blog_post_obj = request.registry['blog.post']
109
110         blog_obj = request.registry['blog.blog']
111         blog_ids = blog_obj.search(cr, uid, [], order="create_date asc", context=context)
112         blogs = blog_obj.browse(cr, uid, blog_ids, context=context)
113
114         domain = []
115         if blog:
116             domain += [('blog_id', '=', blog.id)]
117         if tag:
118             domain += [('tag_ids', 'in', tag.id)]
119         if date_begin and date_end:
120             domain += [("create_date", ">=", date_begin), ("create_date", "<=", date_end)]
121
122         blog_url = QueryURL('', ['blog', 'tag'], blog=blog, tag=tag, date_begin=date_begin, date_end=date_end)
123         post_url = QueryURL('', ['blogpost'], tag_id=tag and tag.id or None, date_begin=date_begin, date_end=date_end)
124
125         blog_post_ids = blog_post_obj.search(cr, uid, domain, order="create_date asc", context=context)
126         blog_posts = blog_post_obj.browse(cr, uid, blog_post_ids, context=context)
127
128         pager = request.website.pager(
129             url=blog_url(),
130             total=len(blog_posts),
131             page=page,
132             step=self._blog_post_per_page,
133         )
134         pager_begin = (page - 1) * self._blog_post_per_page
135         pager_end = page * self._blog_post_per_page
136         blog_posts = blog_posts[pager_begin:pager_end]
137
138         tag_obj = request.registry['blog.tag']
139         tag_ids = tag_obj.search(cr, uid, [], context=context)
140         tags = tag_obj.browse(cr, uid, tag_ids, context=context)
141
142         values = {
143             'blog': blog,
144             'blogs': blogs,
145             'tags': tags,
146             'tag': tag,
147             'blog_posts': blog_posts,
148             'pager': pager,
149             'nav_list': self.nav_list(),
150             'blog_url': blog_url,
151             'post_url': post_url,
152             'date': date_begin,
153         }
154         response = request.website.render("website_blog.blog_post_short", values)
155         return response
156
157     @http.route([
158             '''/blog/<model("blog.blog"):blog>/post/<model("blog.post", "[('blog_id','=',blog[0])]"):blog_post>''',
159     ], type='http', auth="public", website=True, multilang=True)
160     def blog_post(self, blog, blog_post, tag_id=None, page=1, enable_editor=None, **post):
161         """ Prepare all values to display the blog.
162
163         :return dict values: values for the templates, containing
164
165          - 'blog_post': browse of the current post
166          - 'blog': browse of the current blog
167          - 'blogs': list of browse records of blogs
168          - 'tag': current tag, if tag_id in parameters
169          - 'tags': all tags, for tag-based navigation
170          - 'pager': a pager on the comments
171          - 'nav_list': a dict [year][month] for archives navigation
172          - 'next_post': next blog post, to direct the user towards the next interesting post
173         """
174         cr, uid, context = request.cr, request.uid, request.context
175         tag_obj = request.registry['blog.tag']
176         blog_post_obj = request.registry['blog.post']
177         date_begin, date_end = post.get('date_begin'), post.get('date_end')
178
179         pager_url = "/blogpost/%s" % blog_post.id
180
181         pager = request.website.pager(
182             url=pager_url,
183             total=len(blog_post.website_message_ids),
184             page=page,
185             step=self._post_comment_per_page,
186             scope=7
187         )
188         pager_begin = (page - 1) * self._post_comment_per_page
189         pager_end = page * self._post_comment_per_page
190         blog_post.website_message_ids = blog_post.website_message_ids[pager_begin:pager_end]
191
192         tag = None
193         if tag_id:
194             tag = request.registry['blog.tag'].browse(request.cr, request.uid, int(tag_id), context=request.context)
195         post_url = QueryURL('', ['blogpost'], blogpost=blog_post, tag_id=tag_id, date_begin=date_begin, date_end=date_end)
196         blog_url = QueryURL('', ['blog', 'tag'], blog=blog_post.blog_id, tag=tag, date_begin=date_begin, date_end=date_end)
197
198         if not blog_post.blog_id.id == blog.id:
199             return request.redirect("/blog/%s/post/%s" % (slug(blog_post.blog_id), slug(blog_post)))
200
201         tags = tag_obj.browse(cr, uid, tag_obj.search(cr, uid, [], context=context), context=context)
202
203         # Find next Post
204         visited_blogs = request.httprequest.cookies.get('visited_blogs') or ''
205         visited_ids = filter(None, visited_blogs.split(','))
206         visited_ids = map(lambda x: int(x), visited_ids)
207         if blog_post.id not in visited_ids:
208             visited_ids.append(blog_post.id)
209         next_post_id = blog_post_obj.search(cr, uid, [
210             ('id', 'not in', visited_ids),
211         ], order='ranking desc', limit=1, context=context)
212         if not next_post_id:
213             next_post_id = blog_post_obj.search(cr, uid, [('id', '!=', blog.id)], order='ranking desc', limit=1, context=context)
214         next_post = next_post_id and blog_post_obj.browse(cr, uid, next_post_id[0], context=context) or False
215
216         values = {
217             'tags': tags,
218             'tag': tag,
219             'blog': blog,
220             'blog_post': blog_post,
221             'main_object': blog_post,
222             'nav_list': self.nav_list(),
223             'enable_editor': enable_editor,
224             'next_post': next_post,
225             'date': date_begin,
226             'post_url': post_url,
227             'blog_url': blog_url,
228             'pager': pager,
229         }
230         response = request.website.render("website_blog.blog_post_complete", values)
231         response.set_cookie('visited_blogs', ','.join(map(str, visited_ids)))
232
233         request.session[request.session_id] = request.session.get(request.session_id, [])
234         if not (blog_post.id in request.session[request.session_id]):
235             request.session[request.session_id].append(blog_post.id)
236             # Increase counter
237             blog_post_obj.write(cr, SUPERUSER_ID, [blog_post.id], {
238                 'visits': blog_post.visits+1,
239             },context=context)
240         return response
241
242     def _blog_post_message(self, user, blog_post_id=0, **post):
243         cr, uid, context = request.cr, request.uid, request.context
244         blog_post = request.registry['blog.post']
245         partner_obj = request.registry['res.partner']
246         thread_obj = request.registry['mail.thread']
247         website = request.registry['website']
248
249         public_id = website.get_public_user(cr, uid, context)
250         if uid != public_id:
251             partner_ids = [user.partner_id.id]
252         else:
253             partner_ids = blog_post._find_partner_from_emails(
254                 cr, SUPERUSER_ID, 0, [post.get('email')], context=context)
255             if not partner_ids or not partner_ids[0]:
256                 partner_ids = [partner_obj.create(cr, SUPERUSER_ID, {'name': post.get('name'), 'email': post.get('email')}, context=context)]
257
258         message_id = blog_post.message_post(
259             cr, SUPERUSER_ID, int(blog_post_id),
260             body=post.get('comment'),
261             type='comment',
262             subtype='mt_comment',
263             author_id=partner_ids[0],
264             path=post.get('path', False),
265             context=dict(context, mail_create_nosubcribe=True))
266         return message_id
267
268     @http.route(['/blogpost/comment'], type='http', auth="public", methods=['POST'], website=True)
269     def blog_post_comment(self, blog_post_id=0, **post):
270         cr, uid, context = request.cr, request.uid, request.context
271         if post.get('comment'):
272             user = request.registry['res.users'].browse(cr, uid, uid, context=context)
273             blog_post = request.registry['blog.post']
274             blog_post.check_access_rights(cr, uid, 'read')
275             self._blog_post_message(user, blog_post_id, **post)
276         return werkzeug.utils.redirect(request.httprequest.referrer + "#comments")
277
278     def _get_discussion_detail(self, ids, publish=False, **post):
279         cr, uid, context = request.cr, request.uid, request.context
280         values = []
281         mail_obj = request.registry.get('mail.message')
282         for message in mail_obj.browse(cr, SUPERUSER_ID, ids, context=context):
283             values.append({
284                 "id": message.id,
285                 "author_name": message.author_id.name,
286                 "author_image": message.author_id.image and \
287                     ("data:image/png;base64,%s" % message.author_id.image) or \
288                     '/website_blog/static/src/img/anonymous.png',
289                 "date": message.date,
290                 'body': html2plaintext(message.body),
291                 'website_published' : message.website_published,
292                 'publish' : publish,
293             })
294         return values
295
296     @http.route(['/blogpost/post_discussion'], type='json', auth="public", website=True)
297     def post_discussion(self, blog_post_id, **post):
298         cr, uid, context = request.cr, request.uid, request.context
299         publish = request.registry['res.users'].has_group(cr, uid, 'base.group_website_publisher')
300         user = request.registry['res.users'].browse(cr, uid, uid, context=context)
301         id = self._blog_post_message(user, blog_post_id, **post)
302         return self._get_discussion_detail([id], publish, **post)
303
304     @http.route('/blogpost/new', type='http', auth="public", website=True, multilang=True)
305     def blog_post_create(self, blog_id, **post):
306         cr, uid, context = request.cr, request.uid, request.context
307         create_context = dict(context, mail_create_nosubscribe=True)
308         new_blog_post_id = request.registry['blog.post'].create(cr, uid, {
309             'blog_id': blog_id,
310             'name': _("Blog Post Title"),
311             'subtitle': _("Subtitle"),
312             'content': '',
313             'website_published': False,
314         }, context=create_context)
315         new_blog_post = request.registry['blog.post'].browse(cr, uid, new_blog_post_id, context=context)
316         return werkzeug.utils.redirect("/blog/%s/post/%s?enable_editor=1" % (slug(new_blog_post.blog_id), slug(new_blog_post)))
317
318     @http.route('/blogpost/duplicate', type='http', auth="public", website=True)
319     def blog_post_copy(self, blog_post_id, **post):
320         """ Duplicate a blog.
321
322         :param blog_post_id: id of the blog post currently browsed.
323
324         :return redirect to the new blog created
325         """
326         cr, uid, context = request.cr, request.uid, request.context
327         create_context = dict(context, mail_create_nosubscribe=True)
328         nid = request.registry['blog.post'].copy(cr, uid, blog_post_id, {}, context=create_context)
329         new_blog_post = request.registry['blog.post'].browse(cr, uid, nid, context=context)
330         post = request.registry['blog.post'].browse(cr, uid, nid, context)
331         return werkzeug.utils.redirect("/blog/%s/post/%s?enable_editor=1" % (slug(post.blog_id), slug(new_blog_post)))
332
333     @http.route('/blogpost/get_discussion/', type='json', auth="public", website=True)
334     def discussion(self, post_id=0, path=None, count=False, **post):
335         cr, uid, context = request.cr, request.uid, request.context
336         mail_obj = request.registry.get('mail.message')
337         domain = [('res_id', '=', int(post_id)), ('model', '=', 'blog.post'), ('path', '=', path)]
338         #check current user belongs to website publisher group
339         publish = request.registry['res.users'].has_group(cr, uid, 'base.group_website_publisher')
340         if not publish:
341             domain.append(('website_published', '=', True))
342         ids = mail_obj.search(cr, SUPERUSER_ID, domain, count=count)
343         if count:
344             return ids
345         return self._get_discussion_detail(ids, publish, **post)
346
347     @http.route('/blogpost/change_background', type='json', auth="public", website=True)
348     def change_bg(self, post_id=0, image=None, **post):
349         if not post_id:
350             return False
351         return request.registry['blog.post'].write(request.cr, request.uid, [int(post_id)], {'background_image': image}, request.context)
352
353     @http.route('/blog/get_user/', type='json', auth="public", website=True)
354     def get_user(self, **post):
355         return [False if request.session.uid else True]