[IMP] clean sitemap, enumerate pages + fixes
[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.osv import osv, fields
11 from openerp.tools.translate import _
12
13
14 class Blog(osv.Model):
15     _name = 'blog.blog'
16     _description = 'Blogs'
17     _inherit = ['mail.thread', 'website.seo.metadata']
18     _order = 'name'
19     _columns = {
20         'name': fields.char('Blog Name', required=True),
21         'subtitle': fields.char('Blog Subtitle'),
22         'description': fields.text('Description'),
23     }
24
25
26 class BlogTag(osv.Model):
27     _name = 'blog.tag'
28     _description = 'Blog Tag'
29     _inherit = ['website.seo.metadata']
30     _order = 'name'
31     _columns = {
32         'name': fields.char('Name', required=True),
33     }
34
35
36 class BlogPost(osv.Model):
37     _name = "blog.post"
38     _description = "Blog Post"
39     _inherit = ['mail.thread', 'website.seo.metadata']
40     _order = 'id DESC'
41
42     def _compute_ranking(self, cr, uid, ids, name, arg, context=None):
43         res = {}
44         for blog_post in self.browse(cr, uid, ids, context=context):
45             age = datetime.now() - datetime.strptime(blog_post.create_date, tools.DEFAULT_SERVER_DATETIME_FORMAT)
46             res[blog_post.id] = blog_post.visits * (0.5+random.random()) / max(3, age.days)
47         return res
48
49     _columns = {
50         'name': fields.char('Title', required=True, translate=True),
51         'subtitle': fields.char('Sub Title', translate=True),
52         'author_id': fields.many2one('res.partner', 'Author'),
53         'background_image': fields.binary('Background Image', oldname='content_image'),
54         'blog_id': fields.many2one(
55             'blog.blog', 'Blog',
56             required=True, ondelete='cascade',
57         ),
58         'tag_ids': fields.many2many(
59             'blog.tag', string='Tags',
60         ),
61         'content': fields.html('Content', translate=True),
62         # website control
63         'website_published': fields.boolean(
64             'Publish', help="Publish on the website"
65         ),
66         'website_message_ids': fields.one2many(
67             'mail.message', 'res_id',
68             domain=lambda self: [
69                 '&', '&', ('model', '=', self._name), ('type', '=', 'comment'), ('path', '=', False)
70             ],
71             string='Website Messages',
72             help="Website communication history",
73         ),
74         'history_ids': fields.one2many(
75             'blog.post.history', 'post_id',
76             'History', help='Last post modifications',
77             deprecated='This field will be removed for OpenERP v9.'
78         ),
79         # creation / update stuff
80         'create_date': fields.datetime(
81             'Created on',
82             select=True, readonly=True,
83         ),
84         'create_uid': fields.many2one(
85             'res.users', 'Author',
86             select=True, readonly=True,
87         ),
88         'write_date': fields.datetime(
89             'Last Modified on',
90             select=True, readonly=True,
91         ),
92         'write_uid': fields.many2one(
93             'res.users', 'Last Contributor',
94             select=True, readonly=True,
95         ),
96         'visits': fields.integer('No of Views'),
97         'ranking': fields.function(_compute_ranking, string='Ranking', type='float'),
98     }
99
100     _defaults = {
101         'name': _('Blog Post Title'),
102         'subtitle': _('Subtitle'),
103         'author_id': lambda self, cr, uid, ctx=None: self.pool['res.users'].browse(cr, uid, uid, context=ctx).partner_id.id,
104     }
105
106     def html_tag_nodes(self, html, attribute=None, tags=None, context=None):
107         """ Processing of html content to tag paragraphs and set them an unique
108         ID.
109         :return result: (html, mappin), where html is the updated html with ID
110                         and mapping is a list of (old_ID, new_ID), where old_ID
111                         is None is the paragraph is a new one. """
112         mapping = []
113         if not html:
114             return html, mapping
115         if tags is None:
116             tags = ['p']
117         if attribute is None:
118             attribute = 'data-unique-id'
119         counter = 0
120
121         # form a tree
122         root = lxml.html.fragment_fromstring(html, create_parent='div')
123         if not len(root) and root.text is None and root.tail is None:
124             return html, mapping
125
126         # check all nodes, replace :
127         # - img src -> check URL
128         # - a href -> check URL
129         for node in root.iter():
130             if not node.tag in tags:
131                 continue
132             ancestor_tags = [parent.tag for parent in node.iterancestors()]
133             if ancestor_tags:
134                 ancestor_tags.pop()
135             ancestor_tags.append('counter_%s' % counter)
136             new_attribute = '/'.join(reversed(ancestor_tags))
137             old_attribute = node.get(attribute)
138             node.set(attribute, new_attribute)
139             mapping.append((old_attribute, counter))
140             counter += 1
141
142         html = lxml.html.tostring(root, pretty_print=False, method='html')
143         # this is ugly, but lxml/etree tostring want to put everything in a 'div' that breaks the editor -> remove that
144         if html.startswith('<div>') and html.endswith('</div>'):
145             html = html[5:-6]
146         return html, mapping
147
148     def _postproces_content(self, cr, uid, id, content=None, context=None):
149         if content is None:
150             content = self.browse(cr, uid, id, context=context).content
151         if content is False:
152             return content
153         content, mapping = self.html_tag_nodes(content, attribute='data-chatter-id', tags=['p'], context=context)
154         for old_attribute, new_attribute in mapping:
155             if not old_attribute:
156                 continue
157             msg_ids = self.pool['mail.message'].search(cr, SUPERUSER_ID, [('path', '=', old_attribute)], context=context)
158             self.pool['mail.message'].write(cr, SUPERUSER_ID, msg_ids, {'path': new_attribute}, context=context)
159         return content
160
161     def create_history(self, cr, uid, ids, vals, context=None):
162         for i in ids:
163             history = self.pool.get('blog.post.history')
164             if vals.get('content'):
165                 res = {
166                     'content': vals.get('content', ''),
167                     'post_id': i,
168                 }
169                 history.create(cr, uid, res)
170
171     def create(self, cr, uid, vals, context=None):
172         if context is None:
173             context = {}
174         if 'content' in vals:
175             vals['content'] = self._postproces_content(cr, uid, None, vals['content'], context=context)
176         create_context = dict(context, mail_create_nolog=True)
177         post_id = super(BlogPost, self).create(cr, uid, vals, context=create_context)
178         self.create_history(cr, uid, [post_id], vals, context)
179         return post_id
180
181     def write(self, cr, uid, ids, vals, context=None):
182         if 'content' in vals:
183             vals['content'] = self._postproces_content(cr, uid, None, vals['content'], context=context)
184         result = super(BlogPost, self).write(cr, uid, ids, vals, context)
185         self.create_history(cr, uid, ids, vals, context)
186         return result
187
188     def copy(self, cr, uid, id, default=None, context=None):
189         if default is None:
190             default = {}
191         default.update({
192             'website_message_ids': [],
193             'website_published': False,
194             'website_published_datetime': False,
195         })
196         return super(BlogPost, self).copy(cr, uid, id, default=default, context=context)
197
198
199 class BlogPostHistory(osv.Model):
200     _name = "blog.post.history"
201     _description = "Blog Post History"
202     _order = 'id DESC'
203     _rec_name = "create_date"
204
205     _columns = {
206         'post_id': fields.many2one('blog.post', 'Blog Post'),
207         'summary': fields.char('Summary', size=256, select=True),
208         'content': fields.text("Content"),
209         'create_date': fields.datetime("Date"),
210         'create_uid': fields.many2one('res.users', "Modified By"),
211     }
212
213     def getDiff(self, cr, uid, v1, v2, context=None):
214         history_pool = self.pool.get('blog.post.history')
215         text1 = history_pool.read(cr, uid, [v1], ['content'])[0]['content']
216         text2 = history_pool.read(cr, uid, [v2], ['content'])[0]['content']
217         line1 = line2 = ''
218         if text1:
219             line1 = text1.splitlines(1)
220         if text2:
221             line2 = text2.splitlines(1)
222         if (not line1 and not line2) or (line1 == line2):
223             raise osv.except_osv(_('Warning!'), _('There are no changes in revisions.'))
224         diff = difflib.HtmlDiff()
225         return diff.make_table(line1, line2, "Revision-%s" % (v1), "Revision-%s" % (v2), context=True)