]> WPIA git - motion.git/blob - motion.py
Merge branch 'finish_move' into 'master'
[motion.git] / motion.py
1 from flask import g
2 from flask import Flask
3 from flask import render_template, redirect
4 from flask import request
5 from functools import wraps
6 from flask_babel import Babel, gettext
7 import postgresql
8 import filters
9 from flaskext.markdown import Markdown
10 from markdown.extensions import Extension
11 from datetime import date, time, datetime
12 from flask_language import Language, current_language
13 import gettext
14 import click
15 import re
16
17 def get_db():
18     db = getattr(g, '_database', None)
19     if db is None:
20         db = g._database = postgresql.open(app.config.get("DATABASE"), user=app.config.get("USER"), password=app.config.get("PASSWORD"))
21     #db.row_factory = sqlite3.Row
22     return db
23
24 app = Flask(__name__)
25 app.register_blueprint(filters.blueprint)
26 babel = Babel(app)
27 lang = Language(app)
28 gettext.install('motion')
29
30 class EscapeHtml(Extension):
31     def extendMarkdown(self, md, md_globals):
32         del md.preprocessors['html_block']
33         del md.postprocessors['raw_html']
34         del md.inlinePatterns['html']
35
36 md = Markdown(app, extensions=[EscapeHtml()])
37
38 class default_settings(object):
39     COPYRIGHTSTART="2017"
40     COPYRIGHTNAME="WPIA"
41     COPYRIGHTLINK="https://wpia.club"
42     IMPRINTLINK="https://documents.wpia.club/imprint.html"
43     DATAPROTECTIONLINK="https://documents.wpia.club/data_privacy_policy_html_pages_en.html"
44     MAX_PROXY=2
45
46
47 # Load config
48 app.config.from_object('motion.default_settings')
49 app.config.from_pyfile('config.py')
50
51
52 class ConfigProxy:
53     def __init__(self, name):
54         self.name = name
55     @property
56     def per_host(self):
57         dict = app.config.get(self.name)
58         if dict is None:
59             return None
60         return dict.get(request.host)
61
62 prefix = ConfigProxy("GROUP_PREFIX")
63 times = ConfigProxy("DURATION")
64 debuguser = ConfigProxy("DEBUGUSER")
65 motion_wait_minutes = ConfigProxy("MOTION_WAIT_MINUTES")
66
67 max_proxy=app.config.get("MAX_PROXY")
68
69 @babel.localeselector
70 def get_locale():
71     return str(current_language)
72
73 @lang.allowed_languages
74 def get_allowed_languages():
75     return app.config['LANGUAGES'].keys()
76
77 @lang.default_language
78 def get_default_language():
79     return 'en'
80
81 def get_languages():
82     return app.config['LANGUAGES']
83
84 # Manually add vote options to the translation strings. They are used as keys in loops.
85 TRANSLATION_STRINGS={_('yes'), _('no'), _('abstain')}
86
87 @app.before_request
88 def lookup_user():
89     global prefix
90
91     env = request.environ
92     user = None
93     my_debuguser = debuguser.per_host
94     if my_debuguser is not None:
95         parts = my_debuguser.split("/", 1)
96         user = parts[0]
97         roles = parts[1]
98
99     if "USER_ROLES" in env:
100         parts = env.get("USER_ROLES").split("/", 1)
101         user = parts[0]
102         roles = parts[1]
103
104     if "USER" in env and "ROLES" in env:
105         user = env.get("USER")
106         roles = env.get("ROLES")
107
108     if user is None:
109         return _('Server misconfigured'), 500
110     roles = roles.split(" ")
111
112     if user == "<invalid>":
113         return _('Access denied'), 403;
114
115     db = get_db()
116     with db.xact():
117         rv = db.prepare("SELECT id FROM voter WHERE email=$1 AND host=$2")(user, request.host)
118         if len(rv) == 0:
119             db.prepare("INSERT INTO voter(\"email\", \"host\") VALUES($1, $2)")(user, request.host)
120             rv = db.prepare("SELECT id FROM voter WHERE email=$1 AND host=$2")(user, request.host)
121         g.voter = rv[0].get("id");
122         g.proxies_given = ""
123         rv = db.prepare("SELECT email, voter_id FROM voter, proxy WHERE proxy.proxy_id = voter.id AND proxy.revoked IS NULL AND proxy.voter_id = $1 ")(g.voter)
124         if len(rv) != 0:
125             g.proxies_given = rv[0].get("email")
126         rv = db.prepare("SELECT email, voter_id FROM voter, proxy WHERE proxy.voter_id = voter.id AND proxy.revoked IS NULL AND proxy.proxy_id = $1 ")(g.voter)
127         if len(rv) != 0:
128             sep = ""
129             g.proxies_received = ""
130             for x in range(0, len(rv)):
131                 g.proxies_received += sep + rv[x].get("email")
132                 sep =", "
133
134     g.user = user
135     g.roles = {}
136
137     for r in roles:
138         a = r.split(":", 1)
139         if len(r)!=0:
140             val = a[1]
141             if a[0] not in g.roles:
142                 g.roles[a[0]] = []
143             if val == "*":
144                 g.roles[a[0]] = [group for group in prefix.per_host]
145             else:
146                 g.roles[a[0]].append(val)
147
148     return None
149
150 @app.context_processor
151 def init_footer_variables():
152     if int(app.config.get("COPYRIGHTSTART"))<datetime.now().year:
153         version_year = "%s - %s" % (app.config.get("COPYRIGHTSTART"), datetime.now().year)
154     else:
155         version_year = datetime.now().year
156
157     return dict(
158         footer = dict( version_year=version_year, 
159             copyright_link=app.config.get("COPYRIGHTLINK"),
160             copyright_name=app.config.get("COPYRIGHTNAME"),
161             imprint_link=app.config.get("IMPRINTLINK"),
162             dataprotection_link=app.config.get("DATAPROTECTIONLINK")
163         )
164     )
165
166
167 def get_allowed_cats(action):
168     return g.roles.get(action, []);
169
170 def may(action, motion):
171     return motion in get_allowed_cats(action)
172
173 def may_admin(action):
174     return action in g.roles
175
176 def get_voters():
177     rv = get_db().prepare("SELECT email FROM voter WHERE host=$1")(request.host)
178     return rv
179
180 def get_all_proxies():
181     rv = get_db().prepare("SELECT p.id as id, v1.email as voter_email, v1.id as voterid, "\
182                              + "v2.email as proxy_email, v2.id as proxyid "\
183                              + "FROM voter AS v1, voter AS v2, proxy AS p "\
184                              + "WHERE v2.id = p.proxy_id AND v1.id = p.voter_id AND p.revoked is NULL "\
185                              + "AND v1.host=$1 AND v2.host=$1 ORDER BY voter_email, proxy_email")(request.host)
186     return rv
187
188 @app.teardown_appcontext
189 def close_connection(exception):
190     db = getattr(g, '_database', None)
191     if db is not None:
192         db.close()
193
194 def init_db():
195     with app.app_context():
196         db = get_db()
197         try:
198             ver = db.prepare("SELECT version FROM schema_version")()[0][0];
199             print("Database Schema version: ", ver)
200         except postgresql.exceptions.UndefinedTableError:
201             g._database = None
202             db = get_db()
203             ver = 0
204
205         if ver < 1:
206             with app.open_resource('sql/schema.sql', mode='r') as f:
207                 db.execute(f.read())
208             return
209
210         if ver < 2:
211             with app.open_resource('sql/from_1.sql', mode='r') as f:
212                 db.execute(f.read())
213                 ct={}
214                 for group in [group for group in prefix[app.config.get("DEFAULT_HOST")]]:
215                     ct[group] = {"dt": "", "c": 0}
216
217                 p = db.prepare("UPDATE \"motion\" SET \"identifier\"=$1 WHERE \"id\"=$2")
218                 for row in db.prepare("SELECT id, \"type\", \"posed\" FROM \"motion\" ORDER BY \"id\" ASC"):
219                     dt=row[2].strftime("%Y%m%d")
220                     if ct[row[1]]["dt"] != dt:
221                         ct[row[1]]["dt"] = dt
222                         ct[row[1]]["c"] = 0
223                     ct[row[1]]["c"] = ct[row[1]]["c"] + 1
224                     name=prefix[app.config.get("DEFAULT_HOST")][row[1]]+"."+dt+"."+("%03d" % ct[row[1]]["c"])
225                     p(name, row[0])
226                 db.prepare("ALTER TABLE \"motion\" ALTER COLUMN \"identifier\" SET NOT NULL")()
227                 db.prepare("UPDATE \"schema_version\" SET \"version\"=2")()
228                 db.prepare("CREATE UNIQUE INDEX motion_ident ON motion (identifier)")()
229
230         if ver < 3:
231             with app.open_resource('sql/from_2.sql', mode='r') as f:
232                 db.execute(f.read())
233                 db.prepare("UPDATE \"motion\" SET \"host\"=$1")(app.config.get("DEFAULT_HOST"))
234                 db.prepare("ALTER TABLE \"motion\" ALTER COLUMN \"host\" SET NOT NULL")()
235                 db.prepare("UPDATE \"schema_version\" SET \"version\"=3")()
236
237         if ver < 4:
238             with app.open_resource('sql/from_3.sql', mode='r') as f:
239                 db.execute(f.read())
240                 db.prepare("UPDATE \"schema_version\" SET \"version\"=4")()
241
242         if ver < 5:
243             with app.open_resource('sql/from_4.sql', mode='r') as f:
244                 db.execute(f.read())
245                 db.prepare("UPDATE \"schema_version\" SET \"version\"=5")()
246
247         if ver < 6:
248             with app.open_resource('sql/from_5.sql', mode='r') as f:
249                 db.execute(f.read())
250                 rv=db.prepare("INSERT INTO voter (email, host) (SELECT vt.email, m.host FROM motion AS m, voter AS vt, vote as v "\
251                              + "WHERE (m.id=v.motion_id AND v.voter_id = vt.id) OR (m.id=v.motion_id AND v.proxy_id = vt.id) "\
252                              + "GROUP BY m.host, vt.email ORDER BY m.host, vt.email)")()
253                 rv=db.prepare("UPDATE vote SET voter_id = "\
254                              + "(SELECT v_new.id FROM motion AS m, voter AS v_new, voter as v_old "\
255                              + "WHERE v_new.email = v_old.email AND v_old.id = vote.voter_id AND "\
256                              + "vote.motion_id = m.id AND m.host = v_new.host AND v_old.host is NULL)")()
257                 rv=db.prepare("UPDATE vote SET proxy_id = "\
258                              + "(SELECT v_new.id FROM motion AS m, voter AS v_new, voter as v_old "\
259                              + "WHERE v_new.email = v_old.email AND v_old.id = vote.proxy_id AND "\
260                              + "vote.motion_id = m.id AND m.host = v_new.host AND v_old.host is NULL)")()
261                 db.prepare("DELETE FROM voter WHERE host IS Null")()
262                 db.prepare("ALTER TABLE \"voter\" ALTER COLUMN \"host\" SET NOT NULL")()
263                 db.prepare("UPDATE \"schema_version\" SET \"version\"=6")()
264
265         if ver < 7:
266             with app.open_resource('sql/from_6.sql', mode='r') as f:
267                 db.execute(f.read())
268                 db.prepare("UPDATE \"schema_version\" SET \"version\"=7")()
269
270 init_db()
271
272 def is_in_ratelimit(group):
273     rv = get_db().prepare("SELECT EXTRACT(EPOCH FROM (CURRENT_TIMESTAMP - posed)) AS timedifference FROM motion WHERE type=$1 AND host=$2 ORDER BY posed DESC LIMIT 1")(group, request.host)
274     if len(rv) == 0:
275         return True
276     rate_limit = motion_wait_minutes.per_host
277     if rate_limit is None:
278         rate_limit = 0
279     if rv[0]['timedifference'] > rate_limit*60:
280         return True
281     else:
282         return _('Error, time between last motion to short. The current setting is %s minute(s).') % (str(rate_limit))
283
284 @app.route("/")
285 def main():
286     start=int(request.args.get("start", "-1"));
287     q = "SELECT motion.*, votes.*, poser.email AS poser, canceler.email AS canceler, (motion.deadline > CURRENT_TIMESTAMP AND canceled is NULL) AS running FROM motion LEFT JOIN (SELECT motion_id, "\
288                              + "COUNT(CASE WHEN result='yes' THEN 'yes' ELSE NULL END) as yes, "\
289                              + "COUNT(CASE WHEN result='no' THEN 'no' ELSE NULL END) as no, "\
290                              + "COUNT(CASE WHEN result='abstain' THEN 'abstain' ELSE NULL END) as abstain "\
291                              + "FROM vote GROUP BY motion_id) as votes ON votes.motion_id=motion.id "\
292                              + "LEFT JOIN voter poser ON poser.id = motion.posed_by "\
293                              + "LEFT JOIN voter canceler ON canceler.id = motion.canceled_by "
294     prev=None
295     if start == -1:
296         p = get_db().prepare(q + "WHERE motion.host = $1 ORDER BY motion.id DESC LIMIT 11")
297         rv = p(request.host)
298     else:
299         p = get_db().prepare(q + "WHERE motion.host = $1 AND motion.id <= $2 ORDER BY motion.id DESC LIMIT 11")
300         rv = p(request.host, start)
301         rs = get_db().prepare("SELECT id FROM motion WHERE motion.host = $1 AND motion.id > $2 ORDER BY id ASC LIMIT 10")(request.host, start)
302         if len(rs) == 10:
303             prev = rs[9][0]
304         else:
305             prev = -1
306     return render_template('index.html', motions=rv[:10], more=rv[10]["id"] if len(rv) == 11 else None, times=times.per_host, prev=prev,
307                            categories=get_allowed_cats("create"), singlemotion=False, may_proxyadmin=may_admin("proxyadmin"), languages=get_languages())
308
309 def rel_redirect(loc):
310     r = redirect(loc)
311     r.autocorrect_location_header = False
312     return r
313
314 def write_proxy_log(userid, action, comment):
315     get_db().prepare("INSERT INTO adminlog(user_id, action, comment, action_user_id) VALUES($1, $2, $3, $4)")(userid, action, comment, g.voter)
316
317 def write_masking_log(comment):
318     get_db().prepare("INSERT INTO adminlog(user_id, action, comment, action_user_id) VALUES($1, 'motionmasking', $2, $1)")(0, comment)
319
320 @app.route("/motion", methods=['POST'])
321 def put_motion():
322     cat=request.form.get("category", "")
323     if cat not in get_allowed_cats("create"):
324         return _('Forbidden'), 403
325     time = int(request.form.get("days", "3"));
326     if time not in times.per_host:
327         return _('Error, invalid length'), 400
328     title=request.form.get("title", "")
329     title=title.strip()
330     if title =='':
331         return _('Error, missing title'), 400
332     content=request.form.get("content", "")
333     content=content.strip()
334     if content =='':
335         return _('Error, missing content'), 400
336     ratelimit = is_in_ratelimit(cat)
337     if ratelimit is not True:
338         return ratelimit, 400
339
340     db = get_db()
341     with db.xact():
342         t = db.prepare("SELECT CURRENT_TIMESTAMP")()[0][0];
343         s = db.prepare("SELECT MAX(\"identifier\") FROM \"motion\" WHERE \"type\"=$1 AND \"host\"=$2 AND DATE(\"posed\")=DATE(CURRENT_TIMESTAMP)")
344         sr = s(cat, request.host)
345         ident=""
346         if len(sr) == 0 or sr[0][0] is None:
347             ident=prefix.per_host[cat]+"."+t.strftime("%Y%m%d")+".001"
348         else:
349             nextId = int(sr[0][0].split(".")[2])+1
350             if nextId >= 1000:
351                 return _('Too many motions for this day'), 500
352             ident=prefix.per_host[cat]+"."+t.strftime("%Y%m%d")+"."+("%03d" % nextId)
353         p = db.prepare("INSERT INTO motion(\"name\", \"content\", \"deadline\", \"posed_by\", \"type\", \"identifier\", \"host\") VALUES($1, $2, CURRENT_TIMESTAMP + $3 * interval '1 days', $4, $5, $6, $7)")
354         p(title, content, time, g.voter, cat, ident, request.host)
355     return rel_redirect("/")
356
357 def motion_edited(motion):
358     return rel_redirect("/motion/" + motion)
359
360 def validate_motion_access(privilege):
361     def decorator(f):
362         def decorated_function(motion):
363             db = get_db()
364             with db.xact():
365                 rv = db.prepare("SELECT id, type, deadline < CURRENT_TIMESTAMP AS expired, canceled FROM motion WHERE identifier=$1 AND host=$2")(motion, request.host);
366                 if len(rv) == 0:
367                     return _('Error, Not found'), 404
368                 id = rv[0].get("id")
369                 if not may(privilege, rv[0].get("type")):
370                     return _('Forbidden'), 403
371                 if rv[0].get("canceled") is not None:
372                     return _('Error, motion was canceled'), 403
373                 if rv[0].get("expired"):
374                     return _('Error, out of time'), 403
375             return f(motion, id)
376         decorated_function.__name__ = f.__name__
377         return decorated_function
378     return decorator
379     
380 def validate_motion_access_vote(privilege):
381     simple_decorator = validate_motion_access(privilege)
382     def decorator(f):
383         def decorated_function(motion, voter):
384             return simple_decorator(lambda motion, id : f(motion, voter, id))(motion)
385         decorated_function.__name__ = f.__name__
386         return decorated_function
387     return decorator
388
389 @app.route("/motion/<string:motion>/cancel", methods=['POST'])
390 @validate_motion_access('cancel')
391 def cancel_motion(motion, id):
392     if request.form.get("reason", "none") == "none":
393         return _('Error, form requires reason'), 500
394     rv = get_db().prepare("UPDATE motion SET canceled=CURRENT_TIMESTAMP, cancelation_reason=$1, canceled_by=$2 WHERE identifier=$3 AND host=$4 AND canceled is NULL")(request.form.get("reason", ""), g.voter, motion, request.host)
395     return motion_edited(motion)
396
397 @app.route("/motion/<string:motion>/finish", methods=['POST'])
398 @validate_motion_access('finish')
399 def finish_motion(motion, id):
400     rv = get_db().prepare("UPDATE motion SET deadline=CURRENT_TIMESTAMP WHERE identifier=$1 AND host=$2 AND canceled is NULL")(motion, request.host)
401     return motion_edited(motion)
402
403 @app.route("/motion/<string:motion>")
404 def show_motion(motion):
405     p = get_db().prepare("SELECT motion.*, poser.email AS poser, canceler.email AS canceler, (motion.deadline > CURRENT_TIMESTAMP AND canceled is NULL) AS running, vote.result FROM motion "\
406                          + "LEFT JOIN vote on vote.motion_id=motion.id AND vote.voter_id=$2 "\
407                          + "LEFT JOIN voter poser ON poser.id = motion.posed_by "\
408                          + "LEFT JOIN voter canceler ON canceler.id = motion.canceled_by "
409                          + "WHERE motion.identifier=$1 AND motion.host=$3")
410     resultmotion = p(motion, g.voter, request.host)
411     if len(resultmotion) == 0:
412         return _('Error, Not found'), 404
413
414     p = get_db().prepare("SELECT voter.email FROM vote INNER JOIN voter ON vote.proxy_id = voter.id WHERE vote.motion_id=$1 AND vote.voter_id=$2 AND vote.proxy_id <> vote.voter_id")
415     resultproxyname = p(resultmotion[0][0], g.voter)
416
417     p = get_db().prepare("SELECT v.result, proxy.voter_id, voter.email, CASE WHEN proxy.proxy_id = v.proxy_id THEN NULL ELSE voter.email END AS owneremail FROM proxy LEFT JOIN "\
418                           + "(SELECT vote.voter_id, vote.result, vote.proxy_id FROM vote "\
419                           + "WHERE vote.motion_id=$1) AS v ON proxy.voter_id = v.voter_id "\
420                           + "LEFT JOIN voter ON proxy.voter_id = voter.id "\
421                           + "WHERE proxy.proxy_id=$2 AND proxy.revoked IS NULL")
422     resultproxyvote = p(resultmotion[0][0], g.voter)
423
424     votes = None
425     if may("audit", resultmotion[0].get("type")) and not resultmotion[0].get("running") and not resultmotion[0].get("canceled"):
426         votes = get_db().prepare("SELECT vote.result, voter.email FROM vote INNER JOIN voter ON voter.id = vote.voter_id WHERE vote.motion_id=$1")(resultmotion[0].get("id"));
427         votes = get_db().prepare("SELECT vote.result, voter.email, CASE voter.email WHEN proxy.email THEN NULL ELSE proxy.email END as proxyemail FROM vote INNER JOIN voter ON voter.id = vote.voter_id INNER JOIN voter as proxy ON proxy.id = vote.proxy_id WHERE vote.motion_id=$1")(resultmotion[0].get("id"));
428     return render_template('single_motion.html', motion=resultmotion[0], may_vote=may("vote", resultmotion[0].get("type")), may_cancel=may("cancel", resultmotion[0].get("type")), may_finish=may("finish", resultmotion[0].get("type")), votes=votes, proxyvote=resultproxyvote, proxyname=resultproxyname, languages=get_languages())
429
430 @app.route("/motion/<string:motion>/vote/<string:voter>", methods=['POST'])
431 @validate_motion_access_vote('vote')
432 def vote(motion, voter, id):
433     v = request.form.get("vote", "abstain")
434     voterid=int(voter)
435     db = get_db()
436
437     # test if voter is proxy
438     if (voterid != g.voter):
439         rv = db.prepare("SELECT voter_id FROM proxy WHERE proxy.revoked IS NULL AND proxy.proxy_id = $1 AND proxy.voter_id = $2")(g.voter, voterid);
440         if len(rv) == 0:
441             return _('Error, proxy not found.'), 400
442
443     p = db.prepare("SELECT * FROM vote WHERE motion_id = $1 AND voter_id = $2")
444     rv = p(id, voterid)
445     if len(rv) == 0:
446         db.prepare("INSERT INTO vote(motion_id, voter_id, result, proxy_id) VALUES($1,$2,$3,$4)")(id, voterid, v, g.voter)
447     else:
448         db.prepare("UPDATE vote SET result=$3, entered=CURRENT_TIMESTAMP, proxy_id=$4 WHERE motion_id=$1 AND voter_id = $2")(id, voterid, v, g.voter)
449     return motion_edited(motion)
450
451 @app.route("/proxy")
452 def proxy():
453     if not may_admin("proxyadmin"):
454         return _('Forbidden'), 403
455     return render_template('proxy.html', voters=get_voters(), proxies=get_all_proxies(), may_proxyadmin=may_admin("proxyadmin"), languages=get_languages())
456
457 @app.route("/proxy/add", methods=['POST'])
458 def add_proxy():
459     if not may_admin("proxyadmin"):
460         return _('Forbidden'), 403
461     voter=request.form.get("voter", "")
462     proxy=request.form.get("proxy", "")
463     if voter == proxy :
464         return _('Error, voter equals proxy.'), 400
465     rv = get_db().prepare("SELECT id FROM voter WHERE email=$1 AND host=$2")(voter, request.host);
466     if len(rv) == 0:
467         return _('Error, voter not found.'), 400
468     voterid = rv[0].get("id")
469     rv = get_db().prepare("SELECT id, host FROM voter WHERE email=$1 AND host=$2")(proxy, request.host);
470     if len(rv) == 0:
471         return _('Error, proxy not found.'), 400
472     proxyid = rv[0].get("id")
473     rv = get_db().prepare("SELECT id FROM proxy WHERE voter_id=$1 AND revoked is NULL")(voterid);
474     if len(rv) != 0:
475         return _('Error, proxy allready given.'), 400
476     rv = get_db().prepare("SELECT COUNT(id) as c FROM proxy WHERE proxy_id=$1 AND revoked is NULL GROUP BY proxy_id")(proxyid);
477     if len(rv) != 0:
478         if rv[0].get("c") is None or rv[0].get("c") >= max_proxy:
479             return _("Error, Max proxy for '%s' reached.") % (proxy), 400
480     rv = get_db().prepare("INSERT INTO proxy(voter_id, proxy_id, granted_by) VALUES ($1,$2,$3)")(voterid, proxyid, g.voter)
481     write_proxy_log(voterid, 'proxygranted', 'proxy: '+str(proxyid))
482     return rel_redirect("/proxy")
483
484 @app.route("/proxy/revoke", methods=['POST'])
485 def revoke_proxy():
486     if not may_admin("proxyadmin"):
487         return _('Forbidden'), 403
488     id=request.form.get("id", "")
489     rv = get_db().prepare("UPDATE proxy SET revoked=CURRENT_TIMESTAMP, revoked_by=$1 WHERE id=$2")(g.voter, int(id))
490     write_proxy_log(int(id), 'proxyrevoked', '')
491     return rel_redirect("/proxy")
492
493 @app.route("/proxy/revokeall", methods=['POST'])
494 def revoke_proxy_all():
495     if not may_admin("proxyadmin"):
496         return _('Forbidden'), 403
497     rv = get_db().prepare("UPDATE proxy SET revoked=CURRENT_TIMESTAMP, revoked_by=$1 WHERE revoked IS NULL")(g.voter)
498     write_proxy_log(g.voter, 'proxyrevokedall', '')
499     return rel_redirect("/proxy")
500
501 @app.route("/language/<string:language>")
502 def set_language(language):
503     lang.change_language(language)
504     return rel_redirect("/")
505
506 @app.cli.command("create-user")
507 @click.argument("email")
508 @click.argument("host")
509 def create_user(email, host):
510     db = get_db()
511     with db.xact():
512         rv = db.prepare("SELECT id FROM voter WHERE lower(email)=lower($1) AND host=$2")(email, host)
513         messagetext=_("User '%s' already exists on %s.") % (email, host)
514         if len(rv) == 0:
515             db.prepare("INSERT INTO voter(\"email\", \"host\") VALUES($1, $2)")(email, host)
516             messagetext=_("User '%s' inserted to %s.") % (email, host)
517     click.echo(messagetext)
518
519 @app.cli.command("motion-masking")
520 @click.argument("motion")
521 @click.argument("motionreason")
522 @click.argument("host")
523 def motion_masking(motion, motionreason, host):
524     if re.search(r"[%_\\]", motion):
525         messagetext = _("No wildcards allowed for motion entry '%s'.") % (motion)
526         click.echo(messagetext)
527     else:
528         db = get_db()
529         with db.xact():
530             rv = db.prepare("SELECT id FROM motion WHERE identifier LIKE $1 AND host = $2")(motion+"%", host)
531             count = len(rv)
532             messagetext = _("%s record(s) affected by masking of '%s'.") % (count, motion)
533             click.echo(messagetext)
534             if len(rv) != 0:
535                 rv = db.prepare("SELECT id FROM motion WHERE content LIKE $1 AND host = $2")('%'+motionreason+"%", host)
536                 rv = db.prepare("UPDATE motion SET name=$3, content=$4 WHERE identifier LIKE $1 AND host = $2 RETURNING id ")(motion+"%", host, _("Motion masked"), _("Motion masked on base of motion [%s](%s) on %s") % (motionreason, motionreason, datetime.now().strftime("%Y-%m-%d")))
537                 messagetext = _("%s record(s) updated by masking of '%s'.") % (len(rv), motion)
538                 write_masking_log(_("%s motion(s) masked on base of motion %s with motion identifier '%s' on host %s") %(len(rv), motionreason, motion, host))
539                 click.echo(messagetext)