25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

459 lines
13 KiB

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