You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

webutils.py 13 KiB

11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  1. # Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
  2. # MIT License. See license.txt
  3. from __future__ import unicode_literals
  4. import webnotes
  5. import json, os, time, re
  6. from webnotes import _
  7. import webnotes.utils
  8. from webnotes.utils import get_request_site_address, encode, cint
  9. from webnotes.model import default_fields
  10. from webnotes.model.controller import DocListController
  11. from urllib import quote
  12. import mimetypes
  13. from webnotes.website.doctype.website_sitemap.website_sitemap import add_to_sitemap, update_sitemap, remove_sitemap
  14. # frequently used imports (used by other modules)
  15. from webnotes.website.doctype.website_sitemap_permission.website_sitemap_permission \
  16. import get_access, clear_permissions
  17. class PageNotFoundError(Exception): pass
  18. def render(path):
  19. """render html page"""
  20. path = resolve_path(path)
  21. try:
  22. data = render_page(path)
  23. except Exception:
  24. path = "error"
  25. data = render_page(path)
  26. data = set_content_type(data, path)
  27. webnotes._response.data = data
  28. webnotes._response.headers[b"Page Name"] = path.encode("utf-8")
  29. def render_page(path):
  30. """get page html"""
  31. cache_key = ("page_context:{}" if is_ajax() else "page:{}").format(path)
  32. out = None
  33. # try memcache
  34. if can_cache():
  35. out = webnotes.cache().get_value(cache_key)
  36. if out and is_ajax():
  37. out = out.get("data")
  38. if out:
  39. if hasattr(webnotes, "_response"):
  40. webnotes._response.headers[b"From Cache"] = True
  41. return out
  42. return build(path)
  43. def build(path):
  44. if not webnotes.conn:
  45. webnotes.connect()
  46. build_method = (build_json if is_ajax() else build_page)
  47. try:
  48. return build_method(path)
  49. except webnotes.DoesNotExistError:
  50. hooks = webnotes.get_hooks()
  51. if hooks.website_catch_all:
  52. return build_method(hooks.website_catch_all[0])
  53. else:
  54. return build_method("404")
  55. def build_json(path):
  56. return get_context(path).data
  57. def build_page(path):
  58. context = get_context(path)
  59. html = webnotes.get_template(context.base_template_path).render(context)
  60. html = scrub_relative_urls(html)
  61. if can_cache(context.no_cache):
  62. webnotes.cache().set_value("page:" + path, html)
  63. return html
  64. def get_context(path):
  65. context = None
  66. cache_key = "page_context:{}".format(path)
  67. from pickle import dump
  68. from StringIO import StringIO
  69. # try from memcache
  70. if can_cache():
  71. context = webnotes.cache().get_value(cache_key)
  72. if not context:
  73. context = get_sitemap_options(path)
  74. # permission may be required for rendering
  75. context["access"] = get_access(context.pathname)
  76. context = build_context(context)
  77. if can_cache(context.no_cache):
  78. webnotes.cache().set_value(cache_key, context)
  79. else:
  80. context["access"] = get_access(context.pathname)
  81. context.update(context.data or {})
  82. # TODO private pages
  83. return context
  84. def get_sitemap_options(path):
  85. sitemap_options = None
  86. cache_key = "sitemap_options:{}".format(path)
  87. if can_cache():
  88. sitemap_options = webnotes.cache().get_value(cache_key)
  89. if not sitemap_options:
  90. sitemap_options = build_sitemap_options(path)
  91. if can_cache(sitemap_options.no_cache):
  92. webnotes.cache().set_value(cache_key, sitemap_options)
  93. return sitemap_options
  94. def build_sitemap_options(path):
  95. sitemap_options = webnotes.doc("Website Sitemap", path).fields
  96. sitemap_config = webnotes.doc("Website Sitemap Config",
  97. sitemap_options.get("website_sitemap_config")).fields
  98. # get sitemap config fields too
  99. for fieldname in ("base_template_path", "template_path", "controller", "no_cache", "no_sitemap",
  100. "page_name_field", "condition_field"):
  101. sitemap_options[fieldname] = sitemap_config.get(fieldname)
  102. sitemap_options.doctype = sitemap_options.ref_doctype
  103. sitemap_options.title = sitemap_options.page_title
  104. sitemap_options.pathname = sitemap_options.name
  105. # establish hierarchy
  106. sitemap_options.parents = webnotes.conn.sql("""select name, page_title from `tabWebsite Sitemap`
  107. where lft < %s and rgt > %s order by lft asc""", (sitemap_options.lft, sitemap_options.rgt), as_dict=True)
  108. sitemap_options.children = webnotes.conn.sql("""select * from `tabWebsite Sitemap`
  109. where parent_website_sitemap=%s
  110. and public_read=1 order by -idx desc, page_title asc""", (sitemap_options.pathname,), as_dict=True)
  111. # leaf node, show siblings
  112. if not sitemap_options.children:
  113. sitemap_options.children = webnotes.conn.sql("""select * from `tabWebsite Sitemap`
  114. where ifnull(parent_website_sitemap, '')=%s
  115. and public_read=1 order by -idx desc, page_title asc""",
  116. sitemap_options.parent_website_sitemap or "", as_dict=True)
  117. # determine templates to be used
  118. if not sitemap_options.base_template_path:
  119. sitemap_options.base_template_path = "templates/base.html"
  120. return sitemap_options
  121. def build_context(sitemap_options):
  122. """get_context method of bean or module is supposed to render content templates and push it into context"""
  123. context = webnotes._dict(sitemap_options)
  124. context.update(get_website_settings())
  125. # provide bean
  126. if context.doctype and context.docname:
  127. context.bean = webnotes.bean(context.doctype, context.docname)
  128. if context.controller:
  129. module = webnotes.get_module(context.controller)
  130. if module and hasattr(module, "get_context"):
  131. context.update(module.get_context(context) or {})
  132. if context.get("base_template_path") != context.get("template_path") and not context.get("rendered"):
  133. context.data = render_blocks(context)
  134. # remove bean, as it is not pickle friendly and its purpose is over
  135. if context.bean:
  136. del context["bean"]
  137. return context
  138. def can_cache(no_cache=False):
  139. return not (webnotes.conf.disable_website_cache or no_cache)
  140. def get_home_page():
  141. home_page = webnotes.cache().get_value("home_page", \
  142. lambda: (webnotes.get_hooks("home_page") \
  143. or [webnotes.conn.get_value("Website Settings", None, "home_page") \
  144. or "login"])[0])
  145. print home_page
  146. return home_page
  147. def get_website_settings():
  148. # TODO Cache this
  149. hooks = webnotes.get_hooks()
  150. all_top_items = webnotes.conn.sql("""\
  151. select * from `tabTop Bar Item`
  152. where parent='Website Settings' and parentfield='top_bar_items'
  153. order by idx asc""", as_dict=1)
  154. top_items = [d for d in all_top_items if not d['parent_label']]
  155. # attach child items to top bar
  156. for d in all_top_items:
  157. if d['parent_label']:
  158. for t in top_items:
  159. if t['label']==d['parent_label']:
  160. if not 'child_items' in t:
  161. t['child_items'] = []
  162. t['child_items'].append(d)
  163. break
  164. context = webnotes._dict({
  165. 'top_bar_items': top_items,
  166. 'footer_items': webnotes.conn.sql("""\
  167. select * from `tabTop Bar Item`
  168. where parent='Website Settings' and parentfield='footer_items'
  169. order by idx asc""", as_dict=1),
  170. "post_login": [
  171. {"label": "Reset Password", "url": "update-password", "icon": "icon-key"},
  172. {"label": "Logout", "url": "?cmd=web_logout", "icon": "icon-signout"}
  173. ]
  174. })
  175. settings = webnotes.doc("Website Settings", "Website Settings")
  176. for k in ["banner_html", "brand_html", "copyright", "twitter_share_via",
  177. "favicon", "facebook_share", "google_plus_one", "twitter_share", "linked_in_share",
  178. "disable_signup"]:
  179. if k in settings.fields:
  180. context[k] = settings.fields.get(k)
  181. if settings.address:
  182. context["footer_address"] = settings.address
  183. for k in ["facebook_share", "google_plus_one", "twitter_share", "linked_in_share",
  184. "disable_signup"]:
  185. context[k] = cint(context.get(k) or 0)
  186. context.url = quote(str(get_request_site_address(full_address=True)), safe="/:")
  187. context.encoded_title = quote(encode(context.title or ""), str(""))
  188. for update_website_context in hooks.update_website_context or []:
  189. webnotes.get_attr(update_website_context)(context)
  190. context.web_include_js = hooks.web_include_js or []
  191. context.web_include_css = hooks.web_include_css or []
  192. return context
  193. def is_ajax():
  194. return webnotes.get_request_header("X-Requested-With")=="XMLHttpRequest"
  195. def resolve_path(path):
  196. if not path:
  197. path = "index"
  198. if path.endswith('.html'):
  199. path = path[:-5]
  200. if path == "index":
  201. path = get_home_page()
  202. return path
  203. def set_content_type(data, path):
  204. if isinstance(data, dict):
  205. webnotes._response.headers[b"Content-Type"] = b"application/json; charset: utf-8"
  206. data = json.dumps(data)
  207. return data
  208. webnotes._response.headers[b"Content-Type"] = b"text/html; charset: utf-8"
  209. if "." in path and not path.endswith(".html"):
  210. content_type, encoding = mimetypes.guess_type(path)
  211. webnotes._response.headers[b"Content-Type"] = content_type.encode("utf-8")
  212. return data
  213. def clear_cache(path=None):
  214. cache = webnotes.cache()
  215. if path:
  216. delete_page_cache(path)
  217. else:
  218. for p in webnotes.conn.sql_list("""select name from `tabWebsite Sitemap`"""):
  219. if p is not None:
  220. delete_page_cache(p)
  221. cache.delete_value("home_page")
  222. clear_permissions()
  223. for method in webnotes.get_hooks("website_clear_cache"):
  224. webnotes.get_attr(method)(path)
  225. def delete_page_cache(path):
  226. cache = webnotes.cache()
  227. cache.delete_value("page:" + path)
  228. cache.delete_value("page_context:" + path)
  229. cache.delete_value("sitemap_options:" + path)
  230. def is_signup_enabled():
  231. if getattr(webnotes.local, "is_signup_enabled", None) is None:
  232. webnotes.local.is_signup_enabled = True
  233. if webnotes.utils.cint(webnotes.conn.get_value("Website Settings",
  234. "Website Settings", "disable_signup")):
  235. webnotes.local.is_signup_enabled = False
  236. return webnotes.local.is_signup_enabled
  237. def call_website_generator(bean, method, *args, **kwargs):
  238. getattr(WebsiteGenerator(bean.doc, bean.doclist), method)(*args, **kwargs)
  239. class WebsiteGenerator(DocListController):
  240. def autoname(self):
  241. from webnotes.webutils import cleanup_page_name
  242. self.doc.name = cleanup_page_name(self.get_page_title())
  243. def set_page_name(self):
  244. """set page name based on parent page_name and title"""
  245. page_name = cleanup_page_name(self.get_page_title())
  246. if self.doc.is_new():
  247. self.doc.fields[self._website_config.page_name_field] = page_name
  248. else:
  249. webnotes.conn.set(self.doc, self._website_config.page_name_field, page_name)
  250. def setup_generator(self):
  251. self._website_config = webnotes.conn.get_values("Website Sitemap Config",
  252. {"ref_doctype": self.doc.doctype}, "*")[0]
  253. def on_update(self):
  254. self.update_sitemap()
  255. def after_rename(self, olddn, newdn, merge):
  256. webnotes.conn.sql("""update `tabWebsite Sitemap`
  257. set docname=%s where ref_doctype=%s and docname=%s""", (newdn, self.doc.doctype, olddn))
  258. if merge:
  259. self.setup_generator()
  260. remove_sitemap(ref_doctype=self.doc.doctype, docname=olddn)
  261. def on_trash(self):
  262. self.setup_generator()
  263. remove_sitemap(ref_doctype=self.doc.doctype, docname=self.doc.name)
  264. def update_sitemap(self):
  265. self.setup_generator()
  266. if self._website_config.condition_field and \
  267. not self.doc.fields.get(self._website_config.condition_field):
  268. # condition field failed, remove and return!
  269. remove_sitemap(ref_doctype=self.doc.doctype, docname=self.doc.name)
  270. return
  271. self.add_or_update_sitemap()
  272. def add_or_update_sitemap(self):
  273. page_name = self.get_page_name()
  274. existing_site_map = webnotes.conn.get_value("Website Sitemap", {"ref_doctype": self.doc.doctype,
  275. "docname": self.doc.name})
  276. opts = webnotes._dict({
  277. "page_or_generator": "Generator",
  278. "ref_doctype":self.doc.doctype,
  279. "docname": self.doc.name,
  280. "page_name": page_name,
  281. "link_name": self._website_config.name,
  282. "lastmod": webnotes.utils.get_datetime(self.doc.modified).strftime("%Y-%m-%d"),
  283. "parent_website_sitemap": self.doc.parent_website_sitemap,
  284. "page_title": self.get_page_title()
  285. })
  286. self.update_permissions(opts)
  287. if existing_site_map:
  288. update_sitemap(existing_site_map, opts)
  289. else:
  290. add_to_sitemap(opts)
  291. def update_permissions(self, opts):
  292. if self.meta.get_field("public_read"):
  293. opts.public_read = self.doc.public_read
  294. opts.public_write = self.doc.public_write
  295. else:
  296. opts.public_read = 1
  297. def get_page_name(self):
  298. if not self._get_page_name():
  299. self.set_page_name()
  300. return self._get_page_name()
  301. def _get_page_name(self):
  302. return self.doc.fields.get(self._website_config.page_name_field)
  303. def get_page_title(self):
  304. return self.doc.title or (self.doc.name.replace("-", " ").replace("_", " ").title())
  305. def cleanup_page_name(title):
  306. """make page name from title"""
  307. import re
  308. name = title.lower()
  309. name = re.sub('[~!@#$%^&*+()<>,."\'\?]', '', name)
  310. name = re.sub('[:/]', '-', name)
  311. name = '-'.join(name.split())
  312. # replace repeating hyphens
  313. name = re.sub(r"(-)\1+", r"\1", name)
  314. return name
  315. def get_hex_shade(color, percent):
  316. def p(c):
  317. v = int(c, 16) + int(int('ff', 16) * (float(percent)/100))
  318. if v < 0:
  319. v=0
  320. if v > 255:
  321. v=255
  322. h = hex(v)[2:]
  323. if len(h) < 2:
  324. h = "0" + h
  325. return h
  326. r, g, b = color[0:2], color[2:4], color[4:6]
  327. avg = (float(int(r, 16) + int(g, 16) + int(b, 16)) / 3)
  328. # switch dark and light shades
  329. if avg > 128:
  330. percent = -percent
  331. # stronger diff for darker shades
  332. if percent < 25 and avg < 64:
  333. percent = percent * 2
  334. return p(r) + p(g) + p(b)
  335. def render_blocks(context):
  336. """returns a dict of block name and its rendered content"""
  337. from jinja2.utils import concat
  338. out = {}
  339. template = webnotes.get_template(context["template_path"])
  340. # required as per low level API
  341. context = template.new_context(context)
  342. # render each block individually
  343. for block, render in template.blocks.items():
  344. out[block] = scrub_relative_urls(concat(render(context)))
  345. return out
  346. def scrub_relative_urls(html):
  347. """prepend a slash before a relative url"""
  348. return re.sub("""(src|href)[^\w'"]*['"](?!http|ftp|/|#)([^'" >]+)['"]""", '\g<1> = "/\g<2>"', html)