blob: 14e3e13cda3524c50bede43d835232b094bda42f [file] [log] [blame]
Rushabh Mehta3966f1d2012-02-23 12:35:32 +05301# ERPNext - web based ERP (http://erpnext.com)
2# Copyright (C) 2012 Web Notes Technologies Pvt Ltd
3#
4# This program is free software: you can redistribute it and/or modify
5# it under the terms of the GNU General Public License as published by
6# the Free Software Foundation, either version 3 of the License, or
7# (at your option) any later version.
8#
9# This program is distributed in the hope that it will be useful,
10# but WITHOUT ANY WARRANTY; without even the implied warranty of
11# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12# GNU General Public License for more details.
13#
14# You should have received a copy of the GNU General Public License
15# along with this program. If not, see <http://www.gnu.org/licenses/>.
16
Anand Doshi486f9df2012-07-19 13:40:31 +053017from __future__ import unicode_literals
Rushabh Mehta571377a2012-12-07 11:00:26 +053018
19import os
20import conf
Rushabh Mehtada512ba2013-03-22 12:45:44 +053021from website.settings import *
Rushabh Mehtaab1148c2012-01-31 18:01:16 +053022import webnotes
Rushabh Mehtada512ba2013-03-22 12:45:44 +053023import webnotes.utils
Rushabh Mehta5128b662013-03-13 16:36:33 +053024
Rushabh Mehta89c7b412012-12-06 14:58:44 +053025def render(page_name):
26 """render html page"""
Rushabh Mehta89c7b412012-12-06 14:58:44 +053027 try:
28 if page_name:
29 html = get_html(page_name)
30 else:
31 html = get_html('index')
Anand Doshic9629a42013-02-12 12:54:58 +053032 except Exception:
Rushabh Mehtae109fa42012-12-19 10:14:59 +053033 html = get_html('error')
Rushabh Mehta89c7b412012-12-06 14:58:44 +053034
35 from webnotes.handler import eprint, print_zip
36 eprint("Content-Type: text/html")
37 print_zip(html)
38
39def get_html(page_name):
40 """get page html"""
41 page_name = scrub_page_name(page_name)
Rushabh Mehta89c7b412012-12-06 14:58:44 +053042
Rushabh Mehta571377a2012-12-07 11:00:26 +053043 html = ''
44
45 # load from cache, if auto cache clear is falsy
46 if not (hasattr(conf, 'auto_cache_clear') and conf.auto_cache_clear or 0):
Rushabh Mehta5128b662013-03-13 16:36:33 +053047 if not page_name in no_cache:
48 html = webnotes.cache().get_value("page:" + page_name)
49 from_cache = True
Rushabh Mehta571377a2012-12-07 11:00:26 +053050
Rushabh Mehtae109fa42012-12-19 10:14:59 +053051 if not html:
Rushabh Mehta4a80bc62013-03-21 17:23:54 +053052 from webnotes.auth import HTTPRequest
53 webnotes.http_request = HTTPRequest()
54
55 #webnotes.connect()
Rushabh Mehta571377a2012-12-07 11:00:26 +053056 html = load_into_cache(page_name)
Rushabh Mehtae109fa42012-12-19 10:14:59 +053057 from_cache = False
Rushabh Mehta571377a2012-12-07 11:00:26 +053058
Rushabh Mehtae109fa42012-12-19 10:14:59 +053059 if not html:
60 html = get_html("404")
61
62 if page_name=="error":
Rushabh Mehta7edf8992012-12-25 18:18:17 +053063 html = html.replace("%(error)s", webnotes.getTraceback())
Rushabh Mehtae109fa42012-12-19 10:14:59 +053064 else:
65 comments = "\n\npage:"+page_name+\
66 "\nload status: " + (from_cache and "cache" or "fresh")
67 html += """\n<!-- %s -->""" % webnotes.utils.cstr(comments)
Rushabh Mehta571377a2012-12-07 11:00:26 +053068
Rushabh Mehta89c7b412012-12-06 14:58:44 +053069 return html
Rushabh Mehta89c7b412012-12-06 14:58:44 +053070
Anand Doshi51146c02012-07-12 18:41:12 +053071def scrub_page_name(page_name):
72 if page_name.endswith('.html'):
73 page_name = page_name[:-5]
74
75 return page_name
76
Rushabh Mehtaab1148c2012-01-31 18:01:16 +053077def page_name(title):
Anand Doshi72c945b2012-06-22 20:01:07 +053078 """make page name from title"""
79 import re
80 name = title.lower()
81 name = re.sub('[~!@#$%^&*()<>,."\']', '', name)
Nabin Hait80c68122013-01-17 13:24:51 +053082 name = re.sub('[:/]', '-', name)
83
84 name = '-'.join(name.split())
85
86 # replace repeating hyphens
87 name = re.sub(r"(-)\1+", r"\1", name)
88
89 return name
Rushabh Mehtadf0b00a2012-12-06 16:15:38 +053090
91def update_page_name(doc, title):
92 """set page_name and check if it is unique"""
Rushabh Mehtaa2e4cb02012-12-06 17:09:38 +053093 webnotes.conn.set(doc, "page_name", page_name(title))
Rushabh Mehtadf0b00a2012-12-06 16:15:38 +053094
Rushabh Mehta1b151712012-12-27 16:50:24 +053095 standard_pages = get_template_pages()
96 if doc.page_name in standard_pages:
97 webnotes.conn.sql("""Page Name cannot be one of %s""" % ', '.join(standard_pages))
98
Rushabh Mehtadf0b00a2012-12-06 16:15:38 +053099 res = webnotes.conn.sql("""\
100 select count(*) from `tab%s`
101 where page_name=%s and name!=%s""" % (doc.doctype, '%s', '%s'),
102 (doc.page_name, doc.name))
103 if res and res[0][0] > 0:
104 webnotes.msgprint("""A %s with the same title already exists.
105 Please change the title of %s and save again."""
106 % (doc.doctype, doc.name), raise_exception=1)
Rushabh Mehta571377a2012-12-07 11:00:26 +0530107
108 delete_page_cache(doc.page_name)
109
110def load_into_cache(page_name):
111 args = prepare_args(page_name)
Rushabh Mehtae109fa42012-12-19 10:14:59 +0530112 if not args:
113 return ""
Rushabh Mehta571377a2012-12-07 11:00:26 +0530114 html = build_html(args)
115 webnotes.cache().set_value("page:" + page_name, html)
116 return html
117
118def build_html(args):
119 from jinja2 import Environment, FileSystemLoader
120
121 templates_path = os.path.join(os.path.dirname(conf.__file__),
122 'app', 'website', 'templates')
123
Rushabh Mehta7837d802012-12-25 15:09:14 +0530124 args["len"] = len
125
Rushabh Mehta571377a2012-12-07 11:00:26 +0530126 jenv = Environment(loader = FileSystemLoader(templates_path))
127 html = jenv.get_template(args['template']).render(args)
128
129 return html
130
131def prepare_args(page_name):
132 if page_name == 'index':
133 page_name = get_home_page()
134
135 if page_name in get_template_pages():
Rushabh Mehta1b151712012-12-27 16:50:24 +0530136 args = webnotes._dict({
Nabin Haitd68fa3b2013-01-01 12:05:13 +0530137 'template': 'pages/%s.html' % page_name,
Rushabh Mehta571377a2012-12-07 11:00:26 +0530138 'name': page_name,
Rushabh Mehta1b151712012-12-27 16:50:24 +0530139 })
140 if page_name in page_settings_map:
Rushabh Mehtaa2deb682013-03-08 10:44:25 +0530141 target = page_settings_map[page_name]
142 if "." in target:
143 args.update(webnotes.get_method(target)())
144 else:
145 args.obj = webnotes.bean(page_settings_map[page_name]).obj
Akhilesh Darjeec3fde662013-03-22 18:05:22 +0530146
Rushabh Mehta571377a2012-12-07 11:00:26 +0530147 else:
148 args = get_doc_fields(page_name)
149
Rushabh Mehtae109fa42012-12-19 10:14:59 +0530150 if not args:
151 return False
152
Rushabh Mehtaf2b17d92013-02-21 10:49:37 +0530153 get_outer_env(page_name, args)
Rushabh Mehta571377a2012-12-07 11:00:26 +0530154
155 return args
156
Rushabh Mehtaa494b882012-12-07 12:44:45 +0530157def get_template_pages():
Rushabh Mehta571377a2012-12-07 11:00:26 +0530158 pages_path = os.path.join(os.path.dirname(conf.__file__), 'app',
159 'website', 'templates', 'pages')
160 page_list = []
161 for page in os.listdir(pages_path):
162 page_list.append(scrub_page_name(page))
163
164 return page_list
165
166def get_doc_fields(page_name):
167 doc_type, doc_name = get_source_doc(page_name)
Rushabh Mehtae109fa42012-12-19 10:14:59 +0530168 if not doc_type:
169 return False
170
Rushabh Mehta0e9e8482012-12-17 16:00:34 +0530171 obj = webnotes.get_obj(doc_type, doc_name, with_children=True)
Rushabh Mehtaa494b882012-12-07 12:44:45 +0530172
Rushabh Mehta571377a2012-12-07 11:00:26 +0530173 if hasattr(obj, 'prepare_template_args'):
174 obj.prepare_template_args()
Rushabh Mehtaa494b882012-12-07 12:44:45 +0530175
Rushabh Mehta571377a2012-12-07 11:00:26 +0530176 args = obj.doc.fields
Rushabh Mehtaa494b882012-12-07 12:44:45 +0530177 args['template'] = page_map[doc_type].template
Rushabh Mehta0e9e8482012-12-17 16:00:34 +0530178 args['obj'] = obj
Rushabh Mehtafc19f252012-12-20 17:11:51 +0530179 args['int'] = int
Rushabh Mehta571377a2012-12-07 11:00:26 +0530180
181 return args
182
183def get_source_doc(page_name):
184 """get source doc for the given page name"""
Rushabh Mehtaa494b882012-12-07 12:44:45 +0530185 for doctype in page_map:
Rushabh Mehta571377a2012-12-07 11:00:26 +0530186 name = webnotes.conn.sql("""select name from `tab%s` where
Rushabh Mehtaa494b882012-12-07 12:44:45 +0530187 page_name=%s and ifnull(%s, 0)=1""" % (doctype, "%s",
188 page_map[doctype].condition_field), page_name)
Rushabh Mehta571377a2012-12-07 11:00:26 +0530189 if name:
Rushabh Mehtaa494b882012-12-07 12:44:45 +0530190 return doctype, name[0][0]
191
Rushabh Mehta571377a2012-12-07 11:00:26 +0530192 return None, None
193
Rushabh Mehtaf2b17d92013-02-21 10:49:37 +0530194def get_outer_env(page_name, args):
Rushabh Mehta87e48012013-02-20 15:02:21 +0530195 from webnotes.utils import get_request_site_address
196 from urllib import quote
197
Rushabh Mehta571377a2012-12-07 11:00:26 +0530198 all_top_items = webnotes.conn.sql("""\
199 select * from `tabTop Bar Item`
200 where parent='Website Settings' and parentfield='top_bar_items'
201 order by idx asc""", as_dict=1)
Rushabh Mehta60cc0cc2012-12-21 10:52:26 +0530202
Rushabh Mehta571377a2012-12-07 11:00:26 +0530203 top_items = [d for d in all_top_items if not d['parent_label']]
204
205 # attach child items to top bar
206 for d in all_top_items:
207 if d['parent_label']:
208 for t in top_items:
209 if t['label']==d['parent_label']:
210 if not 'child_items' in t:
211 t['child_items'] = []
212 t['child_items'].append(d)
213 break
214
Nabin Haitab573ce2012-12-21 11:01:31 +0530215 if top_items and ("products" in [d.url.split(".")[0] for d in top_items if d.url]):
Rushabh Mehtafc19f252012-12-20 17:11:51 +0530216 # product categories
217 products = webnotes.conn.sql("""select t1.item_group as label,
Rushabh Mehta5f183982013-01-01 10:55:58 +0530218 t2.page_name as url,
Rushabh Mehtafc19f252012-12-20 17:11:51 +0530219 ifnull(t1.indent,0) as indent
220 from `tabWebsite Product Category` t1, `tabItem Group` t2
221 where t1.item_group = t2.name
222 and ifnull(t2.show_in_website,0)=1 order by t1.idx""", as_dict=1)
Rushabh Mehtabda54e52012-12-24 12:52:15 +0530223 products_item = filter(lambda d: d.url and d.url.split(".")[0]=="products", top_items)[0]
Rushabh Mehtafc19f252012-12-20 17:11:51 +0530224 products_item.child_items = products
225
Rushabh Mehta7edf8992012-12-25 18:18:17 +0530226 ret = webnotes._dict({
Rushabh Mehta571377a2012-12-07 11:00:26 +0530227 'top_bar_items': top_items,
Rushabh Mehta571377a2012-12-07 11:00:26 +0530228 'footer_items': webnotes.conn.sql("""\
229 select * from `tabTop Bar Item`
230 where parent='Website Settings' and parentfield='footer_items'
231 order by idx asc""", as_dict=1),
232
Rushabh Mehta8ff938a2013-03-06 11:20:56 +0530233 'int':int,
Rushabh Mehtada512ba2013-03-22 12:45:44 +0530234 "webnotes": webnotes,
235 "utils": webnotes.utils
Rushabh Mehta7edf8992012-12-25 18:18:17 +0530236 })
237
Rushabh Mehtaf2b17d92013-02-21 10:49:37 +0530238 args.update(ret)
239
Rushabh Mehta7edf8992012-12-25 18:18:17 +0530240 settings = webnotes.doc("Website Settings", "Website Settings")
Rushabh Mehta1aff4c32013-03-12 11:22:30 +0530241 for k in ["banner_html", "brand_html", "copyright", "address", "twitter_share_via"
242 "favicon", "facebook_share", "google_plus_one", "twitter_share", "linked_in_share"]:
Rushabh Mehta7edf8992012-12-25 18:18:17 +0530243 if k in settings.fields:
Rushabh Mehtaf2b17d92013-02-21 10:49:37 +0530244 args[k] = settings.fields.get(k)
Rushabh Mehta7edf8992012-12-25 18:18:17 +0530245
Rushabh Mehta891ff092013-02-27 10:51:26 +0530246 for k in ["facebook_share", "google_plus_one", "twitter_share", "linked_in_share"]:
247 args[k] = int(args.get(k) or 0)
Rushabh Mehta87e48012013-02-20 15:02:21 +0530248
Rushabh Mehta1e037fb2013-02-21 11:11:21 +0530249 args.url = quote(str(get_request_site_address(full_address=True)), str(""))
250 args.encoded_title = quote(str(args.title or ""), str(""))
Rushabh Mehta87e48012013-02-20 15:02:21 +0530251
Rushabh Mehtaf2b17d92013-02-21 10:49:37 +0530252 return args
Rushabh Mehta571377a2012-12-07 11:00:26 +0530253
254def get_home_page():
255 doc_name = webnotes.conn.get_value('Website Settings', None, 'home_page')
256 if doc_name:
257 page_name = webnotes.conn.get_value('Web Page', doc_name, 'page_name')
258 else:
259 page_name = 'login'
260
261 return page_name
262
Rushabh Mehta98b99bd2012-12-07 12:55:06 +0530263def clear_cache(page_name=None):
Rushabh Mehta571377a2012-12-07 11:00:26 +0530264 if page_name:
265 delete_page_cache(page_name)
266 else:
Rushabh Mehta28b0b1c2013-01-22 11:04:55 +0530267 cache = webnotes.cache()
268 for p in get_all_pages():
269 cache.delete_value("page:" + p)
270
271def get_all_pages():
272 all_pages = get_template_pages()
273 all_pages += page_settings_map.keys()
274 for doctype in page_map:
275 all_pages += [p[0] for p in webnotes.conn.sql("""select distinct page_name
276 from `tab%s`""" % doctype) if p[0]]
277
278 return all_pages
279
Rushabh Mehta571377a2012-12-07 11:00:26 +0530280def delete_page_cache(page_name):
Anand Doshi65cef742012-12-30 19:58:24 +0530281 if page_name:
282 webnotes.cache().delete_value("page:" + page_name)
Rushabh Mehta5f1d57e2012-12-27 14:05:02 +0530283
284def url_for_website(url):
285 if url and not url.lower().startswith("http"):
286 return "files/" + url
287 else:
Rushabh Mehta860f3ce2013-03-13 12:50:08 +0530288 return url
289
290def get_hex_shade(color, percent):
Rushabh Mehta860f3ce2013-03-13 12:50:08 +0530291
292 def p(c):
293 v = int(c, 16) + int(int('ff', 16) * (float(percent)/100))
294 if v < 0:
295 v=0
296 if v > 255:
297 v=255
298 h = hex(v)[2:]
299 if len(h) < 2:
300 h = "0" + h
301 return h
302
303 r, g, b = color[0:2], color[2:4], color[4:6]
Rushabh Mehta1aab4ea2013-03-14 15:06:44 +0530304
Rushabh Mehta1ffaaf42013-03-14 15:36:43 +0530305 avg = (float(int(r, 16) + int(g, 16) + int(b, 16)) / 3)
306 # switch dark and light shades
307 if avg > 128:
Rushabh Mehta1aab4ea2013-03-14 15:06:44 +0530308 percent = -percent
Rushabh Mehta1ffaaf42013-03-14 15:36:43 +0530309
310 # stronger diff for darker shades
311 if percent < 25 and avg < 64:
312 percent = percent * 2
Rushabh Mehta1aab4ea2013-03-14 15:06:44 +0530313
314 return p(r) + p(g) + p(b)
315
316