shared.py 4.36 KB
Newer Older
1
from flask_sqlalchemy import SQLAlchemy
2
from flask import session, redirect, url_for, flash
3 4

import re
Robin Sonnabend's avatar
Robin Sonnabend committed
5
from functools import wraps
6
from enum import Enum
7

8
from common import back
9

10 11 12 13 14 15
try:
    import configproxy
    config, public_config = configproxy.import_config()
except ImportError as error:
    print(error)
    raise
16 17 18

db = SQLAlchemy()

19 20
# the following code escape_tex is written by Lars Beckers
# and not to be published without permission
21
latex_chars = [
22
    ("\\", "\\backslash"),  # this needs to be first
23 24 25 26 27 28 29
    ("$", "\$"),
    ('%', '\\%'),
    ('&', '\\&'),
    ('#', '\\#'),
    ('_', '\\_'),
    ('{', '\\{'),
    ('}', '\\}'),
30 31
    ('[', '\\['),
    (']', '\\]'),
32 33 34
    ('~', r'$\sim{}$'),
    ('^', r'\textasciicircum{}'),
    ('Ë„', r'\textasciicircum{}'),
35
    ('`', '{}`'),
36 37 38 39 40 41
    ('-->', r'$\longrightarrow$'),
    ('->', r'$\rightarrow$'),
    ('==>', r'$\Longrightarrow$'),
    ('=>', r'$\Rightarrow$'),
    ('>=', r'$\geq$'),
    ('=<', r'$\leq$'),
42 43 44
    ('<', '$<$'),
    ('>', '$>$'),
    ('\\backslashin', '$\\in$'),
45
    ('\\backslash', '$\\backslash$')  # this needs to be last
46 47
]

48

49 50 51 52 53 54
def escape_tex(text):
    out = text
    for old, new in latex_chars:
        out = out.replace(old, new)
    # beware, the following is carefully crafted code
    res = ''
55 56 57 58 59 60 61 62
    start, end = (0, -1)
    while start >= 0:
        start = out.find('"', end + 1)
        if start >= 0:
            res += out[end + 1:start]
            end = out.find('"', start + 1)
            if end >= 0:
                res += '\\enquote{' + out[start + 1:end] + '}'
63
            else:
64 65
                res += '"\'' + out[start + 1:]
            start = end
66
        else:
67
            res += out[end + 1:]
68 69 70 71 72
    # yes, this is not quite escaping latex chars, but anyway...
    res = re.sub('([a-z])\(', '\\1 (', res)
    res = re.sub('\)([a-z])', ') \\1', res)
    return res

73

74 75 76
def unhyphen(text):
    return " ".join([r"\mbox{" + word + "}" for word in text.split(" ")])

77

78 79
def date_filter(date):
    return date.strftime("%d. %B %Y")
80 81


82
def datetime_filter(date):
83 84
    if date is None:
        return ""
85
    return date.strftime("%d. %B %Y, %H:%M")
86 87


88
def date_filter_long(date):
89 90
    if date is None:
        return ""
91
    return date.strftime("%A, %d.%m.%Y, Kalenderwoche %W")
92 93


94
def date_filter_short(date):
95 96
    if date is None:
        return ""
97
    return date.strftime("%d.%m.%Y")
98 99


100
def time_filter(time):
101 102
    if time is None:
        return ""
103
    return time.strftime("%H:%M Uhr")
104 105


106
def time_filter_short(time):
107 108
    if time is None:
        return ""
109
    return time.strftime("%H:%M")
110

111

Robin Sonnabend's avatar
Robin Sonnabend committed
112 113
def needs_date_test(todostate):
    return todostate.needs_date()
114 115


Robin Sonnabend's avatar
Robin Sonnabend committed
116 117 118
def todostate_name_filter(todostate):
    return todostate.get_name()

119

Robin Sonnabend's avatar
Robin Sonnabend committed
120 121 122
def indent_tab_filter(text):
    return "\n".join(map(lambda l: "\t{}".format(l), text.splitlines()))

123

124 125
def class_filter(obj):
    return obj.__class__.__name__
126 127


Robin Sonnabend's avatar
Robin Sonnabend committed
128 129 130
def code_filter(text):
    return "<code>{}</code>".format(text)

131 132
def code_key_filter(text):
    return '<code class="highlight" style="color: inherit;"><span class="kr">{}</span></code>'.format(text)
133

134
from common.auth import UserManager, SecurityManager, User
135 136 137
max_duration = getattr(config, "AUTH_MAX_DURATION")
user_manager = UserManager(backends=config.AUTH_BACKENDS)
security_manager = SecurityManager(config.SECURITY_KEY, max_duration)
Robin Sonnabend's avatar
Robin Sonnabend committed
138

139

Robin Sonnabend's avatar
Robin Sonnabend committed
140
def check_login():
141
    return current_user() is not None
142 143


Robin Sonnabend's avatar
Robin Sonnabend committed
144
def current_user():
145 146 147
    if "auth" not in session:
        return None
    if not security_manager.check_user(session["auth"]):
Robin Sonnabend's avatar
Robin Sonnabend committed
148 149 150
        return None
    return User.from_hashstring(session["auth"])

151

Robin Sonnabend's avatar
Robin Sonnabend committed
152 153 154 155 156 157
def login_required(function):
    @wraps(function)
    def decorated_function(*args, **kwargs):
        if check_login():
            return function(*args, **kwargs)
        else:
158
            return redirect(url_for("login"))
Robin Sonnabend's avatar
Robin Sonnabend committed
159 160
    return decorated_function

161

162 163 164 165 166 167 168
def group_required(group):
    def decorator(function):
        @wraps(function)
        def decorated_function(*args, **kwargs):
            if group in current_user().groups:
                return function(*args, **kwargs)
            else:
169 170
                flash("You do not have the necessary permissions to "
                      "view this page.")
171
                return back.redirect()
172 173
        return decorated_function
    return decorator
Robin Sonnabend's avatar
Robin Sonnabend committed
174

175

176 177 178
DATE_KEY = "Datum"
START_TIME_KEY = "Beginn"
END_TIME_KEY = "Ende"
Robin Sonnabend's avatar
Robin Sonnabend committed
179
KNOWN_KEYS = [DATE_KEY, START_TIME_KEY, END_TIME_KEY]
180

181

182 183 184
class WikiType(Enum):
    MEDIAWIKI = 0
    DOKUWIKI = 1