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.
 
 
 
 
 
 

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