A Python content management system designed for kirsle.net featuring a blog, comments and photo albums. https://rophako.kirsle.net/
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.

297 lines
8.8KB

  1. # -*- coding: utf-8 -*-
  2. from flask import (g, session, request, render_template, flash, redirect,
  3. url_for, current_app)
  4. from functools import wraps
  5. import codecs
  6. import uuid
  7. import datetime
  8. import time
  9. import re
  10. import importlib
  11. import smtplib
  12. import markdown
  13. import json
  14. import urlparse
  15. import traceback
  16. from rophako.log import logger
  17. from rophako.settings import Config
  18. def login_required(f):
  19. """Wrapper for pages that require a logged-in user."""
  20. @wraps(f)
  21. def decorated_function(*args, **kwargs):
  22. if not g.info["session"]["login"]:
  23. session["redirect_url"] = request.url
  24. flash("You must be logged in to do that!")
  25. return redirect(url_for("account.login"))
  26. return f(*args, **kwargs)
  27. return decorated_function
  28. def admin_required(f):
  29. """Wrapper for admin-only pages. Implies login_required."""
  30. @wraps(f)
  31. def decorated_function(*args, **kwargs):
  32. if not g.info["session"]["login"]:
  33. # Not even logged in?
  34. session["redirect_url"] = request.url
  35. flash("You must be logged in to do that!")
  36. return redirect(url_for("account.login"))
  37. if g.info["session"]["role"] != "admin":
  38. logger.warning("User tried to access an Admin page, but wasn't allowed!")
  39. return redirect(url_for("index"))
  40. return f(*args, **kwargs)
  41. return decorated_function
  42. def ajax_response(status, msg):
  43. """Return a standard JSON response."""
  44. status = "ok" if status else "error"
  45. return json.dumps(dict(
  46. status=status,
  47. msg=msg,
  48. ))
  49. def template(name, **kwargs):
  50. """Render a template to the browser."""
  51. html = render_template(name, **kwargs)
  52. # Get the elapsed time for the request.
  53. time_elapsed = "%.03f" % (time.time() - g.info["time"])
  54. html = re.sub(r'\%time_elapsed\%', time_elapsed, html)
  55. return html
  56. def markdown_template(path):
  57. """Render a Markdown page to the browser.
  58. The first line in the Markdown page should be an H1 header beginning with
  59. the # sign. This will set the page's <title> to match the header value.
  60. Pages can include lines that begin with the keyword `:meta` to apply
  61. meta information to control the Markdown parser. Supported meta lines
  62. and examples:
  63. To 'blacklist' extensions, i.e. to turn off line breaks inside a paragraph
  64. getting translated into a <br> tag (the key is the minus sign):
  65. :meta extensions -nl2br
  66. To add an extension, i.e. the abbreviations from PHP Markdown Extra:
  67. :meta extensions abbr"""
  68. # The path is the absolute path to the Markdown file, so open it directly.
  69. fh = codecs.open(path, "r", "utf-8")
  70. body = fh.read()
  71. fh.close()
  72. # Look for meta information in the file.
  73. lines = body.split("\n")
  74. content = list() # New set of lines, without meta info.
  75. extensions = set()
  76. blacklist = set() # Blacklisted extensions
  77. for line in lines:
  78. if line.startswith(":meta"):
  79. parts = line.split(" ")
  80. if len(parts) >= 3:
  81. # Supported meta commands.
  82. if parts[1] == "extensions":
  83. # Extension toggles.
  84. for extension in parts[2:]:
  85. if extension.startswith("-"):
  86. extension = extension[1:]
  87. blacklist.add(extension)
  88. else:
  89. extensions.add(extension)
  90. else:
  91. content.append(line)
  92. # Extract a title from the first line.
  93. first = content[0]
  94. if first.startswith("#"):
  95. first = first[1:].strip()
  96. rendered = render_markdown("\n".join(content),
  97. extensions=extensions,
  98. blacklist=blacklist,
  99. )
  100. return template("markdown.inc.html",
  101. title=first,
  102. markdown=rendered,
  103. )
  104. def render_markdown(body, html_escape=True, extensions=None, blacklist=None):
  105. """Render a block of Markdown text.
  106. This will default to escaping literal HTML characters. Set
  107. `html_escape=False` to trust HTML.
  108. * extensions should be a set() of extensions to add.
  109. * blacklist should be a set() of extensions to blacklist."""
  110. args = dict(
  111. lazy_ol=False, # If a numbered list starts at e.g. 4, show the <ol> there
  112. extensions=[
  113. "fenced_code", # GitHub style code blocks
  114. "tables", # http://michelf.ca/projects/php-markdown/extra/#table
  115. "smart_strong", # Handles double__underscore better.
  116. "codehilite", # Code highlighting with Pygment!
  117. "nl2br", # Line breaks inside a paragraph become <br>
  118. "sane_lists", # Make lists less surprising
  119. ],
  120. extension_configs={
  121. "codehilite": {
  122. "linenums": False,
  123. }
  124. }
  125. )
  126. if html_escape:
  127. args["safe_mode"] = "escape"
  128. # Additional extensions?
  129. if extensions is not None:
  130. for ext in extensions:
  131. args["extensions"].append(ext)
  132. if blacklist is not None:
  133. for ext in blacklist:
  134. args["extensions"].remove(str(ext))
  135. return markdown.markdown(body, **args)
  136. def send_email(to, subject, message, sender=None, reply_to=None):
  137. """Send an e-mail out."""
  138. if sender is None:
  139. sender = Config.mail.sender
  140. if type(to) != list:
  141. to = [to]
  142. logger.info("Send email to {}".format(to))
  143. if Config.mail.method == "smtp":
  144. # Send mail with SMTP.
  145. for email in to:
  146. # Construct the mail headers.
  147. headers = [
  148. "From: {}".format(sender),
  149. "To: {}".format(email),
  150. ]
  151. if reply_to is not None:
  152. headers.append("Reply-To: {}".format(reply_to))
  153. headers.append("Subject: {}".format(subject))
  154. # Prepare the mail for transport.
  155. server = smtplib.SMTP(Config.mail.server, Config.mail.port)
  156. msg = "\n".join(headers) + "\n\n" + message
  157. server.sendmail(sender, email, msg)
  158. server.quit()
  159. def handle_exception(error):
  160. """Send an e-mail to the site admin when an exception occurs."""
  161. if current_app.config.get("DEBUG"):
  162. print traceback.format_exc()
  163. raise
  164. import rophako.jsondb as JsonDB
  165. # Don't spam too many e-mails in a short time frame.
  166. cache = JsonDB.get_cache("exception_catcher")
  167. if cache:
  168. last_exception = int(cache)
  169. if int(time.time()) - last_exception < 120:
  170. # Only one e-mail per 2 minutes, minimum
  171. logger.error("RAPID EXCEPTIONS, DROPPING")
  172. return
  173. JsonDB.set_cache("exception_catcher", int(time.time()))
  174. username = "anonymous"
  175. try:
  176. if "username" in g.info["session"]:
  177. username = g.info["session"]["username"]
  178. except:
  179. pass
  180. # Get the timestamp.
  181. timestamp = time.ctime(time.time())
  182. # Exception's traceback.
  183. error = str(error.__class__.__name__) + ": " + str(error)
  184. stacktrace = error + "\n\n" \
  185. + "==== Start Traceback ====\n" \
  186. + traceback.format_exc() \
  187. + "==== End Traceback ====\n"
  188. # Construct the subject and message
  189. subject = "Internal Server Error on {} - {} - {}".format(
  190. Config.site.site_name,
  191. username,
  192. timestamp,
  193. )
  194. message = "{} has experienced an exception on the route: {}".format(
  195. username,
  196. request.path,
  197. )
  198. message += "\n\n" + stacktrace
  199. # Send the e-mail.
  200. send_email(
  201. to=Config.site.notify_address,
  202. subject=subject,
  203. message=message,
  204. )
  205. def generate_csrf_token():
  206. """Generator for CSRF tokens."""
  207. if "_csrf" not in session:
  208. session["_csrf"] = str(uuid.uuid4())
  209. return session["_csrf"]
  210. def include(endpoint, *args, **kwargs):
  211. """Include another sub-page inside a template."""
  212. # The 'endpoint' should be in the format 'module.function', i.e. 'blog.index'.
  213. module, function = endpoint.split(".")
  214. # Dynamically import the module and call its function.
  215. m = importlib.import_module("rophako.modules.{}".format(module))
  216. html = getattr(m, function)(*args, **kwargs)
  217. return html
  218. def remote_addr():
  219. """Retrieve the end user's remote IP address."""
  220. # TODO: eventually support configurations with X-Forwarded-For, but for
  221. # now at least we're centralizing this in one spot.
  222. return request.remote_addr
  223. def server_name():
  224. """Get the server's hostname."""
  225. urlparts = list(urlparse.urlparse(request.url_root))
  226. return urlparts[1]
  227. def pretty_time(time_format, unix):
  228. """Pretty-print a time stamp."""
  229. date = datetime.datetime.fromtimestamp(unix)
  230. return date.strftime(time_format)
  231. def sanitize_name(name):
  232. """Sanitize a name that may be used in the filesystem.
  233. Only allows numbers, letters, and some symbols."""
  234. return re.sub(r'[^A-Za-z0-9 .\-_]+', '', name)