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.
 
 
 
 
 

341 lines
10 KiB

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