forked from odoo/odoo
/
website.py
1812 lines (1573 loc) · 80.8 KB
/
website.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import base64
import hashlib
import inspect
import json
import logging
import operator
import re
import requests
from collections import defaultdict
from functools import reduce
from lxml import etree, html
from psycopg2 import sql
from werkzeug import urls
from werkzeug.datastructures import OrderedMultiDict
from werkzeug.exceptions import NotFound
from markupsafe import Markup
from odoo import api, fields, models, tools, http, release, registry
from odoo.addons.http_routing.models.ir_http import RequestUID, slugify, url_for
from odoo.addons.website.models.ir_http import sitemap_qs2dom
from odoo.addons.website.tools import similarity_score, text_from_html, get_base_domain
from odoo.addons.portal.controllers.portal import pager
from odoo.addons.iap.tools import iap_tools
from odoo.exceptions import AccessError, MissingError, UserError, ValidationError
from odoo.http import request
from odoo.modules.module import get_resource_path, get_manifest
from odoo.osv.expression import AND, OR, FALSE_DOMAIN, get_unaccent_wrapper
from odoo.tools.translate import _
from odoo.tools import escape_psql, OrderedSet, pycompat
logger = logging.getLogger(__name__)
DEFAULT_CDN_FILTERS = [
"^/[^/]+/static/",
"^/web/(css|js)/",
"^/web/image",
"^/web/content",
"^/web/assets",
# retrocompatibility
"^/website/image/",
]
DEFAULT_ENDPOINT = 'https://website.api.odoo.com'
# TODO: Remove in master.
SEARCH_TYPE_MODELS = defaultdict(OrderedSet)
#: DO NOT USE: this breaks multitenancy, extend '_search_get_details' instead
class Website(models.Model):
_name = "website"
_description = "Website"
_order = "sequence, id"
@api.model
def website_domain(self, website_id=False):
return [('website_id', 'in', (False, website_id or self.id))]
def _active_languages(self):
return self.env['res.lang'].search([]).ids
def _default_language(self):
lang_code = self.env['ir.default'].get('res.partner', 'lang')
def_lang_id = self.env['res.lang']._lang_get_id(lang_code)
return def_lang_id or self._active_languages()[0]
name = fields.Char('Website Name', required=True)
sequence = fields.Integer(default=10)
domain = fields.Char('Website Domain', help='E.g. https://www.mydomain.com')
company_id = fields.Many2one('res.company', string="Company", default=lambda self: self.env.company, required=True)
language_ids = fields.Many2many(
'res.lang', 'website_lang_rel', 'website_id', 'lang_id', string="Languages",
default=_active_languages, required=True)
language_count = fields.Integer('Number of languages', compute='_compute_language_count')
default_lang_id = fields.Many2one('res.lang', string="Default Language", default=_default_language, required=True)
auto_redirect_lang = fields.Boolean('Autoredirect Language', default=True, help="Should users be redirected to their browser's language")
cookies_bar = fields.Boolean('Cookies Bar', help="Display a customizable cookies bar on your website.")
configurator_done = fields.Boolean(help='True if configurator has been completed or ignored')
def _default_social_facebook(self):
return self.env.ref('base.main_company').social_facebook
def _default_social_github(self):
return self.env.ref('base.main_company').social_github
def _default_social_linkedin(self):
return self.env.ref('base.main_company').social_linkedin
def _default_social_youtube(self):
return self.env.ref('base.main_company').social_youtube
def _default_social_instagram(self):
return self.env.ref('base.main_company').social_instagram
def _default_social_twitter(self):
return self.env.ref('base.main_company').social_twitter
def _default_logo(self):
image_path = get_resource_path('website', 'static/src/img', 'website_logo.svg')
with tools.file_open(image_path, 'rb') as f:
return base64.b64encode(f.read())
logo = fields.Binary('Website Logo', default=_default_logo, help="Display this logo on the website.")
social_twitter = fields.Char('Twitter Account', default=_default_social_twitter)
social_facebook = fields.Char('Facebook Account', default=_default_social_facebook)
social_github = fields.Char('GitHub Account', default=_default_social_github)
social_linkedin = fields.Char('LinkedIn Account', default=_default_social_linkedin)
social_youtube = fields.Char('Youtube Account', default=_default_social_youtube)
social_instagram = fields.Char('Instagram Account', default=_default_social_instagram)
social_default_image = fields.Binary(string="Default Social Share Image", help="If set, replaces the website logo as the default social share image.")
has_social_default_image = fields.Boolean(compute='_compute_has_social_default_image', store=True)
google_analytics_key = fields.Char('Google Analytics Key')
google_search_console = fields.Char(help='Google key, or Enable to access first reply')
google_maps_api_key = fields.Char('Google Maps API Key')
plausible_shared_key = fields.Char()
plausible_site = fields.Char()
user_id = fields.Many2one('res.users', string='Public User', required=True)
cdn_activated = fields.Boolean('Content Delivery Network (CDN)')
cdn_url = fields.Char('CDN Base URL', default='')
cdn_filters = fields.Text('CDN Filters', default=lambda s: '\n'.join(DEFAULT_CDN_FILTERS), help="URL matching those filters will be rewritten using the CDN Base URL")
partner_id = fields.Many2one(related='user_id.partner_id', string='Public Partner', readonly=False)
menu_id = fields.Many2one('website.menu', compute='_compute_menu', string='Main Menu')
homepage_url = fields.Char(help='E.g. /contactus or /shop')
custom_code_head = fields.Html('Custom <head> code', sanitize=False)
custom_code_footer = fields.Html('Custom end of <body> code', sanitize=False)
robots_txt = fields.Html('Robots.txt', translate=False, groups='website.group_website_designer', sanitize=False)
def _default_favicon(self):
img_path = get_resource_path('web', 'static/img/favicon.ico')
with tools.file_open(img_path, 'rb') as f:
return base64.b64encode(f.read())
favicon = fields.Binary(string="Website Favicon", help="This field holds the image used to display a favicon on the website.", default=_default_favicon)
theme_id = fields.Many2one('ir.module.module', help='Installed theme')
specific_user_account = fields.Boolean('Specific User Account', help='If True, new accounts will be associated to the current website')
auth_signup_uninvited = fields.Selection([
('b2b', 'On invitation'),
('b2c', 'Free sign up'),
], string='Customer Account', default='b2b')
_sql_constraints = [
('domain_unique', 'unique(domain)', 'Website Domain should be unique.'),
]
@api.onchange('language_ids')
def _onchange_language_ids(self):
language_ids = self.language_ids._origin
if language_ids and self.default_lang_id not in language_ids:
self.default_lang_id = language_ids[0]
@api.depends('social_default_image')
def _compute_has_social_default_image(self):
for website in self:
website.has_social_default_image = bool(website.social_default_image)
@api.depends('language_ids')
def _compute_language_count(self):
for website in self:
website.language_count = len(website.language_ids)
def _compute_menu(self):
for website in self:
menus = self.env['website.menu'].browse(website._get_menu_ids())
# use field parent_id (1 query) to determine field child_id (2 queries by level)"
for menu in menus:
menu._cache['child_id'] = ()
for menu in menus:
# don't add child menu if parent is forbidden
if menu.parent_id and menu.parent_id in menus:
menu.parent_id._cache['child_id'] += (menu.id,)
# prefetch every website.page and ir.ui.view at once
menus.mapped('is_visible')
top_menus = menus.filtered(lambda m: not m.parent_id)
website.menu_id = top_menus and top_menus[0].id or False
# self.env.uid for ir.rule groups on menu
@tools.ormcache('self.env.uid', 'self.id')
def _get_menu_ids(self):
return self.env['website.menu'].search([('website_id', '=', self.id)]).ids
@api.model_create_multi
def create(self, vals_list):
for vals in vals_list:
self._handle_create_write(vals)
if 'user_id' not in vals:
company = self.env['res.company'].browse(vals.get('company_id'))
vals['user_id'] = company._get_public_user().id if company else self.env.ref('base.public_user').id
websites = super().create(vals_list)
websites.company_id._compute_website_id()
for website in websites:
website._bootstrap_homepage()
if not self.env.user.has_group('website.group_multi_website') and self.search_count([]) > 1:
all_user_groups = 'base.group_portal,base.group_user,base.group_public'
groups = self.env['res.groups'].concat(*(self.env.ref(it) for it in all_user_groups.split(',')))
groups.write({'implied_ids': [(4, self.env.ref('website.group_multi_website').id)]})
return websites
def write(self, values):
public_user_to_change_websites = self.env['website']
original_company = self.company_id
self._handle_create_write(values)
self.clear_caches()
if 'company_id' in values and 'user_id' not in values:
public_user_to_change_websites = self.filtered(lambda w: w.sudo().user_id.company_id.id != values['company_id'])
if public_user_to_change_websites:
company = self.env['res.company'].browse(values['company_id'])
super(Website, public_user_to_change_websites).write(dict(values, user_id=company and company._get_public_user().id))
result = super(Website, self - public_user_to_change_websites).write(values)
if 'cdn_activated' in values or 'cdn_url' in values or 'cdn_filters' in values:
# invalidate the caches from static node at compile time
self.env['ir.qweb'].clear_caches()
# invalidate cache for `company.website_id` to be recomputed
if 'sequence' in values or 'company_id' in values:
(original_company | self.company_id)._compute_website_id()
if 'cookies_bar' in values:
existing_policy_page = self.env['website.page'].search([
('website_id', '=', self.id),
('url', '=', '/cookie-policy'),
])
if not values['cookies_bar']:
existing_policy_page.unlink()
elif not existing_policy_page:
cookies_view = self.env.ref('website.cookie_policy', raise_if_not_found=False)
if cookies_view:
cookies_view.with_context(website_id=self.id).write({'website_id': self.id})
specific_cook_view = self.with_context(website_id=self.id).viewref('website.cookie_policy')
self.env['website.page'].create({
'is_published': True,
'website_indexed': False,
'url': '/cookie-policy',
'website_id': self.id,
'view_id': specific_cook_view.id,
})
return result
@api.model
def _handle_create_write(self, vals):
self._handle_favicon(vals)
self._handle_domain(vals)
self._handle_homepage_url(vals)
@api.model
def _handle_favicon(self, vals):
if vals.get('favicon'):
vals['favicon'] = base64.b64encode(tools.image_process(base64.b64decode(vals['favicon']), size=(256, 256), crop='center', output_format='ICO'))
@api.model
def _handle_domain(self, vals):
if 'domain' in vals and vals['domain']:
if not vals['domain'].startswith('http'):
vals['domain'] = 'https://%s' % vals['domain']
vals['domain'] = vals['domain'].rstrip('/')
@api.model
def _handle_homepage_url(self, vals):
homepage_url = vals.get('homepage_url')
if homepage_url:
vals['homepage_url'] = homepage_url.rstrip('/')
@api.constrains('homepage_url')
def _check_homepage_url(self):
for website in self.filtered('homepage_url'):
if not website.homepage_url.startswith('/'):
raise ValidationError(_("The homepage URL should be relative and start with '/'."))
# TODO: rename in master
@api.ondelete(at_uninstall=False)
def _unlink_except_last_remaining_website(self):
website = self.search([('id', 'not in', self.ids)], limit=1)
if not website:
raise UserError(_('You must keep at least one website.'))
default_website = self.env.ref('website.default_website', raise_if_not_found=False)
if default_website and default_website in self:
raise UserError(_("You cannot delete default website %s. Try to change its settings instead", default_website.name))
def unlink(self):
self._remove_attachments_on_website_unlink()
companies = self.company_id
res = super().unlink()
companies._compute_website_id()
return res
def _remove_attachments_on_website_unlink(self):
# Do not delete invoices, delete what's strictly necessary
attachments_to_unlink = self.env['ir.attachment'].search([
('website_id', 'in', self.ids),
'|', '|',
('key', '!=', False), # theme attachment
('url', 'ilike', '.custom.'), # customized theme attachment
('url', 'ilike', '.assets\\_'),
])
attachments_to_unlink.unlink()
def create_and_redirect_configurator(self):
self._force()
configurator_action_todo = self.env.ref('website.website_configurator_todo')
return configurator_action_todo.action_launch()
def _is_indexable_url(self, url):
"""
Returns True if the given url has to be indexed by search engines.
It is considered that the website must be indexed if the domain name
matches the URL. We check if they are equal while ignoring the www. and
http(s). This is to index the site even if the user put the www. in the
settings while he has a configuration that redirects the www. to the
naked domain for example (same thing for http and https).
:param url: the url to check
:return: True if the url has to be indexed, False otherwise
"""
return get_base_domain(url, True) == get_base_domain(self.domain, True)
# ----------------------------------------------------------
# Configurator
# ----------------------------------------------------------
def _website_api_rpc(self, route, params):
params['version'] = release.version
IrConfigParameter = self.env['ir.config_parameter'].sudo()
website_api_endpoint = IrConfigParameter.get_param('website.website_api_endpoint', DEFAULT_ENDPOINT)
endpoint = website_api_endpoint + route
return iap_tools.iap_jsonrpc(endpoint, params=params)
def get_cta_data(self, website_purpose, website_type):
return {'cta_btn_text': False, 'cta_btn_href': '/contactus'}
@api.model
def get_theme_snippet_lists(self, theme_name):
return {
**get_manifest('theme_default')['snippet_lists'],
**get_manifest(theme_name).get('snippet_lists', {}),
}
def configurator_set_menu_links(self, menu_company, module_data):
menus = self.env['website.menu'].search([('url', 'in', list(module_data.keys())), ('website_id', '=', self.id)])
for m in menus:
m.sequence = module_data[m.url]['sequence']
def configurator_get_footer_links(self):
return [
{'text': _("Privacy Policy"), 'href': '/privacy'},
]
@api.model
def configurator_init(self):
r = dict()
company = self.get_current_website().company_id
configurator_features = self.env['website.configurator.feature'].search([])
r['features'] = [{
'id': feature.id,
'name': feature.name,
'description': feature.description,
'type': 'page' if feature.page_view_id else 'app',
'icon': feature.icon,
'website_config_preselection': feature.website_config_preselection,
'module_state': feature.module_id.state,
} for feature in configurator_features]
r['logo'] = False
if company.logo and company.logo != company._get_logo():
r['logo'] = company.logo.decode('utf-8')
try:
result = self._website_api_rpc('/api/website/1/configurator/industries', {'lang': self.env.context.get('lang')})
r['industries'] = result['industries']
except AccessError as e:
logger.warning(e.args[0])
return r
@api.model
def configurator_recommended_themes(self, industry_id, palette):
Module = request.env['ir.module.module']
domain = Module.get_themes_domain()
domain = AND([[('name', '!=', 'theme_default')], domain])
client_themes = Module.search(domain).mapped('name')
client_themes_img = {t: get_manifest(t).get('images_preview_theme', {}) for t in client_themes if get_manifest(t)}
themes_suggested = self._website_api_rpc(
'/api/website/2/configurator/recommended_themes/%s' % industry_id,
{'client_themes': client_themes_img}
)
process_svg = self.env['website.configurator.feature']._process_svg
for theme in themes_suggested:
theme['svg'] = process_svg(theme['name'], palette, theme.pop('image_urls'))
return themes_suggested
@api.model
def configurator_skip(self):
website = self.get_current_website()
website.configurator_done = True
@api.model
def configurator_apply(self, **kwargs):
def set_colors(selected_palette):
url = '/website/static/src/scss/options/user_values.scss'
selected_palette_name = selected_palette if isinstance(selected_palette, str) else 'base-1'
values = {'color-palettes-name': "'%s'" % selected_palette_name}
self.env['web_editor.assets'].make_scss_customization(url, values)
if isinstance(selected_palette, list):
url = '/website/static/src/scss/options/colors/user_color_palette.scss'
values = {f'o-color-{i}': color for i, color in enumerate(selected_palette, 1)}
self.env['web_editor.assets'].make_scss_customization(url, values)
def set_features(selected_features):
features = self.env['website.configurator.feature'].browse(selected_features)
menu_company = self.env['website.menu']
if len(features.filtered('menu_sequence')) > 5 and len(features.filtered('menu_company')) > 1:
menu_company = self.env['website.menu'].create({
'name': _('Company'),
'parent_id': website.menu_id.id,
'website_id': website.id,
'sequence': 40,
})
pages_views = {}
modules = self.env['ir.module.module']
module_data = {}
for feature in features:
add_menu = bool(feature.menu_sequence)
if feature.module_id:
if feature.module_id.state != 'installed':
modules += feature.module_id
if add_menu:
if feature.module_id.name != 'website_blog':
module_data[feature.feature_url] = {'sequence': feature.menu_sequence}
else:
blogs = module_data.setdefault('#blog', [])
blogs.append({'name': feature.name, 'sequence': feature.menu_sequence})
elif feature.page_view_id:
result = self.env['website'].new_page(
name=feature.name,
add_menu=add_menu,
page_values=dict(url=feature.feature_url, is_published=True),
menu_values=add_menu and {
'url': feature.feature_url,
'sequence': feature.menu_sequence,
'parent_id': feature.menu_company and menu_company.id or website.menu_id.id,
},
template=feature.page_view_id.key
)
pages_views[feature.iap_page_code] = result['view_id']
if modules:
modules.button_immediate_install()
assert self.env.registry is registry()
self.env['website'].browse(website.id).configurator_set_menu_links(menu_company, module_data)
return pages_views
def configure_page(page_code, snippet_list, pages_views, cta_data):
if page_code == 'homepage':
page_view_id = self.with_context(website_id=website.id).viewref('website.homepage')
else:
page_view_id = self.env['ir.ui.view'].browse(pages_views[page_code])
rendered_snippets = []
nb_snippets = len(snippet_list)
for i, snippet in enumerate(snippet_list, start=1):
try:
IrQweb = self.env['ir.qweb'].with_context(website_id=website.id, lang=website.default_lang_id.code)
render = IrQweb._render('website.' + snippet, cta_data)
if render:
el = html.fromstring(render)
# Add the data-snippet attribute to identify the snippet
# for compatibility code
el.attrib['data-snippet'] = snippet
# Tweak the shape of the first snippet to connect it
# properly with the header color in some themes
if i == 1:
shape_el = el.xpath("//*[hasclass('o_we_shape')]")
if shape_el:
shape_el[0].attrib['class'] += ' o_header_extra_shape_mapping'
# Tweak the shape of the last snippet to connect it
# properly with the footer color in some themes
if i == nb_snippets:
shape_el = el.xpath("//*[hasclass('o_we_shape')]")
if shape_el:
shape_el[0].attrib['class'] += ' o_footer_extra_shape_mapping'
rendered_snippet = pycompat.to_text(etree.tostring(el))
rendered_snippets.append(rendered_snippet)
except ValueError as e:
logger.warning(e)
page_view_id.save(value=''.join(rendered_snippets), xpath="(//div[hasclass('oe_structure')])[last()]")
def set_images(images):
for name, url in images.items():
try:
response = requests.get(url, timeout=3)
response.raise_for_status()
except Exception as e:
logger.warning("Failed to download image: %s.\n%s", url, e)
else:
attachment = self.env['ir.attachment'].create({
'name': name,
'website_id': website.id,
'key': name,
'type': 'binary',
'raw': response.content,
'public': True,
})
self.env['ir.model.data'].create({
'name': 'configurator_%s_%s' % (website.id, name.split('.')[1]),
'module': 'website',
'model': 'ir.attachment',
'res_id': attachment.id,
'noupdate': True,
})
website = self.get_current_website()
theme_name = kwargs['theme_name']
theme = self.env['ir.module.module'].search([('name', '=', theme_name)])
url = theme.button_choose_theme()
# Force to refresh env after install of module
assert self.env.registry is registry()
website.configurator_done = True
# Enable tour
tour_asset_id = self.env.ref('website.configurator_tour')
tour_asset_id.copy({'key': tour_asset_id.key, 'website_id': website.id, 'active': True})
# Set logo from generated attachment or from company's logo
logo_attachment_id = kwargs.get('logo_attachment_id')
company = website.company_id
if logo_attachment_id:
attachment = self.env['ir.attachment'].browse(logo_attachment_id)
attachment.write({
'res_model': 'website',
'res_field': 'logo',
'res_id': website.id,
})
elif not logo_attachment_id and company.logo and company.logo != company._get_logo():
website.logo = company.logo.decode('utf-8')
# palette
palette = kwargs.get('selected_palette')
if palette:
set_colors(palette)
# Update CTA
cta_data = website.get_cta_data(kwargs.get('website_purpose'), kwargs.get('website_type'))
if cta_data['cta_btn_text']:
xpath_view = 'website.snippets'
parent_view = self.env['website'].with_context(website_id=website.id).viewref(xpath_view)
self.env['ir.ui.view'].create({
'name': parent_view.key + ' CTA',
'key': parent_view.key + "_cta",
'inherit_id': parent_view.id,
'website_id': website.id,
'type': 'qweb',
'priority': 32,
'arch_db': """
<data>
<xpath expr="//t[@t-set='cta_btn_href']" position="replace">
<t t-set="cta_btn_href">%s</t>
</xpath>
<xpath expr="//t[@t-set='cta_btn_text']" position="replace">
<t t-set="cta_btn_text">%s</t>
</xpath>
</data>
""" % (cta_data['cta_btn_href'], cta_data['cta_btn_text'])
})
try:
view_id = self.env['website'].viewref('website.header_call_to_action')
if view_id:
el = etree.fromstring(view_id.arch_db)
btn_cta_el = el.xpath("//a[hasclass('btn_cta')]")
if btn_cta_el:
btn_cta_el[0].attrib['href'] = cta_data['cta_btn_href']
btn_cta_el[0].text = cta_data['cta_btn_text']
view_id.with_context(website_id=website.id).write({'arch_db': etree.tostring(el)})
except ValueError as e:
logger.warning(e)
# modules
pages_views = set_features(kwargs.get('selected_features'))
# We need to refresh the environment of website because set_features installed some new module
# and we need the overrides of these new menus e.g. for .get_cta_data()
website = self.env['website'].browse(website.id)
# Update footers links, needs to be done after `set_features` to go
# through module overide of `configurator_get_footer_links`
footer_links = website.configurator_get_footer_links()
footer_ids = [
'website.template_footer_contact', 'website.template_footer_headline',
'website.footer_custom', 'website.template_footer_links',
'website.template_footer_minimalist',
]
for footer_id in footer_ids:
try:
view_id = self.env['website'].viewref(footer_id)
if view_id:
# Deliberately hardcode dynamic code inside the view arch,
# it will be transformed into static nodes after a save/edit
# thanks to the t-ignore in parents node.
arch_string = etree.fromstring(view_id.arch_db)
el = arch_string.xpath("//t[@t-set='configurator_footer_links']")[0]
el.attrib['t-value'] = json.dumps(footer_links)
view_id.with_context(website_id=website.id).write({'arch_db': etree.tostring(arch_string)})
except Exception as e:
# The xml view could have been modified in the backend, we don't
# want the xpath error to break the configurator feature
logger.warning(e)
# Load suggestion from iap for selected pages
custom_resources = self._website_api_rpc(
'/api/website/2/configurator/custom_resources/%s' % kwargs['industry_id'],
{'theme': theme_name, }
)
# Update pages
requested_pages = list(pages_views.keys()) + ['homepage']
snippet_lists = website.get_theme_snippet_lists(theme_name)
for page_code in requested_pages:
configure_page(page_code, snippet_lists.get(page_code, []), pages_views, cta_data)
images = custom_resources.get('images', {})
set_images(images)
return {'url': url, 'website_id': website.id}
# ----------------------------------------------------------
# Page Management
# ----------------------------------------------------------
def _bootstrap_homepage(self):
Page = self.env['website.page']
standard_homepage = self.env.ref('website.homepage', raise_if_not_found=False)
if not standard_homepage:
return
# keep strange indentation in python file, to get it correctly in database
new_homepage_view = '''<t name="Homepage" t-name="website.homepage">
<t t-call="website.layout">
<t t-set="pageName" t-value="'homepage'"/>
<div id="wrap" class="oe_structure oe_empty"/>
</t>
</t>'''
standard_homepage.with_context(website_id=self.id).arch_db = new_homepage_view
homepage_page = Page.search([
('website_id', '=', self.id),
('key', '=', standard_homepage.key),
], limit=1)
if not homepage_page:
homepage_page = Page.create({
'website_published': True,
'url': '/',
'view_id': self.with_context(website_id=self.id).viewref('website.homepage').id,
})
# prevent /-1 as homepage URL
homepage_page.url = '/'
# Bootstrap default menu hierarchy, create a new minimalist one if no default
default_menu = self.env.ref('website.main_menu')
self.copy_menu_hierarchy(default_menu)
home_menu = self.env['website.menu'].search([('website_id', '=', self.id), ('url', '=', '/')])
home_menu.page_id = homepage_page
def copy_menu_hierarchy(self, top_menu):
def copy_menu(menu, t_menu):
new_menu = menu.copy({
'parent_id': t_menu.id,
'website_id': self.id,
})
for submenu in menu.child_id:
copy_menu(submenu, new_menu)
for website in self:
new_top_menu = top_menu.copy({
'name': _('Top Menu for Website %s', website.id),
'website_id': website.id,
})
for submenu in top_menu.child_id:
copy_menu(submenu, new_top_menu)
@api.model
def new_page(self, name=False, add_menu=False, template='website.default_page', ispage=True, namespace=None, page_values=None, menu_values=None):
""" Create a new website page, and assign it a xmlid based on the given one
:param name : the name of the page
:param add_menu : if True, add a menu for that page
:param template : potential xml_id of the page to create
:param namespace : module part of the xml_id if none, the template module name is used
:param page_values : default values for the page to be created
:param menu_values : default values for the menu to be created
"""
if namespace:
template_module = namespace
else:
template_module, _ = template.split('.')
page_url = '/' + slugify(name, max_length=1024, path=True)
page_url = self.get_unique_path(page_url)
page_key = slugify(name)
result = {'url': page_url}
if not name:
name = 'Home'
page_key = 'home'
template_record = self.env.ref(template)
website_id = self._context.get('website_id')
key = self.get_unique_key(page_key, template_module)
view = template_record.copy({'website_id': website_id, 'key': key})
view.with_context(lang=None).write({
'arch': template_record.arch.replace(template, key),
'name': name,
})
result['view_id'] = view.id
if view.arch_fs:
view.arch_fs = False
website = self.get_current_website()
if ispage:
default_page_values = {
'url': page_url,
'website_id': website.id, # remove it if only one website or not?
'view_id': view.id,
'track': True,
}
if page_values:
default_page_values.update(page_values)
page = self.env['website.page'].create(default_page_values)
result['page_id'] = page.id
if add_menu:
default_menu_values = {
'name': name,
'url': page_url,
'parent_id': website.menu_id.id,
'page_id': page.id,
'website_id': website.id,
}
if menu_values:
default_menu_values.update(menu_values)
menu = self.env['website.menu'].create(default_menu_values)
result['menu_id'] = menu.id
return result
def get_unique_path(self, page_url):
""" Given an url, return that url suffixed by counter if it already exists
:param page_url : the url to be checked for uniqueness
"""
inc = 0
# we only want a unique_path for website specific.
# we need to be able to have /url for website=False, and /url for website=1
# in case of duplicate, page manager will allow you to manage this case
website_id = self.env.context.get('website_id', False) or self.get_current_website().id
domain_static = [('website_id', '=', website_id)] # .website_domain()
page_temp = page_url
while self.env['website.page'].with_context(active_test=False).sudo().search([('url', '=', page_temp)] + domain_static):
inc += 1
page_temp = page_url + (inc and "-%s" % inc or "")
return page_temp
def _get_plausible_script_url(self):
return self.env['ir.config_parameter'].sudo().get_param(
'website.plausible_script',
'https://plausible.io/js/plausible.js'
)
def _get_plausible_server(self):
return self.env['ir.config_parameter'].sudo().get_param(
'website.plausible_server',
'https://plausible.io'
)
def _get_plausible_share_url(self):
embed_url = f'/share/{self.plausible_site}?auth={self.plausible_shared_key}&embed=true&theme=system'
return self.plausible_shared_key and urls.url_join(self._get_plausible_server(), embed_url) or ''
def get_unique_key(self, string, template_module=False):
""" Given a string, return an unique key including module prefix.
It will be suffixed by a counter if it already exists to garantee uniqueness.
:param string : the key to be checked for uniqueness, you can pass it with 'website.' or not
:param template_module : the module to be prefixed on the key, if not set, we will use website
"""
if template_module:
string = template_module + '.' + string
else:
if not string.startswith('website.'):
string = 'website.' + string
# Look for unique key
key_copy = string
inc = 0
domain_static = self.get_current_website().website_domain()
website_id = self.env.context.get('website_id', False)
if website_id:
domain_static = [('website_id', 'in', (False, website_id))]
while self.env['website.page'].with_context(active_test=False).sudo().search([('key', '=', key_copy)] + domain_static):
inc += 1
key_copy = string + (inc and "-%s" % inc or "")
return key_copy
@api.model
def search_url_dependencies(self, res_model, res_ids):
""" Search dependencies just for information. It will not catch 100%
of dependencies and False positive is more than possible
Each module could add dependences in this dict
:returns a dictionnary where key is the 'categorie' of object related to the given
view, and the value is the list of text and link to the resource using given page
"""
dependencies = {}
current_website = self.get_current_website()
page_model_name = 'Page'
def _handle_views_and_pages(views):
page_views = views.filtered('page_ids')
views = views - page_views
if page_views:
dependencies.setdefault(page_model_name, [])
dependencies[page_model_name] += [{
'field_name': 'Content',
'record_name': page.name,
'link': page.url,
'model_name': page_model_name,
} for page in page_views.page_ids]
return views
# Prepare what's needed to later generate the URL search domain for the
# given records
search_criteria = []
for record in self.env[res_model].browse([int(res_id) for res_id in res_ids]):
website = 'website_id' in record and record.website_id or current_website
url = 'website_url' in record and record.website_url or record.url
search_criteria.append((url, website.website_domain()))
# Search the URL in every relevant field
html_fields_attributes = self._get_html_fields_attributes() + [
('website.menu', 'website_menu', 'url', False),
]
for model, _table, column, _translate in html_fields_attributes:
Model = self.env[model]
# Generate the exact domain to search for the URL in this field
domains = []
for url, website_domain in search_criteria:
domains.append(AND([
[(column, 'ilike', url)],
website_domain if hasattr(Model, 'website_id') else [],
]))
dependency_records = Model.search(OR(domains))
if model == 'ir.ui.view':
dependency_records = _handle_views_and_pages(dependency_records)
if dependency_records:
model_name = self.env['ir.model']._display_name_for([model])[0]['display_name']
field_name = Model.fields_get()[column]['string']
dependencies.setdefault(model_name, [])
dependencies[model_name] += [{
'field_name': field_name,
'record_name': rec.display_name,
'link': 'website_url' in rec and rec.website_url or f'/web#id={rec.id}&view_type=form&model={model}',
'model_name': model_name,
} for rec in dependency_records]
return dependencies
# ----------------------------------------------------------
# Languages
# ----------------------------------------------------------
def _get_alternate_languages(self, canonical_params):
self.ensure_one()
if not self._is_canonical_url(canonical_params=canonical_params):
# no hreflang on non-canonical pages
return []
languages = self.language_ids
if len(languages) <= 1:
# no hreflang if no alternate language
return []
langs = []
shorts = []
for lg in languages:
lg_codes = lg.code.split('_')
short = lg_codes[0]
shorts.append(short)
langs.append({
'hreflang': ('-'.join(lg_codes)).lower(),
'short': short,
'href': self._get_canonical_url_localized(lang=lg, canonical_params=canonical_params),
})
# if there is only one region for a language, use only the language code
for lang in langs:
if shorts.count(lang['short']) == 1:
lang['hreflang'] = lang['short']
# add the default
langs.append({
'hreflang': 'x-default',
'href': self._get_canonical_url_localized(lang=self.default_lang_id, canonical_params=canonical_params),
})
return langs
# ----------------------------------------------------------
# Utilities
# ----------------------------------------------------------
@api.model
def get_current_website(self, fallback=True):
""" The current website is returned in the following order:
- the website forced in session `force_website_id`
- the website set in context
- (if frontend or fallback) the website matching the request's "domain"
- arbitrary the first website found in the database if `fallback` is set
to `True`
- empty browse record
"""
is_frontend_request = request and getattr(request, 'is_frontend', False)
if request and request.session.get('force_website_id'):
website_id = self.browse(request.session['force_website_id']).exists()
if not website_id:
# Don't crash is session website got deleted
request.session.pop('force_website_id')
else:
return website_id
website_id = self.env.context.get('website_id')
if website_id:
return self.browse(website_id)
if not is_frontend_request and not fallback:
# It's important than backend requests with no fallback requested
# don't go through
return self.browse(False)
# Reaching this point means that:
# - We didn't find a website in the session or in the context.
# - And we are either:
# - in a frontend context
# - in a backend context (or early in the dispatch stack) and a
# fallback website is requested.
# We will now try to find a website matching the request host/domain (if
# there is one on request) or return a random one.
# The format of `httprequest.host` is `domain:port`
domain_name = request and request.httprequest.host or ''
website_id = self._get_current_website_id(domain_name, fallback=fallback)
return self.browse(website_id)
@tools.ormcache('domain_name', 'fallback')
@api.model
def _get_current_website_id(self, domain_name, fallback=True):
"""Get the current website id.
First find the website for which the configured `domain` (after
ignoring a potential scheme) is equal to the given
`domain_name`. If a match is found, return it immediately.
If there is no website found for the given `domain_name`, either
fallback to the first found website (no matter its `domain`) or return
False depending on the `fallback` parameter.
:param domain_name: the domain for which we want the website.
In regard to the `url_parse` method, only the `netloc` part should
be given here, no `scheme`.
:type domain_name: string
:param fallback: if True and no website is found for the specificed
`domain_name`, return the first website (without filtering them)
:type fallback: bool
:return: id of the found website, or False if no website is found and
`fallback` is False
:rtype: int or False
:raises: if `fallback` is True but no website at all is found
"""
def _remove_port(domain_name):