25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.
 
 
 
 
 
 

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