-
Notifications
You must be signed in to change notification settings - Fork 1
/
pwic.py
4832 lines (4434 loc) · 218 KB
/
pwic.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Pwic.wiki server running on Python and SQLite
# Copyright (C) 2020-2025 Alexandre Bréard
#
# https://pwic.wiki
# https://github.com/gitbra/pwic
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
from typing import Any, Dict, List, Optional, Tuple, Union
import argparse
from bisect import insort, bisect_left
from datetime import datetime
from difflib import HtmlDiff
import gzip
import binascii
from base64 import b64decode
from html import escape
from io import BytesIO
import json
import os
from os import listdir, urandom
from os.path import getsize, isdir, isfile, join
from random import randint
import re
import sqlite3
import sys
from zipfile import ZipFile, ZIP_DEFLATED, ZIP_STORED, BadZipFile
from ipaddress import ip_network, ip_address
from urllib.parse import parse_qs, quote, urlencode
from urllib.request import Request, urlopen
from gettext import translation
from http.cookies import CookieError
import imagesize
from jinja2 import Environment, FileSystemLoader
from multidict import MultiDict
from aiohttp import web, MultipartReader, hdrs
from aiohttp_session import setup, get_session, new_session, Session
from aiohttp_session.cookie_storage import EncryptedCookieStorage
from pyotp import TOTP
from pwic_md import Markdown
from pwic_lib import PwicConst, PwicLib, PwicError
from pwic_extension import PwicExtension
from pwic_exporter import PwicExporter, PwicStylerHtml
from pwic_importer import PwicImporter, PwicImporterHtml
IPR_EQ, IPR_NET, IPR_REG = range(3)
# ==================
# Pwic.wiki server
# ==================
class PwicServer():
''' Main server for Pwic.wiki '''
def __init__(self, dbconn: sqlite3.Connection) -> None:
''' Constructor '''
self.dbconn = dbconn
def _lock(self, sql: Optional[sqlite3.Cursor]) -> bool:
''' Lock the current database '''
if sql is None:
return False
try:
sql.execute(''' BEGIN EXCLUSIVE TRANSACTION''')
return True
except sqlite3.OperationalError:
return False
def _check_mime(self, obj: Dict[str, Any]) -> bool:
''' Check the consistency of the MIME with the file signature'''
extension = PwicLib.file_ext(obj['filename'])
for item in PwicConst.MIMES:
if extension in item.exts:
# Expected mime
if obj['mime'] in ['', 'application/octet-stream']:
obj['mime'] = item.mimes[0]
elif obj['mime'] not in item.mimes:
return False
# Magic bytes
if item.magic is not None:
for mb in item.magic:
if obj['content'][:len(mb)] == PwicLib.str2bytearray(mb):
return True
return False
break
return obj['mime'] != ''
def _check_ip(self, ip: str) -> None:
''' Check if the IP address is authorized '''
# Initialization
okIncl = False
hasIncl = False
koExcl = False
# Apply the rules
try:
ipobj = ip_address(ip)
except ValueError as e:
raise web.HTTPUnauthorized() from e
for mask in app['options']['ip_filter']:
if mask[0] == IPR_NET:
condition = ipobj in mask[2]
elif mask[0] == IPR_REG:
condition = mask[2].match(ip) is not None
else:
condition = ip == mask[2]
# Evaluate
if mask[1]: # Negated
koExcl = koExcl or condition
if koExcl: # Boolean accelerator
break
else:
okIncl = okIncl or condition
hasIncl = True
# Validate the access
unauth = koExcl or (hasIncl != okIncl)
unauth = not PwicExtension.on_ip_check(ip, not unauth)
if unauth:
raise web.HTTPUnauthorized()
def _is_pure_reader(self, sql: sqlite3.Cursor, project: str, user: str) -> Optional[bool]:
# Check if the user is a pure reader
sql.execute(''' SELECT admin, manager, editor, validator, reader
FROM roles
WHERE project = ?
AND user = ?
AND disabled = '' ''',
(project, user))
row = sql.fetchone()
if row is None:
return None
return (not row['admin']
and not row['manager']
and not row['editor']
and not row['validator']
and row['reader'])
def _redirect_revision(self, sql: sqlite3.Cursor, project: str, user: str, page: str, revision: int) -> int:
# Check if the user is a pure reader
pure_reader = self._is_pure_reader(sql, project, user)
if pure_reader is None:
return 0
# Route to the latest validated version
if pure_reader:
if PwicLib.option(sql, project, 'no_history') is not None:
revision = 0
if (revision == 0) and (PwicLib.option(sql, project, 'validated_only') is not None):
sql.execute(''' SELECT MAX(revision) AS revision
FROM pages
WHERE project = ?
AND page = ?
AND valuser <> '' ''',
(project, page))
row = sql.fetchone()
if row['revision'] is not None:
revision = row['revision']
# Check if the chosen revision exists
if revision > 0:
sql.execute(''' SELECT 1
FROM pages
WHERE project = ?
AND page = ?
and revision = ?''',
(project, page, revision))
if sql.fetchone() is None:
revision = 0
# Find the default latest revision
else:
sql.execute(''' SELECT revision
FROM pages
WHERE project = ?
AND page = ?
AND latest = 'X' ''',
(project, page))
row = sql.fetchone()
if row is not None:
revision = row['revision']
return revision
async def _get_session(self, request: web.Request) -> Session:
''' Get the current session safely '''
try:
session = await get_session(request)
except CookieError as e:
# session = await new_session(request)
raise web.HTTPBadRequest() from e
return session
async def _suser(self, request: web.Request) -> str:
''' Retrieve the logged user after some technical checks '''
# Check the IP address
ip = PwicExtension.on_ip_header(request)
self._check_ip(ip)
session = await self._get_session(request)
if ip != session.get('ip', ip):
return ''
# Check the expiration of the session
expiry = app['options']['session_expiry']
if expiry > 0:
cur_time = PwicLib.timestamp()
if PwicLib.intval(session.get('timestamp', cur_time)) < cur_time - expiry:
session.invalidate()
return ''
session['timestamp'] = PwicLib.timestamp()
# Check the HTTP referer in POST method and the user
user = PwicLib.safe_user_name(session.get('user'))
if (request.method == 'POST') and app['options']['http_referer']:
referer = request.headers.get('Referer', '')
if referer[:len(app['options']['base_url'])] != app['options']['base_url']:
user = ''
return PwicConst.USERS['anonymous'] if (user == '') and app['options']['no_login'] else user
async def _handle_post(self, request: web.Request) -> Dict[str, Any]:
''' Return the POST as a readable object.get() '''
result: Dict[str, Any] = {}
if request.body_exists:
data = await request.text()
result = parse_qs(data)
for res in result:
result[res] = result[res][0].replace('\r', '')
if res not in ['markdown']:
result[res] = result[res][:PwicLib.intval(PwicConst.DEFAULTS['limit_field'])]
return result
async def _handle_login(self, request: web.Request) -> web.Response:
''' Show the login page '''
session = await new_session(request)
session['user_secret'] = PwicLib.random_hash()
return await self._handle_output(request, 'login', {})
async def _handle_logout(self, request: web.Request) -> web.Response:
''' Show the logout page '''
# Logging the disconnection (not visible online) aims to not report a reader as inactive.
# Knowing that the session is encrypted in the cookie, the event does NOT guarantee that
# it is effectively destroyed by the user (his web browser generally does it). The session
# is fully lost upon server restart if the option 'keep_sessions' is not used.
user = await self._suser(request)
if user not in ['', PwicConst.USERS['anonymous']]:
sql = self.dbconn.cursor()
PwicLib.audit(sql, {'author': user,
'event': 'logout'},
request)
self.dbconn.commit()
# Destroy the session
session = await self._get_session(request)
session.invalidate()
return await self._handle_output(request, 'logout', {})
async def _handle_output(self, request: web.Request, name: str, pwic: Dict[str, Any]) -> web.Response:
''' Serve the right template, in the right language, with the right structure and additional data '''
# Constants
pwic['user'] = await self._suser(request)
pwic['emojis'] = PwicConst.EMOJIS
pwic['constants'] = {'anonymous_user': PwicConst.USERS['anonymous'],
'default_home': PwicConst.DEFAULTS['page'],
'languages': app['langs'],
'not_project': PwicConst.NOT_PROJECT,
'rtl': PwicConst.RTL,
'unsafe_chars': PwicConst.CHARS_UNSAFE,
'version': PwicConst.VERSION}
# The project-dependent variables have the priority
project = pwic.get('project', '')
sql = self.dbconn.cursor()
sql.execute(''' SELECT project, key, value
FROM env
WHERE ( project = ?
OR project = '' )
AND value <> ''
ORDER BY key ASC,
project DESC''',
(project, ))
pwic['env'] = {}
for row in sql.fetchall():
if row['key'] not in PwicConst.ENV:
continue
(global_, key, value) = (row['project'] == '', row['key'], row['value'])
if PwicConst.ENV[key].private or (key in pwic['env']):
continue
pwic['env'][key] = {'value': value,
'global': global_}
if key in ['document_size_max', 'project_size_max']:
pwic['env'][key + '_str'] = {'value': PwicLib.size2str(PwicLib.intval(value)),
'global': global_}
# Dynamic settings for the robots
robots = PwicLib.str2robots(str(PwicLib.option(sql, project, 'robots', '')))
if PwicExtension.on_html_robots(sql, request, project, pwic['user'], name, pwic, robots):
if 'robots' not in pwic['env']:
pwic['env']['robots'] = {'value': '',
'global': True}
pwic['env']['robots']['value'] = PwicLib.robots2str(robots)
# Session
session = await self._get_session(request)
pwic['oauth_user_secret'] = session.get('user_secret', None)
# ... language
session_lang = session.get('language', '')
new_lang = session_lang or PwicLib.detect_language(request, app['langs'])
if new_lang not in app['langs']:
new_lang = PwicConst.DEFAULTS['language']
if new_lang != session_lang:
session['language'] = new_lang
pwic['language'] = new_lang
# Render the template
pwic['template'] = name
pwic['args'] = request.rel_url.query
PwicExtension.on_render_pre(app, sql, request, pwic)
output = app['jinja'][pwic['language']].get_template(f'html/{name}.html').render(pwic=pwic)
output = PwicExtension.on_render_post(app, sql, request, pwic, output)
headers: MultiDict = MultiDict({})
PwicExtension.on_http_headers(sql, request, headers, project, name)
return web.Response(text=output, content_type=PwicLib.mime('html'), headers=headers)
async def _handle_headers(self, request: web.Request, response: web.Response) -> None:
response.headers['Server'] = f'Pwic.wiki v{PwicConst.VERSION}'
async def project_searchlink(self, request: web.Request) -> web.Response:
''' Search link to be added to the browser '''
# Verify that the user is connected
user = await self._suser(request)
if user == '':
raise web.HTTPUnauthorized()
# Get the parameters
project = PwicLib.safe_name(request.match_info.get('project'))
# Verify that the user has access to the project
sql = self.dbconn.cursor()
sql.execute(''' SELECT b.description
FROM roles AS a
INNER JOIN projects AS b
ON b.project = a.project
WHERE a.project = ?
AND a.user = ?
AND a.disabled = '' ''',
(project, user))
row = sql.fetchone()
if row is None:
raise web.HTTPUnauthorized()
# Additional parameters
if (app['options']['base_url'] == '') or (PwicLib.option(sql, project, 'no_search') is not None):
raise web.HTTPForbidden()
# Result
xml = '''<?xml version="1.0" encoding="UTF-8"?>
<OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/">
<Description>%s</Description>
<InputEncoding>UTF-8</InputEncoding>
<Language>*</Language>
<ShortName>%s</ShortName>
<Url rel="results" type="text/html" method="get" template="%s/%s/special/search?q={searchTerms}"></Url>
</OpenSearchDescription>''' % (escape(row['description']),
escape(project),
escape(app['options']['base_url']),
escape(project))
return web.Response(text=PwicLib.recursive_replace(xml.strip(), ' <', '<'), content_type=PwicLib.mime('xml'))
async def project_sitemap(self, request: web.Request) -> web.Response:
''' Produce the site map of the project '''
# Verify that the user is connected
user = await self._suser(request)
if user == '':
raise web.HTTPUnauthorized()
# Fetch the parameters
project = PwicLib.safe_name(request.match_info.get('project'))
dt = PwicLib.dt()
# Check the authorizations
sql = self.dbconn.cursor()
sql.execute(''' SELECT 1
FROM roles
WHERE project = ?
AND user = ?
AND disabled = '' ''',
(project, user))
if sql.fetchone() is None:
raise web.HTTPUnauthorized()
# Additional parameters
if PwicLib.option(sql, project, 'no_sitemap') is not None:
raise web.HTTPForbidden()
# Generate the site map
buffer = ('<?xml version="1.0" encoding="UTF-8"?>'
+ '\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">')
sql.execute(''' SELECT page, header, date
FROM pages
WHERE project = ?
AND latest = 'X' ''',
(project, ))
while True:
row = sql.fetchone()
if row is None:
break
# Mapping
days = PwicLib.dt_diff(row['date'], dt['date'])
if row['page'] == PwicConst.DEFAULTS['page']:
priority = 1.0
elif row['header']:
priority = 0.7
elif days <= 90:
priority = 0.5
else:
priority = 0.3
buffer += ('\n<url>'
+ ('<loc>%s/%s/%s</loc>' % (escape(app['options']['base_url']), quote(project), quote(row['page'])))
+ ('<changefreq>%s</changefreq>' % ('monthly' if days >= 35 else 'weekly'))
+ ('<lastmod>%s</lastmod>' % escape(row['date']))
+ ('<priority>%.1f</priority>' % priority)
+ '</url>')
buffer += '\n</urlset>'
return web.Response(text=buffer, content_type=PwicLib.mime('xml'))
async def project_feed(self, request: web.Request) -> web.Response:
''' ATOM/RSS/JSON feeds for the project '''
# Sub-features
def _feed_atom(sql: sqlite3.Cursor, project: str, project_description: str, feed_size: int) -> web.Response:
dt = PwicLib.dt()
url = f'{app["options"]["base_url"]}/{project}/special/feed/atom'
legnot = str(PwicLib.option(sql, project, 'legal_notice', ''))
atom = '''<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom" xml:base="%s" xml:lang="%s">
<id>%s</id>
<title type="text">Project %s (ATOM)</title>
<subtitle type="text">%s</subtitle>
<link href="/%s/special/feed/atom" rel="self" type="%s" />
<updated>%sT%sZ</updated>%s
<generator uri="https://pwic.wiki" version="%s">Pwic.wiki v%s</generator>
''' % (escape(app['options']['base_url']),
escape(str(PwicLib.option(sql, project, 'language', PwicConst.DEFAULTS['language']))),
escape(url),
escape(project),
escape(project_description),
escape(project),
escape(str(PwicLib.mime('atom'))),
escape(dt['date']),
escape(dt['time']),
'' if legnot == '' else ('\n<rights>%s</rights>' % escape(legnot)),
escape(PwicConst.VERSION),
escape(PwicConst.VERSION),
)
sql.execute(''' SELECT page, revision, author, date, time, title, tags, comment
FROM pages
WHERE project = ?
AND latest = 'X'
AND date >= ?
ORDER BY date DESC,
time DESC
LIMIT ?''',
(project, dt['date-90d'], feed_size))
for row in sql.fetchall():
url = f'{app["options"]["base_url"]}/{project}/{row["page"]}/rev{row["revision"]}'
atom += '''<entry>
<title>[%s] %s</title>
<summary>%s</summary>
<updated>%sT%sZ</updated>
<link href="%s" />
<id>%s</id>
<author>
<name>%s</name>
<uri>%s/special/user/%s</uri>
</author>
</entry>''' % (escape(row['page']),
escape(row['title']),
escape(row['comment']),
escape(row['date']),
escape(row['time']),
escape(url),
escape(url),
escape(row['author']),
escape(app['options']['base_url']),
escape(row['author']))
atom += '</feed>'
return web.Response(text=PwicLib.recursive_replace(atom.strip(), ' <', '<'), content_type=PwicLib.mime('atom'))
def _feed_rss(sql: sqlite3.Cursor, project: str, project_description: str, feed_size: int) -> web.Response:
def _author2rss(author: str) -> str:
p = author.find('@')
if p == -1:
return f'{author}@no.reply ({author})'
return f'{author} ({author[:p]})'
dt = PwicLib.dt()
url = f'{app["options"]["base_url"]}/{project}/special/feed/rss'
rss = '''<?xml version="1.0" encoding="utf8"?><rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
<channel>
<title>Project %s (RSS)</title>
<description>%s</description>
<lastBuildDate>%s</lastBuildDate>
<link>%s</link>
<atom:link href="%s" rel="self" type="%s" />
''' % (escape(project),
escape(project_description),
escape(PwicLib.dt2rfc822(dt['date'], dt['time'])),
escape(url),
escape(url),
escape(str(PwicLib.mime('rss'))))
sql.execute(''' SELECT page, revision, author, date, time, title, tags, comment
FROM pages
WHERE project = ?
AND latest = 'X'
AND date >= ?
ORDER BY date DESC,
time DESC
LIMIT ?''',
(project, dt['date-90d'], feed_size))
for row in sql.fetchall():
url = f'{app["options"]["base_url"]}/{project}/{row["page"]}/rev{row["revision"]}'
rss += '''<item>
<title>[%s] %s</title>
<description>%s</description>
<pubDate>%s</pubDate>
<author>%s</author>%s
<link>%s</link>
<guid isPermaLink="false">%s</guid>
</item>''' % (escape(row['page']),
escape(row['title']),
escape(row['comment']),
escape(PwicLib.dt2rfc822(row['date'], row['time'])),
escape(_author2rss(row['author'])),
'' if row['tags'] == '' else ('\n<category>%s</category>' % escape(row['tags'])),
escape(url),
escape('%s-%s-%d' % (project, row['page'], row['revision'])))
rss += '</channel></rss>'
return web.Response(text=PwicLib.recursive_replace(rss.strip(), ' <', '<'), content_type=PwicLib.mime('rss'))
def _feed_json(sql: sqlite3.Cursor, project: str, days: int) -> web.Response:
dt = PwicLib.dt(days=days)
sql.execute(''' SELECT page, MAX(date, valdate) AS date
FROM pages
WHERE project = ?
AND latest = 'X'
AND ( date >= ?
OR valdate >= ? )
ORDER BY date DESC,
page ASC''',
(project, dt['date-nd'], dt['date-nd']))
return web.Response(text=json.dumps(sql.fetchall()), content_type=PwicLib.mime('json'))
# Verify that the user is connected
user = await self._suser(request)
if user == '':
raise web.HTTPUnauthorized()
# Get the parameters
fmt = request.match_info.get('format', 'atom')
project = PwicLib.safe_name(request.match_info.get('project'))
days = min(max(0, PwicLib.intval(request.rel_url.query.get('days', '7'))), 90)
if fmt not in ['atom', 'rss', 'json']:
raise web.HTTPBadRequest()
# Verify that the user has access to the feed
sql = self.dbconn.cursor()
if PwicLib.option(sql, project, 'no_feed') is not None:
raise web.HTTPForbidden()
sql.execute(''' SELECT b.description
FROM roles AS a
INNER JOIN projects AS b
ON b.project = a.project
WHERE a.project = ?
AND a.user = ?
AND a.disabled = '' ''',
(project, user))
row = sql.fetchone()
if row is None:
raise web.HTTPUnauthorized()
if self._is_pure_reader(sql, project, user) and (PwicLib.option(sql, project, 'no_history') is not None):
raise web.HTTPForbidden()
# Result
feed_size = max(1, PwicLib.intval(PwicLib.option(sql, project, 'feed_size', '25')))
if fmt == 'atom':
return _feed_atom(sql, project, row['description'], feed_size)
if fmt == 'rss':
return _feed_rss(sql, project, row['description'], feed_size)
return _feed_json(sql, project, days)
async def project_manifest(self, request: web.Request) -> web.Response:
# Verify that the user is connected
user = await self._suser(request)
if user == '':
raise web.HTTPUnauthorized()
# Verify the authorization
project = PwicLib.safe_name(request.match_info.get('project'))
sql = self.dbconn.cursor()
if PwicLib.option(sql, project, 'manifest') is None:
raise web.HTTPServiceUnavailable()
sql.execute(''' SELECT b.description
FROM roles AS a
INNER JOIN projects AS b
ON b.project = a.project
WHERE a.project = ?
AND a.user = ?
AND a.disabled = '' ''',
(project, user))
row = sql.fetchone()
if row is None:
raise web.HTTPUnauthorized()
# Manifest
manifest = {'name': project,
'short_name': project,
'description': row['description'],
'start_url': f'/{project}',
'scope': f'/{project}',
'display': 'standalone',
'orientation': 'portrait',
'lang': PwicLib.option(sql, project, 'language', PwicConst.DEFAULTS['language']),
'icons': [{'src': '/static/icon.png', 'sizes': '320x320', 'type': 'image/png'}],
'screenshots': [{'src': '/static/icon.png', 'type': 'image/png', 'sizes': '320x320', 'form_factor': 'narrow'},
{'src': '/static/icon.png', 'type': 'image/jpg', 'sizes': '320x320', 'form_factor': 'wide'}]}
return web.Response(text=json.dumps(manifest), content_type=PwicLib.mime('json'))
async def project_export(self, request: web.Request) -> web.Response:
''' Download the project as a ZIP file '''
# Verify that the user is connected
user = await self._suser(request)
if user == '':
raise web.HTTPUnauthorized()
# Get the parameters
project = PwicLib.safe_name(request.match_info.get('project'))
fmt = request.match_info.get('format')
if fmt != 'zip':
raise web.HTTPUnsupportedMediaType()
# Verify that the export is authorized
sql = self.dbconn.cursor()
sql.execute(''' SELECT 1
FROM roles
WHERE project = ?
AND user = ?
AND admin = 'X'
AND disabled = '' ''',
(project, user))
if sql.fetchone() is None:
raise web.HTTPUnauthorized()
if PwicLib.option(sql, project, 'no_export_project') is not None:
raise web.HTTPForbidden()
with_revisions = PwicLib.option(sql, project, 'export_project_revisions') is not None
# Fetch the attached documents
sql.execute(''' SELECT id, filename, SUBSTR(mime, 1, 6) == 'image/' AS image, exturl
FROM documents
WHERE project = ?''',
(project, ))
documents = sql.fetchall()
for doc in documents:
doc['image'] = doc['image'] == 1
# Build the ZIP file
folder_rev = 'revisions/'
converter = PwicExporter(app['markdown'], user)
converter.set_option('relative_html', True)
try:
inmemory = BytesIO()
with ZipFile(inmemory, mode='w', compression=ZIP_DEFLATED) as archive:
# Fetch the relevant pages
sql_sub = self.dbconn.cursor()
sql.execute(''' SELECT page, revision, latest, author, date, time, title, markdown
FROM pages
WHERE project = ?
AND ( latest = 'X'
OR draft = '' )''',
(project, ))
while True:
page = sql.fetchone()
if page is None:
break
if not with_revisions and not page['latest']:
continue
# Raw markdown
if with_revisions:
archive.writestr(f'{folder_rev}{page["page"]}.rev{page["revision"]}.md', page['markdown'])
if page['latest']:
archive.writestr(f'{page["page"]}.md', page['markdown'])
# Regenerate HTML
html = converter.convert(sql_sub, project, page['page'], page['revision'], 'html')
if html is None:
continue
html = str(html)
# Fix the relative links
for doc in documents:
if doc['exturl'] == '':
if doc['image']:
html = html.replace(f'<img src="/special/document/{doc["id"]}"', f'<img src="documents/{doc["filename"]}"')
html = html.replace(f'<a href="/special/document/{doc["id"]}"', f'<a href="documents/{doc["filename"]}"')
html = html.replace(f'<a href="/special/document/{doc["id"]}/', f'<a href="documents/{doc["filename"]}')
else:
if doc['image']:
html = html.replace(f'<img src="/special/document/{doc["id"]}"', f'<img src="{doc["exturl"]}"')
html = html.replace(f'<a href="/special/document/{doc["id"]}"', f'<a href="{doc["exturl"]}"')
html = html.replace(f'<a href="/special/document/{doc["id"]}/', f'<a href="{doc["exturl"]}')
if with_revisions:
archive.writestr(f'{folder_rev}{page["page"]}.rev{page["revision"]}.html', html)
if page['latest']:
archive.writestr(f'{page["page"]}.html', html)
# Dependent files for the pages
cssfn = PwicStylerHtml().css
content = b''
with open(cssfn, 'rb') as f:
content = f.read()
archive.writestr(cssfn, content)
if with_revisions:
archive.writestr(folder_rev + cssfn, content)
del content
# Attached documents
PwicExtension.on_project_export_documents(sql, request, project, user, documents)
for doc in documents:
if doc['exturl'] == '':
fn = join(PwicConst.DOCUMENTS_PATH % project, doc['filename'])
if isfile(fn):
content = b''
with open(fn, 'rb') as f:
content = f.read()
if PwicLib.mime_compressed(PwicLib.file_ext(doc['filename'])):
archive.writestr(f'documents/{doc["filename"]}', content, compress_type=ZIP_STORED, compresslevel=0)
else:
archive.writestr(f'documents/{doc["filename"]}', content)
del content
except Exception as e:
raise web.HTTPInternalServerError() from e
# Audit the action
PwicLib.audit(sql, {'author': user,
'event': 'export-project',
'project': project,
'string': 'zip-full' if with_revisions else 'zip-latest'},
request)
self.dbconn.commit()
# Return the file
buffer = inmemory.getvalue()
inmemory.close()
headers = {'Content-Type': str(PwicLib.mime('zip')),
'Content-Disposition': 'attachment; filename="%s"' % PwicLib.attachment_name(project + '.zip')}
return web.Response(body=buffer, headers=MultiDict(headers))
async def page(self, request: web.Request) -> web.Response:
''' Serve the pages '''
# Verify that the user is connected
user = await self._suser(request)
if user == '':
return await self._handle_login(request)
# Show the requested page
project = PwicLib.safe_name(request.match_info.get('project'))
page = PwicLib.safe_name(request.match_info.get('page', PwicConst.DEFAULTS['page']))
page_special = page == 'special'
revision = PwicLib.intval(request.match_info.get('revision', '0'))
action = request.match_info.get('action', 'view')
pwic: Dict[str, Any] = {'project': project,
'page': page,
'revision': revision}
# Fetch the name of the project or ask the user to pick a project
sql = self.dbconn.cursor()
if project == '':
return await self._page_pick(sql, request, user, pwic)
if not await self._page_prepare(sql, request, project, user, pwic):
return await self._handle_output(request, 'project-access', pwic) # Unauthorized users can request an access
# Fetch the links of the header line
sql.execute(''' SELECT a.page, a.title
FROM pages AS a
WHERE a.project = ?
AND a.latest = 'X'
AND a.header = 'X'
ORDER BY a.title''',
(project, ))
pwic['links'] = sql.fetchall()
for i, row in enumerate(pwic['links']):
if row['page'] == PwicConst.DEFAULTS['page']:
pwic['links'].insert(0, pwic['links'].pop(i)) # Move to the top because it is the home page
break
# Verify that the page exists
if not page_special:
revision = self._redirect_revision(sql, project, user, page, revision)
if revision == 0:
return await self._handle_output(request, 'page-404', pwic) # Page not found
# Show the requested page
PwicExtension.on_api_page_requested(sql, request, action, project, page, revision)
if action == 'view':
if page_special:
return await self._page_view_special(sql, request, project, user, pwic)
return await self._page_view(sql, request, project, user, page, revision, pwic)
if action == 'edit':
return await self._page_edit(sql, request, project, page, revision, pwic)
if action == 'history':
return await self._page_history(sql, request, project, page, pwic)
if action == 'move':
return await self._page_move(sql, request, project, user, page, pwic)
raise web.HTTPNotFound()
async def _page_prepare(self,
sql: sqlite3.Cursor,
request: web.Request,
project: str,
user: str,
pwic: Dict[str, Any],
) -> bool:
# Verify if the project exists
sql.execute(''' SELECT description
FROM projects
WHERE project = ?''',
(project, ))
row = sql.fetchone()
if row is None:
raise web.HTTPTemporaryRedirect('/') # Project not found
pwic['project_description'] = row['description']
pwic['title'] = row['description']
# Grant the default rights as a reader
if (not PwicLib.reserved_user_name(user)) and (PwicLib.option(sql, project, 'auto_join') == 'passive'):
if sql.execute(''' SELECT 1
FROM roles
WHERE project = ?
AND user = ?''',
(project, user)).fetchone() is None:
sql.execute(''' INSERT INTO roles (project, user, reader)
VALUES (?, ?, 'X')''', (project, user))
if sql.rowcount > 0:
PwicLib.audit(sql, {'author': PwicConst.USERS['system'],
'event': 'grant-reader',
'project': project,
'user': user,
'string': 'auto_join'},
request)
self.dbconn.commit()
# Verify the access
sql.execute(''' SELECT admin, manager, editor, validator, reader
FROM roles
WHERE project = ?
AND user = ?
AND disabled = '' ''',
(project, user))
row = sql.fetchone()
if row is None:
return False
pwic.update(row)
pwic['pure_reader'] = pwic['reader'] and not pwic['admin'] and not pwic['manager'] and not pwic['editor'] and not pwic['validator']
return True
async def _page_pick(self,
sql: sqlite3.Cursor,
request: web.Request,
user: str,
pwic: Dict[str, Any],
) -> web.Response:
# Projects joined
dt = PwicLib.dt()
sql.execute(''' SELECT a.project, a.description, a.date, c.last_activity
FROM projects AS a
INNER JOIN roles AS b
ON b.project = a.project
AND b.user = ?
AND b.disabled = ''
LEFT OUTER JOIN (
SELECT project, MAX(date) AS last_activity
FROM audit.audit
WHERE date >= ?
AND author = ?
GROUP BY project
) AS c
ON c.project = a.project
ORDER BY c.last_activity DESC,
a.date DESC,
a.description ASC''',
(user, dt['date-90d'], user))
pwic['projects'] = sql.fetchall()
# Projects not joined yet
sql.execute(''' SELECT a.project, c.description, c.date
FROM env AS a
LEFT OUTER JOIN roles AS b
ON b.project = a.project
AND b.user = ?
INNER JOIN projects AS c
ON c.project = a.project
WHERE a.project <> ''
AND a.key = 'auto_join'
AND a.value IN ('passive', 'active')
AND b.project IS NULL
ORDER BY c.date DESC,
c.description ASC''',
(user, ))
pwic['joinable_projects'] = sql.fetchall()
# Output
if (len(pwic['projects']) == 1) and (len(pwic['joinable_projects']) == 0):
suffix = '?failed' if request.rel_url.query.get('failed', None) is not None else ''
raise web.HTTPTemporaryRedirect(f'/{pwic["projects"][0]["project"]}{suffix}')
return await self._handle_output(request, 'project-select', pwic)
async def _page_view(self,
sql: sqlite3.Cursor,
request: web.Request,
project: str,
user: str,
page: str,
revision: int,
pwic: Dict[str, Any],
) -> web.Response:
# Content of the page
sql.execute(''' SELECT revision, latest, draft, final, protection,
author, date, time, title, markdown,
tags, valuser, valdate, valtime
FROM pages
WHERE project = ?
AND page = ?
AND revision = ?''',
(project, page, revision))
row = sql.fetchone()
row['tags'] = PwicLib.list(row['tags'])
pwic.update(row)
# Read the HTML cache
cache = ((PwicLib.option(sql, project, 'no_cache') is None)
and PwicExtension.on_cache(sql, request, project, user, page, revision))
if cache:
row = sql.execute(''' SELECT html
FROM cache
WHERE project = ?
AND page = ?
AND revision = ?''',
(project, page, revision)).fetchone()
else:
row = None
# Update the HTML cache if needed
if row is not None:
if isinstance(row['html'], bytes):
html = str(gzip.decompress(row['html']).decode())
else:
html = row['html']
else:
row = {'project': project,
'page': page,
'revision': revision,
'markdown': pwic['markdown']}
converter = PwicExporter(app['markdown'], user)
html = converter.md2corehtml(sql, row, export_odt=False)
del converter
if cache:
sql.execute(''' INSERT OR REPLACE INTO cache (project, page, revision, html)
VALUES (?, ?, ?, ?)''',
(project, page, revision,
gzip.compress(html.encode(), compresslevel=9) if app['options']['compressed_cache'] else html))
self.dbconn.commit()
# Enhance the page
pwic['html'], pwic['tmap'] = PwicLib.extended_syntax(html,
PwicLib.option(sql, project, 'heading_mask'),
headerNumbering=PwicLib.option(sql, project, 'no_heading') is None)
pwic['hash'] = PwicLib.sha256(pwic['markdown'], salt=False)
pwic['removable'] = ((pwic['admin']
and not pwic['final']
and (pwic['valuser'] == ''))
or ((pwic['author'] == user)
and pwic['draft']))
pwic['file_formats'] = PwicExporter.get_allowed_extensions()
pwic['canonical'] = f'{app["options"]["base_url"]}/{project}/{page}' + ('' if pwic['latest'] else f'/rev{revision}')
pwic['description'] = PwicExtension.on_html_description(sql, project, user, page, revision)
pwic['keywords'] = PwicExtension.on_html_keywords(sql, project, user, page, revision)