[IMP] renamed controllers
[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 from openerp.addons.web import http
23 from openerp.addons.web.http import request
24 from openerp.tools.translate import _
25 from openerp import SUPERUSER_ID
26
27 import werkzeug
28 import random
29 import json
30 from datetime import datetime
31 import random
32
33 from openerp.tools import html2plaintext
34
35
36 class WebsiteBlog(http.Controller):
37     _blog_post_per_page = 20
38     _post_comment_per_page = 10
39
40     def nav_list(self):
41         blog_post_obj = request.registry['blog.post']
42         groups = blog_post_obj.read_group(request.cr, request.uid, [], ['name', 'create_date'],
43             groupby="create_date", orderby="create_date asc", context=request.context)
44         for group in groups:
45             group['date'] = "%s_%s" % (group['__domain'][0][2], group['__domain'][1][2])
46         return groups
47
48     @http.route([
49         '/blog',
50         '/blog/page/<int:page>',
51     ], type='http', auth="public", website=True, multilang=True)
52     def blogs(self, page=1):
53         BYPAGE = 60
54         cr, uid, context = request.cr, request.uid, request.context
55         blog_obj = request.registry['blog.post']
56         total = blog_obj.search(cr, uid, [], count=True, context=context)
57         pager = request.website.pager(
58             url='/blog/',
59             total=total,
60             page=page,
61             step=BYPAGE,
62         )
63         bids = blog_obj.search(cr, uid, [], offset=(page-1)*BYPAGE, limit=BYPAGE, context=context)
64         blogs = blog_obj.browse(cr, uid, bids, context=context)
65         return request.website.render("website_blog.latest_blogs", {
66             'blogs': blogs,
67             'pager': pager
68         })
69
70     @http.route([
71         '/blog/<model("blog.blog"):blog>',
72         '/blog/<model("blog.blog"):blog>/page/<int:page>',
73         '/blog/<model("blog.blog"):blog>/tag/<model("blog.tag"):tag>',
74         '/blog/<model("blog.blog"):blog>/tag/<model("blog.tag"):tag>/page/<int:page>',
75         '/blog/<model("blog.blog"):blog>/date/<string(length=21):date>',
76         '/blog/<model("blog.blog"):blog>/date/<string(length=21):date>/page/<int:page>',
77         '/blog/<model("blog.blog"):blog>/tag/<model("blog.tag"):tag>/date/<string(length=21):date>',
78         '/blog/<model("blog.blog"):blog>/tag/<model("blog.tag"):tag>/date/<string(length=21):date>/page/<int:page>',
79     ], type='http', auth="public", website=True, multilang=True)
80     def blog(self, blog=None, tag=None, date=None, page=1, **opt):
81         """ Prepare all values to display the blog.
82
83         :param blog: blog currently browsed.
84         :param tag: tag that is currently used to filter blog posts
85         :param integer page: current page of the pager. Can be the blog or
86                             post pager.
87         :param date: date currently used to filter blog posts (dateBegin_dateEnd)
88
89         :return dict values: values for the templates, containing
90
91          - 'blog_posts': list of browse records that are the posts to display
92                          in a given blog, if not blog_post_id
93          - 'blog': browse of the current blog, if blog_id
94          - 'blogs': list of browse records of blogs
95          - 'pager': the pager to display posts pager in a blog
96          - 'tag': current tag, if tag_id
97          - 'nav_list': a dict [year][month] for archives navigation
98         """
99         cr, uid, context = request.cr, request.uid, request.context
100         blog_post_obj = request.registry['blog.post']
101
102         blog_obj = request.registry['blog.blog']
103         blog_ids = blog_obj.search(cr, uid, [], context=context)
104         blogs = blog_obj.browse(cr, uid, blog_ids, context=context)
105
106         path_filter = ""
107         domain = []
108         if blog:
109             path_filter += "%s/" % blog.id
110             domain += [("blog_id", "=", [blog.id])]
111         if tag:
112             path_filter += 'tag/%s/' % tag.id
113             domain += [("tag_ids", "in", [tag.id])]
114         if date:
115             path_filter += "date/%s/" % date
116             domain += [("create_date", ">=", date.split("_")[0]), ("create_date", "<=", date.split("_")[1])]
117
118         blog_post_count = blog_post_obj.search(cr, uid, domain, count=True, context=context)
119         pager = request.website.pager(
120             url="/blog/%s" % path_filter,
121             total=blog_post_count,
122             page=page,
123             step=self._blog_post_per_page,
124             scope=10
125         )
126         blog_posts = blog_post_obj.browse(cr, uid, blog_post_ids, context=context, limit=self._blog_post_per_page, offset=pager['offset'])
127
128         tag_obj = request.registry['blog.tag']
129         tag_ids = tag_obj.search(cr, uid, [], context=context)
130         tags = tag_obj.browse(cr, uid, tag_ids, context=context)
131
132         values = {
133             'blog': blog,
134             'blogs': blogs,
135             'tags': tags,
136             'tag': tag,
137             'blog_posts': blog_posts,
138             'pager': pager,
139             'nav_list': self.nav_list(),
140             'path_filter': path_filter,
141             'date': date,
142         }
143         response = request.website.render("website_blog.blog_post_short", values)
144         return response
145
146     @http.route([
147         '/blog/<model("blog.blog"):blog>/post/<model("blog.post"):blog_post>',
148     ], type='http', auth="public", website=True, multilang=True)
149     def blog_post(self, blog, blog_post, enable_editor=None, **post):
150         """ Prepare all values to display the blog.
151
152         :param blog_post: blog post currently browsed. If not set, the user is
153                           browsing the blog and a post pager is calculated.
154                           If set the user is reading the blog post and a
155                           comments pager is calculated.
156         :param blog: blog currently browsed.
157         :param tag: tag that is currently used to filter blog posts
158         :param integer page: current page of the pager. Can be the blog or
159                             post pager.
160         :param date: date currently used to filter blog posts (dateBegin_dateEnd)
161
162          - 'enable_editor': editor control
163
164         :return dict values: values for the templates, containing
165
166          - 'blog_post': browse of the current post, if blog_post_id
167          - 'blog': browse of the current blog, if blog_id
168          - 'blogs': list of browse records of blogs
169          - 'pager': the pager to display comments pager in a blog post
170          - 'tag': current tag, if tag_id
171          - 'nav_list': a dict [year][month] for archives navigation
172          - 'next_blog': next blog post , display in footer
173         """
174         cr, uid, context = request.cr, request.uid, request.context
175         if not blog_post.blog_id.id==blog.id:
176             return request.redirect("/blog/%s/post/%s" % (blog_post.blog_id.id, blog_post.id))
177         blog_post_obj = request.registry.get('blog.post')
178
179         # Find next Post
180         visited_blogs = request.httprequest.cookies.get('visited_blogs') or ''
181         visited_ids = filter(None, visited_blogs.split(','))
182         visited_ids = map(lambda x: int(x), visited_ids)
183         if blog_post.id not in visited_ids:
184             visited_ids.append(blog_post.id)
185         next_post_id = blog_post_obj.search(cr, uid, [
186             ('id', 'not in', visited_ids),
187             ], order='ranking desc', limit=1, context=context)
188         next_post = next_post_id and blog_post_obj.browse(cr, uid, next_post_id[0], context=context) or False
189
190         values = {
191             'blog': blog,
192             'blog_post': blog_post,
193             'main_object': blog_post,
194             'enable_editor': enable_editor,
195             'next_post' : next_post,
196         }
197         response = request.website.render("website_blog.blog_post_complete", values)
198         response.set_cookie('visited_blogs', ','.join(map(str, visited_ids)))
199
200         # Increase counter and ranking ratio for order
201         d = datetime.now() - datetime.strptime(blog_post.create_date, "%Y-%m-%d %H:%M:%S")
202         blog_post_obj.write(cr, SUPERUSER_ID, [blog_post.id], {
203             'visits': blog_post.visits+1,
204             'ranking': (blog_post.visits+1) * (1+random.random()) / max(1, 10+d.days)
205         },context=context)
206         return response
207
208     def _blog_post_message(self, user, blog_post_id=0, **post):
209         cr, uid, context = request.cr, request.uid, request.context
210         blog_post = request.registry['blog.post']
211         message_id = blog_post.message_post(
212             cr, uid, int(blog_post_id),
213             body=post.get('comment'),
214             type='comment',
215             subtype='mt_comment',
216             author_id= user.partner_id.id,
217             discussion=post.get('discussion'),
218             context=dict(context, mail_create_nosubcribe=True))
219         return message_id
220
221     @http.route(['/blogpost/comment'], type='http', auth="public", methods=['POST'], website=True)
222     def blog_post_comment(self, blog_post_id=0, **post):
223         cr, uid, context = request.cr, request.uid, request.context
224         if post.get('comment'):
225             user = request.registry['res.users'].browse(cr, SUPERUSER_ID, uid, context=context)
226             group_ids = user.groups_id
227             group_id = request.registry["ir.model.data"].get_object_reference(cr, uid, 'website_mail', 'group_comment')[1]
228             if group_id in [group.id for group in group_ids]:
229                 blog_post = request.registry['blog.post']
230                 blog_post.check_access_rights(cr, uid, 'read')
231                 self._blog_post_message(user, blog_post_id, **post)
232         return werkzeug.utils.redirect(request.httprequest.referrer + "#comments")
233
234     @http.route(['/blogpost/post_discussion'], type='json', auth="public", website=True)
235     def post_discussion(self, blog_post_id=0, **post):
236         cr, uid, context = request.cr, request.uid, request.context
237         values = []
238         if post.get('comment'):
239             user = request.registry['res.users'].browse(cr, SUPERUSER_ID, uid, context=context)
240             id = self._blog_post_message(user, blog_post_id, **post)
241             mail_obj = request.registry.get('mail.message')
242             post = mail_obj.browse(cr, SUPERUSER_ID, id)
243             values = {
244                 "author_name": post.author_id.name,
245                 "date": post.date,
246                 "body": html2plaintext(post.body),
247                 "author_image": "data:image/png;base64,%s" % post.author_id.image,
248                 }
249         return values
250     
251     @http.route('/blogpost/new', type='http', auth="public", website=True, multilang=True)
252     def blog_post_create(self, blog_id, **post):
253         cr, uid, context = request.cr, request.uid, request.context
254         create_context = dict(context, mail_create_nosubscribe=True)
255         new_blog_post_id = request.registry['blog.post'].create(cr, uid, {
256                 'blog_id': blog_id,
257                 'name': _("Blog Post Title"),
258                 'sub_title': _("Subtitle"),
259                 'content': '',
260                 'website_published': False,
261             }, context=create_context)
262         return werkzeug.utils.redirect("/blog/%s/post/%s/?enable_editor=1" % (blog_id, new_blog_post_id))
263
264     @http.route('/blogpost/duplicate', type='http', auth="public", website=True)
265     def blog_post_copy(self, blog_post_id, **post):
266         """ Duplicate a blog.
267
268         :param blog_post_id: id of the blog post currently browsed.
269
270         :return redirect to the new blog created
271         """
272         cr, uid, context = request.cr, request.uid, request.context
273         create_context = dict(context, mail_create_nosubscribe=True)
274         nid = request.registry['blog.post'].copy(cr, uid, blog_post_id, {}, context=create_context)
275         post = request.registry['blog.post'].browse(cr, uid, nid, context)
276         return werkzeug.utils.redirect("/blog/%s/post/%s/?enable_editor=1" % (post.blog_id.id, nid))
277
278     @http.route('/blogpost/get_discussion/', type='json', auth="public", website=True)
279     def discussion(self, post_id=0, discussion=None, **post):
280         mail_obj = request.registry.get('mail.message')
281         values = []
282         ids = mail_obj.search(request.cr, SUPERUSER_ID, [('res_id', '=', int(post_id)) ,('model','=','blog.post'), ('discussion', '=', discussion)])
283         if ids:
284             for post in mail_obj.browse(request.cr, SUPERUSER_ID, ids):
285                 values.append({
286                     "author_name": post.author_id.name,
287                     "date": post.date,
288                     'body': html2plaintext(post.body),
289                     'author_image': "data:image/png;base64,%s" % post.author_id.image,
290                 })
291         return values
292
293     @http.route('/blogpsot/change_background', type='json', auth="public", website=True)
294     def change_bg(self, post_id=0,image=None, **post):
295         post_obj = request.registry.get('blog.post')
296         values = {'content_image' : image}
297         ids = post_obj.write(request.cr, SUPERUSER_ID, [int(post_id)], values)
298         return []
299