[FIX] website_blog: Show tag by blog. No interest to display all tag, anyway the...
[odoo/odoo.git] / addons / website_blog / models / website_blog.py
1 # -*- coding: utf-8 -*-
2
3 from datetime import datetime
4 import difflib
5 import lxml
6 import random
7
8 from openerp import tools
9 from openerp import SUPERUSER_ID
10 from openerp.addons.website.models.website import slug
11 from openerp.osv import osv, fields
12 from openerp.tools.translate import _
13
14
15 class Blog(osv.Model):
16     _name = 'blog.blog'
17     _description = 'Blogs'
18     _inherit = ['mail.thread', 'website.seo.metadata']
19     _order = 'name'
20     _columns = {
21         'name': fields.char('Blog Name', required=True),
22         'subtitle': fields.char('Blog Subtitle'),
23         'description': fields.text('Description'),
24     }
25
26     def all_tags(self, cr, uid, ids, min_limit=1, context=None):
27         req = """
28             SELECT
29                 p.blog_id, count(*), r.blog_tag_id
30             FROM
31                 blog_post_blog_tag_rel r
32                     join blog_post p on r.blog_post_id=p.id
33             WHERE
34                 p.blog_id in %s
35             GROUP BY
36                 p.blog_id,
37                 r.blog_tag_id
38             ORDER BY
39                 count(*) DESC
40         """
41         cr.execute(req, [tuple(ids)])
42         tag_by_blog = {i: [] for i in ids}
43         for blog_id, freq, tag_id in cr.fetchall():
44             if freq >= min_limit:
45                 tag_by_blog[blog_id].append(tag_id)
46
47         tag_obj = self.pool['blog.tag']
48         for blog_id in tag_by_blog:
49             tag_by_blog[blog_id] = tag_obj.browse(cr, uid, tag_by_blog[blog_id], context=context)
50         return tag_by_blog
51
52
53 class BlogTag(osv.Model):
54     _name = 'blog.tag'
55     _description = 'Blog Tag'
56     _inherit = ['website.seo.metadata']
57     _order = 'name'
58     _columns = {
59         'name': fields.char('Name', required=True),
60         'post_ids': fields.many2many(
61             'blog.post', string='Posts',
62         ),
63     }
64
65
66 class BlogPost(osv.Model):
67     _name = "blog.post"
68     _description = "Blog Post"
69     _inherit = ['mail.thread', 'website.seo.metadata']
70     _order = 'id DESC'
71
72     def _compute_ranking(self, cr, uid, ids, name, arg, context=None):
73         res = {}
74         for blog_post in self.browse(cr, uid, ids, context=context):
75             age = datetime.now() - datetime.strptime(blog_post.create_date, tools.DEFAULT_SERVER_DATETIME_FORMAT)
76             res[blog_post.id] = blog_post.visits * (0.5+random.random()) / max(3, age.days)
77         return res
78
79     _columns = {
80         'name': fields.char('Title', required=True, translate=True),
81         'subtitle': fields.char('Sub Title', translate=True),
82         'author_id': fields.many2one('res.partner', 'Author'),
83         'background_image': fields.binary('Background Image', oldname='content_image'),
84         'blog_id': fields.many2one(
85             'blog.blog', 'Blog',
86             required=True, ondelete='cascade',
87         ),
88         'tag_ids': fields.many2many(
89             'blog.tag', string='Tags',
90         ),
91         'content': fields.html('Content', translate=True, sanitize=False),
92         # website control
93         'website_published': fields.boolean(
94             'Publish', help="Publish on the website", copy=False,
95         ),
96         'website_message_ids': fields.one2many(
97             'mail.message', 'res_id',
98             domain=lambda self: [
99                 '&', '&', ('model', '=', self._name), ('type', '=', 'comment'), ('path', '=', False)
100             ],
101             string='Website Messages',
102             help="Website communication history",
103         ),
104         'history_ids': fields.one2many(
105             'blog.post.history', 'post_id',
106             'History', help='Last post modifications',
107         ),
108         # creation / update stuff
109         'create_date': fields.datetime(
110             'Created on',
111             select=True, readonly=True,
112         ),
113         'create_uid': fields.many2one(
114             'res.users', 'Author',
115             select=True, readonly=True,
116         ),
117         'write_date': fields.datetime(
118             'Last Modified on',
119             select=True, readonly=True,
120         ),
121         'write_uid': fields.many2one(
122             'res.users', 'Last Contributor',
123             select=True, readonly=True,
124         ),
125         'author_avatar': fields.related(
126             'author_id', 'image_small',
127             string="Avatar", type="binary"),
128         'visits': fields.integer('No of Views'),
129         'ranking': fields.function(_compute_ranking, string='Ranking', type='float'),
130     }
131
132     _defaults = {
133         'name': _('Blog Post Title'),
134         'subtitle': _('Subtitle'),
135         'author_id': lambda self, cr, uid, ctx=None: self.pool['res.users'].browse(cr, uid, uid, context=ctx).partner_id.id,
136     }
137
138     def html_tag_nodes(self, html, attribute=None, tags=None, context=None):
139         """ Processing of html content to tag paragraphs and set them an unique
140         ID.
141         :return result: (html, mappin), where html is the updated html with ID
142                         and mapping is a list of (old_ID, new_ID), where old_ID
143                         is None is the paragraph is a new one. """
144         mapping = []
145         if not html:
146             return html, mapping
147         if tags is None:
148             tags = ['p']
149         if attribute is None:
150             attribute = 'data-unique-id'
151         counter = 0
152
153         # form a tree
154         root = lxml.html.fragment_fromstring(html, create_parent='div')
155         if not len(root) and root.text is None and root.tail is None:
156             return html, mapping
157
158         # check all nodes, replace :
159         # - img src -> check URL
160         # - a href -> check URL
161         for node in root.iter():
162             if not node.tag in tags:
163                 continue
164             ancestor_tags = [parent.tag for parent in node.iterancestors()]
165             if ancestor_tags:
166                 ancestor_tags.pop()
167             ancestor_tags.append('counter_%s' % counter)
168             new_attribute = '/'.join(reversed(ancestor_tags))
169             old_attribute = node.get(attribute)
170             node.set(attribute, new_attribute)
171             mapping.append((old_attribute, counter))
172             counter += 1
173
174         html = lxml.html.tostring(root, pretty_print=False, method='html')
175         # this is ugly, but lxml/etree tostring want to put everything in a 'div' that breaks the editor -> remove that
176         if html.startswith('<div>') and html.endswith('</div>'):
177             html = html[5:-6]
178         return html, mapping
179
180     def _postproces_content(self, cr, uid, id, content=None, context=None):
181         if content is None:
182             content = self.browse(cr, uid, id, context=context).content
183         if content is False:
184             return content
185         content, mapping = self.html_tag_nodes(content, attribute='data-chatter-id', tags=['p'], context=context)
186         for old_attribute, new_attribute in mapping:
187             if not old_attribute:
188                 continue
189             msg_ids = self.pool['mail.message'].search(cr, SUPERUSER_ID, [('path', '=', old_attribute)], context=context)
190             self.pool['mail.message'].write(cr, SUPERUSER_ID, msg_ids, {'path': new_attribute}, context=context)
191         return content
192
193     def create_history(self, cr, uid, ids, vals, context=None):
194         for i in ids:
195             history = self.pool.get('blog.post.history')
196             if vals.get('content'):
197                 res = {
198                     'content': vals.get('content', ''),
199                     'post_id': i,
200                 }
201                 history.create(cr, uid, res)
202
203     def _check_for_publication(self, cr, uid, ids, vals, context=None):
204         if vals.get('website_published'):
205             base_url = self.pool['ir.config_parameter'].get_param(cr, uid, 'web.base.url')
206             for post in self.browse(cr, uid, ids, context=context):
207                 post.blog_id.message_post(
208                     body='<p>%(post_publication)s <a href="%(base_url)s/blog/%(blog_slug)s/post/%(post_slug)s">%(post_link)s</a></p>' % {
209                         'post_publication': _('A new post %s has been published on the %s blog.') % (post.name, post.blog_id.name),
210                         'post_link': _('Click here to access the post.'),
211                         'base_url': base_url,
212                         'blog_slug': slug(post.blog_id),
213                         'post_slug': slug(post),
214                     },
215                     subtype='website_blog.mt_blog_blog_published',
216                     context=context)
217             return True
218         return False
219
220     def create(self, cr, uid, vals, context=None):
221         if context is None:
222             context = {}
223         if 'content' in vals:
224             vals['content'] = self._postproces_content(cr, uid, None, vals['content'], context=context)
225         create_context = dict(context, mail_create_nolog=True)
226         post_id = super(BlogPost, self).create(cr, uid, vals, context=create_context)
227         self.create_history(cr, uid, [post_id], vals, context)
228         self._check_for_publication(cr, uid, [post_id], vals, context=context)
229         return post_id
230
231     def write(self, cr, uid, ids, vals, context=None):
232         if 'content' in vals:
233             vals['content'] = self._postproces_content(cr, uid, None, vals['content'], context=context)
234         result = super(BlogPost, self).write(cr, uid, ids, vals, context)
235         self.create_history(cr, uid, ids, vals, context)
236         self._check_for_publication(cr, uid, ids, vals, context=context)
237         return result
238
239 class BlogPostHistory(osv.Model):
240     _name = "blog.post.history"
241     _description = "Blog Post History"
242     _order = 'id DESC'
243     _rec_name = "create_date"
244
245     _columns = {
246         'post_id': fields.many2one('blog.post', 'Blog Post'),
247         'summary': fields.char('Summary', select=True),
248         'content': fields.text("Content"),
249         'create_date': fields.datetime("Date"),
250         'create_uid': fields.many2one('res.users', "Modified By"),
251     }
252
253     def getDiff(self, cr, uid, v1, v2, context=None):
254         history_pool = self.pool.get('blog.post.history')
255         text1 = history_pool.read(cr, uid, [v1], ['content'])[0]['content']
256         text2 = history_pool.read(cr, uid, [v2], ['content'])[0]['content']
257         line1 = line2 = ''
258         if text1:
259             line1 = text1.splitlines(1)
260         if text2:
261             line2 = text2.splitlines(1)
262         if (not line1 and not line2) or (line1 == line2):
263             raise osv.except_osv(_('Warning!'), _('There are no changes in revisions.'))
264         diff = difflib.HtmlDiff()
265         return diff.make_table(line1, line2, "Revision-%s" % (v1), "Revision-%s" % (v2), context=True)