1 # -*- coding: utf-8 -*-
3 from datetime import datetime
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 _
15 class Blog(osv.Model):
17 _description = 'Blogs'
18 _inherit = ['mail.thread', 'website.seo.metadata']
21 'name': fields.char('Blog Name', required=True),
22 'subtitle': fields.char('Blog Subtitle'),
23 'description': fields.text('Description'),
27 class BlogTag(osv.Model):
29 _description = 'Blog Tag'
30 _inherit = ['website.seo.metadata']
33 'name': fields.char('Name', required=True),
34 'post_ids': fields.many2many(
35 'blog.post', string='Posts',
40 class BlogPost(osv.Model):
42 _description = "Blog Post"
43 _inherit = ['mail.thread', 'website.seo.metadata']
46 def _compute_ranking(self, cr, uid, ids, name, arg, context=None):
48 for blog_post in self.browse(cr, uid, ids, context=context):
49 age = datetime.now() - datetime.strptime(blog_post.create_date, tools.DEFAULT_SERVER_DATETIME_FORMAT)
50 res[blog_post.id] = blog_post.visits * (0.5+random.random()) / max(3, age.days)
54 'name': fields.char('Title', required=True, translate=True),
55 'subtitle': fields.char('Sub Title', translate=True),
56 'author_id': fields.many2one('res.partner', 'Author'),
57 'background_image': fields.binary('Background Image', oldname='content_image'),
58 'blog_id': fields.many2one(
60 required=True, ondelete='cascade',
62 'tag_ids': fields.many2many(
63 'blog.tag', string='Tags',
65 'content': fields.html('Content', translate=True, sanitize=False),
67 'website_published': fields.boolean(
68 'Publish', help="Publish on the website", copy=False,
70 'website_message_ids': fields.one2many(
71 'mail.message', 'res_id',
73 '&', '&', ('model', '=', self._name), ('type', '=', 'comment'), ('path', '=', False)
75 string='Website Messages',
76 help="Website communication history",
78 'history_ids': fields.one2many(
79 'blog.post.history', 'post_id',
80 'History', help='Last post modifications',
82 # creation / update stuff
83 'create_date': fields.datetime(
85 select=True, readonly=True,
87 'create_uid': fields.many2one(
88 'res.users', 'Author',
89 select=True, readonly=True,
91 'write_date': fields.datetime(
93 select=True, readonly=True,
95 'write_uid': fields.many2one(
96 'res.users', 'Last Contributor',
97 select=True, readonly=True,
99 'author_avatar': fields.related(
100 'author_id', 'image_small',
101 string="Avatar", type="binary"),
102 'visits': fields.integer('No of Views'),
103 'ranking': fields.function(_compute_ranking, string='Ranking', type='float'),
107 'name': _('Blog Post Title'),
108 'subtitle': _('Subtitle'),
109 'author_id': lambda self, cr, uid, ctx=None: self.pool['res.users'].browse(cr, uid, uid, context=ctx).partner_id.id,
112 def html_tag_nodes(self, html, attribute=None, tags=None, context=None):
113 """ Processing of html content to tag paragraphs and set them an unique
115 :return result: (html, mappin), where html is the updated html with ID
116 and mapping is a list of (old_ID, new_ID), where old_ID
117 is None is the paragraph is a new one. """
123 if attribute is None:
124 attribute = 'data-unique-id'
128 root = lxml.html.fragment_fromstring(html, create_parent='div')
129 if not len(root) and root.text is None and root.tail is None:
132 # check all nodes, replace :
133 # - img src -> check URL
134 # - a href -> check URL
135 for node in root.iter():
136 if not node.tag in tags:
138 ancestor_tags = [parent.tag for parent in node.iterancestors()]
141 ancestor_tags.append('counter_%s' % counter)
142 new_attribute = '/'.join(reversed(ancestor_tags))
143 old_attribute = node.get(attribute)
144 node.set(attribute, new_attribute)
145 mapping.append((old_attribute, counter))
148 html = lxml.html.tostring(root, pretty_print=False, method='html')
149 # this is ugly, but lxml/etree tostring want to put everything in a 'div' that breaks the editor -> remove that
150 if html.startswith('<div>') and html.endswith('</div>'):
154 def _postproces_content(self, cr, uid, id, content=None, context=None):
156 content = self.browse(cr, uid, id, context=context).content
159 content, mapping = self.html_tag_nodes(content, attribute='data-chatter-id', tags=['p'], context=context)
160 for old_attribute, new_attribute in mapping:
161 if not old_attribute:
163 msg_ids = self.pool['mail.message'].search(cr, SUPERUSER_ID, [('path', '=', old_attribute)], context=context)
164 self.pool['mail.message'].write(cr, SUPERUSER_ID, msg_ids, {'path': new_attribute}, context=context)
167 def create_history(self, cr, uid, ids, vals, context=None):
169 history = self.pool.get('blog.post.history')
170 if vals.get('content'):
172 'content': vals.get('content', ''),
175 history.create(cr, uid, res)
177 def _check_for_publication(self, cr, uid, ids, vals, context=None):
178 if vals.get('website_published'):
179 base_url = self.pool['ir.config_parameter'].get_param(cr, uid, 'web.base.url')
180 for post in self.browse(cr, uid, ids, context=context):
181 post.blog_id.message_post(
182 body='<p>%(post_publication)s <a href="%(base_url)s/blog/%(blog_slug)s/post/%(post_slug)s">%(post_link)s</a></p>' % {
183 'post_publication': _('A new post %s has been published on the %s blog.') % (post.name, post.blog_id.name),
184 'post_link': _('Click here to access the post.'),
185 'base_url': base_url,
186 'blog_slug': slug(post.blog_id),
187 'post_slug': slug(post),
189 subtype='website_blog.mt_blog_blog_published',
194 def create(self, cr, uid, vals, context=None):
197 if 'content' in vals:
198 vals['content'] = self._postproces_content(cr, uid, None, vals['content'], context=context)
199 create_context = dict(context, mail_create_nolog=True)
200 post_id = super(BlogPost, self).create(cr, uid, vals, context=create_context)
201 self.create_history(cr, uid, [post_id], vals, context)
202 self._check_for_publication(cr, uid, [post_id], vals, context=context)
205 def write(self, cr, uid, ids, vals, context=None):
206 if 'content' in vals:
207 vals['content'] = self._postproces_content(cr, uid, None, vals['content'], context=context)
208 result = super(BlogPost, self).write(cr, uid, ids, vals, context)
209 self.create_history(cr, uid, ids, vals, context)
210 self._check_for_publication(cr, uid, ids, vals, context=context)
213 class BlogPostHistory(osv.Model):
214 _name = "blog.post.history"
215 _description = "Blog Post History"
217 _rec_name = "create_date"
220 'post_id': fields.many2one('blog.post', 'Blog Post'),
221 'summary': fields.char('Summary', select=True),
222 'content': fields.text("Content"),
223 'create_date': fields.datetime("Date"),
224 'create_uid': fields.many2one('res.users', "Modified By"),
227 def getDiff(self, cr, uid, v1, v2, context=None):
228 history_pool = self.pool.get('blog.post.history')
229 text1 = history_pool.read(cr, uid, [v1], ['content'])[0]['content']
230 text2 = history_pool.read(cr, uid, [v2], ['content'])[0]['content']
233 line1 = text1.splitlines(1)
235 line2 = text2.splitlines(1)
236 if (not line1 and not line2) or (line1 == line2):
237 raise osv.except_osv(_('Warning!'), _('There are no changes in revisions.'))
238 diff = difflib.HtmlDiff()
239 return diff.make_table(line1, line2, "Revision-%s" % (v1), "Revision-%s" % (v2), context=True)