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.
 
 
 
 
 

313 lines
9.3 KiB

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