├── app.log ├── runtime.txt ├── Procfile ├── .bowerrc ├── requirements.txt ├── static ├── img │ ├── next.png │ ├── prev.png │ ├── close.png │ ├── favicon.png │ └── loading.gif ├── bower_components │ ├── core-component-page │ │ ├── bowager-logo.png │ │ ├── bower.json │ │ ├── README.md │ │ ├── .bower.json │ │ ├── index.html │ │ └── demo.html │ ├── platform │ │ ├── README.md │ │ ├── bower.json │ │ └── .bower.json │ ├── polymer │ │ ├── bower.json │ │ ├── .bower.json │ │ ├── polymer.html │ │ ├── README.md │ │ └── layout.html │ └── github-gist │ │ ├── bower.json │ │ ├── index.html │ │ ├── .bower.json │ │ ├── LICENSE │ │ ├── README.md │ │ └── github-gist.html ├── js │ ├── main.js │ ├── lightbox-2.6.min.js │ ├── a-tools.js │ ├── mdmagick.js │ └── showdown.js └── css │ ├── mdmagick.css │ ├── main.css │ └── lightbox.css ├── templates ├── footer.html ├── 404.html ├── sidebar.html ├── head.html ├── nav.html ├── users.html ├── posts.html ├── single_post.html ├── preview.html ├── login.html ├── index.html ├── add_user.html ├── new_post.html ├── settings.html ├── edit_post.html ├── edit_user.html └── install.html ├── mdx_strike.py ├── mdx_quote.py ├── bower.json ├── mdx_code_multiline.py ├── mdx_github_gists.py ├── pagination.py ├── LICENSE ├── config.py ├── helper_functions.py ├── README.md ├── settings.py ├── post.py ├── user.py └── web.py /app.log: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /runtime.txt: -------------------------------------------------------------------------------- 1 | python-2.7.5 2 | -------------------------------------------------------------------------------- /Procfile: -------------------------------------------------------------------------------- 1 | web: gunicorn web:app 2 | -------------------------------------------------------------------------------- /.bowerrc: -------------------------------------------------------------------------------- 1 | { 2 | "directory": "/static/bower_components" 3 | } 4 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | flask==0.10.1 2 | flask-markdown 3 | pymongo==3.0.3 4 | gunicorn 5 | -------------------------------------------------------------------------------- /static/img/next.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dmaslov/flask-blog/HEAD/static/img/next.png -------------------------------------------------------------------------------- /static/img/prev.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dmaslov/flask-blog/HEAD/static/img/prev.png -------------------------------------------------------------------------------- /static/img/close.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dmaslov/flask-blog/HEAD/static/img/close.png -------------------------------------------------------------------------------- /static/img/favicon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dmaslov/flask-blog/HEAD/static/img/favicon.png -------------------------------------------------------------------------------- /static/img/loading.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dmaslov/flask-blog/HEAD/static/img/loading.gif -------------------------------------------------------------------------------- /static/bower_components/core-component-page/bowager-logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dmaslov/flask-blog/HEAD/static/bower_components/core-component-page/bowager-logo.png -------------------------------------------------------------------------------- /static/bower_components/platform/README.md: -------------------------------------------------------------------------------- 1 | Platform 2 | ======== 3 | 4 | Aggregated polyfills the Polymer platform. 5 | 6 | [![Analytics](https://ga-beacon.appspot.com/UA-39334307-2/Polymer/platform/README)](https://github.com/igrigorik/ga-beacon) 7 | -------------------------------------------------------------------------------- /static/bower_components/core-component-page/bower.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "core-component-page", 3 | "private": true, 4 | "dependencies": { 5 | "platform": "Polymer/platform#>=0.3.0 <1.0.0", 6 | "polymer": "Polymer/polymer#>=0.3.0 <1.0.0" 7 | } 8 | } -------------------------------------------------------------------------------- /static/bower_components/polymer/bower.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "polymer", 3 | "private": true, 4 | "dependencies": { 5 | "platform": "Polymer/platform#>=0.3.0 <1.0.0", 6 | "core-component-page": "Polymer/core-component-page#>=0.3.0 <1.0.0" 7 | } 8 | } -------------------------------------------------------------------------------- /templates/footer.html: -------------------------------------------------------------------------------- 1 | 6 | 7 | -------------------------------------------------------------------------------- /static/bower_components/core-component-page/README.md: -------------------------------------------------------------------------------- 1 | core-component-page 2 | =================== 3 | 4 | See the [component page](http://polymer-project.org/docs/elements/core-elements.html#core-component-page) for more information. 5 | 6 | Note: this is the vulcanized version of [`core-component-page-dev`](https://github.com/Polymer/core-component-page-dev) (the source). 7 | -------------------------------------------------------------------------------- /mdx_strike.py: -------------------------------------------------------------------------------- 1 | import markdown 2 | 3 | STRIKE_RE = r'(-{2})(.+?)\2' 4 | 5 | 6 | class StrikeExtension(markdown.Extension): 7 | def extendMarkdown(self, md, md_globals): 8 | md.inlinePatterns.add('strike', markdown.inlinepatterns.SimpleTagPattern(STRIKE_RE, 'strike'), '>strong') 9 | 10 | 11 | def makeExtension(configs=None): 12 | return StrikeExtension(configs = configs) -------------------------------------------------------------------------------- /mdx_quote.py: -------------------------------------------------------------------------------- 1 | import markdown 2 | 3 | BLOCKQUOTE_RE = r'(~{2})(.+?)\2' 4 | 5 | 6 | class QuoteExtension(markdown.Extension): 7 | def extendMarkdown(self, md, md_globals): 8 | md.inlinePatterns.add('blockquote', markdown.inlinepatterns.SimpleTagPattern(BLOCKQUOTE_RE, 'blockquote'), '>strong') 9 | 10 | 11 | def makeExtension(configs=None): 12 | return QuoteExtension(configs = configs) -------------------------------------------------------------------------------- /bower.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "flask_blog", 3 | "version": "0.0.0", 4 | "authors": [ 5 | "Dmitry Maslov " 6 | ], 7 | "license": "MIT", 8 | "private": true, 9 | "ignore": [ 10 | "**/.*", 11 | "node_modules", 12 | "bower_components", 13 | "test", 14 | "tests" 15 | ], 16 | "devDependencies": { 17 | "github-gist": "~0.1.1" 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /static/bower_components/platform/bower.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "platform", 3 | "main": "platform.js", 4 | "homepage": "https://github.com/Polymer/platform", 5 | "authors": [ 6 | "The Polymer Authors" 7 | ], 8 | "description": "Integrate platform polyfills: load, build, test", 9 | "keywords": [ 10 | "polymer", 11 | "web", 12 | "components" 13 | ], 14 | "license": "BSD", 15 | "private": true 16 | } -------------------------------------------------------------------------------- /templates/404.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | {%- block head -%}{%- include 'head.html' -%}{%- endblock -%} 4 | 5 |
6 |
7 |
8 |

Oops! 404

9 |

not found...

10 |
11 |
12 |
13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /static/bower_components/polymer/.bower.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "polymer", 3 | "private": true, 4 | "dependencies": { 5 | "platform": "Polymer/platform#>=0.3.0 <1.0.0", 6 | "core-component-page": "Polymer/core-component-page#>=0.3.0 <1.0.0" 7 | }, 8 | "homepage": "https://github.com/Polymer/polymer", 9 | "version": "0.3.5", 10 | "_release": "0.3.5", 11 | "_resolution": { 12 | "type": "version", 13 | "tag": "0.3.5", 14 | "commit": "a09a0e689fdeab11b53b41eaed033781733bf1eb" 15 | }, 16 | "_source": "git://github.com/Polymer/polymer.git", 17 | "_target": "~0.3.0", 18 | "_originalSource": "Polymer/polymer" 19 | } -------------------------------------------------------------------------------- /static/bower_components/core-component-page/.bower.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "core-component-page", 3 | "private": true, 4 | "dependencies": { 5 | "platform": "Polymer/platform#>=0.3.0 <1.0.0", 6 | "polymer": "Polymer/polymer#>=0.3.0 <1.0.0" 7 | }, 8 | "homepage": "https://github.com/Polymer/core-component-page", 9 | "version": "0.3.5", 10 | "_release": "0.3.5", 11 | "_resolution": { 12 | "type": "version", 13 | "tag": "0.3.5", 14 | "commit": "87617aa1282994eecf5f1f57ef149155ed96f7f1" 15 | }, 16 | "_source": "git://github.com/Polymer/core-component-page.git", 17 | "_target": ">=0.3.0 <1.0.0", 18 | "_originalSource": "Polymer/core-component-page" 19 | } -------------------------------------------------------------------------------- /static/bower_components/github-gist/bower.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "github-gist", 3 | "version": "0.1.1", 4 | "authors": [ 5 | "Dmitry Maslov " 6 | ], 7 | "description": "A web component to display github gists", 8 | "main": "github-gist.html", 9 | "keywords": [ 10 | "web-components", 11 | "polymer", 12 | "github", 13 | "gist" 14 | ], 15 | "license": "MIT", 16 | "homepage": "https://github.com/dmaslov/github-gist", 17 | "ignore": [ 18 | "**/.*", 19 | "node_modules", 20 | "bower_components", 21 | "test", 22 | "tests" 23 | ], 24 | "dependencies": { 25 | "polymer": "Polymer/polymer#~0.3.0" 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /templates/sidebar.html: -------------------------------------------------------------------------------- 1 | {%- if recent_posts -%} 2 | 20 | {%- endif -%} 21 | -------------------------------------------------------------------------------- /mdx_code_multiline.py: -------------------------------------------------------------------------------- 1 | from markdown import Extension 2 | from markdown.util import etree 3 | from markdown.inlinepatterns import Pattern 4 | 5 | RE = r'\[code\](.*?)\[\/code\]' 6 | 7 | 8 | class MultilineCodeExtension(Extension): 9 | def extendMarkdown(self, md, md_globals): 10 | element = NestedElements(RE) 11 | md.inlinePatterns.add('pre', element, ' 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /static/bower_components/platform/.bower.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "platform", 3 | "main": "platform.js", 4 | "homepage": "https://github.com/Polymer/platform", 5 | "authors": [ 6 | "The Polymer Authors" 7 | ], 8 | "description": "Integrate platform polyfills: load, build, test", 9 | "keywords": [ 10 | "polymer", 11 | "web", 12 | "components" 13 | ], 14 | "license": "BSD", 15 | "private": true, 16 | "version": "0.3.5", 17 | "_release": "0.3.5", 18 | "_resolution": { 19 | "type": "version", 20 | "tag": "0.3.5", 21 | "commit": "413707498b62d2c66f923dcac6809d56e7d6dab6" 22 | }, 23 | "_source": "git://github.com/Polymer/platform.git", 24 | "_target": ">=0.3.0 <1.0.0", 25 | "_originalSource": "Polymer/platform" 26 | } -------------------------------------------------------------------------------- /mdx_github_gists.py: -------------------------------------------------------------------------------- 1 | from markdown import Extension 2 | from markdown.util import etree 3 | from markdown.inlinepatterns import Pattern 4 | 5 | 6 | class GitHubGistExtension(Extension): 7 | def extendMarkdown(self, md, md_globals): 8 | RE = r'\[gist\](\w+)\[\/gist\]' 9 | gistPattern = GitHubGist(RE) 10 | md.inlinePatterns.add('github-gist', gistPattern, ">not_strong") 11 | 12 | 13 | class GitHubGist(Pattern): 14 | def handleMatch(self, m): 15 | gistid_value = m.group(2).strip() 16 | if gistid_value: 17 | element = etree.Element('github-gist') 18 | element.set('gistid', gistid_value) 19 | else: 20 | element = '' 21 | 22 | return element 23 | 24 | 25 | def makeExtension(configs=None): 26 | return GitHubGist(configs=configs) -------------------------------------------------------------------------------- /static/bower_components/core-component-page/index.html: -------------------------------------------------------------------------------- 1 | 2 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /static/bower_components/core-component-page/demo.html: -------------------------------------------------------------------------------- 1 | 2 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /static/bower_components/github-gist/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | <github-gist> 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /static/bower_components/github-gist/.bower.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "github-gist", 3 | "version": "0.1.1", 4 | "authors": [ 5 | "Dmitry Maslov " 6 | ], 7 | "description": "A web component to display github gists", 8 | "main": "github-gist.html", 9 | "keywords": [ 10 | "web-components", 11 | "polymer", 12 | "github", 13 | "gist" 14 | ], 15 | "license": "MIT", 16 | "homepage": "https://github.com/dmaslov/github-gist", 17 | "ignore": [ 18 | "**/.*", 19 | "node_modules", 20 | "bower_components", 21 | "test", 22 | "tests" 23 | ], 24 | "dependencies": { 25 | "polymer": "Polymer/polymer#~0.3.0" 26 | }, 27 | "_release": "0.1.1", 28 | "_resolution": { 29 | "type": "version", 30 | "tag": "0.1.1", 31 | "commit": "ed597aea96ba2f299deba55ada0869166524c4f0" 32 | }, 33 | "_source": "git://github.com/dmaslov/github-gist.git", 34 | "_target": "~0.1.1", 35 | "_originalSource": "github-gist" 36 | } -------------------------------------------------------------------------------- /pagination.py: -------------------------------------------------------------------------------- 1 | from math import ceil 2 | 3 | 4 | class Pagination(object): 5 | 6 | def __init__(self, page, per_page, total_count): 7 | self.page = page 8 | self.per_page = per_page 9 | self.total_count = total_count 10 | 11 | @property 12 | def pages(self): 13 | return int(ceil(self.total_count / float(self.per_page))) 14 | 15 | @property 16 | def has_prev(self): 17 | return self.page > 1 18 | 19 | @property 20 | def has_next(self): 21 | return self.page < self.pages 22 | 23 | def iter_pages(self, left_edge=2, left_current=2, 24 | right_current=5, right_edge=2): 25 | last = 0 26 | for num in xrange(1, self.pages + 1): 27 | if num <= left_edge or (num > self.page - left_current - 1 and num < self.page + right_current) or num > self.pages - right_edge: 28 | if last + 1 != num: 29 | yield None 30 | yield num 31 | last = num 32 | -------------------------------------------------------------------------------- /static/js/main.js: -------------------------------------------------------------------------------- 1 | window.MDM_SILENT = true; 2 | $(function(){ 3 | $('a[data-target="_blank"]').attr('target', '_blank'); 4 | 5 | if($('#post-short').length && $('#post-full').length) { 6 | $('#post-short').mdmagick(); 7 | $('#post-full').mdmagick(); 8 | } 9 | 10 | $('.post .article img').each(function(index, el){ 11 | var anchor = ''+$(el).attr('alt')+''; 12 | $(el).replaceWith(anchor); 13 | }); 14 | 15 | $('#post-preview').on('click', function(){ 16 | var postForm = $('#post-form'); 17 | postForm.find('#preview').val('1'); 18 | }); 19 | $('#post-submit').on('click', function(){ 20 | var postForm = $('#post-form'); 21 | postForm.find('#preview').val(''); 22 | }); 23 | $('a.icon').on('click', function(){ 24 | return confirm('Are you sure?'); 25 | }); 26 | }); 27 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2013 Maslov Dmitry 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy of 6 | this software and associated documentation files (the "Software"), to deal in 7 | the Software without restriction, including without limitation the rights to 8 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software is furnished to do so, 10 | subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 17 | FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 18 | COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 19 | IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 20 | CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------------- /static/bower_components/github-gist/LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2014 Dmitry Maslov 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /config.py: -------------------------------------------------------------------------------- 1 | import pymongo 2 | import os 3 | 4 | CONNECTION_STRING = "mongodb://localhost" # replace it with your settings 5 | CONNECTION = pymongo.MongoClient(CONNECTION_STRING) 6 | 7 | '''Leave this as is if you dont have other configuration''' 8 | DATABASE = CONNECTION.blog 9 | POSTS_COLLECTION = DATABASE.posts 10 | USERS_COLLECTION = DATABASE.users 11 | SETTINGS_COLLECTION = DATABASE.settings 12 | 13 | SECRET_KEY = "" 14 | basedir = os.path.abspath(os.path.dirname(__file__)) 15 | secret_file = os.path.join(basedir, '.secret') 16 | if os.path.exists(secret_file): 17 | # Read SECRET_KEY from .secret file 18 | f = open(secret_file, 'r') 19 | SECRET_KEY = f.read().strip() 20 | f.close() 21 | else: 22 | # Generate SECRET_KEY & save it away 23 | SECRET_KEY = os.urandom(24) 24 | f = open(secret_file, 'w') 25 | f.write(SECRET_KEY) 26 | f.close() 27 | # Modeify .gitignore to include .secret file 28 | gitignore_file = os.path.join(basedir, '.gitignore') 29 | f = open(gitignore_file, 'a+') 30 | if '.secret' not in f.readlines() and '.secret\n' not in f.readlines(): 31 | f.write('.secret\n') 32 | f.close() 33 | 34 | LOG_FILE = "app.log" 35 | 36 | DEBUG = True # set it to False on production 37 | -------------------------------------------------------------------------------- /templates/head.html: -------------------------------------------------------------------------------- 1 | 2 | {%- if meta_title -%}{{ meta_title }}{%- else -%}FlaskBlog{%- endif -%} 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | {%- block additional_css -%}{%- endblock -%} 11 | 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /static/bower_components/polymer/README.md: -------------------------------------------------------------------------------- 1 | # Polymer 2 | 3 | [![Analytics](https://ga-beacon.appspot.com/UA-39334307-2/Polymer/polymer/README)](https://github.com/igrigorik/ga-beacon) 4 | 5 | Build Status: [http://build.chromium.org/p/client.polymer/waterfall](http://build.chromium.org/p/client.polymer/waterfall) 6 | 7 | ## Brief Overview 8 | 9 | For more detailed info goto [http://polymer-project.org/](http://polymer-project.org/). 10 | 11 | Polymer is a new type of library for the web, designed to leverage the existing browser infrastructure to provide the encapsulation and extendability currently only available in JS libraries. 12 | 13 | Polymer is based on a set of future technologies, including [Shadow DOM](https://dvcs.w3.org/hg/webcomponents/raw-file/tip/spec/shadow/index.html), [Custom Elements](https://dvcs.w3.org/hg/webcomponents/raw-file/tip/spec/custom/index.html) and Model Driven Views. Currently these technologies are implemented as polyfills or shims, but as browsers adopt these features natively, the platform code that drives Polymer evacipates, leaving only the value-adds. 14 | 15 | ## Tools & Testing 16 | 17 | For running tests or building minified files, consult the [tooling information](http://www.polymer-project.org/resources/tooling-strategy.html). 18 | -------------------------------------------------------------------------------- /static/bower_components/github-gist/README.md: -------------------------------------------------------------------------------- 1 | # <github-gist> 2 | 3 | A [Polymer](http://polymer-project.org) element for displaying github [gists](https://gist.github.com) 4 | 5 | ## Demo 6 | 7 | > [Check it live](http://dmaslov.github.io/github-gist). 8 | 9 | ## Installation 10 | 11 | Install using [Bower](http://bower.io): 12 | 13 | ```shell 14 | bower install github-gist 15 | ``` 16 | 17 | ## Usage 18 | 19 | * Import Web Components' polyfill: 20 | 21 | ``` 22 | 23 | 24 | ``` 25 | 26 | * Import Custom Element: 27 | 28 | ``` 29 | 30 | ``` 31 | 32 | * Start using it! 33 | 34 | ``` 35 | 36 | ``` 37 | 38 | ## Options 39 | 40 | Attribute | Options | Default | Description 41 | --- | --- | --- | --- 42 | `gistid` | *string* | `` | id of gist that will be loaded 43 | 44 | 45 | ## Examples: 46 | 47 | ``` 48 | 49 | ``` 50 | ## License 51 | 52 | [MIT License](http://opensource.org/licenses/MIT) 53 | -------------------------------------------------------------------------------- /templates/nav.html: -------------------------------------------------------------------------------- 1 | 34 | -------------------------------------------------------------------------------- /helper_functions.py: -------------------------------------------------------------------------------- 1 | import re 2 | import string 3 | import random 4 | from urlparse import urljoin 5 | from flask import request, url_for, session, flash, redirect 6 | from functools import wraps 7 | 8 | 9 | def url_for_other_page(page): 10 | args = request.view_args.copy() 11 | args['page'] = page 12 | return url_for(request.endpoint, **args) 13 | 14 | 15 | def extract_tags(tags): 16 | whitespace = re.compile('\s') 17 | nowhite = whitespace.sub("", tags) 18 | tags_array = nowhite.split(',') 19 | 20 | cleaned = [] 21 | for tag in tags_array: 22 | if tag not in cleaned and tag != "": 23 | cleaned.append(tag) 24 | 25 | return cleaned 26 | 27 | 28 | def random_string(size=6, chars=string.ascii_uppercase + string.digits): 29 | return ''.join(random.choice(chars) for x in range(size)) 30 | 31 | 32 | def generate_csrf_token(): 33 | if '_csrf_token' not in session: 34 | session['_csrf_token'] = random_string() 35 | return session['_csrf_token'] 36 | 37 | 38 | def make_external(url): 39 | return urljoin(request.url_root, url) 40 | 41 | 42 | def login_required(): 43 | def wrapper(f): 44 | @wraps(f) 45 | def wrapped(*args, **kwargs): 46 | if not session.get('user'): 47 | flash('You must be logged in..', 'error') 48 | return redirect(url_for('login')) 49 | return f(*args, **kwargs) 50 | return wrapped 51 | return wrapper 52 | -------------------------------------------------------------------------------- /templates/users.html: -------------------------------------------------------------------------------- 1 | {%- extends 'index.html' -%} 2 | {%- block body -%} 3 |
4 |
5 |
6 | {%- if users -%} 7 | 10 |
11 | {%- with messages = get_flashed_messages(with_categories=True) -%} 12 | {%- if messages -%} 13 | {%- for category, message in messages -%} 14 |
15 | {%- if category == 'success' -%}✔{%- endif -%} {{ message }} 16 |
17 | {%- endfor -%} 18 | {%- endif -%} 19 | {%- endwith -%} 20 | Add User 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | {%- for user in users -%} 29 | 30 | 31 | 32 | 33 | 34 | 35 | {%- endfor -%} 36 |
UsernameEmailRegistration DateAction
{{ user['id'] }}{{ user['email'] }}{{ user['date'] |formatdate }}{%- if user['id'] != session['user']['username'] -%}  {%- endif -%}
37 |
38 | {%- endif -%} 39 |
40 |
41 |
42 | {%- endblock -%} 43 | -------------------------------------------------------------------------------- /templates/posts.html: -------------------------------------------------------------------------------- 1 | {%- extends 'index.html' -%} 2 | {%- block body -%} 3 |
4 |
5 |
6 | {%- if posts -%} 7 | 10 |
11 | {%- with messages = get_flashed_messages(with_categories=True) -%} 12 | {%- if messages -%} 13 | {%- for category, message in messages -%} 14 |
15 | {%- if category == 'success' -%}✔{%- endif -%} {{ message }} 16 |
17 | {%- endfor -%} 18 | {%- endif -%} 19 | {%- endwith -%} 20 | Add new 21 | 22 | 23 | 24 | 25 | 26 | 27 | {%- for post in posts -%} 28 | 29 | 30 | 31 | 32 | 33 | {%- endfor -%} 34 |
TitlePost DateAction
{{ post['title'] | safe }}{{ post['date'] |formatdate }}{%- if posts|length > 1 -%}  {%- endif -%}
35 |
36 | {%- else -%} 37 | 40 | {%- endif -%} 41 |
42 |
43 |
44 | {%- endblock -%} 45 | -------------------------------------------------------------------------------- /templates/single_post.html: -------------------------------------------------------------------------------- 1 | {%- extends 'index.html' -%} 2 | {%- block head -%}{%- include 'head.html' -%}{%- block additional_css -%}{%- endblock -%}{%- endblock -%} 3 | {%- block body -%} 4 | {%- if post -%} 5 |
6 |
7 |
8 | 24 |
25 | {{ post['preview']|markdown }} 26 | {{ post['body']|markdown }} 27 |
28 |
29 |
30 | tags: 31 | {%- if post['tags'] -%} 32 | {%- for tag in post['tags'] -%} 33 |  {{ tag }} 34 | {%- endfor -%} 35 | {%- endif -%} 36 |
37 |
38 |
39 |
40 |
41 | {%- endif -%} 42 | {%- include 'sidebar.html' -%} 43 | {%- endblock -%} 44 | {%- block additional_js -%}{%- endblock -%} 45 | -------------------------------------------------------------------------------- /templates/preview.html: -------------------------------------------------------------------------------- 1 | {%- extends 'index.html' -%} 2 | {%- block head -%}{%- include 'head.html' -%}{%- block additional_css -%}{%- endblock -%}{%- endblock -%} 3 | {%- block body -%} 4 | {%- if post -%} 5 |
6 |
7 |
8 | 24 |
25 | {{ post['preview']|markdown }} 26 | {{ post['body']|markdown }} 27 |
28 |
29 |
30 | tags: 31 | {%- if post['tags'] -%} 32 | {%- for tag in post['tags'] -%} 33 |  {{ tag }} 34 | {%- endfor -%} 35 | {%- endif -%} 36 |
37 |
38 |
39 | < Back 40 |
41 |
42 |
43 |
44 | {%- endif -%} 45 | {%- include 'sidebar.html' -%} 46 | {%- endblock -%} 47 | {%- block additional_js -%}{%- endblock -%} 48 | -------------------------------------------------------------------------------- /templates/login.html: -------------------------------------------------------------------------------- 1 | {%- extends 'index.html' -%} 2 | {%- block body -%} 3 |
4 |
5 |
6 | 9 |
10 | {%- with messages = get_flashed_messages(with_categories=True) -%} 11 | {%- if messages -%} 12 | {%- for category, message in messages -%} 13 |
14 | {%- if category == 'success' -%}✔{%- endif -%} {{ message }} 15 |
16 | {%- endfor -%} 17 | {%- endif -%} 18 | {%- endwith -%} 19 |
20 |
21 | {%- if error and error_type == 'validate' -%} 22 | 23 | {%- endif -%} 24 | 25 |
26 |
27 | {%- if error and error_type == 'validate' -%} 28 | 29 | {%- endif -%} 30 | 31 |
32 |
33 | 34 | 35 |
36 |
37 |
38 |
39 |
40 |
41 | {%- endblock -%} 42 | -------------------------------------------------------------------------------- /templates/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | {%- block head -%}{%- include 'head.html' -%}{%- endblock -%} 4 | 5 |
6 | {%- block nav -%}{%- include 'nav.html' -%}{%- endblock -%} 7 |
8 | {%- block body -%} 9 | {%- if posts -%} 10 | {%- for post in posts -%} 11 |
12 |
13 |
14 | 18 |
19 | {%- if post['preview'] -%} 20 | {{ post['preview']|markdown }} 21 | {%- else -%} 22 | {{ post['body']|markdown }} 23 | {%- endif -%} 24 |
25 |
26 |
27 |
  • 28 | {%- if post['tags'] -%} 29 | {%- for tag in post['tags'] -%} 30 |  {{ tag }} 31 | {%- endfor -%} 32 | {%- endif -%} 33 |
    34 |
    35 |
    36 |
    37 |
    38 | {%- endfor -%} 39 | {% else %} 40 |
    41 |
    42 |
    43 | 46 |
    47 |
    48 |
    49 | {%- endif -%} 50 | {%- include 'sidebar.html' -%} 51 | {%- endblock -%} 52 | {% if pagination and pagination.pages > 1 %} 53 |
    54 |
      55 | {% for page in pagination.iter_pages() %} 56 | {% if page %} 57 |
    • {{ page }}
    • 58 | {% else %} 59 |
    • 60 | {% endif %} 61 | {% endfor %} 62 | {% if pagination.has_next %} 63 |
    • »
    • 65 | {% endif %} 66 |
    67 |
    68 | {% endif %} 69 |
    70 |
    71 | {%- include 'footer.html' -%} 72 | {%- block scripts -%} 73 | 74 | 75 | {%- block additional_js -%}{%- endblock -%} 76 | 77 | {%- endblock -%} 78 | 79 | 80 | -------------------------------------------------------------------------------- /static/css/mdmagick.css: -------------------------------------------------------------------------------- 1 | @keyframes slideOut { 2 | from { max-height: 0px; } 3 | to { max-height: 500px; } 4 | } 5 | 6 | @keyframes slideIn { 7 | from { max-height: 500px; } 8 | to { max-height: 0px; } 9 | } 10 | 11 | @-webkit-keyframes slideOut { 12 | from { max-height: 0px; } 13 | to { max-height: 500px; } 14 | } 15 | 16 | @-webkit-keyframes slideIn { 17 | from { max-height: 500px; } 18 | to { max-height: 0px; } 19 | } 20 | 21 | @-o-keyframes slideOut { 22 | from { max-height: 0px; } 23 | to { max-height: 500px; } 24 | } 25 | 26 | @-o-keyframes slideIn { 27 | from { max-height: 500px; } 28 | to { max-height: 0px; } 29 | } 30 | 31 | @-moz-keyframes slideOut { 32 | from { max-height: 0px; } 33 | to { max-height: 500px; } 34 | } 35 | 36 | @-moz-keyframes slideIn { 37 | from { max-height: 500px; } 38 | to { max-height: 0px; } 39 | } 40 | 41 | div.mdm-buttons, 42 | div.mdm-preview { 43 | line-height: 1em; 44 | padding: 0px; 45 | max-height: 0px; 46 | overflow: hidden; 47 | background-color: white; 48 | box-sizing: border-box; 49 | } 50 | 51 | div.mdm-buttons.blur, 52 | div.mdm-preview.blur { 53 | -webkit-animation: slideIn .5s; 54 | -webkit-animation-fill-mode: forwards; 55 | -moz-animation: slideIn .5s; 56 | -moz-animation-fill-mode: forwards; 57 | -o-animation: slideIn .5s; 58 | -o-animation-fill-mode: forwards; 59 | animation: slideIn .5s; 60 | animation-fill-mode: forwards; 61 | } 62 | 63 | div.mdm-buttons.focus, 64 | div.mdm-preview.focus { 65 | -webkit-animation: slideOut 2s; 66 | -webkit-animation-fill-mode: forwards; 67 | -moz-animation: slideOut 2s; 68 | -moz-animation-fill-mode: forwards; 69 | -o-animation: slideOut 2s; 70 | -o-animation-fill-mode: forwards; 71 | animation: slideOut 2s; 72 | animation-fill-mode: forwards; 73 | } 74 | 75 | div.mdm-preview.focus { 76 | padding: 5px; 77 | } 78 | 79 | div.mdm-buttons { 80 | width: 148px; 81 | 82 | font-size: 12px; 83 | } 84 | 85 | div.mdm-buttons ul { 86 | margin: 10px; 87 | } 88 | 89 | div.mdm-buttons ul li{ 90 | display: inline; 91 | margin: 0; 92 | } 93 | 94 | div.mdm-buttons ul li a{ 95 | padding: 5px; 96 | color: black; 97 | text-decoration: none; 98 | } 99 | 100 | div.mdm-buttons ul li a span{ 101 | display: none; 102 | } 103 | 104 | div.mdm-buttons ul li a:active{ 105 | color: #ccc; 106 | position: relative; 107 | top: 1px; 108 | } 109 | 110 | div.mdm-preview strong { 111 | font-weight: bold; 112 | } 113 | 114 | div.mdm-preview em { 115 | font-style: italic; 116 | } 117 | 118 | div.mdm-preview ul { 119 | margin-left: 20px; 120 | list-style-type: disc; 121 | } 122 | 123 | 124 | div.mdm-preview h1, 125 | div.mdm-preview h2, 126 | div.mdm-preview h3{ 127 | font-weight: bold; 128 | } 129 | 130 | div.mdm-preview h1 { 131 | font-size: 18px; 132 | } 133 | 134 | div.mdm-preview h2 { 135 | font-size: 14px; 136 | } 137 | 138 | div.mdm-preview h3 { 139 | font-size: 12px; 140 | } 141 | -------------------------------------------------------------------------------- /templates/add_user.html: -------------------------------------------------------------------------------- 1 | {%- extends 'index.html' -%} 2 | {%- block body -%} 3 |
    4 |
    5 |
    6 | 9 |
    10 | {%- with messages = get_flashed_messages(with_categories=True) -%} 11 | {%- if messages -%} 12 | {%- for category, message in messages -%} 13 |
    14 | {%- if category == 'success' -%}✔{%- endif -%} {{ message }} 15 |
    16 | {%- endfor -%} 17 | {%- endif -%} 18 | {%- endwith -%} 19 |
    20 |
    21 | 22 |
    23 |
    24 |
    25 |
    26 | {%- if error and error_type == 'validate' -%} 27 | 28 | {%- endif -%} 29 | 30 |
    31 |
    32 | {%- if error and error_type == 'validate' -%} 33 | 34 | {%- endif -%} 35 | 36 |
    37 |
    38 |
    39 | Password section 40 |
    41 | {%- if error and error_type == 'validate' -%} 42 | 43 | {%- endif -%} 44 | 45 |
    46 |
    47 | {%- if error and error_type == 'validate' -%} 48 | 49 | {%- endif -%} 50 | 51 |
    52 |
    53 |
    54 | 55 | 56 |
    57 |
    58 |
    59 |
    60 |
    61 |
    62 |
    63 | {%- endblock -%} 64 | -------------------------------------------------------------------------------- /templates/new_post.html: -------------------------------------------------------------------------------- 1 | {%- extends 'index.html' -%} 2 | {%- block body -%} 3 | {% if session.get('post-preview') %} 4 | {% set post_title = session['post-preview'].get('title', None) %} 5 | {% set post_preview = session['post-preview'].get('preview', None) %} 6 | {% set post_body = session['post-preview'].get('body', None) %} 7 | {% set post_tags = session['post-preview'].get('tags', None) %} 8 | {% else %} 9 | {% set post_title = '' %} 10 | {% set post_preview = '' %} 11 | {% set post_body = '' %} 12 | {% set post_tags = '' %} 13 | {% endif %} 14 | 15 |
    16 |
    17 |
    18 | 21 |
    22 | {%- with messages = get_flashed_messages(with_categories=True) -%} 23 | {%- if messages -%} 24 | {%- for category, message in messages -%} 25 |
    26 | {%- if category == 'success' -%}✔{%- endif -%} {{ message }} 27 |
    28 | {%- endfor -%} 29 | {%- endif -%} 30 | {%- endwith -%} 31 |
    32 |
    33 | {%- if error and error_type == 'validate' -%} 34 | 35 | {%- endif -%} 36 | 37 |
    38 |
    39 | 40 |
    41 |
    42 | {%- if error and error_type == 'validate' -%} 43 | 44 | {%- endif -%} 45 | 46 |
    47 |
    48 | 49 | 50 |
    51 |
    52 | 53 | 54 | 55 | 56 |
    57 |
    58 |
    59 |
    60 |
    61 |
    62 | {%- endblock -%} 63 | {%- block scripts -%} 64 | 65 | 66 | 67 | 68 | 69 | 70 | {%- endblock -%} 71 | -------------------------------------------------------------------------------- /templates/settings.html: -------------------------------------------------------------------------------- 1 | {%- extends 'index.html' -%} 2 | {%- block body -%} 3 |
    4 |
    5 |
    6 | 9 |
    10 | {%- with messages = get_flashed_messages(with_categories=True) -%} 11 | {%- if messages -%} 12 | {%- for category, message in messages -%} 13 |
    14 | {%- if category == 'success' -%}✔{%- endif -%} {{ message }} 15 |
    16 | {%- endfor -%} 17 | {%- endif -%} 18 | {%- endwith -%} 19 | 20 |
    21 |
    22 | {%- if error and error_type == 'validate' -%} 23 | 24 | {%- else -%} 25 | 26 | {%- endif -%} 27 | 28 |
    29 |
    30 | 31 | 32 |
    33 |
    34 | {%- if error and error_type == 'validate' -%} 35 | 36 | {%- else -%} 37 | 38 | {%- endif -%} 39 | 40 |
    41 |
    42 | 45 |
    46 |
    47 | 48 | 49 |
    50 |
    51 |
    52 |
    53 |
    54 |
    55 | {%- endblock -%} 56 | -------------------------------------------------------------------------------- /templates/edit_post.html: -------------------------------------------------------------------------------- 1 | {%- extends 'index.html' -%} 2 | {%- block body -%} 3 | {% if session.get('post-preview', None) %} 4 | {% set post_title = session['post-preview'].get('title', None) %} 5 | {% set post_preview = session['post-preview'].get('preview', None) %} 6 | {% set post_body = session['post-preview'].get('body', None) %} 7 | {% set tags = session['post-preview'].get('tags', None) %} 8 | {% if tags %} 9 | {% set post_tags = ','.join(tags) %} 10 | {% endif %} 11 | {% else %} 12 | {% set post_title = post.get('title') %} 13 | {% set post_preview = post.get('preview') %} 14 | {% set post_body = post.get('body') %} 15 | {% set post_tags = post.get('tags') %} 16 | {% endif %} 17 |
    18 |
    19 |
    20 | 23 |
    24 | {%- with messages = get_flashed_messages(with_categories=True) -%} 25 | {%- if messages -%} 26 | {%- for category, message in messages -%} 27 |
    28 | {%- if category == 'success' -%}✔{%- endif -%} {{ message }} 29 |
    30 | {%- endfor -%} 31 | {%- endif -%} 32 | {%- endwith -%} 33 |
    34 |
    35 | {%- if error and error_type == 'validate' -%} 36 | 37 | {%- endif -%} 38 | 39 |
    40 |
    41 | 42 |
    43 |
    44 | {%- if error and error_type == 'validate' -%} 45 | 46 | {%- endif -%} 47 | 48 |
    49 |
    50 | 51 | 52 |
    53 |
    54 | 55 | 56 | 57 | 58 | 59 |
    60 |
    61 |
    62 |
    63 |
    64 |
    65 | {%- endblock -%} 66 | {%- block scripts -%} 67 | 68 | 69 | 70 | 71 | 72 | 73 | {%- endblock -%} 74 | -------------------------------------------------------------------------------- /templates/edit_user.html: -------------------------------------------------------------------------------- 1 | {%- extends 'index.html' -%} 2 | {%- block body -%} 3 |
    4 |
    5 |
    6 | 9 |
    10 | {%- with messages = get_flashed_messages(with_categories=True) -%} 11 | {%- if messages -%} 12 | {%- for category, message in messages -%} 13 |
    14 | {%- if category == 'success' -%}✔{%- endif -%} {{ message }} 15 |
    16 | {%- endfor -%} 17 | {%- endif -%} 18 | {%- endwith -%} 19 | {%- if user -%} 20 |
    21 |
    22 | 23 |
    24 |
    25 |
    26 |
    27 | {%- if error and error_type == 'validate' -%} 28 | 29 | {%- endif -%} 30 | 31 |
    32 |
    33 | {%- if error and error_type == 'validate' -%} 34 | 35 | {%- endif -%} 36 | 37 |
    38 |
    39 |
    40 | Password section 41 |
    42 | {%- if error and error_type == 'validate' -%} 43 | 44 | {%- endif -%} 45 | 46 |
    47 |
    48 | {%- if error and error_type == 'validate' -%} 49 | 50 | {%- endif -%} 51 | 52 |
    53 |
    54 | {%- if error and error_type == 'validate' -%} 55 | 56 | {%- endif -%} 57 | 58 |
    59 |
    60 |
    61 | 62 | 63 | 64 | 65 |
    66 |
    67 |
    68 | {%- endif -%} 69 |
    70 |
    71 |
    72 |
    73 | {%- endblock -%} 74 | -------------------------------------------------------------------------------- /static/bower_components/github-gist/github-gist.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 93 | 94 | -------------------------------------------------------------------------------- /static/css/main.css: -------------------------------------------------------------------------------- 1 | html, body {height: 100%;margin: 0;} 2 | body { 3 | padding-top:20px; 4 | min-width:320px; 5 | } 6 | #wrapper {min-height: 100%;} 7 | .container {padding-bottom: 100px;} 8 | 9 | .post {margin-top:2em;} 10 | .post img { 11 | max-width: 100%; 12 | height: auto; 13 | } 14 | .content {font-size: 18px;line-height: 24px;} 15 | 16 | .infopanel { 17 | display: inline-block; 18 | vertical-align: middle; 19 | font-size: 12px; 20 | border: 1px solid #E5E5E5; 21 | padding: 0 10px; 22 | margin-top: 10px; 23 | } 24 | .infopanel .tags {margin:5px 0 5px 0;} 25 | 26 | .pagination-wrap {text-align: center;} 27 | .pagination { 28 | margin:80px 0 0; 29 | display: inline-block; 30 | } 31 | .pagination>li { 32 | float:left; 33 | margin:0 7px; 34 | } 35 | 36 | .page-header a { 37 | color:#333; 38 | text-decoration: none; 39 | cursor:pointer; 40 | } 41 | .page-header a:hover{text-decoration: underline;} 42 | .page-header h1,.splash h1 {font-size:4em;} 43 | 44 | footer { 45 | color: #cccccc; 46 | height: 35px; 47 | margin-top: -35px; 48 | } 49 | footer .container {padding-bottom:0;} 50 | footer p { 51 | clear:left; 52 | color: #d6d8dd; 53 | font-size: 12px; 54 | } 55 | footer a {color: #d6d8dd;} 56 | 57 | .sidebar { 58 | float: right; 59 | position: absolute; 60 | top: 92px; 61 | right: 5px; 62 | } 63 | .sidebar hr {margin-top:0;} 64 | .sidebar ul {padding:0;} 65 | .sidebar li { 66 | list-style-type: none; 67 | line-height: 24px; 68 | } 69 | 70 | .badge {font-size: 10px;} 71 | 72 | .not-found {text-align: center;} 73 | .not-found h1 { 74 | font-size: 100px !important; 75 | font-weight: bold; 76 | margin-top: 50px; 77 | } 78 | .not-found p { 79 | color: #cccccc; 80 | font-size: 11px; 81 | margin:-26px 0 0 8px; 82 | } 83 | 84 | .response {margin-bottom: 24px;} 85 | .message { 86 | padding: 15px 10px; 87 | font-size: 14px; 88 | font-weight: bold; 89 | line-height: 1.1; 90 | text-align: center; 91 | border-radius: 4px; 92 | border: 1px solid #ddd; 93 | box-sizing: border-box; 94 | color: #999; 95 | } 96 | .error, .success {display:block;} 97 | .success {background-color: #dff0d8;} 98 | .error {background-color: #f2dede;} 99 | 100 | .preview-back {margin-top: 20px;} 101 | 102 | div.mdm-buttons {width: 100% !important; background-color: #d6d8dd;} 103 | div.mdm-buttons ul {margin: 10px 0 10px -30px;} 104 | .mdm-control a {font-size: 16px !important;} 105 | .mdm-control a.bigger {font-size: 2em !important;} 106 | 107 | a.icon { 108 | text-decoration: none; 109 | cursor: pointer; 110 | color: inherit; 111 | } 112 | 113 | .search-form { 114 | width:250px; 115 | margin:5px 0; 116 | padding-right:0; 117 | } 118 | .photo-user { 119 | position:absolute; 120 | top:0; 121 | left:10px; 122 | } 123 | .form-user { 124 | position:relative; 125 | padding-left:115px; 126 | } 127 | 128 | .nav>li>a { 129 | padding-left:12px; 130 | padding-right:12px; 131 | } 132 | .navbar-header .navbar-nav { 133 | float:left; 134 | margin:0; 135 | } 136 | .navbar-header .nav>li {float:left;} 137 | .navbar-header .navbar-nav>li>a { 138 | padding-top:14.5px; 139 | padding-bottom:14.5px; 140 | } 141 | .navbar {min-height:53px;} 142 | 143 | legend { 144 | padding-top:20px; 145 | border:none; 146 | } 147 | 148 | .radio, .checkbox {margin-bottom:15px;} 149 | .radio:last-child, 150 | .checkbox:last-child {margin-bottom:10px;} 151 | input[type='checkbox'] { 152 | display:inline-block; 153 | vertical-align:middle; 154 | float:none !important; 155 | margin-top:-1px; 156 | } 157 | 158 | @media only screen and (max-width: 850px) { 159 | .search-form {width:185px;} 160 | } 161 | @media only screen and (max-width: 767px) { 162 | .search-form {width:100%;} 163 | } 164 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # flask-blog 2 | 3 | simple blog ~~engine~~ written on [Flask](http://flask.pocoo.org/) 4 | 5 | # Demo: 6 | you can try it [here](http://flask-blog-demo.herokuapp.com/) 7 | 8 | login:demo 9 | 10 | pass:demo 11 | 12 | # Under the hood: 13 | - [Python](http://python.org/) 14 | - [Flask](http://flask.pocoo.org/) 15 | - [MongoDB](http://www.mongodb.org/) 16 | - [Bootstrap 3](http://getbootstrap.com/) 17 | - [jQuery](http://jquery.com) 18 | - [Lightbox 2](https://github.com/lokesh/lightbox2) 19 | - [Markdown](http://daringfireball.net/projects/markdown/syntax) 20 | - [Polymer](http://www.polymer-project.org) 21 | 22 | 23 | # What it can: 24 | - create/preview/update/delete articles; 25 | - create/update/delete users; 26 | - search; 27 | - atom feed. 28 | 29 | # It contains: 30 | - WYSIWYG Markdown editor; 31 | - [AddThis](http://www.addthis.com/) social buttons; 32 | - [Gravatar](http://gravatar.com) for userpic. 33 | 34 | 35 | # Requirements: 36 | - mongoDB >= 2.2 37 | 38 | 39 | # Installation: 40 | `git clone https://github.com/dmaslov/flask-blog.git` 41 | 42 | `cd flask-blog` 43 | 44 | `virtualenv --no-site-packages ./env` 45 | 46 | `source ./env/bin/activate` 47 | 48 | `pip install -r requirements.txt` 49 | 50 | 51 | After this edit the `config.py` file 52 | 53 | - Replace the `CONNECTION_STRING` variable with your own connection string; 54 | 55 | - Replace the `DATABASE` variable to your own one; 56 | 57 | - If the default collection names don't work for you please replace the `POSTS_COLLECTION`, `USERS_COLLECTION` and `USERS_COLLECTION` variables to any names you like; 58 | 59 | - If you use this code on a production sever replace the `DEBUG` variable with `False`. 60 | 61 | # Run: 62 | Start `mongod`, then when you in project dir with actived environment just type in terminal 63 | 64 | `python web.py` 65 | 66 | ![builtin_run](http://i.imgur.com/dkEL5aS.png?2) 67 | 68 | or 69 | 70 | `gunicorn web:app` 71 | 72 | ![gunicorn_run](http://i.imgur.com/rCp0g25.png?2) 73 | 74 | # Usage: 75 | When you run the application for the first time the "Install" page appears. You need to create a user profile and set some display settings on this page. 76 | 77 | ![install_page](http://i.imgur.com/gkWI10v.png) 78 | 79 | If you have an account on [Gravatar](http://gravatar.com) and your logged-in email links to it, the userpic will display. It will be a random gravatar image if it doesn't. 80 | 81 | All necessary MongoDB indexes will be created during the installation. A test text post will be created as well. 82 | 83 | There should be at least one post and one user for the database to be installed. That is why it's impossible to delete the last post or user. 84 | 85 | If you want to start it from scratch please remove all existing collections from your database and delete the browser session cookie. The Install page will show up again. 86 | 87 | For deploying you can use [Heroku](http://heroku.com) and [mongolab](http://mongolab.com) for example. 88 | 89 | If you are using mongolab, please copy the outlined on the screenshot line to connect using driver, type in your dbuser and dbpassword and paste the line into the `CONNECTION_STRING` variable in the `config.py` file. 90 | 91 | ![mongolab_databases](http://i.imgur.com/VcoTh16.png) 92 | 93 | 94 | For Heroku you'll find `gunicorn` server in the `requirements.txt` file. You are welcome to see how to deploy a Python web application on Heroku [here](https://devcenter.heroku.com/categories/python). 95 | 96 | 97 | # WYSIWYG editor: 98 | WYSIWYG editor uses [Markdown](http://daringfireball.net/projects/markdown/syntax). Only available on the editor panel tags are intepreted. 99 | 100 | ![wysiwyg_editor_panel](http://i.imgur.com/D6aFuLT.png) 101 | 102 | The editor is based on [MDMagick](https://github.com/fguillen/MDMagick) project. 103 | 104 | To insert any tag you need to SELECT a word and then click on a needed tag on the editor panel. 105 | 106 | You can insert github [Gists](https://gist.github.com/). 107 | 108 | For this click on the Gist tag on the panel, copy the gist id from the github gists page and paste it to the dialog window. 109 | 110 | The word will be replaced with a working gist tag. 111 | 112 | ![gist_page](http://i.imgur.com/1hQKsaX.png) 113 | 114 | ![inser_gist](http://i.imgur.com/x5Yb9es.png) 115 | 116 | ~~To insert an image you also need to select a word that will be used like a title attribute and paste the image URL into the dialog window.~~ 117 | 118 | ![insert_image](http://i.imgur.com/suxPgI0.png) 119 | 120 | 121 | # Upd: 122 | Don't need to highlight text to add a link or an image anymore. Now you can simply click some tag in the editor menu and put a link. The 'Markdown' tag will be created automatically with a highlighted temporary description. The existing pasting algorithm works as it did before. 123 | -------------------------------------------------------------------------------- /static/css/lightbox.css: -------------------------------------------------------------------------------- 1 | /* line 7, ../sass/lightbox.sass */ 2 | body:after { 3 | content: url(../img/close.png) url(../img/loading.gif) url(../img/prev.png) url(../img/next.png); 4 | display: none; 5 | } 6 | 7 | /* line 11, ../sass/lightbox.sass */ 8 | .lightboxOverlay { 9 | position: absolute; 10 | top: 0; 11 | left: 0; 12 | z-index: 9999; 13 | background-color: black; 14 | filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=80); 15 | opacity: 0.8; 16 | display: none; 17 | } 18 | 19 | /* line 20, ../sass/lightbox.sass */ 20 | .lightbox { 21 | position: absolute; 22 | left: 0; 23 | width: 100%; 24 | z-index: 10000; 25 | text-align: center; 26 | line-height: 0; 27 | font-weight: normal; 28 | } 29 | /* line 28, ../sass/lightbox.sass */ 30 | .lightbox .lb-image { 31 | display: block; 32 | height: auto; 33 | -webkit-border-radius: 3px; 34 | -moz-border-radius: 3px; 35 | -ms-border-radius: 3px; 36 | -o-border-radius: 3px; 37 | border-radius: 3px; 38 | } 39 | /* line 32, ../sass/lightbox.sass */ 40 | .lightbox a img { 41 | border: none; 42 | } 43 | 44 | /* line 35, ../sass/lightbox.sass */ 45 | .lb-outerContainer { 46 | position: relative; 47 | background-color: white; 48 | *zoom: 1; 49 | width: 250px; 50 | height: 250px; 51 | margin: 0 auto; 52 | -webkit-border-radius: 4px; 53 | -moz-border-radius: 4px; 54 | -ms-border-radius: 4px; 55 | -o-border-radius: 4px; 56 | border-radius: 4px; 57 | } 58 | /* line 38, ../../../../.rvm/gems/ruby-1.9.3-p392/gems/compass-0.12.2/frameworks/compass/stylesheets/compass/utilities/general/_clearfix.scss */ 59 | .lb-outerContainer:after { 60 | content: ""; 61 | display: table; 62 | clear: both; 63 | } 64 | 65 | /* line 44, ../sass/lightbox.sass */ 66 | .lb-container { 67 | padding: 4px; 68 | } 69 | 70 | /* line 47, ../sass/lightbox.sass */ 71 | .lb-loader { 72 | position: absolute; 73 | top: 43%; 74 | left: 0%; 75 | height: 25%; 76 | width: 100%; 77 | text-align: center; 78 | line-height: 0; 79 | } 80 | 81 | /* line 56, ../sass/lightbox.sass */ 82 | .lb-cancel { 83 | display: block; 84 | width: 32px; 85 | height: 32px; 86 | margin: 0 auto; 87 | background: url(../img/loading.gif) no-repeat; 88 | } 89 | 90 | /* line 63, ../sass/lightbox.sass */ 91 | .lb-nav { 92 | position: absolute; 93 | top: 0; 94 | left: 0; 95 | height: 100%; 96 | width: 100%; 97 | z-index: 10; 98 | } 99 | 100 | /* line 71, ../sass/lightbox.sass */ 101 | .lb-container > .nav { 102 | left: 0; 103 | } 104 | 105 | /* line 74, ../sass/lightbox.sass */ 106 | .lb-nav a { 107 | outline: none; 108 | } 109 | 110 | /* line 77, ../sass/lightbox.sass */ 111 | .lb-prev, .lb-next { 112 | width: 49%; 113 | height: 100%; 114 | cursor: pointer; 115 | /* Trick IE into showing hover */ 116 | display: block; 117 | } 118 | 119 | /* line 84, ../sass/lightbox.sass */ 120 | .lb-prev { 121 | left: 0; 122 | float: left; 123 | } 124 | /* line 87, ../sass/lightbox.sass */ 125 | .lb-prev:hover { 126 | background: url(../img/prev.png) left 48% no-repeat; 127 | } 128 | 129 | /* line 90, ../sass/lightbox.sass */ 130 | .lb-next { 131 | right: 0; 132 | float: right; 133 | } 134 | /* line 93, ../sass/lightbox.sass */ 135 | .lb-next:hover { 136 | background: url(../img/next.png) right 48% no-repeat; 137 | } 138 | 139 | /* line 96, ../sass/lightbox.sass */ 140 | .lb-dataContainer { 141 | margin: 0 auto; 142 | padding-top: 5px; 143 | *zoom: 1; 144 | width: 100%; 145 | -moz-border-radius-bottomleft: 4px; 146 | -webkit-border-bottom-left-radius: 4px; 147 | border-bottom-left-radius: 4px; 148 | -moz-border-radius-bottomright: 4px; 149 | -webkit-border-bottom-right-radius: 4px; 150 | border-bottom-right-radius: 4px; 151 | } 152 | /* line 38, ../../../../.rvm/gems/ruby-1.9.3-p392/gems/compass-0.12.2/frameworks/compass/stylesheets/compass/utilities/general/_clearfix.scss */ 153 | .lb-dataContainer:after { 154 | content: ""; 155 | display: table; 156 | clear: both; 157 | } 158 | 159 | /* line 103, ../sass/lightbox.sass */ 160 | .lb-data { 161 | padding: 0 4px; 162 | color: #bbbbbb; 163 | } 164 | /* line 106, ../sass/lightbox.sass */ 165 | .lb-data .lb-details { 166 | width: 85%; 167 | float: left; 168 | text-align: left; 169 | line-height: 1.1em; 170 | } 171 | /* line 111, ../sass/lightbox.sass */ 172 | .lb-data .lb-caption { 173 | font-size: 13px; 174 | font-weight: bold; 175 | line-height: 1em; 176 | } 177 | /* line 115, ../sass/lightbox.sass */ 178 | .lb-data .lb-number { 179 | display: block; 180 | clear: left; 181 | padding-bottom: 1em; 182 | font-size: 12px; 183 | color: #999999; 184 | } 185 | /* line 121, ../sass/lightbox.sass */ 186 | .lb-data .lb-close { 187 | display: block; 188 | float: right; 189 | width: 30px; 190 | height: 30px; 191 | background: url(../img/close.png) top right no-repeat; 192 | text-align: right; 193 | outline: none; 194 | filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=70); 195 | opacity: 0.7; 196 | } 197 | /* line 130, ../sass/lightbox.sass */ 198 | .lb-data .lb-close:hover { 199 | cursor: pointer; 200 | filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=100); 201 | opacity: 1; 202 | } 203 | -------------------------------------------------------------------------------- /templates/install.html: -------------------------------------------------------------------------------- 1 | {%- extends 'index.html' -%} 2 | {%- block nav -%} 3 | 4 | {%- endblock -%} 5 | {%- block body -%} 6 |
    7 |
    8 |
    9 | 12 |
    13 | {%- with messages = get_flashed_messages(with_categories=True) -%} 14 | {%- if messages -%} 15 | {%- for category, message in messages -%} 16 |
    17 | {%- if category == 'success' -%}✔{%- endif -%} {{ message }} 18 |
    19 | {%- endfor -%} 20 | {%- endif -%} 21 | {%- endwith -%} 22 | 23 |
    24 |
    25 | Blog section 26 |
    27 | {%- if error and error_type == 'validate' -%} 28 | 29 | {%- endif -%} 30 | 31 |
    32 |
    33 | 34 |
    35 |
    36 | {%- if error and error_type == 'validate' -%} 37 | 38 | {%- endif -%} 39 | 40 |
    41 |
    42 | 45 |
    46 |
    47 |
    48 | User section 49 |
    50 | {%- if error and error_type == 'validate' -%} 51 | 52 | {%- endif -%} 53 | 54 |
    55 |
    56 | {%- if error and error_type == 'validate' -%} 57 | 58 | {%- endif -%} 59 | 60 |
    61 |
    62 | {%- if error and error_type == 'validate' -%} 63 | 64 | {%- endif -%} 65 | 66 |
    67 |
    68 | {%- if error and error_type == 'validate' -%} 69 | 70 | {%- endif -%} 71 | 72 |
    73 |
    74 |
    75 | 76 | 77 |
    78 |
    79 |
    80 |
    81 |
    82 |
    83 | {%- endblock -%} 84 | -------------------------------------------------------------------------------- /settings.py: -------------------------------------------------------------------------------- 1 | from flask import session 2 | 3 | 4 | class Settings: 5 | 6 | def __init__(self, default_config): 7 | self.collection = default_config['SETTINGS_COLLECTION'] 8 | 9 | self.config = default_config 10 | self.config['PER_PAGE'] = 15 11 | self.config['SEARCH'] = False 12 | self.config['BLOG_TITLE'] = 'Blog' 13 | self.config['BLOG_DESCRIPTION'] = '' 14 | 15 | self.response = {'error': None, 'data': None} 16 | self.debug_mode = default_config['DEBUG'] 17 | 18 | def get_config(self): 19 | try: 20 | cursor = self.collection.find_one() 21 | if cursor: 22 | self.config['PER_PAGE'] = cursor.get( 23 | 'per_page', self.config['PER_PAGE']) 24 | self.config['SEARCH'] = cursor.get( 25 | 'use_search', self.config['SEARCH']) 26 | self.config['BLOG_TITLE'] = cursor.get( 27 | 'title', self.config['BLOG_TITLE']) 28 | self.config['BLOG_DESCRIPTION'] = cursor.get( 29 | 'description', self.config['BLOG_DESCRIPTION']) 30 | return self.config 31 | except Exception, e: 32 | self.print_debug_info(e, self.debug_mode) 33 | self.response['error'] = 'System error..' 34 | 35 | def is_installed(self): 36 | posts_cnt = self.config['POSTS_COLLECTION'].find().count() 37 | users_cnt = self.config['USERS_COLLECTION'].find().count() 38 | configs_cnt = self.config['SETTINGS_COLLECTION'].find().count() 39 | if posts_cnt and users_cnt and configs_cnt: 40 | session['installed'] = True 41 | return True 42 | else: 43 | session['installed'] = False 44 | return False 45 | 46 | def install(self, blog_data, user_data): 47 | import user 48 | import post 49 | 50 | userClass = user.User(self.config) 51 | postClass = post.Post(self.config) 52 | self.response['error'] = None 53 | try: 54 | self.config['POSTS_COLLECTION'].ensure_index([('date', -1)]) 55 | self.config['POSTS_COLLECTION'].ensure_index( 56 | [('tags', 1), ('date', -1)]) 57 | self.config['POSTS_COLLECTION'].ensure_index([('permalink', 1)]) 58 | self.config['POSTS_COLLECTION'].ensure_index( 59 | [('query', 1), ('orderby', 1)]) 60 | self.config['USERS_COLLECTION'].ensure_index([('date', 1)]) 61 | 62 | post_data = {'title': 'Hello World!', 63 | 'preview': 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod', 64 | 'body': 'tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam', 65 | 'tags': [], 66 | 'author': user_data['_id']} 67 | post = postClass.validate_post_data(post_data) 68 | 69 | user_create = userClass.save_user(user_data) 70 | post_create = postClass.create_new_post(post) 71 | 72 | if blog_data['per_page'].isdigit(): 73 | blog_settings_error = None 74 | self.collection.insert(blog_data) 75 | else: 76 | blog_settings_error = '"Per page" field need to be integer..' 77 | 78 | if user_create['error'] or post_create['error'] or blog_settings_error: 79 | self.response['error'] = [] 80 | self.response['error'].append(user_create['error']) 81 | self.response['error'].append(post_create['error']) 82 | self.response['error'].append(blog_settings_error) 83 | self.config['POSTS_COLLECTION'].drop() 84 | self.config['USERS_COLLECTION'].drop() 85 | self.collection.drop() 86 | return self.response 87 | except Exception, e: 88 | self.print_debug_info(e, self.debug_mode) 89 | self.response['error'] = 'Installation error..' 90 | 91 | def update_settings(self, data): 92 | self.response['error'] = None 93 | try: 94 | cursor = self.collection.find_one() 95 | self.collection.update( 96 | {'_id': cursor['_id']}, {'$set': data}, upsert=False, multi=False) 97 | self.response['data'] = True 98 | return self.response 99 | except Exception, e: 100 | self.print_debug_info(e, self.debug_mode) 101 | self.response['error'] = 'Settings update error..' 102 | 103 | @staticmethod 104 | def print_debug_info(msg, show=False): 105 | if show: 106 | import sys 107 | import os 108 | 109 | error_color = '\033[32m' 110 | error_end = '\033[0m' 111 | 112 | error = {'type': sys.exc_info()[0].__name__, 113 | 'file': os.path.basename(sys.exc_info()[2].tb_frame.f_code.co_filename), 114 | 'line': sys.exc_info()[2].tb_lineno, 115 | 'details': str(msg)} 116 | 117 | print error_color 118 | print '\n\n---\nError type: %s in file: %s on line: %s\nError details: %s\n---\n\n'\ 119 | % (error['type'], error['file'], error['line'], error['details']) 120 | print error_end 121 | -------------------------------------------------------------------------------- /static/bower_components/polymer/layout.html: -------------------------------------------------------------------------------- 1 | 9 | -------------------------------------------------------------------------------- /static/js/lightbox-2.6.min.js: -------------------------------------------------------------------------------- 1 | (function(){var b,d,c;b=jQuery;c=(function(){function b(){this.fadeDuration=500;this.fitImagesInViewport=true;this.resizeDuration=700;this.showImageNumberLabel=true;this.wrapAround=false}b.prototype.albumLabel=function(b,c){return"Image "+b+" of "+c};return b})();d=(function(){function c(b){this.options=b;this.album=[];this.currentImageIndex=void 0;this.init()}c.prototype.init=function(){this.enable();return this.build()};c.prototype.enable=function(){var c=this;return b('body').on('click','a[rel^=lightbox], area[rel^=lightbox], a[data-lightbox], area[data-lightbox]',function(d){c.start(b(d.currentTarget));return false})};c.prototype.build=function(){var c=this;b("
    ").appendTo(b('body'));this.$lightbox=b('#lightbox');this.$overlay=b('#lightboxOverlay');this.$outerContainer=this.$lightbox.find('.lb-outerContainer');this.$container=this.$lightbox.find('.lb-container');this.containerTopPadding=parseInt(this.$container.css('padding-top'),10);this.containerRightPadding=parseInt(this.$container.css('padding-right'),10);this.containerBottomPadding=parseInt(this.$container.css('padding-bottom'),10);this.containerLeftPadding=parseInt(this.$container.css('padding-left'),10);this.$overlay.hide().on('click',function(){c.end();return false});this.$lightbox.hide().on('click',function(d){if(b(d.target).attr('id')==='lightbox'){c.end()}return false});this.$outerContainer.on('click',function(d){if(b(d.target).attr('id')==='lightbox'){c.end()}return false});this.$lightbox.find('.lb-prev').on('click',function(){if(c.currentImageIndex===0){c.changeImage(c.album.length-1)}else{c.changeImage(c.currentImageIndex-1)}return false});this.$lightbox.find('.lb-next').on('click',function(){if(c.currentImageIndex===c.album.length-1){c.changeImage(0)}else{c.changeImage(c.currentImageIndex+1)}return false});return this.$lightbox.find('.lb-loader, .lb-close').on('click',function(){c.end();return false})};c.prototype.start=function(c){var f,e,j,d,g,n,o,k,l,m,p,h,i;b(window).on("resize",this.sizeOverlay);b('select, object, embed').css({visibility:"hidden"});this.$overlay.width(b(document).width()).height(b(document).height()).fadeIn(this.options.fadeDuration);this.album=[];g=0;j=c.attr('data-lightbox');if(j){h=b(c.prop("tagName")+'[data-lightbox="'+j+'"]');for(d=k=0,m=h.length;kj)||(c.height>i)){if((c.width/j)>(c.height/i)){h=j;g=parseInt(c.height/(c.width/h),10);d.width(h);d.height(g)}else{g=i;h=parseInt(c.width/(c.height/g),10);d.width(h);d.height(g)}}}return e.sizeContainer(d.width(),d.height())};c.src=this.album[f].link;this.currentImageIndex=f};c.prototype.sizeOverlay=function(){return b('#lightboxOverlay').width(b(document).width()).height(b(document).height())};c.prototype.sizeContainer=function(f,g){var b,d,e,h,c=this;h=this.$outerContainer.outerWidth();e=this.$outerContainer.outerHeight();d=f+this.containerLeftPadding+this.containerRightPadding;b=g+this.containerTopPadding+this.containerBottomPadding;this.$outerContainer.animate({width:d,height:b},this.options.resizeDuration,'swing');setTimeout(function(){c.$lightbox.find('.lb-dataContainer').width(d);c.$lightbox.find('.lb-prevLink').height(b);c.$lightbox.find('.lb-nextLink').height(b);c.showImage()},this.options.resizeDuration)};c.prototype.showImage=function(){this.$lightbox.find('.lb-loader').hide();this.$lightbox.find('.lb-image').fadeIn('slow');this.updateNav();this.updateDetails();this.preloadNeighboringImages();this.enableKeyboardNav()};c.prototype.updateNav=function(){this.$lightbox.find('.lb-nav').show();if(this.album.length>1){if(this.options.wrapAround){this.$lightbox.find('.lb-prev, .lb-next').show()}else{if(this.currentImageIndex>0){this.$lightbox.find('.lb-prev').show()}if(this.currentImageIndex1&&this.options.showImageNumberLabel){this.$lightbox.find('.lb-number').text(this.options.albumLabel(this.currentImageIndex+1,this.album.length)).fadeIn('fast')}else{this.$lightbox.find('.lb-number').hide()}this.$outerContainer.removeClass('animating');this.$lightbox.find('.lb-dataContainer').fadeIn(this.resizeDuration,function(){return b.sizeOverlay()})};c.prototype.preloadNeighboringImages=function(){var c,b;if(this.album.length>this.currentImageIndex+1){c=new Image();c.src=this.album[this.currentImageIndex+1].link}if(this.currentImageIndex>0){b=new Image();b.src=this.album[this.currentImageIndex-1].link}};c.prototype.enableKeyboardNav=function(){b(document).on('keyup.keyboard',b.proxy(this.keyboardAction,this))};c.prototype.disableKeyboardNav=function(){b(document).off('.keyboard')};c.prototype.keyboardAction=function(g){var d,e,f,c,b;d=27;e=37;f=39;b=g.keyCode;c=String.fromCharCode(b).toLowerCase();if(b===d||c.match(/x|o|c/)){this.end()}else if(c==='p'||b===e){if(this.currentImageIndex!==0){this.changeImage(this.currentImageIndex-1)}}else if(c==='n'||b===f){if(this.currentImageIndex!==this.album.length-1){this.changeImage(this.currentImageIndex+1)}}};c.prototype.end=function(){this.disableKeyboardNav();b(window).off("resize",this.sizeOverlay);this.$lightbox.fadeOut(this.options.fadeDuration);this.$overlay.fadeOut(this.options.fadeDuration);return b('select, object, embed').css({visibility:"visible"})};return c})();b(function(){var e,b;b=new c();return e=new d(b)})}).call(this); -------------------------------------------------------------------------------- /post.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | import cgi 3 | from bson.objectid import ObjectId 4 | from helper_functions import * 5 | 6 | 7 | class Post: 8 | 9 | def __init__(self, default_config): 10 | self.collection = default_config['POSTS_COLLECTION'] 11 | self.response = {'error': None, 'data': None} 12 | self.debug_mode = default_config['DEBUG'] 13 | 14 | def get_posts(self, limit, skip, tag=None, search=None): 15 | self.response['error'] = None 16 | cond = {} 17 | if tag is not None: 18 | cond = {'tags': tag} 19 | elif search is not None: 20 | cond = {'$or': [ 21 | {'title': {'$regex': search, '$options': 'i'}}, 22 | {'body': {'$regex': search, '$options': 'i'}}, 23 | {'preview': {'$regex': search, '$options': 'i'}}]} 24 | try: 25 | cursor = self.collection.find(cond).sort( 26 | 'date', direction=-1).skip(skip).limit(limit) 27 | self.response['data'] = [] 28 | for post in cursor: 29 | if 'tags' not in post: 30 | post['tags'] = [] 31 | if 'comments' not in post: 32 | post['comments'] = [] 33 | if 'preview' not in post: 34 | post['preview'] = '' 35 | 36 | self.response['data'].append({'id': post['_id'], 37 | 'title': post['title'], 38 | 'body': post['body'], 39 | 'preview': post['preview'], 40 | 'date': post['date'], 41 | 'permalink': post['permalink'], 42 | 'tags': post['tags'], 43 | 'author': post['author'], 44 | 'comments': post['comments']}) 45 | except Exception, e: 46 | self.print_debug_info(e, self.debug_mode) 47 | self.response['error'] = 'Posts not found..' 48 | 49 | return self.response 50 | 51 | def get_post_by_permalink(self, permalink): 52 | self.response['error'] = None 53 | try: 54 | self.response['data'] = self.collection.find_one( 55 | {'permalink': permalink}) 56 | except Exception, e: 57 | self.print_debug_info(e, self.debug_mode) 58 | self.response['error'] = 'Post not found..' 59 | 60 | return self.response 61 | 62 | def get_post_by_id(self, post_id): 63 | self.response['error'] = None 64 | try: 65 | self.response['data'] = self.collection.find_one( 66 | {'_id': ObjectId(post_id)}) 67 | if self.response['data']: 68 | if 'tags' not in self.response['data']: 69 | self.response['data']['tags'] = '' 70 | else: 71 | self.response['data']['tags'] = ','.join( 72 | self.response['data']['tags']) 73 | if 'preview' not in self.response['data']: 74 | self.response['data']['preview'] = '' 75 | except Exception, e: 76 | self.print_debug_info(e, self.debug_mode) 77 | self.response['error'] = 'Post not found..' 78 | 79 | return self.response 80 | 81 | def get_total_count(self, tag=None, search=None): 82 | cond = {} 83 | if tag is not None: 84 | cond = {'tags': tag} 85 | elif search is not None: 86 | cond = {'$or': [ 87 | {'title': {'$regex': search, '$options': 'i'}}, 88 | {'body': {'$regex': search, '$options': 'i'}}, 89 | {'preview': {'$regex': search, '$options': 'i'}}]} 90 | 91 | return self.collection.find(cond).count() 92 | 93 | def get_tags(self): 94 | self.response['error'] = None 95 | try: 96 | self.response['data'] = list(self.collection.aggregate([ 97 | {'$unwind': '$tags'}, 98 | {'$group': {'_id': '$tags', 'count': {'$sum': 1}}}, 99 | {'$sort': {'count': -1}}, 100 | {'$limit': 10}, 101 | {'$project': {'title': '$_id', 'count': 1, '_id': 0}} 102 | ])) 103 | except Exception, e: 104 | self.print_debug_info(e, self.debug_mode) 105 | self.response['error'] = 'Get tags error..' 106 | 107 | return self.response 108 | 109 | def create_new_post(self, post_data): 110 | self.response['error'] = None 111 | try: 112 | self.response['data'] = self.collection.insert(post_data) 113 | except Exception, e: 114 | self.print_debug_info(e, self.debug_mode) 115 | self.response['error'] = 'Adding post error..' 116 | 117 | return self.response 118 | 119 | def edit_post(self, post_id, post_data): 120 | self.response['error'] = None 121 | del post_data['date'] 122 | del post_data['permalink'] 123 | 124 | try: 125 | self.collection.update( 126 | {'_id': ObjectId(post_id)}, {"$set": post_data}, upsert=False) 127 | self.response['data'] = True 128 | except Exception, e: 129 | self.print_debug_info(e, self.debug_mode) 130 | self.response['error'] = 'Post update error..' 131 | 132 | return self.response 133 | 134 | def delete_post(self, post_id): 135 | self.response['error'] = None 136 | try: 137 | if self.get_post_by_id(post_id) and self.collection.remove({'_id': ObjectId(post_id)}): 138 | self.response['data'] = True 139 | else: 140 | self.response['data'] = False 141 | except Exception, e: 142 | self.print_debug_info(e, self.debug_mode) 143 | self.response['error'] = 'Deleting post error..' 144 | 145 | return self.response 146 | 147 | @staticmethod 148 | def validate_post_data(post_data): 149 | permalink = random_string(12) 150 | #exp = re.compile('\W') 151 | #whitespace = re.compile('\s') 152 | #temp_title = whitespace.sub("_", post_data['title']) 153 | #permalink = exp.sub('', temp_title) 154 | 155 | post_data['title'] = cgi.escape(post_data['title']) 156 | post_data['preview'] = cgi.escape(post_data['preview'], quote=True) 157 | post_data['body'] = cgi.escape(post_data['body'], quote=True) 158 | post_data['date'] = datetime.datetime.utcnow() 159 | post_data['permalink'] = permalink 160 | 161 | return post_data 162 | 163 | @staticmethod 164 | def print_debug_info(msg, show=False): 165 | if show: 166 | import sys 167 | import os 168 | 169 | error_color = '\033[32m' 170 | error_end = '\033[0m' 171 | 172 | error = {'type': sys.exc_info()[0].__name__, 173 | 'file': os.path.basename(sys.exc_info()[2].tb_frame.f_code.co_filename), 174 | 'line': sys.exc_info()[2].tb_lineno, 175 | 'details': str(msg)} 176 | 177 | print error_color 178 | print '\n\n---\nError type: %s in file: %s on line: %s\nError details: %s\n---\n\n'\ 179 | % (error['type'], error['file'], error['line'], error['details']) 180 | print error_end 181 | -------------------------------------------------------------------------------- /user.py: -------------------------------------------------------------------------------- 1 | import urllib 2 | import hashlib 3 | import re 4 | import datetime 5 | from werkzeug.security import check_password_hash, generate_password_hash 6 | from flask import session 7 | 8 | 9 | class User: 10 | 11 | def __init__(self, default_config): 12 | self.collection = default_config['USERS_COLLECTION'] 13 | self.username = None 14 | self.email = None 15 | self.session_key = 'user' 16 | self.response = {'error': None, 'data': None} 17 | self.debug_mode = default_config['DEBUG'] 18 | 19 | def login(self, username, password): 20 | self.response['error'] = None 21 | try: 22 | admin = self.collection.find_one({'_id': username}) 23 | if admin: 24 | if self.validate_login(admin['password'], password): 25 | self.username = admin['_id'] 26 | self.email = admin['email'] 27 | else: 28 | self.response['error'] = 'Password doesn\'t match..' 29 | else: 30 | self.response['error'] = 'User not found..' 31 | 32 | except Exception, e: 33 | self.print_debug_info(e, self.debug_mode) 34 | self.response['error'] = 'System error..' 35 | 36 | self.response['data'] = {'username': 37 | self.username, 'email': self.email} 38 | return self.response 39 | 40 | @staticmethod 41 | def validate_login(password_hash, password): 42 | return check_password_hash(password_hash, password) 43 | 44 | def start_session(self, obj): 45 | session[self.session_key] = obj 46 | return True 47 | 48 | def logout(self): 49 | if session.pop(self.session_key, None): 50 | return True 51 | else: 52 | return False 53 | 54 | def get_users(self): 55 | self.response['error'] = None 56 | try: 57 | users = self.collection.find().sort('date', direction=-1) 58 | self.response['data'] = [] 59 | for user in users: 60 | self.response['data'].append({'id': user['_id'], 61 | 'email': user['email'], 62 | 'date': user['date']}) 63 | except Exception, e: 64 | self.print_debug_info(e, self.debug_mode) 65 | self.response['error'] = 'Users not found..' 66 | return self.response 67 | 68 | def get_user(self, user_id): 69 | self.response['error'] = None 70 | try: 71 | user = self.collection.find_one({'_id': user_id}) 72 | gravatar_url = self.get_gravatar_link(user.get('email', '')) 73 | self.response['data'] = user 74 | self.response['data']['gravatar_url'] = gravatar_url 75 | except Exception, e: 76 | self.print_debug_info(e, self.debug_mode) 77 | self.response['error'] = 'User not found..' 78 | return self.response 79 | 80 | @staticmethod 81 | def get_gravatar_link(email=''): 82 | gravatar_url = "http://www.gravatar.com/avatar/" + \ 83 | hashlib.md5(email.lower()).hexdigest() + "?" 84 | gravatar_url += urllib.urlencode({'d': 'retro'}) 85 | return gravatar_url 86 | 87 | def delete_user(self, user_id): 88 | self.response['error'] = None 89 | try: 90 | self.collection.remove({'_id': user_id}) 91 | self.response['data'] = True 92 | except Exception, e: 93 | self.print_debug_info(e, self.debug_mode) 94 | self.response['error'] = 'Delete user error..' 95 | return self.response 96 | 97 | def save_user(self, user_data): 98 | self.response['error'] = None 99 | if user_data: 100 | if not re.match(r"^[A-Za-z0-9\.\+_-]+@[A-Za-z0-9\._-]+\.[a-zA-Z]*$", user_data['email']): 101 | self.response['error'] = 'Email is invalid..' 102 | return self.response 103 | 104 | exist_user = self.collection.find_one({'_id': user_data['_id']}) 105 | if user_data['update'] is not False: 106 | if exist_user: 107 | if user_data['old_pass']: 108 | if self.validate_login(exist_user['password'], user_data['old_pass']): 109 | if user_data['new_pass'] and user_data['new_pass'] == user_data['new_pass_again']: 110 | password_hash = generate_password_hash( 111 | user_data['new_pass'], method='pbkdf2:sha256') 112 | record = {'password': password_hash, 113 | 'email': user_data['email']} 114 | try: 115 | self.collection.update( 116 | {'_id': user_data['_id']}, {'$set': record}, upsert=False, multi=False) 117 | self.response['data'] = True 118 | except Exception, e: 119 | self.print_debug_info(e, self.debug_mode) 120 | self.response[ 121 | 'error'] = 'Update user error..' 122 | else: 123 | self.response[ 124 | 'error'] = 'New password doesn\'t match..' 125 | return self.response 126 | else: 127 | self.response[ 128 | 'error'] = 'Old password doesn\'t match..' 129 | return self.response 130 | else: 131 | try: 132 | self.collection.update( 133 | {'_id': user_data['_id']}, {'$set': {'email': user_data['email']}}, upsert=False, multi=False) 134 | self.response['data'] = True 135 | except Exception, e: 136 | self.print_debug_info(e, self.debug_mode) 137 | self.response['error'] = 'Update user error..' 138 | else: 139 | self.response['error'] = 'User not found..' 140 | return self.response 141 | else: 142 | if exist_user: 143 | self.response['error'] = 'Username already exists..' 144 | return self.response 145 | else: 146 | if user_data['new_pass'] and user_data['new_pass'] == user_data['new_pass_again']: 147 | password_hash = generate_password_hash( 148 | user_data['new_pass'], method='pbkdf2:sha256') 149 | record = {'_id': user_data['_id'], 'password': password_hash, 'email': user_data[ 150 | 'email'], 'date': datetime.datetime.utcnow()} 151 | try: 152 | self.collection.insert(record) 153 | self.response['data'] = True 154 | except Exception, e: 155 | self.print_debug_info(e, self.debug_mode) 156 | self.response['error'] = 'Create user error..' 157 | else: 158 | self.response[ 159 | 'error'] = 'Password cannot be blank and must be the same..' 160 | return self.response 161 | else: 162 | self.response['error'] = 'Error..' 163 | return self.response 164 | 165 | @staticmethod 166 | def print_debug_info(msg, show=False): 167 | if show: 168 | import sys 169 | import os 170 | 171 | error_color = '\033[32m' 172 | error_end = '\033[0m' 173 | 174 | error = {'type': sys.exc_info()[0].__name__, 175 | 'file': os.path.basename(sys.exc_info()[2].tb_frame.f_code.co_filename), 176 | 'line': sys.exc_info()[2].tb_lineno, 177 | 'details': str(msg)} 178 | 179 | print error_color 180 | print '\n\n---\nError type: %s in file: %s on line: %s\nError details: %s\n---\n\n'\ 181 | % (error['type'], error['file'], error['line'], error['details']) 182 | print error_end 183 | -------------------------------------------------------------------------------- /static/js/a-tools.js: -------------------------------------------------------------------------------- 1 | /*! 2 | * a-tools 1.5.1 3 | * 4 | * Copyright (c) 2009 Andrey Kramarev(andrey.kramarev[at]ampparit.com), Ampparit Inc. (www.ampparit.com) 5 | * Licensed under the MIT license. 6 | * http://www.ampparit.fi/a-tools/license.txt 7 | * 8 | * Basic usage: 9 | 10 | 11 | 12 | 13 | // Get current selection 14 | var sel = $("textarea").getSelection() 15 | 16 | // Replace current selection 17 | $("input").replaceSelection("foo"); 18 | 19 | // Count characters 20 | alert($("textarea").countCharacters()); 21 | 22 | // Set max length without callback function 23 | $("textarea").setMaxLength(7); 24 | 25 | // Set max length with callback function which will be called when limit is exceeded 26 | $("textarea").setMaxLength(10, function() { 27 | alert("hello") 28 | }); 29 | 30 | // Removing limit: 31 | $("textarea").setMaxLength(-1); 32 | 33 | // Insert text at current caret position 34 | $("#textarea").insertAtCaretPos("hello"); 35 | 36 | // Set caret position (1 = beginning, -1 = end) 37 | $("#textArea").setCaretPos(10); 38 | 39 | // Set Selection 40 | $("#textArea").setSelection(10,15); 41 | 42 | */ 43 | var caretPositionAmp=[]; function init(){if(navigator.appName=="Microsoft Internet Explorer"){obj=document.getElementsByTagName("TEXTAREA");var b,a=0;for(a=0;afirstRe.length)return{start:caretPositionAmp[c],end:caretPositionAmp[c],text:"",length:0};a=e.text.length;c=e.text.length+d.text.length}if(h>0)for(e=0;e<=h;e++){var k=b.value.indexOf("\n",g);if(k!=-1&&k=a&&k<=c)if(k==a+1){f--;i--;g=k+1}else{g=k+1;i++}else e=h}if(d.text.indexOf("\n",0)==1)i+=2;a-=f;c-=i;return{start:a,end:c,text:d.text,length:c-a}}b.focus();if(typeof b.selectionStart=="number")a=b.selectionStart;else{d=document.selection.createRange();a=b.createTextRange();e=a.duplicate();a.moveToBookmark(d.getBookmark());e.setEndPoint("EndToStart",a);a=e.text.length}if(h>0)for(e=0;e<=h;e++){k=b.value.indexOf("\n",g);if(k!=-1&&kc.length)return this}if(i.text){part=i.text;if(a.value.match(/\n/g)!=null)f=a.value.match(/\n/g).length;c=h.text.length;if(f>0)for(j=0;j<=f;j++){var l= a.value.indexOf("\n",e);if(l!=-1&&l0)for(var g=0;g<=e;g++){var i=c.value.indexOf("\n",d);if(i!=-1&&i=b&&i<=a)if(i==b+1){h--;f--;d=i+1}else{d=i+1;f++}else g=e}b+=h;a+=f;c.selectionStart=b;c.selectionEnd=a}c.focus()}return this}else if(c.selectionStart||c.selectionStart==0){c.focus();window.getSelection().removeAllRanges();c.selectionStart=b;c.selectionEnd=a;c.focus();return this}},insertAtCaretPos:function(b){var a=this.jquery?this[0]:this,c,e,h,d,f,g,i;c=e=0;var k=a.scrollTop==undefined?0:a.scrollTop;i=document.getElementsByTagName("TEXTAREA");for(var j=0;j0)for(var m=0;m<=c;m++){var l=a.value.indexOf("\n",h);if(l!=-1&&l<=i){h=l+1;i-=1;e++}}}caretPositionAmp[j]=parseInt(caretPositionAmp[j]);a.onkeyup=function(){if(document.selection&&typeof a.selectionStart!="number"){a.focus();d=document.selection.createRange();f=a.createTextRange();g=f.duplicate();f.moveToBookmark(d.getBookmark());g.setEndPoint("EndToStart", f);caretPositionAmp[j]=g.text.length}};a.onmouseup=function(){if(document.selection&&typeof a.selectionStart!="number"){a.focus();d=document.selection.createRange();f=a.createTextRange();g=f.duplicate();f.moveToBookmark(d.getBookmark());g.setEndPoint("EndToStart",f);caretPositionAmp[j]=g.text.length}};if(document.selection&&typeof a.selectionStart!="number"){d=document.selection.createRange();if(d.text.length!=0)return this;f=a.createTextRange();textLength=f.text.length;g=f.duplicate();f.moveToBookmark(d.getBookmark()); g.setEndPoint("EndToStart",f);c=g.text.length;if(caretPositionAmp[j]>0&&c==0){e=caretPositionAmp[j]-e;f.move("character",e);f.select();d=document.selection.createRange();caretPositionAmp[j]+=b.length}else if(!(caretPositionAmp[j]>=0)&&textLength==0){d=document.selection.createRange();caretPositionAmp[j]=b.length+textLength}else if(!(caretPositionAmp[j]>=0)&&c==0){f.move("character",textLength);f.select();d=document.selection.createRange();caretPositionAmp[j]=b.length+textLength}else if(!(caretPositionAmp[j]>= 0)&&c>0){f.move("character",0);document.selection.empty();f.select();d=document.selection.createRange();caretPositionAmp[j]=c+b.length}else if(caretPositionAmp[j]>=0&&caretPositionAmp[j]==textLength){if(textLength!=0){f.move("character",textLength);f.select()}else f.move("character",0);d=document.selection.createRange();caretPositionAmp[j]=b.length+textLength}else{if(caretPositionAmp[j]>=0&&c!=0&&caretPositionAmp[j]>=c){e=caretPositionAmp[j]-c;f.move("character",e)}else caretPositionAmp[j]>=0&&c!= 0&&caretPositionAmp[j]0){b=parseInt(b)-1;if(document.selection&&typeof a.selectionStart=="number"&&a.selectionStart==a.selectionEnd){if(a.value.match(/\n/g)!=null)e=a.value.match(/\n/g).length;if(e>0)for(var g=0;g<=e;g++){d=a.value.indexOf("\n",c);if(d!=-1&&d<=b){c=d+1;b=parseInt(b)+1}}}}else if(parseInt(b)<0){b=parseInt(b)+1;if(document.selection&&typeof a.selectionStart!="number"){b= a.value.length+parseInt(b);if(a.value.match(/\n/g)!=null)e=a.value.match(/\n/g).length;if(e>0){for(g=0;g<=e;g++){d=a.value.indexOf("\n",c);if(d!=-1&&d<=b){c=d+1;b=parseInt(b)-1;h+=1}}b=b+h-e}}else if(document.selection&&typeof a.selectionStart=="number"){b=a.value.length+parseInt(b);if(a.value.match(/\n/g)!=null)e=a.value.match(/\n/g).length;if(e>0){b=parseInt(b)-e;for(g=0;g<=e;g++){d=a.value.indexOf("\n",c);if(d!=-1&&d<=b){c=d+1;b=parseInt(b)+1;h+=1}}}}else b=a.value.length+parseInt(b)}else return this; if(document.selection&&typeof a.selectionStart!="number"){c=document.selection.createRange();if(c.text!=0)return this;a=a.createTextRange();a.collapse(true);a.moveEnd("character",b);a.moveStart("character",b);a.select();caretPositionAmp[f]=b;return this}else if(typeof a.selectionStart=="number"&&a.selectionStart==a.selectionEnd){a.setSelectionRange(b,b);return this}return this},countCharacters:function(){var b=this.jquery?this[0]:this;if(b.value.match(/\r/g)!=null)return b.value.length-b.value.match(/\r/g).length; return b.value.length},setMaxLength:function(b,a){this.each(function(){var c=this.jquery?this[0]:this,e=c.type,h,d;if(parseInt(b)<0)b=1E8;if(e=="text")c.maxLength=b;if(e=="textarea"||e=="text"){c.onkeypress=function(f){var g=c.value.match(/\r/g);d=b;if(g!=null)d=parseInt(d)+g.length;f=f||event;g=f.keyCode;h=document.selection?document.selection.createRange().text.length>0:c.selectionStart!=c.selectionEnd;if(c.value.length>=d&&(g>47||g==32||g==0||g==13)&&!f.ctrlKey&&!f.altKey&&!h){c.value=c.value.substring(0, d);typeof a=="function"&&a();return false}};c.onkeyup=function(){var f=c.value.match(/\r/g),g=0,i=0;d=b;if(f!=null){for(var k=0;k<=f.length;k++)if(c.value.indexOf("\n",i)<=parseInt(b)){g++;i=c.value.indexOf("\n",i)+1}d=parseInt(b)+g}if(c.value.length>d){c.value=c.value.substring(0,d);typeof a=="function"&&a();return this}}}else return this});return this}}); -------------------------------------------------------------------------------- /static/js/mdmagick.js: -------------------------------------------------------------------------------- 1 | /* 2 | # MDMagick 3 | 4 | * url: https://github.com/fguillen/MDMagick 5 | * author: http://fernandoguillen.info 6 | * demo page: http://fguillen.github.com/MDMagick/ 7 | 8 | ## Version 9 | 10 | v0.0.3 11 | 12 | ## Documentation 13 | 14 | * README: https://github.com/fguillen/MDMagick/blob/master/README.md 15 | */ 16 | 17 | var MDM_VERSION = "0.0.3"; 18 | 19 | function MDM( inputElement ) { 20 | this.inputElement = inputElement; 21 | 22 | this.initialize = function(){ 23 | this.controlsElement = MDM.Utils.appendControls( inputElement ); 24 | this.previewElement = MDM.Utils.appendPreview( inputElement ); 25 | 26 | this.activatePreview( this.inputElement, this.previewElement ); 27 | this.activateControls( this.controlsElement ); 28 | this.activateInput( this.inputElement, this.controlsElement, this.previewElement ); 29 | 30 | this.updatePreview(); 31 | }; 32 | 33 | this.click_on_control = false; 34 | 35 | this.activateControls = function( controlsElement ){ 36 | var _self = this; 37 | ["bold", "italic", "link", "title", "list", "quote", "code", "multilineCode", "img", "strike", "gist"].forEach( function( actionName ){ 38 | $( controlsElement ).find( ".mdm-" + actionName ).click( function( event ){ _self.action( actionName, event ) } ); 39 | }); 40 | }; 41 | 42 | this.activatePreview = function( inputElement, previewElement ) { 43 | $(inputElement).keyup( $.proxy( this.updatePreview, this ) ); 44 | }; 45 | 46 | this.activateInput = function( inputElement, controlsElement, previewElement ){ 47 | var _self = this; 48 | 49 | $(controlsElement).mousedown( function(){ 50 | _self.click_on_control = true; 51 | }); 52 | 53 | $(inputElement).focus( function(){ 54 | _self.click_on_control = false; 55 | $(controlsElement).addClass( "focus" ); 56 | $(previewElement).addClass( "focus" ); 57 | $(controlsElement).removeClass( "blur" ); 58 | $(previewElement).removeClass( "blur" ); 59 | }); 60 | 61 | $(inputElement).blur( function(){ 62 | if (!_self.click_on_control) { 63 | $(controlsElement).removeClass( "focus" ); 64 | $(previewElement).removeClass( "focus" ); 65 | $(controlsElement).addClass( "blur" ); 66 | $(previewElement).addClass( "blur" ); 67 | } 68 | }); 69 | }; 70 | 71 | this.updatePreview = function(){ 72 | var converter = new Attacklab.showdown.converter(); 73 | $( this.previewElement ).html( 74 | converter.makeHtml( $( this.inputElement ).val().replace(//g,'>') ) 75 | ); 76 | }; 77 | 78 | this.action = function( actionName, event ){ 79 | event.preventDefault(); 80 | MDM.Actions[ actionName ]( this.inputElement ); 81 | this.updatePreview(); 82 | }; 83 | 84 | this.initialize(); 85 | } 86 | 87 | 88 | /* 89 | The logic of each of the control buttons 90 | */ 91 | MDM.Actions = { 92 | bold: function( inputElement ){ 93 | var selection = $( inputElement ).getSelection(); 94 | $( inputElement ).replaceSelection( "**" + selection.text + "**" ); 95 | }, 96 | 97 | italic: function( inputElement ){ 98 | var selection = $( inputElement ).getSelection(); 99 | $( inputElement ).replaceSelection( "_" + selection.text + "_" ); 100 | }, 101 | 102 | link: function( inputElement ){ 103 | var link = prompt( "Link to URL", "http://" ); 104 | if(link) { 105 | var selection = $( inputElement ).getSelection(); 106 | var objectValue = $(inputElement).val(); 107 | if(!selection.text){ 108 | $(inputElement).val(objectValue + "\n" + 'link description'); 109 | $(inputElement).setCaretPos(-1); 110 | MDM.Utils.selectWholeLines( inputElement ); 111 | selection = $( inputElement ).getSelection(); 112 | } 113 | 114 | $( inputElement ).replaceSelection( "[" + selection.text + "](" + link + ")" ); 115 | $( inputElement ).setSelection(selection.start + 1, selection.end + 1); //select description text 116 | } 117 | }, 118 | 119 | title: function( inputElement ){ 120 | MDM.Utils.selectWholeLines( inputElement ); 121 | var selection = $( inputElement ).getSelection(); 122 | var hash = (selection.text.charAt( 0 ) == "#") ? "#" : "# "; 123 | $( inputElement ).replaceSelection( hash + selection.text ); 124 | }, 125 | 126 | list: function( inputElement ){ 127 | MDM.Utils.selectWholeLines( inputElement ); 128 | var selection = $( inputElement ).getSelection(); 129 | var text = selection.text; 130 | var result = ""; 131 | var lines = text.split( "\n" ); 132 | for( var i = 0; i < lines.length; i++ ){ 133 | var line = $.trim( lines[i] ); 134 | if( line.length > 0 ) result += "- " + line + "\n"; 135 | } 136 | 137 | $( inputElement ).replaceSelection( result ); 138 | }, 139 | 140 | quote: function( inputElement ){ 141 | var selection = $( inputElement ).getSelection(); 142 | $( inputElement ).replaceSelection( "~~" + selection.text + "~~" ); 143 | }, 144 | 145 | strike: function( inputElement ){ 146 | var selection = $( inputElement ).getSelection(); 147 | $( inputElement ).replaceSelection( "--" + selection.text + "--" ); 148 | }, 149 | 150 | code: function( inputElement ){ 151 | var selection = $( inputElement ).getSelection(); 152 | $( inputElement ).replaceSelection( "`" + selection.text + "`" ); 153 | }, 154 | 155 | multilineCode: function( inputElement ){ 156 | var selection = $( inputElement ).getSelection(); 157 | //TODO: cut all empty lines from selection.text 158 | $( inputElement ).replaceSelection( "[code]\n" + selection.text + "\n[/code]" ); 159 | }, 160 | 161 | img: function( inputElement ){ 162 | var link = prompt( "Image URL", "http://" ); 163 | if(link) { 164 | var selection = $( inputElement ).getSelection(); 165 | var objectValue = $(inputElement).val(); 166 | if(!selection.text){ 167 | $(inputElement).val(objectValue + "\n" + 'img description'); 168 | $(inputElement).setCaretPos(-1); 169 | MDM.Utils.selectWholeLines( inputElement ); 170 | selection = $( inputElement ).getSelection(); 171 | } 172 | 173 | $( inputElement ).replaceSelection( "![" + selection.text + "](" + link + ")" ); 174 | $( inputElement ).setSelection(selection.start + 2, selection.end + 2); //select description text 175 | } 176 | }, 177 | 178 | gist: function( inputElement ){ 179 | var string = prompt( "GitHub Gist ID", "" ); 180 | if(string) { 181 | var selection = $( inputElement ).getSelection(); 182 | var objectValue = $(inputElement).val(); 183 | if(!selection.text){ 184 | $(inputElement).val(objectValue + "\n" + 'link description'); 185 | $(inputElement).setCaretPos(-1); 186 | MDM.Utils.selectWholeLines( inputElement ); 187 | } 188 | $( inputElement ).replaceSelection( "\n[gist]" + string + "[/gist]\n" ); 189 | } 190 | } 191 | } 192 | 193 | MDM.Utils = { 194 | appendControls: function( inputElement ){ 195 | var element = $( MDM.Utils.controlsTemplate() ); 196 | $(inputElement).before( element ); 197 | 198 | return element; 199 | }, 200 | 201 | appendPreview: function( inputElement ){ 202 | return false; 203 | var element = $( MDM.Utils.previewTemplate() ); 204 | element.css( "width", $( inputElement ).css( "width" ) ); 205 | // element.css( "padding", $( inputElement ).css( "padding" ) ); 206 | element.css( "font-size", $( inputElement ).css( "font-size" ) ); 207 | $(inputElement).after( element ); 208 | 209 | return element; 210 | }, 211 | 212 | selectWholeLines: function( inputElement ){ 213 | var content = $( inputElement ).val(); 214 | var selection = $( inputElement ).getSelection(); 215 | var iniPosition = (selection.start > 0) ? (selection.start - 1) : 0; 216 | var endPosition = selection.end; 217 | 218 | // going back until a "\n" 219 | while( content[iniPosition] != "\n" && iniPosition >= 0 ) { 220 | iniPosition--; 221 | } 222 | 223 | while( content[endPosition] != "\n" && endPosition <= content.length ) { 224 | endPosition++; 225 | } 226 | 227 | $( inputElement ).setSelection( iniPosition + 1, endPosition ); 228 | }, 229 | 230 | controlsTemplate: function(){ 231 | 232 | var template = 233 | "
    " + 234 | "
      " + 235 | "
    • B
    • " + 236 | "
    • I
    • " + 237 | "
    • S
    • " + 238 | "
    • T
    • " + 239 | "
    • Q
    • " + 240 | "
    • C
    • " + 241 | "
    • MLC
    • " + 242 | "
    • l
    • " + 243 | "
    • a
    • " + 244 | "
    • Img
    • " + 245 | "
    • G
    • " + 246 | "
    " + 247 | "
    "; 248 | 249 | return template; 250 | }, 251 | 252 | previewTemplate: function(){ 253 | var template = "
    "; 254 | 255 | return template; 256 | } 257 | } 258 | 259 | $(function(){ 260 | if( typeof window.MDM_SILENT == 'undefined' || window.MDM_SILENT == false ) { 261 | console.debug( "loading MDMagick v" + MDM_VERSION + "..." ); 262 | } 263 | 264 | jQuery.fn.mdmagick = function(){ 265 | this.each( function( index, inputElement ){ 266 | var mdm = new MDM( inputElement ); 267 | }); 268 | }; 269 | 270 | $(".mdm-input").mdmagick(); 271 | }); 272 | -------------------------------------------------------------------------------- /web.py: -------------------------------------------------------------------------------- 1 | import cgi 2 | import os 3 | from flask import Flask, render_template, abort, url_for, request, flash, session, redirect 4 | from flaskext.markdown import Markdown 5 | from mdx_github_gists import GitHubGistExtension 6 | from mdx_strike import StrikeExtension 7 | from mdx_quote import QuoteExtension 8 | from mdx_code_multiline import MultilineCodeExtension 9 | from werkzeug.contrib.atom import AtomFeed 10 | import post 11 | import user 12 | import pagination 13 | import settings 14 | from helper_functions import * 15 | 16 | 17 | app = Flask('FlaskBlog') 18 | md = Markdown(app) 19 | md.register_extension(GitHubGistExtension) 20 | md.register_extension(StrikeExtension) 21 | md.register_extension(QuoteExtension) 22 | md.register_extension(MultilineCodeExtension) 23 | app.config.from_object('config') 24 | 25 | 26 | @app.route('/', defaults={'page': 1}) 27 | @app.route('/page-') 28 | def index(page): 29 | skip = (page - 1) * int(app.config['PER_PAGE']) 30 | posts = postClass.get_posts(int(app.config['PER_PAGE']), skip) 31 | count = postClass.get_total_count() 32 | pag = pagination.Pagination(page, app.config['PER_PAGE'], count) 33 | return render_template('index.html', posts=posts['data'], pagination=pag, meta_title=app.config['BLOG_TITLE']) 34 | 35 | 36 | @app.route('/tag/', defaults={'page': 1}) 37 | @app.route('/tag//page-') 38 | def posts_by_tag(tag, page): 39 | skip = (page - 1) * int(app.config['PER_PAGE']) 40 | posts = postClass.get_posts(int(app.config['PER_PAGE']), skip, tag=tag) 41 | count = postClass.get_total_count(tag=tag) 42 | if not posts['data']: 43 | abort(404) 44 | pag = pagination.Pagination(page, app.config['PER_PAGE'], count) 45 | return render_template('index.html', posts=posts['data'], pagination=pag, meta_title='Posts by tag: ' + tag) 46 | 47 | 48 | @app.route('/post/') 49 | def single_post(permalink): 50 | post = postClass.get_post_by_permalink(permalink) 51 | if not post['data']: 52 | abort(404) 53 | return render_template('single_post.html', post=post['data'], meta_title=app.config['BLOG_TITLE'] + '::' + post['data']['title']) 54 | 55 | 56 | @app.route('/q/', defaults={'page': 1}) 57 | @app.route('/q//page-') 58 | def search_results(page, query): 59 | skip = (page - 1) * int(app.config['PER_PAGE']) 60 | if query: 61 | posts = postClass.get_posts( 62 | int(app.config['PER_PAGE']), skip, search=query) 63 | else: 64 | posts = [] 65 | posts['data'] = [] 66 | count = postClass.get_total_count(search=query) 67 | pag = pagination.Pagination(page, app.config['PER_PAGE'], count) 68 | return render_template('index.html', posts=posts['data'], pagination=pag, meta_title='Search results') 69 | 70 | 71 | @app.route('/search', methods=['GET', 'POST']) 72 | def search(): 73 | if request.method != 'POST': 74 | return redirect(url_for('index')) 75 | 76 | query = request.form.get('query', None) 77 | if query: 78 | return redirect(url_for('search_results', query=query)) 79 | else: 80 | return redirect(url_for('index')) 81 | 82 | 83 | @app.route('/newpost', methods=['GET', 'POST']) 84 | @login_required() 85 | def new_post(): 86 | error = False 87 | error_type = 'validate' 88 | if request.method == 'POST': 89 | post_title = request.form.get('post-title').strip() 90 | post_full = request.form.get('post-full') 91 | 92 | if not post_title or not post_full: 93 | error = True 94 | else: 95 | tags = cgi.escape(request.form.get('post-tags')) 96 | tags_array = extract_tags(tags) 97 | post_data = {'title': post_title, 98 | 'preview': request.form.get('post-short'), 99 | 'body': post_full, 100 | 'tags': tags_array, 101 | 'author': session['user']['username']} 102 | 103 | post = postClass.validate_post_data(post_data) 104 | if request.form.get('post-preview') == '1': 105 | session['post-preview'] = post 106 | session[ 107 | 'post-preview']['action'] = 'edit' if request.form.get('post-id') else 'add' 108 | if request.form.get('post-id'): 109 | session[ 110 | 'post-preview']['redirect'] = url_for('post_edit', id=request.form.get('post-id')) 111 | else: 112 | session['post-preview']['redirect'] = url_for('new_post') 113 | return redirect(url_for('post_preview')) 114 | else: 115 | session.pop('post-preview', None) 116 | 117 | if request.form.get('post-id'): 118 | response = postClass.edit_post( 119 | request.form['post-id'], post) 120 | if not response['error']: 121 | flash('Post updated!', 'success') 122 | else: 123 | flash(response['error'], 'error') 124 | return redirect(url_for('posts')) 125 | else: 126 | response = postClass.create_new_post(post) 127 | if response['error']: 128 | error = True 129 | error_type = 'post' 130 | flash(response['error'], 'error') 131 | else: 132 | flash('New post created!', 'success') 133 | else: 134 | if session.get('post-preview') and session['post-preview']['action'] == 'edit': 135 | session.pop('post-preview', None) 136 | return render_template('new_post.html', 137 | meta_title='New post', 138 | error=error, 139 | error_type=error_type) 140 | 141 | 142 | @app.route('/post_preview') 143 | @login_required() 144 | def post_preview(): 145 | post = session.get('post-preview') 146 | return render_template('preview.html', post=post, meta_title='Preview post::' + post['title']) 147 | 148 | 149 | @app.route('/posts_list', defaults={'page': 1}) 150 | @app.route('/posts_list/page-') 151 | @login_required() 152 | def posts(page): 153 | session.pop('post-preview', None) 154 | skip = (page - 1) * int(app.config['PER_PAGE']) 155 | posts = postClass.get_posts(int(app.config['PER_PAGE']), skip) 156 | count = postClass.get_total_count() 157 | pag = pagination.Pagination(page, app.config['PER_PAGE'], count) 158 | 159 | if not posts['data']: 160 | abort(404) 161 | 162 | return render_template('posts.html', posts=posts['data'], pagination=pag, meta_title='Posts') 163 | 164 | 165 | @app.route('/post_edit?id=') 166 | @login_required() 167 | def post_edit(id): 168 | post = postClass.get_post_by_id(id) 169 | if post['error']: 170 | flash(post['error'], 'error') 171 | return redirect(url_for('posts')) 172 | 173 | if session.get('post-preview') and session['post-preview']['action'] == 'add': 174 | session.pop('post-preview', None) 175 | return render_template('edit_post.html', 176 | meta_title='Edit post::' + post['data']['title'], 177 | post=post['data'], 178 | error=False, 179 | error_type=False) 180 | 181 | 182 | @app.route('/post_delete?id=') 183 | @login_required() 184 | def post_del(id): 185 | if postClass.get_total_count() > 1: 186 | response = postClass.delete_post(id) 187 | if response['data'] is True: 188 | flash('Post removed!', 'success') 189 | else: 190 | flash(response['error'], 'error') 191 | else: 192 | flash('Need to be at least one post..', 'error') 193 | 194 | return redirect(url_for('posts')) 195 | 196 | 197 | @app.route('/login', methods=['GET', 'POST']) 198 | def login(): 199 | error = False 200 | error_type = 'validate' 201 | if request.method == 'POST': 202 | username = request.form.get('login-username') 203 | password = request.form.get('login-password') 204 | if not username or not password: 205 | error = True 206 | else: 207 | user_data = userClass.login(username.lower().strip(), password) 208 | if user_data['error']: 209 | error = True 210 | error_type = 'login' 211 | flash(user_data['error'], 'error') 212 | else: 213 | userClass.start_session(user_data['data']) 214 | flash('You are logged in!', 'success') 215 | return redirect(url_for('posts')) 216 | else: 217 | if session.get('user'): 218 | return redirect(url_for('posts')) 219 | 220 | return render_template('login.html', 221 | meta_title='Login', 222 | error=error, 223 | error_type=error_type) 224 | 225 | 226 | @app.route('/logout') 227 | def logout(): 228 | if userClass.logout(): 229 | flash('You are logged out!', 'success') 230 | return redirect(url_for('login')) 231 | 232 | 233 | @app.route('/users') 234 | @login_required() 235 | def users_list(): 236 | users = userClass.get_users() 237 | return render_template('users.html', users=users['data'], meta_title='Users') 238 | 239 | 240 | @app.route('/add_user') 241 | @login_required() 242 | def add_user(): 243 | gravatar_url = userClass.get_gravatar_link() 244 | return render_template('add_user.html', gravatar_url=gravatar_url, meta_title='Add user') 245 | 246 | 247 | @app.route('/edit_user?id=') 248 | @login_required() 249 | def edit_user(id): 250 | user = userClass.get_user(id) 251 | return render_template('edit_user.html', user=user['data'], meta_title='Edit user') 252 | 253 | 254 | @app.route('/delete_user?id=') 255 | @login_required() 256 | def delete_user(id): 257 | if id != session['user']['username']: 258 | user = userClass.delete_user(id) 259 | if user['error']: 260 | flash(user['error'], 'error') 261 | else: 262 | flash('User deleted!', 'success') 263 | return redirect(url_for('users_list')) 264 | 265 | 266 | @app.route('/save_user', methods=['POST']) 267 | @login_required() 268 | def save_user(): 269 | post_data = { 270 | '_id': request.form.get('user-id', None).lower().strip(), 271 | 'email': request.form.get('user-email', None), 272 | 'old_pass': request.form.get('user-old-password', None), 273 | 'new_pass': request.form.get('user-new-password', None), 274 | 'new_pass_again': request.form.get('user-new-password-again', None), 275 | 'update': request.form.get('user-update', False) 276 | } 277 | if not post_data['email'] or not post_data['_id']: 278 | flash('Username and Email are required..', 'error') 279 | if post_data['update']: 280 | return redirect(url_for('edit_user', id=post_data['_id'])) 281 | else: 282 | return redirect(url_for('add_user')) 283 | else: 284 | user = userClass.save_user(post_data) 285 | if user['error']: 286 | flash(user['error'], 'error') 287 | if post_data['update']: 288 | return redirect(url_for('edit_user', id=post_data['_id'])) 289 | else: 290 | return redirect(url_for('add_user')) 291 | else: 292 | message = 'User updated!' if post_data['update'] else 'User added!' 293 | flash(message, 'success') 294 | return redirect(url_for('edit_user', id=post_data['_id'])) 295 | 296 | 297 | @app.route('/recent_feed') 298 | def recent_feed(): 299 | feed = AtomFeed(app.config['BLOG_TITLE'] + '::Recent Articles', 300 | feed_url=request.url, url=request.url_root) 301 | posts = postClass.get_posts(int(app.config['PER_PAGE']), 0) 302 | for post in posts['data']: 303 | post_entry = post['preview'] if post['preview'] else post['body'] 304 | feed.add(post['title'], md(post_entry), 305 | content_type='html', 306 | author=post['author'], 307 | url=make_external( 308 | url_for('single_post', permalink=post['permalink'])), 309 | updated=post['date']) 310 | return feed.get_response() 311 | 312 | 313 | @app.route('/settings', methods=['GET', 'POST']) 314 | @login_required() 315 | def blog_settings(): 316 | error = None 317 | error_type = 'validate' 318 | if request.method == 'POST': 319 | blog_data = { 320 | 'title': request.form.get('blog-title', None), 321 | 'description': request.form.get('blog-description', None), 322 | 'per_page': request.form.get('blog-perpage', None), 323 | 'text_search': request.form.get('blog-text-search', None) 324 | } 325 | blog_data['text_search'] = 1 if blog_data['text_search'] else 0 326 | for key, value in blog_data.items(): 327 | if not value and key != 'text_search' and key != 'description': 328 | error = True 329 | break 330 | if not error: 331 | update_result = settingsClass.update_settings(blog_data) 332 | if update_result['error']: 333 | flash(update_result['error'], 'error') 334 | else: 335 | flash('Settings updated!', 'success') 336 | return redirect(url_for('blog_settings')) 337 | 338 | return render_template('settings.html', 339 | default_settings=app.config, 340 | meta_title='Settings', 341 | error=error, 342 | error_type=error_type) 343 | 344 | 345 | @app.route('/install', methods=['GET', 'POST']) 346 | def install(): 347 | if session.get('installed', None): 348 | return redirect(url_for('index')) 349 | 350 | error = False 351 | error_type = 'validate' 352 | if request.method == 'POST': 353 | user_error = False 354 | blog_error = False 355 | 356 | user_data = { 357 | '_id': request.form.get('user-id', None).lower().strip(), 358 | 'email': request.form.get('user-email', None), 359 | 'new_pass': request.form.get('user-new-password', None), 360 | 'new_pass_again': request.form.get('user-new-password-again', None), 361 | 'update': False 362 | } 363 | blog_data = { 364 | 'title': request.form.get('blog-title', None), 365 | 'description': request.form.get('blog-description', None), 366 | 'per_page': request.form.get('blog-perpage', None), 367 | 'text_search': request.form.get('blog-text-search', None) 368 | } 369 | blog_data['text_search'] = 1 if blog_data['text_search'] else 0 370 | 371 | for key, value in user_data.items(): 372 | if not value and key != 'update': 373 | user_error = True 374 | break 375 | for key, value in blog_data.items(): 376 | if not value and key != 'text_search' and key != 'description': 377 | blog_error = True 378 | break 379 | 380 | if user_error or blog_error: 381 | error = True 382 | else: 383 | install_result = settingsClass.install(blog_data, user_data) 384 | if install_result['error']: 385 | for i in install_result['error']: 386 | if i is not None: 387 | flash(i, 'error') 388 | else: 389 | session['installed'] = True 390 | flash('Successfully installed!', 'success') 391 | user_login = userClass.login( 392 | user_data['_id'], user_data['new_pass']) 393 | if user_login['error']: 394 | flash(user_login['error'], 'error') 395 | else: 396 | userClass.start_session(user_login['data']) 397 | flash('You are logged in!', 'success') 398 | return redirect(url_for('posts')) 399 | else: 400 | if settingsClass.is_installed(): 401 | return redirect(url_for('index')) 402 | 403 | return render_template('install.html', 404 | default_settings=app.config, 405 | error=error, 406 | error_type=error_type, 407 | meta_title='Install') 408 | 409 | 410 | @app.before_request 411 | def csrf_protect(): 412 | if request.method == "POST": 413 | token = session.pop('_csrf_token', None) 414 | if not token or token != request.form.get('_csrf_token'): 415 | abort(400) 416 | 417 | 418 | @app.before_request 419 | def is_installed(): 420 | app.config = settingsClass.get_config() 421 | app.jinja_env.globals['meta_description'] = app.config['BLOG_DESCRIPTION'] 422 | if not session.get('installed', None): 423 | if url_for('static', filename='') not in request.path and request.path != url_for('install'): 424 | if not settingsClass.is_installed(): 425 | return redirect(url_for('install')) 426 | 427 | 428 | @app.before_request 429 | def set_globals(): 430 | app.jinja_env.globals['csrf_token'] = generate_csrf_token 431 | app.jinja_env.globals['recent_posts'] = postClass.get_posts(10, 0)['data'] 432 | app.jinja_env.globals['tags'] = postClass.get_tags()['data'] 433 | 434 | 435 | @app.errorhandler(404) 436 | def page_not_found(error): 437 | return render_template('404.html', meta_title='404'), 404 438 | 439 | 440 | @app.template_filter('formatdate') 441 | def format_datetime_filter(input_value, format_="%a, %d %b %Y"): 442 | return input_value.strftime(format_) 443 | 444 | 445 | settingsClass = settings.Settings(app.config) 446 | postClass = post.Post(app.config) 447 | userClass = user.User(app.config) 448 | 449 | app.jinja_env.globals['url_for_other_page'] = url_for_other_page 450 | app.jinja_env.globals['meta_description'] = app.config['BLOG_DESCRIPTION'] 451 | 452 | if not app.config['DEBUG']: 453 | import logging 454 | from logging import FileHandler 455 | file_handler = FileHandler(app.config['LOG_FILE']) 456 | file_handler.setLevel(logging.WARNING) 457 | app.logger.addHandler(file_handler) 458 | 459 | if __name__ == '__main__': 460 | app.run(host="0.0.0.0", port=int(os.environ.get("PORT", 8080)), 461 | debug=app.config['DEBUG']) 462 | -------------------------------------------------------------------------------- /static/js/showdown.js: -------------------------------------------------------------------------------- 1 | // 2 | // showdown.js -- A javascript port of Markdown. 3 | // 4 | // Copyright (c) 2007 John Fraser. 5 | // 6 | // Original Markdown Copyright (c) 2004-2005 John Gruber 7 | // 8 | // 9 | // The full source distribution is at: 10 | // 11 | // A A L 12 | // T C A 13 | // T K B 14 | // 15 | // 16 | // 17 | 18 | // 19 | // Wherever possible, Showdown is a straight, line-by-line port 20 | // of the Perl version of Markdown. 21 | // 22 | // This is not a normal parser design; it's basically just a 23 | // series of string substitutions. It's hard to read and 24 | // maintain this way, but keeping Showdown close to the original 25 | // design makes it easier to port new features. 26 | // 27 | // More importantly, Showdown behaves like markdown.pl in most 28 | // edge cases. So web applications can do client-side preview 29 | // in Javascript, and then build identical HTML on the server. 30 | // 31 | // This port needs the new RegExp functionality of ECMA 262, 32 | // 3rd Edition (i.e. Javascript 1.5). Most modern web browsers 33 | // should do fine. Even with the new regular expression features, 34 | // We do a lot of work to emulate Perl's regex functionality. 35 | // The tricky changes in this file mostly have the "attacklab:" 36 | // label. Major or self-explanatory changes don't. 37 | // 38 | // Smart diff tools like Araxis Merge will be able to match up 39 | // this file with markdown.pl in a useful way. A little tweaking 40 | // helps: in a copy of markdown.pl, replace "#" with "//" and 41 | // replace "$text" with "text". Be sure to ignore whitespace 42 | // and line endings. 43 | // 44 | 45 | 46 | // 47 | // Showdown usage: 48 | // 49 | // var text = "Markdown *rocks*."; 50 | // 51 | // var converter = new Attacklab.showdown.converter(); 52 | // var html = converter.makeHtml(text); 53 | // 54 | // alert(html); 55 | // 56 | // Note: move the sample code to the bottom of this 57 | // file before uncommenting it. 58 | // 59 | 60 | 61 | // 62 | // Attacklab namespace 63 | // 64 | var Attacklab = Attacklab || {} 65 | 66 | // 67 | // Showdown namespace 68 | // 69 | Attacklab.showdown = Attacklab.showdown || {} 70 | 71 | // 72 | // converter 73 | // 74 | // Wraps all "globals" so that the only thing 75 | // exposed is makeHtml(). 76 | // 77 | Attacklab.showdown.converter = function() { 78 | 79 | // 80 | // Globals: 81 | // 82 | 83 | // Global hashes, used by various utility routines 84 | var g_urls; 85 | var g_titles; 86 | var g_html_blocks; 87 | 88 | // Used to track when we're inside an ordered or unordered list 89 | // (see _ProcessListItems() for details): 90 | var g_list_level = 0; 91 | 92 | 93 | this.makeHtml = function(text) { 94 | // 95 | // Main function. The order in which other subs are called here is 96 | // essential. Link and image substitutions need to happen before 97 | // _EscapeSpecialCharsWithinTagAttributes(), so that any *'s or _'s in the 98 | // and tags get encoded. 99 | // 100 | 101 | // Clear the global hashes. If we don't clear these, you get conflicts 102 | // from other articles when generating a page which contains more than 103 | // one article (e.g. an index page that shows the N most recent 104 | // articles): 105 | g_urls = new Array(); 106 | g_titles = new Array(); 107 | g_html_blocks = new Array(); 108 | 109 | // attacklab: Replace ~ with ~T 110 | // This lets us use tilde as an escape char to avoid md5 hashes 111 | // The choice of character is arbitray; anything that isn't 112 | // magic in Markdown will work. 113 | text = text.replace(/~/g,"~T"); 114 | 115 | // attacklab: Replace $ with ~D 116 | // RegExp interprets $ as a special character 117 | // when it's in a replacement string 118 | text = text.replace(/\$/g,"~D"); 119 | 120 | // Standardize line endings 121 | text = text.replace(/\r\n/g,"\n"); // DOS to Unix 122 | text = text.replace(/\r/g,"\n"); // Mac to Unix 123 | 124 | // Make sure text begins and ends with a couple of newlines: 125 | text = "\n\n" + text + "\n\n"; 126 | 127 | // Convert all tabs to spaces. 128 | text = _Detab(text); 129 | 130 | // Strip any lines consisting only of spaces and tabs. 131 | // This makes subsequent regexen easier to write, because we can 132 | // match consecutive blank lines with /\n+/ instead of something 133 | // contorted like /[ \t]*\n+/ . 134 | text = text.replace(/^[ \t]+$/mg,""); 135 | 136 | // Turn block-level HTML blocks into hash entries 137 | text = _HashHTMLBlocks(text); 138 | 139 | // Strip link definitions, store in hashes. 140 | text = _StripLinkDefinitions(text); 141 | 142 | text = _RunBlockGamut(text); 143 | 144 | text = _UnescapeSpecialChars(text); 145 | 146 | // attacklab: Restore dollar signs 147 | text = text.replace(/~D/g,"$$"); 148 | 149 | // attacklab: Restore tildes 150 | text = text.replace(/~T/g,"~"); 151 | 152 | return text; 153 | } 154 | 155 | var _StripLinkDefinitions = function(text) { 156 | // 157 | // Strips link definitions from text, stores the URLs and titles in 158 | // hash references. 159 | // 160 | 161 | // Link defs are in the form: ^[id]: url "optional title" 162 | 163 | /* 164 | var text = text.replace(/ 165 | ^[ ]{0,3}\[(.+)\]: // id = $1 attacklab: g_tab_width - 1 166 | [ \t]* 167 | \n? // maybe *one* newline 168 | [ \t]* 169 | ? // url = $2 170 | [ \t]* 171 | \n? // maybe one newline 172 | [ \t]* 173 | (?: 174 | (\n*) // any lines skipped = $3 attacklab: lookbehind removed 175 | ["(] 176 | (.+?) // title = $4 177 | [")] 178 | [ \t]* 179 | )? // title is optional 180 | (?:\n+|$) 181 | /gm, 182 | function(){...}); 183 | */ 184 | var text = text.replace(/^[ ]{0,3}\[(.+)\]:[ \t]*\n?[ \t]*?[ \t]*\n?[ \t]*(?:(\n*)["(](.+?)[")][ \t]*)?(?:\n+)/gm, 185 | function (wholeMatch,m1,m2,m3,m4) { 186 | m1 = m1.toLowerCase(); 187 | g_urls[m1] = _EncodeAmpsAndAngles(m2); // Link IDs are case-insensitive 188 | if (m3) { 189 | // Oops, found blank lines, so it's not a title. 190 | // Put back the parenthetical statement we stole. 191 | return m3+m4; 192 | } else if (m4) { 193 | g_titles[m1] = m4.replace(/"/g,"""); 194 | } 195 | 196 | // Completely remove the definition from the text 197 | return ""; 198 | } 199 | ); 200 | 201 | return text; 202 | } 203 | 204 | var _HashHTMLBlocks = function(text) { 205 | // attacklab: Double up blank lines to reduce lookaround 206 | text = text.replace(/\n/g,"\n\n"); 207 | 208 | // Hashify HTML blocks: 209 | // We only want to do this for block-level HTML tags, such as headers, 210 | // lists, and tables. That's because we still want to wrap

    s around 211 | // "paragraphs" that are wrapped in non-block-level tags, such as anchors, 212 | // phrase emphasis, and spans. The list of tags we're looking for is 213 | // hard-coded: 214 | var block_tags_a = "p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math|ins|del" 215 | var block_tags_b = "p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math" 216 | 217 | // First, look for nested blocks, e.g.: 218 | //

    219 | //
    220 | // tags for inner block must be indented. 221 | //
    222 | //
    223 | // 224 | // The outermost tags must start at the left margin for this to match, and 225 | // the inner nested divs must be indented. 226 | // We need to do this before the next, more liberal match, because the next 227 | // match will start at the first `
    ` and stop at the first `
    `. 228 | 229 | // attacklab: This regex can be expensive when it fails. 230 | /* 231 | var text = text.replace(/ 232 | ( // save in $1 233 | ^ // start of line (with /m) 234 | <($block_tags_a) // start tag = $2 235 | \b // word break 236 | // attacklab: hack around khtml/pcre bug... 237 | [^\r]*?\n // any number of lines, minimally matching 238 | // the matching end tag 239 | [ \t]* // trailing spaces/tabs 240 | (?=\n+) // followed by a newline 241 | ) // attacklab: there are sentinel newlines at end of document 242 | /gm,function(){...}}; 243 | */ 244 | text = text.replace(/^(<(p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math|ins|del)\b[^\r]*?\n<\/\2>[ \t]*(?=\n+))/gm,hashElement); 245 | 246 | // 247 | // Now match more liberally, simply from `\n` to `\n` 248 | // 249 | 250 | /* 251 | var text = text.replace(/ 252 | ( // save in $1 253 | ^ // start of line (with /m) 254 | <($block_tags_b) // start tag = $2 255 | \b // word break 256 | // attacklab: hack around khtml/pcre bug... 257 | [^\r]*? // any number of lines, minimally matching 258 | .* // the matching end tag 259 | [ \t]* // trailing spaces/tabs 260 | (?=\n+) // followed by a newline 261 | ) // attacklab: there are sentinel newlines at end of document 262 | /gm,function(){...}}; 263 | */ 264 | text = text.replace(/^(<(p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math)\b[^\r]*?.*<\/\2>[ \t]*(?=\n+)\n)/gm,hashElement); 265 | 266 | // Special case just for
    . It was easier to make a special case than 267 | // to make the other regex more complicated. 268 | 269 | /* 270 | text = text.replace(/ 271 | ( // save in $1 272 | \n\n // Starting after a blank line 273 | [ ]{0,3} 274 | (<(hr) // start tag = $2 275 | \b // word break 276 | ([^<>])*? // 277 | \/?>) // the matching end tag 278 | [ \t]* 279 | (?=\n{2,}) // followed by a blank line 280 | ) 281 | /g,hashElement); 282 | */ 283 | text = text.replace(/(\n[ ]{0,3}(<(hr)\b([^<>])*?\/?>)[ \t]*(?=\n{2,}))/g,hashElement); 284 | 285 | // Special case for standalone HTML comments: 286 | 287 | /* 288 | text = text.replace(/ 289 | ( // save in $1 290 | \n\n // Starting after a blank line 291 | [ ]{0,3} // attacklab: g_tab_width - 1 292 | 295 | [ \t]* 296 | (?=\n{2,}) // followed by a blank line 297 | ) 298 | /g,hashElement); 299 | */ 300 | text = text.replace(/(\n\n[ ]{0,3}[ \t]*(?=\n{2,}))/g,hashElement); 301 | 302 | // PHP and ASP-style processor instructions ( and <%...%>) 303 | 304 | /* 305 | text = text.replace(/ 306 | (?: 307 | \n\n // Starting after a blank line 308 | ) 309 | ( // save in $1 310 | [ ]{0,3} // attacklab: g_tab_width - 1 311 | (?: 312 | <([?%]) // $2 313 | [^\r]*? 314 | \2> 315 | ) 316 | [ \t]* 317 | (?=\n{2,}) // followed by a blank line 318 | ) 319 | /g,hashElement); 320 | */ 321 | text = text.replace(/(?:\n\n)([ ]{0,3}(?:<([?%])[^\r]*?\2>)[ \t]*(?=\n{2,}))/g,hashElement); 322 | 323 | // attacklab: Undo double lines (see comment at top of this function) 324 | text = text.replace(/\n\n/g,"\n"); 325 | return text; 326 | } 327 | 328 | var hashElement = function(wholeMatch,m1) { 329 | var blockText = m1; 330 | 331 | // Undo double lines 332 | blockText = blockText.replace(/\n\n/g,"\n"); 333 | blockText = blockText.replace(/^\n/,""); 334 | 335 | // strip trailing blank lines 336 | blockText = blockText.replace(/\n+$/g,""); 337 | 338 | // Replace the element text with a marker ("~KxK" where x is its key) 339 | blockText = "\n\n~K" + (g_html_blocks.push(blockText)-1) + "K\n\n"; 340 | 341 | return blockText; 342 | }; 343 | 344 | var _RunBlockGamut = function(text) { 345 | // 346 | // These are all the transformations that form block-level 347 | // tags like paragraphs, headers, and list items. 348 | // 349 | text = _DoHeaders(text); 350 | 351 | // Do Horizontal Rules: 352 | var key = hashBlock("
    "); 353 | text = text.replace(/^[ ]{0,2}([ ]?\*[ ]?){3,}[ \t]*$/gm,key); 354 | text = text.replace(/^[ ]{0,2}([ ]?-[ ]?){3,}[ \t]*$/gm,key); 355 | text = text.replace(/^[ ]{0,2}([ ]?_[ ]?){3,}[ \t]*$/gm,key); 356 | 357 | text = _DoLists(text); 358 | text = _DoCodeBlocks(text); 359 | text = _DoBlockQuotes(text); 360 | 361 | // We already ran _HashHTMLBlocks() before, in Markdown(), but that 362 | // was to escape raw HTML in the original Markdown source. This time, 363 | // we're escaping the markup we've just created, so that we don't wrap 364 | //

    tags around block-level tags. 365 | text = _HashHTMLBlocks(text); 366 | text = _FormParagraphs(text); 367 | 368 | return text; 369 | } 370 | 371 | 372 | var _RunSpanGamut = function(text) { 373 | // 374 | // These are all the transformations that occur *within* block-level 375 | // tags like paragraphs, headers, and list items. 376 | // 377 | 378 | text = _DoCodeSpans(text); 379 | text = _EscapeSpecialCharsWithinTagAttributes(text); 380 | text = _EncodeBackslashEscapes(text); 381 | 382 | // Process anchor and image tags. Images must come first, 383 | // because ![foo][f] looks like an anchor. 384 | text = _DoImages(text); 385 | text = _DoAnchors(text); 386 | 387 | // Make links out of things like `` 388 | // Must come after _DoAnchors(), because you can use < and > 389 | // delimiters in inline links like [this](). 390 | text = _DoAutoLinks(text); 391 | text = _EncodeAmpsAndAngles(text); 392 | text = _DoItalicsAndBold(text); 393 | 394 | // Do hard breaks: 395 | text = text.replace(/ +\n/g,"
    \n"); 396 | 397 | return text; 398 | } 399 | 400 | var _EscapeSpecialCharsWithinTagAttributes = function(text) { 401 | // 402 | // Within tags -- meaning between < and > -- encode [\ ` * _] so they 403 | // don't conflict with their use in Markdown for code, italics and strong. 404 | // 405 | 406 | // Build a regex to find HTML tags and comments. See Friedl's 407 | // "Mastering Regular Expressions", 2nd Ed., pp. 200-201. 408 | var regex = /(<[a-z\/!$]("[^"]*"|'[^']*'|[^'">])*>|)/gi; 409 | 410 | text = text.replace(regex, function(wholeMatch) { 411 | var tag = wholeMatch.replace(/(.)<\/?code>(?=.)/g,"$1`"); 412 | tag = escapeCharacters(tag,"\\`*_"); 413 | return tag; 414 | }); 415 | 416 | return text; 417 | } 418 | 419 | var _DoAnchors = function(text) { 420 | // 421 | // Turn Markdown link shortcuts into XHTML
    tags. 422 | // 423 | // 424 | // First, handle reference-style links: [link text] [id] 425 | // 426 | 427 | /* 428 | text = text.replace(/ 429 | ( // wrap whole match in $1 430 | \[ 431 | ( 432 | (?: 433 | \[[^\]]*\] // allow brackets nested one level 434 | | 435 | [^\[] // or anything else 436 | )* 437 | ) 438 | \] 439 | 440 | [ ]? // one optional space 441 | (?:\n[ ]*)? // one optional newline followed by spaces 442 | 443 | \[ 444 | (.*?) // id = $3 445 | \] 446 | )()()()() // pad remaining backreferences 447 | /g,_DoAnchors_callback); 448 | */ 449 | text = text.replace(/(\[((?:\[[^\]]*\]|[^\[\]])*)\][ ]?(?:\n[ ]*)?\[(.*?)\])()()()()/g,writeAnchorTag); 450 | 451 | // 452 | // Next, inline-style links: [link text](url "optional title") 453 | // 454 | 455 | /* 456 | text = text.replace(/ 457 | ( // wrap whole match in $1 458 | \[ 459 | ( 460 | (?: 461 | \[[^\]]*\] // allow brackets nested one level 462 | | 463 | [^\[\]] // or anything else 464 | ) 465 | ) 466 | \] 467 | \( // literal paren 468 | [ \t]* 469 | () // no id, so leave $3 empty 470 | ? // href = $4 471 | [ \t]* 472 | ( // $5 473 | (['"]) // quote char = $6 474 | (.*?) // Title = $7 475 | \6 // matching quote 476 | [ \t]* // ignore any spaces/tabs between closing quote and ) 477 | )? // title is optional 478 | \) 479 | ) 480 | /g,writeAnchorTag); 481 | */ 482 | text = text.replace(/(\[((?:\[[^\]]*\]|[^\[\]])*)\]\([ \t]*()?[ \t]*((['"])(.*?)\6[ \t]*)?\))/g,writeAnchorTag); 483 | 484 | // 485 | // Last, handle reference-style shortcuts: [link text] 486 | // These must come last in case you've also got [link test][1] 487 | // or [link test](/foo) 488 | // 489 | 490 | /* 491 | text = text.replace(/ 492 | ( // wrap whole match in $1 493 | \[ 494 | ([^\[\]]+) // link text = $2; can't contain '[' or ']' 495 | \] 496 | )()()()()() // pad rest of backreferences 497 | /g, writeAnchorTag); 498 | */ 499 | text = text.replace(/(\[([^\[\]]+)\])()()()()()/g, writeAnchorTag); 500 | 501 | return text; 502 | } 503 | 504 | var writeAnchorTag = function(wholeMatch,m1,m2,m3,m4,m5,m6,m7) { 505 | if (m7 == undefined) m7 = ""; 506 | var whole_match = m1; 507 | var link_text = m2; 508 | var link_id = m3.toLowerCase(); 509 | var url = m4; 510 | var title = m7; 511 | 512 | if (url == "") { 513 | if (link_id == "") { 514 | // lower-case and turn embedded newlines into spaces 515 | link_id = link_text.toLowerCase().replace(/ ?\n/g," "); 516 | } 517 | url = "#"+link_id; 518 | 519 | if (g_urls[link_id] != undefined) { 520 | url = g_urls[link_id]; 521 | if (g_titles[link_id] != undefined) { 522 | title = g_titles[link_id]; 523 | } 524 | } 525 | else { 526 | if (whole_match.search(/\(\s*\)$/m)>-1) { 527 | // Special case for explicit empty url 528 | url = ""; 529 | } else { 530 | return whole_match; 531 | } 532 | } 533 | } 534 | 535 | url = escapeCharacters(url,"*_"); 536 | var result = ""; 545 | 546 | return result; 547 | } 548 | 549 | 550 | var _DoImages = function(text) { 551 | // 552 | // Turn Markdown image shortcuts into tags. 553 | // 554 | 555 | // 556 | // First, handle reference-style labeled images: ![alt text][id] 557 | // 558 | 559 | /* 560 | text = text.replace(/ 561 | ( // wrap whole match in $1 562 | !\[ 563 | (.*?) // alt text = $2 564 | \] 565 | 566 | [ ]? // one optional space 567 | (?:\n[ ]*)? // one optional newline followed by spaces 568 | 569 | \[ 570 | (.*?) // id = $3 571 | \] 572 | )()()()() // pad rest of backreferences 573 | /g,writeImageTag); 574 | */ 575 | text = text.replace(/(!\[(.*?)\][ ]?(?:\n[ ]*)?\[(.*?)\])()()()()/g,writeImageTag); 576 | 577 | // 578 | // Next, handle inline images: ![alt text](url "optional title") 579 | // Don't forget: encode * and _ 580 | 581 | /* 582 | text = text.replace(/ 583 | ( // wrap whole match in $1 584 | !\[ 585 | (.*?) // alt text = $2 586 | \] 587 | \s? // One optional whitespace character 588 | \( // literal paren 589 | [ \t]* 590 | () // no id, so leave $3 empty 591 | ? // src url = $4 592 | [ \t]* 593 | ( // $5 594 | (['"]) // quote char = $6 595 | (.*?) // title = $7 596 | \6 // matching quote 597 | [ \t]* 598 | )? // title is optional 599 | \) 600 | ) 601 | /g,writeImageTag); 602 | */ 603 | text = text.replace(/(!\[(.*?)\]\s?\([ \t]*()?[ \t]*((['"])(.*?)\6[ \t]*)?\))/g,writeImageTag); 604 | 605 | return text; 606 | } 607 | 608 | var writeImageTag = function(wholeMatch,m1,m2,m3,m4,m5,m6,m7) { 609 | var whole_match = m1; 610 | var alt_text = m2; 611 | var link_id = m3.toLowerCase(); 612 | var url = m4; 613 | var title = m7; 614 | 615 | if (!title) title = ""; 616 | 617 | if (url == "") { 618 | if (link_id == "") { 619 | // lower-case and turn embedded newlines into spaces 620 | link_id = alt_text.toLowerCase().replace(/ ?\n/g," "); 621 | } 622 | url = "#"+link_id; 623 | 624 | if (g_urls[link_id] != undefined) { 625 | url = g_urls[link_id]; 626 | if (g_titles[link_id] != undefined) { 627 | title = g_titles[link_id]; 628 | } 629 | } 630 | else { 631 | return whole_match; 632 | } 633 | } 634 | 635 | alt_text = alt_text.replace(/"/g,"""); 636 | url = escapeCharacters(url,"*_"); 637 | var result = "\""" + _RunSpanGamut(m1) + "");}); 665 | 666 | text = text.replace(/^(.+)[ \t]*\n-+[ \t]*\n+/gm, 667 | function(matchFound,m1){return hashBlock("

    " + _RunSpanGamut(m1) + "

    ");}); 668 | 669 | // atx-style headers: 670 | // # Header 1 671 | // ## Header 2 672 | // ## Header 2 with closing hashes ## 673 | // ... 674 | // ###### Header 6 675 | // 676 | 677 | /* 678 | text = text.replace(/ 679 | ^(\#{1,6}) // $1 = string of #'s 680 | [ \t]* 681 | (.+?) // $2 = Header text 682 | [ \t]* 683 | \#* // optional closing #'s (not counted) 684 | \n+ 685 | /gm, function() {...}); 686 | */ 687 | 688 | text = text.replace(/^(\#{1,6})[ \t]*(.+?)[ \t]*\#*\n+/gm, 689 | function(wholeMatch,m1,m2) { 690 | var h_level = m1.length; 691 | return hashBlock("" + _RunSpanGamut(m2) + ""); 692 | }); 693 | 694 | return text; 695 | } 696 | 697 | // This declaration keeps Dojo compressor from outputting garbage: 698 | var _ProcessListItems; 699 | 700 | var _DoLists = function(text) { 701 | // 702 | // Form HTML ordered (numbered) and unordered (bulleted) lists. 703 | // 704 | 705 | // attacklab: add sentinel to hack around khtml/safari bug: 706 | // http://bugs.webkit.org/show_bug.cgi?id=11231 707 | text += "~0"; 708 | 709 | // Re-usable pattern to match any entirel ul or ol list: 710 | 711 | /* 712 | var whole_list = / 713 | ( // $1 = whole list 714 | ( // $2 715 | [ ]{0,3} // attacklab: g_tab_width - 1 716 | ([*+-]|\d+[.]) // $3 = first list item marker 717 | [ \t]+ 718 | ) 719 | [^\r]+? 720 | ( // $4 721 | ~0 // sentinel for workaround; should be $ 722 | | 723 | \n{2,} 724 | (?=\S) 725 | (?! // Negative lookahead for another list item marker 726 | [ \t]* 727 | (?:[*+-]|\d+[.])[ \t]+ 728 | ) 729 | ) 730 | )/g 731 | */ 732 | var whole_list = /^(([ ]{0,3}([*+-]|\d+[.])[ \t]+)[^\r]+?(~0|\n{2,}(?=\S)(?![ \t]*(?:[*+-]|\d+[.])[ \t]+)))/gm; 733 | 734 | if (g_list_level) { 735 | text = text.replace(whole_list,function(wholeMatch,m1,m2) { 736 | var list = m1; 737 | var list_type = (m2.search(/[*+-]/g)>-1) ? "ul" : "ol"; 738 | 739 | // Turn double returns into triple returns, so that we can make a 740 | // paragraph for the last item in a list, if necessary: 741 | list = list.replace(/\n{2,}/g,"\n\n\n");; 742 | var result = _ProcessListItems(list); 743 | 744 | // Trim any trailing whitespace, to put the closing `` 745 | // up on the preceding line, to get it past the current stupid 746 | // HTML block parser. This is a hack to work around the terrible 747 | // hack that is the HTML block parser. 748 | result = result.replace(/\s+$/,""); 749 | result = "<"+list_type+">" + result + "\n"; 750 | return result; 751 | }); 752 | } else { 753 | whole_list = /(\n\n|^\n?)(([ ]{0,3}([*+-]|\d+[.])[ \t]+)[^\r]+?(~0|\n{2,}(?=\S)(?![ \t]*(?:[*+-]|\d+[.])[ \t]+)))/g; 754 | text = text.replace(whole_list,function(wholeMatch,m1,m2,m3) { 755 | var runup = m1; 756 | var list = m2; 757 | 758 | var list_type = (m3.search(/[*+-]/g)>-1) ? "ul" : "ol"; 759 | // Turn double returns into triple returns, so that we can make a 760 | // paragraph for the last item in a list, if necessary: 761 | var list = list.replace(/\n{2,}/g,"\n\n\n");; 762 | var result = _ProcessListItems(list); 763 | result = runup + "<"+list_type+">\n" + result + "\n"; 764 | return result; 765 | }); 766 | } 767 | 768 | // attacklab: strip sentinel 769 | text = text.replace(/~0/,""); 770 | 771 | return text; 772 | } 773 | 774 | _ProcessListItems = function(list_str) { 775 | // 776 | // Process the contents of a single ordered or unordered list, splitting it 777 | // into individual list items. 778 | // 779 | // The $g_list_level global keeps track of when we're inside a list. 780 | // Each time we enter a list, we increment it; when we leave a list, 781 | // we decrement. If it's zero, we're not in a list anymore. 782 | // 783 | // We do this because when we're not inside a list, we want to treat 784 | // something like this: 785 | // 786 | // I recommend upgrading to version 787 | // 8. Oops, now this line is treated 788 | // as a sub-list. 789 | // 790 | // As a single paragraph, despite the fact that the second line starts 791 | // with a digit-period-space sequence. 792 | // 793 | // Whereas when we're inside a list (or sub-list), that line will be 794 | // treated as the start of a sub-list. What a kludge, huh? This is 795 | // an aspect of Markdown's syntax that's hard to parse perfectly 796 | // without resorting to mind-reading. Perhaps the solution is to 797 | // change the syntax rules such that sub-lists must start with a 798 | // starting cardinal number; e.g. "1." or "a.". 799 | 800 | g_list_level++; 801 | 802 | // trim trailing blank lines: 803 | list_str = list_str.replace(/\n{2,}$/,"\n"); 804 | 805 | // attacklab: add sentinel to emulate \z 806 | list_str += "~0"; 807 | 808 | /* 809 | list_str = list_str.replace(/ 810 | (\n)? // leading line = $1 811 | (^[ \t]*) // leading whitespace = $2 812 | ([*+-]|\d+[.]) [ \t]+ // list marker = $3 813 | ([^\r]+? // list item text = $4 814 | (\n{1,2})) 815 | (?= \n* (~0 | \2 ([*+-]|\d+[.]) [ \t]+)) 816 | /gm, function(){...}); 817 | */ 818 | list_str = list_str.replace(/(\n)?(^[ \t]*)([*+-]|\d+[.])[ \t]+([^\r]+?(\n{1,2}))(?=\n*(~0|\2([*+-]|\d+[.])[ \t]+))/gm, 819 | function(wholeMatch,m1,m2,m3,m4){ 820 | var item = m4; 821 | var leading_line = m1; 822 | var leading_space = m2; 823 | 824 | if (leading_line || (item.search(/\n{2,}/)>-1)) { 825 | item = _RunBlockGamut(_Outdent(item)); 826 | } 827 | else { 828 | // Recursion for sub-lists: 829 | item = _DoLists(_Outdent(item)); 830 | item = item.replace(/\n$/,""); // chomp(item) 831 | item = _RunSpanGamut(item); 832 | } 833 | 834 | return "
  • " + item + "
  • \n"; 835 | } 836 | ); 837 | 838 | // attacklab: strip sentinel 839 | list_str = list_str.replace(/~0/g,""); 840 | 841 | g_list_level--; 842 | return list_str; 843 | } 844 | 845 | 846 | var _DoCodeBlocks = function(text) { 847 | // 848 | // Process Markdown `
    ` blocks.
     849 | //  
     850 | 
     851 | 	/*
     852 | 		text = text.replace(text,
     853 | 			/(?:\n\n|^)
     854 | 			(								// $1 = the code block -- one or more lines, starting with a space/tab
     855 | 				(?:
     856 | 					(?:[ ]{4}|\t)			// Lines must start with a tab or a tab-width of spaces - attacklab: g_tab_width
     857 | 					.*\n+
     858 | 				)+
     859 | 			)
     860 | 			(\n*[ ]{0,3}[^ \t\n]|(?=~0))	// attacklab: g_tab_width
     861 | 		/g,function(){...});
     862 | 	*/
     863 | 
     864 | 	// attacklab: sentinel workarounds for lack of \A and \Z, safari\khtml bug
     865 | 	text += "~0";
     866 | 	
     867 | 	text = text.replace(/(?:\n\n|^)((?:(?:[ ]{4}|\t).*\n+)+)(\n*[ ]{0,3}[^ \t\n]|(?=~0))/g,
     868 | 		function(wholeMatch,m1,m2) {
     869 | 			var codeblock = m1;
     870 | 			var nextChar = m2;
     871 | 		
     872 | 			codeblock = _EncodeCode( _Outdent(codeblock));
     873 | 			codeblock = _Detab(codeblock);
     874 | 			codeblock = codeblock.replace(/^\n+/g,""); // trim leading newlines
     875 | 			codeblock = codeblock.replace(/\n+$/g,""); // trim trailing whitespace
     876 | 
     877 | 			codeblock = "
    " + codeblock + "\n
    "; 878 | 879 | return hashBlock(codeblock) + nextChar; 880 | } 881 | ); 882 | 883 | // attacklab: strip sentinel 884 | text = text.replace(/~0/,""); 885 | 886 | return text; 887 | } 888 | 889 | var hashBlock = function(text) { 890 | text = text.replace(/(^\n+|\n+$)/g,""); 891 | return "\n\n~K" + (g_html_blocks.push(text)-1) + "K\n\n"; 892 | } 893 | 894 | 895 | var _DoCodeSpans = function(text) { 896 | // 897 | // * Backtick quotes are used for spans. 898 | // 899 | // * You can use multiple backticks as the delimiters if you want to 900 | // include literal backticks in the code span. So, this input: 901 | // 902 | // Just type ``foo `bar` baz`` at the prompt. 903 | // 904 | // Will translate to: 905 | // 906 | //

    Just type foo `bar` baz at the prompt.

    907 | // 908 | // There's no arbitrary limit to the number of backticks you 909 | // can use as delimters. If you need three consecutive backticks 910 | // in your code, use four for delimiters, etc. 911 | // 912 | // * You can use spaces to get literal backticks at the edges: 913 | // 914 | // ... type `` `bar` `` ... 915 | // 916 | // Turns to: 917 | // 918 | // ... type `bar` ... 919 | // 920 | 921 | /* 922 | text = text.replace(/ 923 | (^|[^\\]) // Character before opening ` can't be a backslash 924 | (`+) // $2 = Opening run of ` 925 | ( // $3 = The code block 926 | [^\r]*? 927 | [^`] // attacklab: work around lack of lookbehind 928 | ) 929 | \2 // Matching closer 930 | (?!`) 931 | /gm, function(){...}); 932 | */ 933 | 934 | text = text.replace(/(^|[^\\])(`+)([^\r]*?[^`])\2(?!`)/gm, 935 | function(wholeMatch,m1,m2,m3,m4) { 936 | var c = m3; 937 | c = c.replace(/^([ \t]*)/g,""); // leading whitespace 938 | c = c.replace(/[ \t]*$/g,""); // trailing whitespace 939 | c = _EncodeCode(c); 940 | return m1+""+c+""; 941 | }); 942 | 943 | return text; 944 | } 945 | 946 | 947 | var _EncodeCode = function(text) { 948 | // 949 | // Encode/escape certain characters inside Markdown code runs. 950 | // The point is that in code, these characters are literals, 951 | // and lose their special Markdown meanings. 952 | // 953 | // Encode all ampersands; HTML entities are not 954 | // entities within a Markdown code span. 955 | text = text.replace(/&/g,"&"); 956 | 957 | // Do the angle bracket song and dance: 958 | text = text.replace(//g,">"); 960 | 961 | // Now, escape characters that are magic in Markdown: 962 | text = escapeCharacters(text,"\*_{}[]\\",false); 963 | 964 | // jj the line above breaks this: 965 | //--- 966 | 967 | //* Item 968 | 969 | // 1. Subitem 970 | 971 | // special char: * 972 | //--- 973 | 974 | return text; 975 | } 976 | 977 | 978 | var _DoItalicsAndBold = function(text) { 979 | 980 | // must go first: 981 | text = text.replace(/(\*\*|__)(?=\S)([^\r]*?\S[\*_]*)\1/g, 982 | "$2"); 983 | 984 | text = text.replace(/(\*|_)(?=\S)([^\r]*?\S)\1/g, 985 | "$2"); 986 | 987 | return text; 988 | } 989 | 990 | 991 | var _DoBlockQuotes = function(text) { 992 | 993 | /* 994 | text = text.replace(/ 995 | ( // Wrap whole match in $1 996 | ( 997 | ^[ \t]*>[ \t]? // '>' at the start of a line 998 | .+\n // rest of the first line 999 | (.+\n)* // subsequent consecutive lines 1000 | \n* // blanks 1001 | )+ 1002 | ) 1003 | /gm, function(){...}); 1004 | */ 1005 | 1006 | text = text.replace(/((^[ \t]*>[ \t]?.+\n(.+\n)*\n*)+)/gm, 1007 | function(wholeMatch,m1) { 1008 | var bq = m1; 1009 | 1010 | // attacklab: hack around Konqueror 3.5.4 bug: 1011 | // "----------bug".replace(/^-/g,"") == "bug" 1012 | 1013 | bq = bq.replace(/^[ \t]*>[ \t]?/gm,"~0"); // trim one level of quoting 1014 | 1015 | // attacklab: clean up hack 1016 | bq = bq.replace(/~0/g,""); 1017 | 1018 | bq = bq.replace(/^[ \t]+$/gm,""); // trim whitespace-only lines 1019 | bq = _RunBlockGamut(bq); // recurse 1020 | 1021 | bq = bq.replace(/(^|\n)/g,"$1 "); 1022 | // These leading spaces screw with
     content, so we need to fix that:
    1023 | 			bq = bq.replace(
    1024 | 					/(\s*
    [^\r]+?<\/pre>)/gm,
    1025 | 				function(wholeMatch,m1) {
    1026 | 					var pre = m1;
    1027 | 					// attacklab: hack around Konqueror 3.5.4 bug:
    1028 | 					pre = pre.replace(/^  /mg,"~0");
    1029 | 					pre = pre.replace(/~0/g,"");
    1030 | 					return pre;
    1031 | 				});
    1032 | 			
    1033 | 			return hashBlock("
    \n" + bq + "\n
    "); 1034 | }); 1035 | return text; 1036 | } 1037 | 1038 | 1039 | var _FormParagraphs = function(text) { 1040 | // 1041 | // Params: 1042 | // $text - string to process with html

    tags 1043 | // 1044 | 1045 | // Strip leading and trailing lines: 1046 | text = text.replace(/^\n+/g,""); 1047 | text = text.replace(/\n+$/g,""); 1048 | 1049 | var grafs = text.split(/\n{2,}/g); 1050 | var grafsOut = new Array(); 1051 | 1052 | // 1053 | // Wrap

    tags. 1054 | // 1055 | var end = grafs.length; 1056 | for (var i=0; i= 0) { 1061 | grafsOut.push(str); 1062 | } 1063 | else if (str.search(/\S/) >= 0) { 1064 | str = _RunSpanGamut(str); 1065 | str = str.replace(/^([ \t]*)/g,"

    "); 1066 | str += "

    " 1067 | grafsOut.push(str); 1068 | } 1069 | 1070 | } 1071 | 1072 | // 1073 | // Unhashify HTML blocks 1074 | // 1075 | end = grafsOut.length; 1076 | for (var i=0; i= 0) { 1079 | var blockText = g_html_blocks[RegExp.$1]; 1080 | blockText = blockText.replace(/\$/g,"$$$$"); // Escape any dollar signs 1081 | grafsOut[i] = grafsOut[i].replace(/~K\d+K/,blockText); 1082 | } 1083 | } 1084 | 1085 | return grafsOut.join("\n\n"); 1086 | } 1087 | 1088 | 1089 | var _EncodeAmpsAndAngles = function(text) { 1090 | // Smart processing for ampersands and angle brackets that need to be encoded. 1091 | 1092 | // Ampersand-encoding based entirely on Nat Irons's Amputator MT plugin: 1093 | // http://bumppo.net/projects/amputator/ 1094 | text = text.replace(/&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)/g,"&"); 1095 | 1096 | // Encode naked <'s 1097 | text = text.replace(/<(?![a-z\/?\$!])/gi,"<"); 1098 | 1099 | return text; 1100 | } 1101 | 1102 | 1103 | var _EncodeBackslashEscapes = function(text) { 1104 | // 1105 | // Parameter: String. 1106 | // Returns: The string, with after processing the following backslash 1107 | // escape sequences. 1108 | // 1109 | 1110 | // attacklab: The polite way to do this is with the new 1111 | // escapeCharacters() function: 1112 | // 1113 | // text = escapeCharacters(text,"\\",true); 1114 | // text = escapeCharacters(text,"`*_{}[]()>#+-.!",true); 1115 | // 1116 | // ...but we're sidestepping its use of the (slow) RegExp constructor 1117 | // as an optimization for Firefox. This function gets called a LOT. 1118 | 1119 | text = text.replace(/\\(\\)/g,escapeCharacters_callback); 1120 | text = text.replace(/\\([`*_{}\[\]()>#+-.!])/g,escapeCharacters_callback); 1121 | return text; 1122 | } 1123 | 1124 | 1125 | var _DoAutoLinks = function(text) { 1126 | 1127 | text = text.replace(/<((https?|ftp|dict):[^'">\s]+)>/gi,"
    $1"); 1128 | 1129 | // Email addresses: 1130 | 1131 | /* 1132 | text = text.replace(/ 1133 | < 1134 | (?:mailto:)? 1135 | ( 1136 | [-.\w]+ 1137 | \@ 1138 | [-a-z0-9]+(\.[-a-z0-9]+)*\.[a-z]+ 1139 | ) 1140 | > 1141 | /gi, _DoAutoLinks_callback()); 1142 | */ 1143 | text = text.replace(/<(?:mailto:)?([-.\w]+\@[-a-z0-9]+(\.[-a-z0-9]+)*\.[a-z]+)>/gi, 1144 | function(wholeMatch,m1) { 1145 | return _EncodeEmailAddress( _UnescapeSpecialChars(m1) ); 1146 | } 1147 | ); 1148 | 1149 | return text; 1150 | } 1151 | 1152 | 1153 | var _EncodeEmailAddress = function(addr) { 1154 | // 1155 | // Input: an email address, e.g. "foo@example.com" 1156 | // 1157 | // Output: the email address as a mailto link, with each character 1158 | // of the address encoded as either a decimal or hex entity, in 1159 | // the hopes of foiling most address harvesting spam bots. E.g.: 1160 | // 1161 | // foo 1163 | // @example.com 1164 | // 1165 | // Based on a filter by Matthew Wickline, posted to the BBEdit-Talk 1166 | // mailing list: 1167 | // 1168 | 1169 | // attacklab: why can't javascript speak hex? 1170 | function char2hex(ch) { 1171 | var hexDigits = '0123456789ABCDEF'; 1172 | var dec = ch.charCodeAt(0); 1173 | return(hexDigits.charAt(dec>>4) + hexDigits.charAt(dec&15)); 1174 | } 1175 | 1176 | var encode = [ 1177 | function(ch){return "&#"+ch.charCodeAt(0)+";";}, 1178 | function(ch){return "&#x"+char2hex(ch)+";";}, 1179 | function(ch){return ch;} 1180 | ]; 1181 | 1182 | addr = "mailto:" + addr; 1183 | 1184 | addr = addr.replace(/./g, function(ch) { 1185 | if (ch == "@") { 1186 | // this *must* be encoded. I insist. 1187 | ch = encode[Math.floor(Math.random()*2)](ch); 1188 | } else if (ch !=":") { 1189 | // leave ':' alone (to spot mailto: later) 1190 | var r = Math.random(); 1191 | // roughly 10% raw, 45% hex, 45% dec 1192 | ch = ( 1193 | r > .9 ? encode[2](ch) : 1194 | r > .45 ? encode[1](ch) : 1195 | encode[0](ch) 1196 | ); 1197 | } 1198 | return ch; 1199 | }); 1200 | 1201 | addr = "" + addr + ""; 1202 | addr = addr.replace(/">.+:/g,"\">"); // strip the mailto: from the visible part 1203 | 1204 | return addr; 1205 | } 1206 | 1207 | 1208 | var _UnescapeSpecialChars = function(text) { 1209 | // 1210 | // Swap back in all the special characters we've hidden. 1211 | // 1212 | text = text.replace(/~E(\d+)E/g, 1213 | function(wholeMatch,m1) { 1214 | var charCodeToReplace = parseInt(m1); 1215 | return String.fromCharCode(charCodeToReplace); 1216 | } 1217 | ); 1218 | return text; 1219 | } 1220 | 1221 | 1222 | var _Outdent = function(text) { 1223 | // 1224 | // Remove one level of line-leading tabs or spaces 1225 | // 1226 | 1227 | // attacklab: hack around Konqueror 3.5.4 bug: 1228 | // "----------bug".replace(/^-/g,"") == "bug" 1229 | 1230 | text = text.replace(/^(\t|[ ]{1,4})/gm,"~0"); // attacklab: g_tab_width 1231 | 1232 | // attacklab: clean up hack 1233 | text = text.replace(/~0/g,"") 1234 | 1235 | return text; 1236 | } 1237 | 1238 | var _Detab = function(text) { 1239 | // attacklab: Detab's completely rewritten for speed. 1240 | // In perl we could fix it by anchoring the regexp with \G. 1241 | // In javascript we're less fortunate. 1242 | 1243 | // expand first n-1 tabs 1244 | text = text.replace(/\t(?=\t)/g," "); // attacklab: g_tab_width 1245 | 1246 | // replace the nth with two sentinels 1247 | text = text.replace(/\t/g,"~A~B"); 1248 | 1249 | // use the sentinel to anchor our regex so it doesn't explode 1250 | text = text.replace(/~B(.+?)~A/g, 1251 | function(wholeMatch,m1,m2) { 1252 | var leadingText = m1; 1253 | var numSpaces = 4 - leadingText.length % 4; // attacklab: g_tab_width 1254 | 1255 | // there *must* be a better way to do this: 1256 | for (var i=0; i