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.
 
 
 
 
 
 

210 line
5.4 KiB

  1. # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
  2. # MIT License. See license.txt
  3. from __future__ import unicode_literals
  4. import frappe, re, os
  5. def delete_page_cache(path):
  6. cache = frappe.cache()
  7. groups = ("website_page", "page_context")
  8. if path:
  9. for name in groups:
  10. cache.hdel(name, path)
  11. else:
  12. for name in groups:
  13. cache.delete_key(name)
  14. def find_first_image(html):
  15. m = re.finditer("""<img[^>]*src\s?=\s?['"]([^'"]*)['"]""", html)
  16. try:
  17. return m.next().groups()[0]
  18. except StopIteration:
  19. return None
  20. def can_cache(no_cache=False):
  21. return not (frappe.conf.disable_website_cache or getattr(frappe.local, "no_cache", False) or no_cache)
  22. def get_comment_list(doctype, name):
  23. return frappe.db.sql("""select
  24. content, sender_full_name, creation, sender
  25. from `tabCommunication`
  26. where
  27. communication_type='Comment'
  28. and reference_doctype=%s
  29. and reference_name=%s
  30. and (comment_type is null or comment_type in ('Comment', 'Communication'))
  31. and modified >= DATE_SUB(NOW(),INTERVAL 1 YEAR)
  32. order by creation""", (doctype, name), as_dict=1) or []
  33. def get_home_page():
  34. if frappe.local.flags.home_page:
  35. return frappe.local.flags.home_page
  36. def _get_home_page():
  37. home_page = None
  38. get_website_user_home_page = frappe.get_hooks('get_website_user_home_page')
  39. if get_website_user_home_page:
  40. home_page = frappe.get_attr(get_website_user_home_page[-1])(frappe.session.user)
  41. if not home_page:
  42. role_home_page = frappe.get_hooks("role_home_page")
  43. if role_home_page:
  44. for role in frappe.get_roles():
  45. if role in role_home_page:
  46. home_page = role_home_page[role][-1]
  47. break
  48. if not home_page:
  49. home_page = frappe.get_hooks("home_page")
  50. if home_page:
  51. home_page = home_page[-1]
  52. if not home_page:
  53. home_page = frappe.db.get_value("Website Settings", None, "home_page") or "login"
  54. home_page = home_page.strip('/')
  55. return home_page
  56. return frappe.cache().hget("home_page", frappe.session.user, _get_home_page)
  57. def is_signup_enabled():
  58. if getattr(frappe.local, "is_signup_enabled", None) is None:
  59. frappe.local.is_signup_enabled = True
  60. if frappe.utils.cint(frappe.db.get_value("Website Settings",
  61. "Website Settings", "disable_signup")):
  62. frappe.local.is_signup_enabled = False
  63. return frappe.local.is_signup_enabled
  64. def cleanup_page_name(title):
  65. """make page name from title"""
  66. if not title:
  67. return title
  68. name = title.lower()
  69. name = re.sub('[~!@#$%^&*+()<>,."\'\?]', '', name)
  70. name = re.sub('[:/]', '-', name)
  71. name = '-'.join(name.split())
  72. # replace repeating hyphens
  73. name = re.sub(r"(-)\1+", r"\1", name)
  74. return name[:140]
  75. def get_shade(color, percent):
  76. color, color_format = detect_color_format(color)
  77. r, g, b, a = color
  78. avg = (float(int(r) + int(g) + int(b)) / 3)
  79. # switch dark and light shades
  80. if avg > 128:
  81. percent = -percent
  82. # stronger diff for darker shades
  83. if percent < 25 and avg < 64:
  84. percent = percent * 2
  85. new_color = []
  86. for channel_value in (r, g, b):
  87. new_color.append(get_shade_for_channel(channel_value, percent))
  88. r, g, b = new_color
  89. return format_color(r, g, b, a, color_format)
  90. def detect_color_format(color):
  91. if color.startswith("rgba"):
  92. color_format = "rgba"
  93. color = [c.strip() for c in color[5:-1].split(",")]
  94. elif color.startswith("rgb"):
  95. color_format = "rgb"
  96. color = [c.strip() for c in color[4:-1].split(",")] + [1]
  97. else:
  98. # assume hex
  99. color_format = "hex"
  100. if color.startswith("#"):
  101. color = color[1:]
  102. if len(color) == 3:
  103. # hex in short form like #fff
  104. color = "{0}{0}{1}{1}{2}{2}".format(*tuple(color))
  105. color = [int(color[0:2], 16), int(color[2:4], 16), int(color[4:6], 16), 1]
  106. return color, color_format
  107. def get_shade_for_channel(channel_value, percent):
  108. v = int(channel_value) + int(int('ff', 16) * (float(percent)/100))
  109. if v < 0:
  110. v=0
  111. if v > 255:
  112. v=255
  113. return v
  114. def format_color(r, g, b, a, color_format):
  115. if color_format == "rgba":
  116. return "rgba({0}, {1}, {2}, {3})".format(r, g, b, a)
  117. elif color_format == "rgb":
  118. return "rgb({0}, {1}, {2})".format(r, g, b)
  119. else:
  120. # assume hex
  121. return "#{0}{1}{2}".format(convert_to_hex(r), convert_to_hex(g), convert_to_hex(b))
  122. def convert_to_hex(channel_value):
  123. h = hex(channel_value)[2:]
  124. if len(h) < 2:
  125. h = "0" + h
  126. return h
  127. def abs_url(path):
  128. """Deconstructs and Reconstructs a URL into an absolute URL or a URL relative from root '/'"""
  129. if not path:
  130. return
  131. if path.startswith('http://') or path.startswith('https://'):
  132. return path
  133. if not path.startswith("/"):
  134. path = "/" + path
  135. return path
  136. def get_full_index(route=None, doctype="Web Page", extn = False):
  137. """Returns full index of the website (on Web Page) upto the n-th level"""
  138. all_routes = []
  139. def get_children(parent):
  140. children = frappe.db.get_all(doctype, ["parent_website_route", "page_name", "title", "template_path"],
  141. {"parent_website_route": parent}, order_by="idx asc")
  142. for d in children:
  143. d.url = abs_url(os.path.join(d.parent_website_route or "", d.page_name))
  144. if d.url not in all_routes:
  145. d.children = get_children(d.url.lstrip("/"))
  146. all_routes.append(d.url)
  147. if extn and os.path.basename(d.template_path).split(".")[0] != "index":
  148. d.url = d.url + ".html"
  149. # no index.html for home page
  150. # home should not be in table of contents
  151. if not parent:
  152. children = [d for d in children if d.page_name not in ("index.html", "index",
  153. "", "contents")]
  154. return children
  155. return get_children(route or "")