[MERGE] : with trunk and resolve conflicts
[odoo/odoo.git] / addons / website_blog / controllers / main.py
1 # -*- coding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2013-Today OpenERP SA (<http://www.openerp.com>).
6 #
7 #    This program is free software: you can redistribute it and/or modify
8 #    it under the terms of the GNU Affero General Public License as
9 #    published by the Free Software Foundation, either version 3 of the
10 #    License, or (at your option) any later version.
11 #
12 #    This program is distributed in the hope that it will be useful,
13 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
14 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 #    GNU Affero General Public License for more details.
16 #
17 #    You should have received a copy of the GNU Affero General Public License
18 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 #
20 ##############################################################################
21
22 import werkzeug
23 from datetime import datetime
24
25 from openerp.addons.web import http
26 from openerp.addons.web.http import request
27 from openerp.tools.translate import _
28 from openerp import SUPERUSER_ID
29 from openerp.tools import html2plaintext
30 from openerp import tools
31
32 class WebsiteBlog(http.Controller):
33     _blog_post_per_page = 20
34     _post_comment_per_page = 10
35
36     def nav_list(self):
37         blog_post_obj = request.registry['blog.post']
38         groups = blog_post_obj.read_group(request.cr, request.uid, [], ['name', 'create_date'],
39             groupby="create_date", orderby="create_date asc", context=request.context)
40         for group in groups:
41             group['date'] = "%s_%s" % (group['__domain'][0][2], group['__domain'][1][2])
42         return groups
43
44     @http.route([
45         '/blog',
46         '/blog/page/<int:page>',
47     ], type='http', auth="public", website=True, multilang=True)
48     def blogs(self, page=1):
49         cr, uid, context = request.cr, request.uid, request.context
50         blog_obj = request.registry['blog.post']
51         total = blog_obj.search(cr, uid, [], count=True, context=context)
52         pager = request.website.pager(
53             url='/blog',
54             total=total,
55             page=page,
56             step=self._blog_post_per_page,
57         )
58         bids = blog_obj.search(cr, uid, [], offset=pager['offset'], limit=self._blog_post_per_page, context=context)
59         blogs = blog_obj.browse(cr, uid, bids, context=context)
60         return request.website.render("website_blog.latest_blogs", {
61             'blogs': blogs,
62             'pager': pager
63         })
64
65     @http.route([
66         '/blog/<model("blog.blog"):blog>',
67         '/blog/<model("blog.blog"):blog>/page/<int:page>',
68         '/blog/<model("blog.blog"):blog>/tag/<model("blog.tag"):tag>',
69         '/blog/<model("blog.blog"):blog>/tag/<model("blog.tag"):tag>/page/<int:page>',
70     ], type='http', auth="public", website=True, multilang=True)
71     def blog(self, blog=None, tag=None, date=None, page=1, **opt):
72         """ Prepare all values to display the blog.
73
74         :param blog: blog currently browsed.
75         :param tag: tag that is currently used to filter blog posts
76         :param integer page: current page of the pager. Can be the blog or
77                             post pager.
78         :param date: date currently used to filter blog posts (dateBegin_dateEnd)
79
80         :return dict values: values for the templates, containing
81
82          - 'blog_posts': list of browse records that are the posts to display
83                          in a given blog, if not blog_post_id
84          - 'blog': browse of the current blog, if blog_id
85          - 'blogs': list of browse records of blogs
86          - 'pager': the pager to display posts pager in a blog
87          - 'tag': current tag, if tag_id
88          - 'nav_list': a dict [year][month] for archives navigation
89         """
90         cr, uid, context = request.cr, request.uid, request.context
91         blog_post_obj = request.registry['blog.post']
92
93         blog_obj = request.registry['blog.blog']
94         blog_ids = blog_obj.search(cr, uid, [], order="create_date asc", context=context)
95         blogs = blog_obj.browse(cr, uid, blog_ids, context=context)
96
97         path_filter = ""
98         domain = []
99         if blog:
100             path_filter += "%s" % blog.id
101             domain += [("blog_id", "in", [blog.id])]
102         if tag:
103             path_filter += 'tag/%s' % tag.id
104             domain += [("tag_ids", "in", [tag.id])]
105         if date:
106             path_filter += "date/%s" % date
107             domain += [("create_date", ">=", date.split("_")[0]), ("create_date", "<=", date.split("_")[1])]
108
109         blog_post_count = blog_post_obj.search(cr, uid, domain, count=True, context=context)
110         pager = request.website.pager(
111             url="/blog/%s" % path_filter,
112             total=blog_post_count,
113             page=page,
114             step=self._blog_post_per_page,
115             scope=10
116         )
117         blog_post_ids = blog_post_obj.search(cr, uid, domain, order="create_date asc", context=context)
118         blog_posts = blog_post_obj.browse(cr, uid, blog_post_ids, context=context)
119
120         tag_obj = request.registry['blog.tag']
121         tag_ids = tag_obj.search(cr, uid, [], context=context)
122         tags = tag_obj.browse(cr, uid, tag_ids, context=context)
123
124         values = {
125             'blog': blog,
126             'blogs': blogs,
127             'tags': tags,
128             'tag': tag,
129             'blog_posts': blog_posts,
130             'pager': pager,
131             'nav_list': self.nav_list(),
132             'path_filter': path_filter,
133             'date': date,
134         }
135         response = request.website.render("website_blog.blog_post_short", values)
136         return response
137
138     @http.route([
139         '/blog/<model("blog.blog"):blog>/post/<model("blog.post"):blog_post>',
140     ], type='http', auth="public", website=True, multilang=True)
141     def blog_post(self, blog, blog_post, enable_editor=None, **post):
142         """ Prepare all values to display the blog.
143
144         :param blog_post: blog post currently browsed. If not set, the user is
145                           browsing the blog and a post pager is calculated.
146                           If set the user is reading the blog post and a
147                           comments pager is calculated.
148         :param blog: blog currently browsed.
149         :param tag: tag that is currently used to filter blog posts
150         :param integer page: current page of the pager. Can be the blog or
151                             post pager.
152         :param date: date currently used to filter blog posts (dateBegin_dateEnd)
153
154          - 'enable_editor': editor control
155
156         :return dict values: values for the templates, containing
157
158          - 'blog_post': browse of the current post, if blog_post_id
159          - 'blog': browse of the current blog, if blog_id
160          - 'blogs': list of browse records of blogs
161          - 'pager': the pager to display comments pager in a blog post
162          - 'tag': current tag, if tag_id
163          - 'nav_list': a dict [year][month] for archives navigation
164          - 'next_blog': next blog post , display in footer
165         """
166         cr, uid, context = request.cr, request.uid, request.context
167         if not blog_post.blog_id.id==blog.id:
168             return request.redirect("/blog/%s/post/%s" % (blog_post.blog_id.id, blog_post.id))
169         blog_post_obj = request.registry.get('blog.post')
170
171         # Find next Post
172         visited_blogs = request.httprequest.cookies.get('visited_blogs') or ''
173         visited_ids = filter(None, visited_blogs.split(','))
174         visited_ids = map(lambda x: int(x), visited_ids)
175         if blog_post.id not in visited_ids:
176             visited_ids.append(blog_post.id)
177         next_post_id = blog_post_obj.search(cr, uid, [
178             ('id', 'not in', visited_ids),
179             ], order='ranking desc', limit=1, context=context)
180         next_post = next_post_id and blog_post_obj.browse(cr, uid, next_post_id[0], context=context) or False
181
182         values = {
183             'blog': blog,
184             'blog_post': blog_post,
185             'main_object': blog_post,
186             'enable_editor': enable_editor,
187             'next_post' : next_post,
188         }
189         response = request.website.render("website_blog.blog_post_complete", values)
190         response.set_cookie('visited_blogs', ','.join(map(str, visited_ids)))
191
192         request.session[request.session_id] = request.session.get(request.session_id, [])
193         if not (blog_post.id in request.session[request.session_id]):
194             request.session[request.session_id].append(blog_post.id)
195             # Increase counter
196             blog_post_obj.write(cr, SUPERUSER_ID, [blog_post.id], {
197                 'visits': blog_post.visits+1,
198             },context=context)
199         return response
200
201     def _blog_post_message(self, user, blog_post_id=0, **post):
202         cr, uid, context = request.cr, request.uid, request.context
203         blog_post = request.registry['blog.post']
204         partner_obj = request.registry['res.partner']
205         thread_obj = request.registry['mail.thread']
206         website = request.registry['website']
207
208         public_id = website.get_public_user(cr, uid, context)
209         if uid != public_id:
210             partner_ids = [user.partner_id.id]
211         else:
212             partner_ids = blog_post._find_partner_from_emails(
213                 cr, SUPERUSER_ID, 0, [post.get('email')], context=context)
214             if not partner_ids or not partner_ids[0]:
215                 partner_ids = [partner_obj.create(cr, SUPERUSER_ID, {'name': post.get('name'), 'email': post.get('email')}, context=context)]
216
217         message_id = blog_post.message_post(
218             cr, SUPERUSER_ID, int(blog_post_id),
219             body=post.get('comment'),
220             type='comment',
221             subtype='mt_comment',
222             author_id=partner_ids[0],
223             discussion=post.get('discussion'),
224             context=dict(context, mail_create_nosubcribe=True))
225         return message_id
226
227     @http.route(['/blogpost/comment'], type='http', auth="public", methods=['POST'], website=True)
228     def blog_post_comment(self, blog_post_id=0, **post):
229         cr, uid, context = request.cr, request.uid, request.context
230         if post.get('comment'):
231             user = request.registry['res.users'].browse(cr, uid, uid, context=context)
232             blog_post = request.registry['blog.post']
233             blog_post.check_access_rights(cr, uid, 'read')
234             self._blog_post_message(user, blog_post_id, **post)
235         return werkzeug.utils.redirect(request.httprequest.referrer + "#comments")
236
237     def _get_discussion_detail(self, ids, publish=False, **post):
238         cr, uid, context = request.cr, request.uid, request.context
239         values = []
240         mail_obj = request.registry.get('mail.message')
241         for message in mail_obj.browse(cr, SUPERUSER_ID, ids, context=context):
242             values.append({
243                 "id": message.id,
244                 "author_name": message.author_id.name,
245                 "author_image": message.author_id.image and \
246                     ("data:image/png;base64,%s" % message.author_id.image) or \
247                     '/website_blog/static/src/img/anonymous.png',
248                 "date": message.date,
249                 'body': html2plaintext(message.body),
250                 'website_published' : message.website_published,
251                 'publish' : publish,
252             })
253         return values
254
255     @http.route(['/blogpost/post_discussion'], type='json', auth="public", website=True)
256     def post_discussion(self, blog_post_id=0, **post):
257         cr, uid, context = request.cr, request.uid, request.context
258         publish = request.registry['res.users'].has_group(cr, uid, 'base.group_website_publisher')
259         user = request.registry['res.users'].browse(cr, uid, uid, context=context)
260         id = self._blog_post_message(user, blog_post_id, **post)
261         return self._get_discussion_detail([id], publish, **post)
262     
263     @http.route('/blogpost/new', type='http', auth="public", website=True, multilang=True)
264     def blog_post_create(self, blog_id, **post):
265         cr, uid, context = request.cr, request.uid, request.context
266         create_context = dict(context, mail_create_nosubscribe=True)
267         new_blog_post_id = request.registry['blog.post'].create(cr, uid, {
268                 'blog_id': blog_id,
269                 'name': _("Blog Post Title"),
270                 'sub_title': _("Subtitle"),
271                 'content': '',
272                 'website_published': False,
273             }, context=create_context)
274         return werkzeug.utils.redirect("/blog/%s/post/%s/?enable_editor=1" % (blog_id, new_blog_post_id))
275
276     @http.route('/blogpost/duplicate', type='http', auth="public", website=True)
277     def blog_post_copy(self, blog_post_id, **post):
278         """ Duplicate a blog.
279
280         :param blog_post_id: id of the blog post currently browsed.
281
282         :return redirect to the new blog created
283         """
284         cr, uid, context = request.cr, request.uid, request.context
285         create_context = dict(context, mail_create_nosubscribe=True)
286         nid = request.registry['blog.post'].copy(cr, uid, blog_post_id, {}, context=create_context)
287         post = request.registry['blog.post'].browse(cr, uid, nid, context)
288         return werkzeug.utils.redirect("/blog/%s/post/%s/?enable_editor=1" % (post.blog_id.id, nid))
289
290     @http.route('/blogpost/get_discussion/', type='json', auth="public", website=True)
291     def discussion(self, post_id=0, discussion=None, count=False, **post):
292         cr, uid, context = request.cr, request.uid, request.context
293         mail_obj = request.registry.get('mail.message')
294         domain = [('res_id', '=', int(post_id)) ,('model','=','blog.post'), ('discussion', '=', discussion)]
295         #check current user belongs to website publisher group
296         publish = request.registry['res.users'].has_group(cr, uid, 'base.group_website_publisher')
297         if not publish:
298             domain.append(('website_published', '=', True))
299         ids = mail_obj.search(cr, SUPERUSER_ID, domain, count=count)
300         if count:
301             return ids
302         return self._get_discussion_detail(ids, publish, **post)
303
304     @http.route('/blogpsot/change_background', type='json', auth="public", website=True)
305     def change_bg(self, post_id=0, image=None, **post):
306         post_obj = request.registry.get('blog.post')
307         values = {'content_image' : image}
308
309         ids = post_obj.write(request.cr, request.uid, [int(post_id)], values, request.context)
310         return []
311
312     @http.route('/blog/get_user/', type='json', auth="public", website=True)
313     def get_user(self, **post):
314         return [False if request.session.uid else True]