-
Notifications
You must be signed in to change notification settings - Fork 0
/
pwic_admin.py
2663 lines (2446 loc) · 113 KB
/
pwic_admin.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-2024 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
import sqlite3
import gzip
import datetime
import sys
import os
import ssl
from os import chmod, listdir, makedirs, mkdir, removedirs, rename, rmdir, system
from os.path import getsize, isdir, isfile, join, splitext
from shutil import copyfile, copyfileobj
from subprocess import call
from stat import S_IREAD
from urllib.error import HTTPError, URLError
from urllib.request import Request, urlopen
from urllib.parse import urlencode, urlparse
from http.client import RemoteDisconnected
import imagesize
from prettytable import PrettyTable
import pyotp
from pwic_lib import PwicConst, PwicLib
from pwic_extension import PwicExtension
class PwicAdmin():
''' Administration tools for Pwic.wiki '''
# ======
# Main
# ======
def __init__(self):
self.db = None
def main(self) -> bool:
# Default encoding
try:
sys.stdout.reconfigure(encoding='utf-8')
except AttributeError:
pass
# Check root
try:
if os.geteuid() == 0:
print('Error: Pwic.wiki cannot be administrated with the root account')
return False
except AttributeError:
pass # No check on Windows
# Prepare the command line (subparsers cannot be grouped)
parser = argparse.ArgumentParser(prog='python3 pwic_admin.py', description=f'Pwic.wiki Management Console v{PwicConst.VERSION}')
subparsers = parser.add_subparsers(dest='command')
# ... Initialization
subparsers.add_parser('init-db', help='Initialize the database once')
spb = subparsers.add_parser('show-env', help='Show the current configuration')
spb.add_argument('--project', default='', help='Name of the project')
spb.add_argument('--var', default='', help='Name of the variable for exclusive display')
spb.add_argument('--list', action='store_true', help='Show the result in a list')
spb = subparsers.add_parser('set-env', help='Set a global or a project-dependent parameter')
spb.add_argument('--project', default='', help='Name of the project (if project-dependent)')
spb.add_argument('name', default='', help='Name of the variable')
spb.add_argument('value', default='', help='Value of the variable')
spb.add_argument('--override', action='store_true', help='Remove the existing project-dependent values')
spb.add_argument('--append', action='store_true', help='Append the value to the existing one')
spb.add_argument('--remove', action='store_true', help='Remove the value from the existing one')
spb = subparsers.add_parser('repair-env', help='Fix the incorrect environment variables')
spb.add_argument('--test', action='store_true', help='Verbose simulation')
subparsers.add_parser('show-mime', help='Show the MIME types defined on the server (Windows only)')
# ... Projects
subparsers.add_parser('show-projects', help='Show the existing projects')
spb = subparsers.add_parser('create-project', help='Create a new project')
spb.add_argument('project', default='', help='Project name')
spb.add_argument('description', default='', help='Project description')
spb.add_argument('admin', default='', help='User name of the administrator of the project')
spb = subparsers.add_parser('takeover-project', help='Assign an administrator to a project')
spb.add_argument('project', default='', help='Project name')
spb.add_argument('admin', default='', help='User name of the administrator')
spb = subparsers.add_parser('split-project', help='Copy a project into a dedicated database')
spb.add_argument('--no-history', action='store_true', help='Remove the history')
spb.add_argument('project', nargs='+', default='', help='Project name')
spb = subparsers.add_parser('delete-project', help='Delete an existing project (irreversible)')
spb.add_argument('project', default='', help='Project name')
# ... Users
spb = subparsers.add_parser('list-users', help='List the user accounts')
spb.add_argument('--project', default='', help='Name of the project (if project-dependent)')
spb = subparsers.add_parser('show-user', help='Show the current roles for one user')
spb.add_argument('user', default='', help='User name')
spb = subparsers.add_parser('create-user', help='Create a user with no assignment to a project')
spb.add_argument('user', default='', help='User name')
spb.add_argument('--totp', action='store_true', help='Enable 2FA TOTP for the user')
spb = subparsers.add_parser('reset-password', help='Reset the password of a user')
spb.add_argument('user', default='', help='User name')
spb.add_argument('--create', action='store_true', help='Create the user account if needed')
spb.add_argument('--oauth', action='store_true', help='Force the federated authentication')
spb = subparsers.add_parser('reset-totp', help="Reset the user's secret key of the 2FA authentication")
spb.add_argument('user', default='', help='User name')
spb.add_argument('--disable', action='store_true', help='Turn off 2FA TOTP')
spb = subparsers.add_parser('assign-user', help='Assign a user to a project as a reader')
spb.add_argument('project', default='', help='Project name')
spb.add_argument('user', default='', help='User name')
spb = subparsers.add_parser('revoke-user', help='Revoke a user')
spb.add_argument('user', default='', help='User name')
spb.add_argument('--force', action='store_true', help='Force the operation despite the user can be the sole administrator of a project')
# ... Maintenance
spb = subparsers.add_parser('show-audit', help='Show the log of the database (no HTTP traffic)')
spb.add_argument('--min', type=int, default=30, help='From MIN days in the past', metavar='30')
spb.add_argument('--max', type=int, default=0, help='To MAX days in the past', metavar='0')
spb = subparsers.add_parser('show-login', help='Show the last logins of the users')
spb.add_argument('--days', type=int, default=30, help='Number of days in the past', metavar='30')
subparsers.add_parser('show-stats', help='Show some statistics')
spb = subparsers.add_parser('show-inactivity', help='Show the inactive users who have a write access')
spb.add_argument('--project', default='', help='Name of the project (if project-dependent)')
spb.add_argument('--days', type=int, default=90, help='Number of days in the past', metavar='90')
spb = subparsers.add_parser('compress-static', help='Compress the static files for a faster delivery (optional)')
spb.add_argument('--revert', action='store_true', help='Revert the operation')
spb = subparsers.add_parser('clear-cache', help='Clear the cache of the pages (required after upgrade or restoration)')
spb.add_argument('--project', default='', help='Name of the project (if project-dependent)')
spb.add_argument('--selective', action='store_true', help='Keep the latest pages in cache')
spb = subparsers.add_parser('regenerate-cache', help='Regenerate the cache of the pages through mass HTTP requests')
spb.add_argument('--project', default='', help='Name of the project (if project-dependent)')
spb.add_argument('--user', default='', help='User account to access some private projects')
spb.add_argument('--full', action='store_true', help='Include the revisions (not recommended)')
spb.add_argument('--port', type=int, default=PwicConst.DEFAULTS['port'], help='Target instance defined by the listened port', metavar=PwicConst.DEFAULTS['port'])
spb = subparsers.add_parser('rotate-logs', help='Rotate Pwic.wiki\'s HTTP log files')
spb.add_argument('--count', type=int, default=9, help='Number of log files', metavar='9')
spb = subparsers.add_parser('archive-audit', help='Clean the obsolete entries of audit')
spb.add_argument('--selective', type=int, default=90, help='Horizon for a selective cleanup', metavar='90')
spb.add_argument('--complete', type=int, default=0, help='Horizon for a complete cleanup', metavar='365')
spb = subparsers.add_parser('show-git', help='Show the current git version')
spb.add_argument('--agree', action='store_true', help='If you understand what this command does')
subparsers.add_parser('create-backup', help='Make a backup copy of the database file *without* the attached documents')
spb = subparsers.add_parser('repair-documents', help='Repair the index of the documents (recommended after the database is restored)')
spb.add_argument('--project', default='', help='Name of the project (if project-dependent)')
spb.add_argument('--no-hash', action='store_true', help='Do not recalculate the hashes of the files (faster but not recommended)')
spb.add_argument('--no-magic', action='store_true', help='Do not verify the magic bytes of the files')
spb.add_argument('--keep-orphans', action='store_true', help='Do not delete the orphaned folders and files')
spb.add_argument('--test', action='store_true', help='Verbose simulation')
subparsers.add_parser('execute-optimize', help='Run the optimizer')
spb = subparsers.add_parser('unlock-db', help='Unlock the database after an internal Python error')
spb.add_argument('--port', type=int, default=PwicConst.DEFAULTS['port'], help='Target instance defined by the listened port', metavar=PwicConst.DEFAULTS['port'])
spb.add_argument('--force', action='store_true', help='No confirmation')
spb = subparsers.add_parser('execute-sql', help='Execute an SQL query on the database (dangerous)')
spb.add_argument('--file', default='', help='SQL query from file')
spb = subparsers.add_parser('shutdown-server', help='Terminate the server')
spb.add_argument('--port', type=int, default=PwicConst.DEFAULTS['port'], help='Target instance defined by the listened port', metavar=PwicConst.DEFAULTS['port'])
spb.add_argument('--force', action='store_true', help='No confirmation')
# Parse the command line
args = parser.parse_args()
if args.command == 'init-db':
return self.init_db()
if args.command == 'show-env':
return self.show_env(args.project, args.var, args.list)
if args.command == 'set-env':
return self.set_env(args.project, args.name, args.value, args.override, args.append, args.remove)
if args.command == 'repair-env':
return self.repair_env(args.test)
if args.command == 'show-mime':
return self.show_mime()
if args.command == 'show-projects':
return self.show_projects()
if args.command == 'create-project':
return self.create_project(args.project, args.description, args.admin)
if args.command == 'takeover-project':
return self.takeover_project(args.project, args.admin)
if args.command == 'split-project':
return self.split_project(args.project, args.no_history)
if args.command == 'delete-project':
return self.delete_project(args.project)
if args.command == 'list-users':
return self.list_users(args.project)
if args.command == 'show-user':
return self.show_user(args.user)
if args.command == 'create-user':
return self.create_user(args.user, args.totp)
if args.command == 'reset-password':
return self.reset_password(args.user, args.create, args.oauth)
if args.command == 'reset-totp':
return self.reset_totp(args.user, args.disable)
if args.command == 'assign-user':
return self.assign_user(args.project, args.user)
if args.command == 'revoke-user':
return self.revoke_user(args.user, args.force)
if args.command == 'show-audit':
return self.show_audit(args.min, args.max)
if args.command == 'show-login':
return self.show_login(args.days)
if args.command == 'show-stats':
return self.show_stats()
if args.command == 'show-inactivity':
return self.show_inactivity(args.project, args.days)
if args.command == 'compress-static':
return self.compress_static(args.revert)
if args.command == 'clear-cache':
return self.clear_cache(args.project, args.selective)
if args.command == 'regenerate-cache':
return self.regenerate_cache(args.project, args.user, args.full, args.port)
if args.command == 'rotate-logs':
return self.rotate_logs(args.count)
if args.command == 'archive-audit':
return self.archive_audit(args.selective, args.complete)
if args.command == 'show-git':
return self.show_git(args.agree)
if args.command == 'create-backup':
return self.create_backup()
if args.command == 'repair-documents':
return self.repair_documents(args.project, args.no_hash, args.no_magic, args.keep_orphans, args.test)
if args.command == 'execute-optimize':
return self.execute_optimize()
if args.command == 'unlock-db':
return self.unlock_db(args.port, args.force)
if args.command == 'execute-sql':
return self.execute_sql(args.file)
if args.command == 'shutdown-server':
return self.shutdown_server(args.port, args.force)
# Default behavior
parser.print_help()
return False
def _prepare_prettytable(self, fields: List[str], header: bool = True, border: bool = True) -> PrettyTable:
tab = PrettyTable()
tab.header = header
tab.border = border
tab.field_names = fields
for f in tab.field_names:
tab.align[f] = 'l'
return tab
# ==========
# Database
# ==========
def db_connect(self, init: bool = False, dbfile: str = PwicConst.DB_SQLITE) -> Optional[sqlite3.Cursor]:
if not init and not isfile(dbfile):
print('Error: the database is not created yet')
return None
try:
self.db, sql = PwicLib.connect(dbfile=dbfile,
dbaudit=PwicConst.DB_SQLITE_AUDIT if dbfile == PwicConst.DB_SQLITE else None)
return sql
except sqlite3.OperationalError:
print('Error: the database cannot be opened')
return None
def db_lock(self, sql: sqlite3.Cursor) -> bool:
if sql is None:
return False
try:
sql.execute(''' BEGIN EXCLUSIVE TRANSACTION''')
return True
except sqlite3.OperationalError:
return False
def db_create_tables_audit(self) -> bool:
sql = self.db_connect(init=True, dbfile=PwicConst.DB_SQLITE_AUDIT)
if sql is None:
return False
# Table AUDIT
sql.execute(''' CREATE TABLE "audit" (
"id" INTEGER NOT NULL,
"date" TEXT NOT NULL,
"time" TEXT NOT NULL,
"author" TEXT NOT NULL,
"event" TEXT NOT NULL,
"user" TEXT NOT NULL DEFAULT '',
"project" TEXT NOT NULL DEFAULT '',
"page" TEXT NOT NULL DEFAULT '',
"reference" INTEGER NOT NULL DEFAULT 0,
"string" TEXT NOT NULL DEFAULT '',
"ip" TEXT NOT NULL DEFAULT '',
PRIMARY KEY("id" AUTOINCREMENT)
)''')
sql.execute(''' CREATE INDEX "audit_index" ON "audit" (
"date",
"project"
)''')
sql.execute(''' CREATE TABLE "audit_arch" (
"id" INTEGER NOT NULL,
"date" TEXT NOT NULL,
"time" TEXT NOT NULL,
"author" TEXT NOT NULL,
"event" TEXT NOT NULL,
"user" TEXT NOT NULL,
"project" TEXT NOT NULL,
"page" TEXT NOT NULL,
"reference" INTEGER NOT NULL,
"string" TEXT NOT NULL,
"ip" TEXT NOT NULL,
PRIMARY KEY("id") -- No AUTOINCREMENT
)''')
# Triggers
sql.execute(''' CREATE TRIGGER audit_no_update
BEFORE UPDATE ON audit
BEGIN
SELECT RAISE (ABORT, 'The table AUDIT should not be modified');
END''')
sql.execute(''' CREATE TRIGGER audit_archiver
BEFORE DELETE ON audit
BEGIN
INSERT INTO audit_arch
SELECT *
FROM audit
WHERE id = OLD.id;
END''')
self.db_commit()
return True
def db_create_tables_main(self, dbfile: str = PwicConst.DB_SQLITE) -> bool:
sql = self.db_connect(init=True, dbfile=dbfile)
if sql is None:
return False
dt = PwicLib.dt()
# Table PROJECTS
sql.execute(''' CREATE TABLE "projects" (
"project" TEXT NOT NULL,
"description" TEXT NOT NULL,
"date" TEXT NOT NULL,
PRIMARY KEY("project")
)''')
sql.execute(''' INSERT INTO projects (project, description, date)
VALUES ('', '', ?)''',
(dt['date'], ))
# Table ENV
sql.execute(''' CREATE TABLE "env" (
"project" TEXT NOT NULL, -- Never default to ''
"key" TEXT NOT NULL,
"value" TEXT NOT NULL,
FOREIGN KEY("project") REFERENCES "projects"("project"),
PRIMARY KEY("key","project")
)''')
# Table USERS
sql.execute(''' CREATE TABLE "users" (
"user" TEXT NOT NULL,
"password" TEXT NOT NULL,
"initial" TEXT NOT NULL CHECK("initial" IN ('', 'X')),
"totp" TEXT NOT NULL,
"password_date" TEXT NOT NULL,
"password_time" TEXT NOT NULL,
PRIMARY KEY("user")
)''')
for e in ['', PwicConst.USERS['anonymous'], PwicConst.USERS['ghost']]:
sql.execute(''' INSERT INTO users (user, password, initial, totp, password_date, password_time)
VALUES (?, '', '', '', ?, ?)''',
(e, dt['date'], dt['time']))
# Table ROLES
sql.execute(''' CREATE TABLE "roles" (
"project" TEXT NOT NULL,
"user" TEXT NOT NULL,
"admin" TEXT NOT NULL DEFAULT '' CHECK("admin" IN ('', 'X') AND ("admin" = "X" OR "manager" = "X" OR "editor" = "X" OR "validator" = "X" OR "reader" = "X")),
"manager" TEXT NOT NULL DEFAULT '' CHECK("manager" IN ('', 'X')),
"editor" TEXT NOT NULL DEFAULT '' CHECK("editor" IN ('', 'X')),
"validator" TEXT NOT NULL DEFAULT '' CHECK("validator" IN ('', 'X')),
"reader" TEXT NOT NULL DEFAULT '' CHECK("reader" IN ('', 'X')),
"disabled" TEXT NOT NULL DEFAULT '' CHECK("disabled" IN ('', 'X')),
FOREIGN KEY("project") REFERENCES "projects"("project"),
FOREIGN KEY("user") REFERENCES "users"("user"),
PRIMARY KEY("user","project")
)''')
# Table PAGES
sql.execute(''' CREATE TABLE "pages" (
"project" TEXT NOT NULL,
"page" TEXT NOT NULL CHECK("page" <> ''),
"revision" INTEGER NOT NULL CHECK("revision" > 0),
"latest" TEXT NOT NULL DEFAULT 'X' CHECK("latest" IN ('', 'X')),
"draft" TEXT NOT NULL DEFAULT '' CHECK("draft" IN ('', 'X')),
"final" TEXT NOT NULL DEFAULT '' CHECK("final" IN ('', 'X')),
"header" TEXT NOT NULL DEFAULT '' CHECK("header" IN ('', 'X')),
"protection" TEXT NOT NULL DEFAULT '' CHECK("protection" IN ('', 'X')),
"author" TEXT NOT NULL CHECK("author" <> ''),
"date" TEXT NOT NULL CHECK("date" <> ''),
"time" TEXT NOT NULL CHECK("time" <> ''),
"title" TEXT NOT NULL CHECK("title" <> ''),
"markdown" TEXT NOT NULL DEFAULT '',
"tags" TEXT NOT NULL DEFAULT '',
"comment" TEXT NOT NULL CHECK("comment" <> ''),
"milestone" TEXT NOT NULL DEFAULT '',
"valuser" TEXT NOT NULL DEFAULT '',
"valdate" TEXT NOT NULL DEFAULT '',
"valtime" TEXT NOT NULL DEFAULT '',
PRIMARY KEY("project","page","revision"),
FOREIGN KEY("author") REFERENCES "users"("user"),
FOREIGN KEY("valuser") REFERENCES "users"("user"),
FOREIGN KEY("project") REFERENCES "projects"("project")
)''')
sql.execute(''' CREATE INDEX "pages_index" ON "pages" (
"project",
"page",
"latest"
)''')
# Table CACHE
sql.execute(''' CREATE TABLE "cache" (
"project" TEXT NOT NULL,
"page" TEXT NOT NULL,
"revision" INTEGER NOT NULL,
"html" TEXT NOT NULL,
FOREIGN KEY("project") REFERENCES "projects"("project"),
PRIMARY KEY("project","page","revision")
)''')
# Table DOCUMENTS
sql.execute(''' CREATE TABLE "documents" (
"id" INTEGER NOT NULL,
"project" TEXT NOT NULL CHECK("project" <> ''),
"page" TEXT NOT NULL CHECK("page" <> ''),
"filename" TEXT NOT NULL CHECK("filename" <> ''),
"mime" TEXT NOT NULL CHECK("mime" <> ''),
"size" INTEGER NOT NULL CHECK("size" > 0),
"width" INTEGER NOT NULL CHECK("width" >= 0),
"height" INTEGER NOT NULL CHECK("height" >= 0),
"hash" TEXT NOT NULL DEFAULT '' CHECK("hash" <> ''),
"author" TEXT NOT NULL CHECK("author" <> ''),
"date" TEXT NOT NULL CHECK("date" <> ''),
"time" TEXT NOT NULL CHECK("time" <> ''),
"exturl" TEXT NOT NULL,
FOREIGN KEY("project") REFERENCES "projects"("project"),
FOREIGN KEY("author") REFERENCES "users"("user"),
PRIMARY KEY("id" AUTOINCREMENT),
UNIQUE("project","filename")
)''')
self.db_commit()
return True
def db_commit(self) -> None:
if self.db is not None:
self.db.commit()
def db_rollback(self) -> None:
if self.db is not None:
self.db.rollback()
def db_sql2table(self, sql: sqlite3.Cursor) -> Optional[PrettyTable]:
tab = None
for row in sql.fetchall():
if tab is None:
tab = self._prepare_prettytable([k[:1].upper() + k[1:] for k in row])
tab.add_row([str(row[k]).replace('\r', '').replace('\n', ' ').strip()[:255].strip() for k in row])
return tab
# =========
# Methods
# =========
def init_db(self) -> bool:
# Check that the database does not exist already
if not isdir(PwicConst.DB):
mkdir(PwicConst.DB)
if isfile(PwicConst.DB_SQLITE) or isfile(PwicConst.DB_SQLITE_AUDIT):
print('Error: the databases are already created')
return False
# Create the dbfiles
ok = self.db_create_tables_audit() and self.db_create_tables_main() # Audit first
if not ok:
print('Error: the databases cannot be created')
return False
# Connect to the databases
sql = self.db_connect()
if sql is None:
print('Error: the databases cannot be opened')
return False
# Add the default, safe or mandatory configuration
PwicLib.audit(sql, {'author': PwicConst.USERS['system'],
'event': 'init-db'})
for (key, value) in [('base_url', f'http://127.0.0.1:{PwicConst.DEFAULTS["port"]}')]:
sql.execute(''' INSERT INTO env (project, key, value)
VALUES ('', ?, ?)''',
(key, value))
PwicLib.audit(sql, {'author': PwicConst.USERS['system'],
'event': f'set-{key}',
'string': '' if PwicConst.ENV[key].private else value})
# Confirmation
self.db_commit()
print(f'The databases are created in "{PwicConst.DB_SQLITE}" and "{PwicConst.DB_SQLITE_AUDIT}"')
return True
def show_env(self, project: str, var: str, dolist: bool) -> bool:
# Package info
if var == '':
try:
from importlib.metadata import PackageNotFoundError, version
print('Python packages:')
tab = self._prepare_prettytable(['Package', 'Version'])
tab.align['Version'] = 'r'
for package in ['aiohttp', 'aiohttp-cors', 'aiohttp-session', 'cryptography', 'imagesize',
'jinja2', 'PrettyTable', 'pygments', 'pyotp']:
try:
tab.add_row([package, version(package)])
except PackageNotFoundError:
pass
print(tab.get_string())
except ImportError:
pass
# Environment variables
sql = self.db_connect()
if sql is None:
return False
print('\nGlobal and project-dependent variables:')
if var != '':
sql.execute(''' SELECT project, key, value
FROM env
WHERE key LIKE ?
AND value <> ''
ORDER BY project, key''',
('%%%s%%' % var.replace('*', '%'), ))
else:
sql.execute(''' SELECT project, key, value
FROM env
WHERE value <> ''
ORDER BY project, key''')
ok = False
tab = self._prepare_prettytable(['Project', 'Key', 'Value'])
for row in sql.fetchall():
if (project != '') and (row['project'] not in ['', project]):
continue
value = row['value']
if (row['key'] in PwicConst.ENV) and PwicConst.ENV[row['key']].private:
value = '(Secret value not displayed)'
value = value.replace('\r', '').replace('\n', '\\n')
if dolist:
print(f'{row["project"] or "*"}.{row["key"]} = {value}')
else:
tab.add_row([row['project'], row['key'], value])
ok = True
if tab.rowcount > 0:
print(tab.get_string())
return ok
def set_env(self, project: str, key: str, value: str, override: bool, append: bool, remove: bool) -> bool:
# Check the parameters
if override and (project != ''):
print('Error: useless parameter --override if a project is indicated')
return False
if append and remove:
print('Error: the options append and remove cannot be used together')
return False
allkeys = list(PwicConst.ENV)
if key not in allkeys:
print('Error: the name of the variable must be one of "%s"' % ', '.join(allkeys))
return False
if (project != '') and not PwicConst.ENV[key].pdep:
print('Error: the parameter is not project-dependent')
return False
if (project == '') and not PwicConst.ENV[key].pindep:
print('Error: the parameter is not project-independent')
return False
value = value.replace('\r', '').strip()
# Connect to the database
sql = self.db_connect()
if sql is None:
return False
# Adapt the value
current = str(PwicLib.option(sql, project, key, ''))
if remove:
value = current.replace(value, '').replace(' ', ' ').strip()
elif append:
value = f'{current} {value}'.strip()
# Reset the project-dependent values if --override
if override:
sql.execute(''' SELECT project
FROM env
WHERE project <> ''
AND key = ?''',
(key, ))
for row in sql.fetchall():
PwicLib.audit(sql, {'author': PwicConst.USERS['system'],
'event': f'unset-{key}',
'project': row['project']})
sql.execute(''' DELETE FROM env WHERE key = ?''', (key, ))
# Update the variable
if value == '':
sql.execute(''' DELETE FROM env
WHERE project = ?
AND key = ?''',
(project, key))
verb = 'deleted'
else:
sql.execute(''' INSERT OR REPLACE INTO env (project, key, value)
VALUES (?, ?, ?)''',
(project, key, value))
verb = 'updated'
PwicLib.audit(sql, {'author': PwicConst.USERS['system'],
'event': '%sset-%s' % ('un' if value == '' else '', key),
'project': project,
'string': '' if PwicConst.ENV[key].private else value})
self.db_commit()
if project != '':
print(f'Variable {verb} for the project "{project}"')
else:
print(f'Variable {verb} globally')
return True
def repair_env(self, test: bool) -> bool:
# Connect to the database
sql = self.db_connect()
if sql is None:
return False
# Analyze each variables
all_keys = list(PwicConst.ENV)
buffer = []
sql.execute(''' SELECT project, key, value
FROM env
ORDER BY project, key''')
for row in sql.fetchall():
if (((row['key'] not in all_keys)
or ((row['project'] != '') and not PwicConst.ENV[row['key']].pdep)
or ((row['project'] == '') and not PwicConst.ENV[row['key']].pindep)
or (row['value'] in [None, '']))):
buffer.append((row['project'], row['key']))
if not test:
for e in buffer:
sql.execute(''' DELETE FROM env
WHERE project = ?
AND key = ?''', e)
PwicLib.audit(sql, {'author': PwicConst.USERS['system'],
'event': f'unset-{e[1]}',
'project': e[0]})
self.db_commit()
# Report
if len(buffer) == 0:
print('No change is required.')
else:
if test:
print('List of the options to be deleted:')
else:
print('List of the deleted options:')
tab = self._prepare_prettytable(['Project', 'Variable'])
tab.add_rows(buffer)
print(tab.get_string())
return True
def show_mime(self) -> bool:
# Load the platform-dependent library
try:
import winreg
win = True
except ImportError:
win = False
# Mime types for Linux
if not win:
system('cat /etc/mime.types')
return True
# Buffer
tab = self._prepare_prettytable(['Extension', 'MIME'])
tab.sortby = 'Extension'
# Read all the file extensions
root = winreg.HKEY_CLASSES_ROOT
for i in range(winreg.QueryInfoKey(root)[0]):
name = winreg.EnumKey(root, i)
if name[:1] == '.':
# Read the declared content type
handle = winreg.OpenKey(root, name)
try:
value, typ = winreg.QueryValueEx(handle, 'Content Type')
except FileNotFoundError:
value, typ = None, winreg.REG_NONE
winreg.CloseKey(handle)
# Consider the mime if it exists
if typ == winreg.REG_SZ:
tab.add_row([name, value])
# Final output
print(tab.get_string())
return True
def show_projects(self) -> bool:
# Connect to the database
sql = self.db_connect()
if sql is None:
return False
# Select the projects
sql.execute(''' SELECT a.project, a.description, b.user
FROM projects AS a
LEFT OUTER JOIN roles AS b
ON b.project = a.project
AND b.admin = 'X'
AND b.disabled = ''
WHERE a.project <> ''
ORDER BY a.project ASC,
b.user ASC''')
data = {}
for row in sql.fetchall():
if row['project'] not in data:
data[row['project']] = {'description': row['description'],
'admin': []}
if row['user'] is not None:
data[row['project']]['admin'].append(row['user'])
# Display the entries
tab = self._prepare_prettytable(['Project', 'Description', 'Administrators', 'Count'])
for key in data:
tab.add_row([key, data[key]['description'], ', '.join(data[key]['admin']), len(data[key]['admin'])])
print(tab.get_string())
return True
def create_project(self, project: str, description: str, admin: str) -> bool:
# Check the arguments
project = PwicLib.safe_name(project)
description = description.strip()
admin = PwicLib.safe_user_name(admin)
if (((project in PwicConst.NOT_PROJECT)
or ('' in [description, admin])
or (project[:4] == 'pwic')
or (admin[:4] == 'pwic'))):
print('Error: invalid arguments')
return False
# Connect to the database
sql = self.db_connect()
if sql is None:
return False
dt = PwicLib.dt()
# Verify that the project does not exist yet
sql.execute(''' SELECT project FROM projects WHERE project = ?''', (project, ))
if sql.fetchone() is not None:
print('Error: the project already exists')
return False
# Create the workspace for the documents of the project
try:
path = PwicConst.DOCUMENTS_PATH % project
if not isdir(path):
makedirs(path)
except OSError:
print(f'Error: impossible to create "{path}"')
return False
# Add the user account
sql.execute(''' INSERT OR IGNORE INTO users (user, password, initial, totp, password_date, password_time)
VALUES (?, ?, 'X', '', ?, ?)''',
(admin, PwicLib.sha256(PwicConst.DEFAULTS['password']), dt['date'], dt['time']))
if sql.rowcount > 0:
PwicLib.audit(sql, {'author': PwicConst.USERS['system'],
'event': 'create-user',
'user': admin})
# Add the project
sql.execute(''' INSERT INTO projects (project, description, date) VALUES (?, ?, ?)''',
(project, description, dt['date']))
PwicLib.audit(sql, {'author': PwicConst.USERS['system'],
'event': 'create-project',
'project': project})
# Add the role
sql.execute(''' INSERT INTO roles (project, user, admin) VALUES (?, ?, 'X')''', (project, admin))
PwicLib.audit(sql, {'author': PwicConst.USERS['system'],
'event': 'grant-admin',
'project': project,
'user': admin})
sql.execute(''' INSERT INTO roles (project, user, reader, disabled) VALUES (?, ?, 'X', 'X')''', (project, PwicConst.USERS['anonymous']))
sql.execute(''' INSERT INTO roles (project, user, reader, disabled) VALUES (?, ?, 'X', 'X')''', (project, PwicConst.USERS['ghost']))
# Add a default homepage
sql.execute(''' INSERT INTO pages (project, page, revision, latest, header, author, date, time, title, markdown, comment)
VALUES (?, ?, 1, 'X', 'X', ?, ?, ?, 'Home', 'Thanks for using **Pwic.wiki**. This is the homepage.', 'Initial commit')''',
(project, PwicConst.DEFAULTS['page'], admin, dt['date'], dt['time']))
PwicLib.audit(sql, {'author': PwicConst.USERS['system'],
'event': 'create-revision',
'project': project,
'page': PwicConst.DEFAULTS['page'],
'reference': 1})
# Finalization
self.db_commit()
print('The project is created:')
print(f'- Project : {project}')
print(f'- Administrator : {admin}')
print(f'- Password : "{PwicConst.DEFAULTS["password"]}" or the existing password')
print('')
print('WARNING:')
print("To create new pages in the project, you must change your password and grant the role 'manager' or 'editor' to the suitable user account.")
print('')
print('Thanks for using Pwic.wiki!')
return True
def takeover_project(self, project: str, admin: str) -> bool:
# Connect to the database
sql = self.db_connect()
if sql is None:
return False
# Verify that the project exists
project = PwicLib.safe_name(project)
if project == '' or sql.execute(''' SELECT project
FROM projects
WHERE project = ?''',
(project, )).fetchone() is None:
print(f'Error: the project "{project}" does not exist')
return False
# Verify that the user is valid and has changed his password
admin = PwicLib.safe_user_name(admin)
if admin[:4] == 'pwic':
return False
if sql.execute(''' SELECT user
FROM users
WHERE user = ?
AND initial = '' ''',
(admin, )).fetchone() is None:
print(f'Error: the user "{admin}" is unknown or has not changed his password yet')
return False
# Assign the user to the project
if not self.db_lock(sql):
return False
sql.execute(''' UPDATE roles
SET admin = 'X',
disabled = ''
WHERE project = ?
AND user = ?''',
(project, admin))
if sql.rowcount == 0:
sql.execute(''' INSERT INTO roles (project, user, admin) VALUES (?, ?, 'X')''', (project, admin))
PwicLib.audit(sql, {'author': PwicConst.USERS['system'],
'event': 'grant-admin',
'project': project,
'user': admin})
self.db_commit()
print(f'The user "{admin}" is now an administrator of the project "{project}"')
return True
def split_project(self, projects: List[str], collapse: bool) -> bool:
# Helpers
def _transfer_record(sql: sqlite3.Cursor, table: str, row: Dict[str, Any]) -> None:
for k in row:
if isinstance(row[k], bool):
row[k] = PwicLib.x(row[k])
query = ''' INSERT OR REPLACE INTO %s
(%s) VALUES (%s)''' % (table,
', '.join(row.keys()),
', '.join('?' * len(row)))
sql.execute(query, list(row.values()))
# Connect to the database
sql = self.db_connect() # Don't lock this connection
if sql is None:
return False
# Fetch the projects
projects = sorted(set(projects))
if len(projects) == 0:
return False
for p in projects:
sql.execute(''' SELECT project
FROM projects
WHERE project = ?''',
(p, ))
if (sql.fetchone() is None) or (p != PwicLib.safe_name(p)):
print(f'Error: unknown project "{p}"')
return False
# Create the new database
fn = PwicConst.DB_SQLITE_BACKUP % 'split'
if isfile(fn):
print(f'Error: the split database "{fn}" already exists')
return False
if not self.db_create_tables_main(fn):
print('Error: the tables cannot be created in the the split database')
return False
try:
newsql = sqlite3.connect(fn).cursor()
except sqlite3.OperationalError:
print('Error: the split database cannot be opened')
return False
# Transfer the data
if not self.db_lock(sql):
return False
# ... projects
for p in projects:
row = sql.execute(''' SELECT *
FROM projects
WHERE project = ?''',
(p, )).fetchone()
_transfer_record(newsql, 'projects', row)
# ... users
buffer = []
for p in projects:
sql.execute(''' SELECT DISTINCT user
FROM ( SELECT user
FROM roles
WHERE project = ?
UNION
SELECT DISTINCT valuser AS user
FROM pages
WHERE project = ?
AND valuser <> ''
)
WHERE user NOT LIKE 'pwic%'
ORDER BY user''',
(p, p))
for row in sql.fetchall():
if row['user'] not in buffer:
buffer.append(row['user'])
for e in buffer:
sql.execute(''' SELECT *
FROM users
WHERE user = ?''',
(e, ))
for row in sql.fetchall():
_transfer_record(newsql, 'users', row)
# ... roles
for p in projects:
sql.execute(''' SELECT *
FROM roles
WHERE project = ?''',
(p, ))
for row in sql.fetchall():
_transfer_record(newsql, 'roles', row)
# ... env
for p in ([''] + projects):
sql.execute(''' SELECT *
FROM env
WHERE project = ?
AND key NOT LIKE 'pwic%'
AND value <> '' ''',
(p, ))
for row in sql.fetchall():
_transfer_record(newsql, 'env', row)
# ... pages
for p in projects: