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.
 
 
 
 
 

240 lines
7.3 KiB

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