-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathdoc_system.py
executable file
·1993 lines (1845 loc) · 60 KB
/
doc_system.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
#!/usr/bin/python
# -*- coding: utf-8 -*-
docsystemcfgname = 'doc_system.cfg'
warning = ''
debug = ''
do_debug = False
buggery = ''
doc ="""Documentation Generation System
Author: fyngyrz (Ben)
Contact: fyngyrz@gmail.com (bugs, feature requests, kudos, bitter rejections)
Project: doc_system.py
Homepage: https://github.com/fyngyrz/wtfm
License: None. It's free. *Really* free. Defy invalid social and legal norms.
Disclaimers: 1) Probably completely broken. Do Not Use. You were explicitly warned. Phbbbbt.
2) My code is blackbox, meaning I wrote it without reference to other people's code
3) I can't check other people's contributions effectively, so if you use any version
of doc_system.py that incorporates accepted commits from others, you are risking
the use of OPC, which may or may not be protected by copyright, patent, and the
like, because our intellectual property system is pathological. The risks and
responsibilities and any subsequent consequences are entirely yours. Have you
written your congresscritter about patent and copyright reform yet?
Incep Date: June 17th, 2015
LastRev: November 29th, 2017
LastDocRev: November 28th, 2017
Tab spacing: 4 (set your editor to this for sane formatting while reading)
Dev Env: Ubuntu 12.04.5 LTS, Python 2.7.3
Status: BETA
1st-Rel: 0.0.1
Version: 0.0.25 Beta
Policies: 1) I will make every effort to never remove functionality or
alter existing functionality once past BETA stage. Anything
new will be implemented as something new, thus preserving all
behavior and the API. The only intentional exceptions to this
are if a bug is found that does not match the intended behavior,
or I determine there is some kind of security risk. What I
*will* do is not document older and less capable versions of a
function, unless the new functionality is incapable of doing
something the older version(s) could do. So your use of older
API will always work (instead of being "deprecated" and then
yanked right out from under you), while the documentation
encourages new and (hopefully) better stuff. But remember,
this only applies to production code. Until the BETA status
is removed, ANYTHING may change. Having said that, if something
changes that seriously inconveniences you, let me know, and
I will try to do something about it if it is reasonably possible.
History: See changes.md
"""
import os
import cgi
import random
import Cookie
import datetime
from aa_webpage import *
from aa_formboiler import *
from aa_sqlite import *
from aa_tablelib import *
from aa_macro import *
from aa_datafile import *
# global configuration
# --------------------
cfg = readDataFile(docsystemcfgname)
xprefix = cfg['xprefix']
xsystem = cfg['xsystem']
dprefix = cfg['dprefix']
dname = cfg['dname']
password= cfg['passwords']
user = cfg['users']
limitip = cfg['iplimit']
logtime = cfg['logtime']
domain = cfg['domain']
timezone= cfg['timezone']
try:
logtime = int(logtime)
except:
logtime = 30
cookiejar = ''
charcounter = """
<SCRIPT>
function onCharInput()
{
var conpagechars = document.getElementById("pagecontentx").value;
var conpagecharcount = conpagechars.length.toString();
document.getElementById("pccount").innerHTML = conpagecharcount;
}
</SCRIPT>
"""
previewblock = """
<br>
<div style="text-align: center;">
<div style="padding: .5em;
overflow-y: auto;
overflow-x: auto;
white-space: pre-wrap;
margin-left: auto; margin-right: auto;
color: #00ff00;
text-align: left;
font-weight: bold;
width: 90%;
height: 8em;
background-color: #000000;
font-family: Courier;"
id="pretty"></div>
<div id="mesg"
style="width: 90%;
margin-left: auto; margin-right: auto;
text-align:
left;">Balance: </div>
<br>
<div onkeyup="onpCharInput(event)"
class="foo"
id="dpagecontentx"
contenteditable="true"
style="padding: .5em;
overflow-y: auto;
overflow-x: auto;
white-space: pre-wrap;
margin-left: auto; margin-right: auto;
font-family: Courier;
padding: .5em;
text-align: left;
border-color: #000000;
border-width: 1px;
border-style: solid;
width: 90%;
height: 8em;"></div>
<div style="margin-top: .5em; width: 90%; margin-left: auto; margin-right: auto; text-align: left;">
Content Size: <span class="bar" id="xpccount">0</span></div>
<div style="margin-left: auto; margin-right: auto; width: 90%;">
<button onclick=showem()>Click for Demo</button>
<button onclick=clearem()>Click to Clear</button>
</div>
<div style="width: 90%; margin-left: auto; margin-right: auto; text-align: left;">
<br>
<b>Reference:</b><br>
<a target="_blank" href="http://ourtimelines.com/aamacrodoc/tocpage.html">aa_macro manual</a><br>
<a target="_blank" href="http://ourtimelines.com/wtfm/tocpage.html">wtfm manual</a>
</div>
"""
previewscript = """<SCRIPT>
function clearem()
{
var clr = document.getElementById("dpagecontentx");
clr.focus();
clr.innerText = '';
clr = document.getElementById("pretty");
clr.innerText = '';
clr = document.getElementById("xpccount");
clr.innerHTML = '0';
}
function showem()
{
var samt = '<htmltag style="width: 30em;">foo<\/htmltag> {style content} [built-in content]\\n' +
'{style [built-in {style content} content]} unincorporated text\\n' +
'[built-in] {style} unincorporated "quoted" text can'+"'"+'t stop this\\n\\n' +
'[style italics <i>[b]</i>]\\n' +
'{italics slanty text}';
var src = document.getElementById("dpagecontentx");
src.innerText = samt;
onpCharInput('foo');
src.focus();
}
function onpCharInput(e)
{
var brco = "ffff00";
var brtco = "888888";
var brtag = "008800";
var sqco = "ff0000";
var sqtco = "ff8800";
var sqtag = "ff00ff";
var anco = "884444";
var antco = "5599FF";
var quco = "00ffff";
var qutco = "ffffff";
var squco = "ff00ff";
var squtco = "4488FF";
var msg = document.getElementById("mesg");
var src = document.getElementById("dpagecontentx");
var dig = document.getElementById("pretty");
var cpco = src.innerText;
var cpc = cpco;
var cpct = cpc.length.toString();
var cpcr = '';
var insq = 0;
var inbr = 0;
var inq = 0;
var ins = 0;
var pushed = '';
var bc = 0;
var sc = 0;
var sqb = 0;
var dqb = 0;
for (var i = 0; i < cpco.length; i++) // >
{
var c = cpco[i];
if (c == '[') { bc = bc + 1; inbr += 1; pushed = '<font color="#'+brtco+'">'; c = '<font color="#'+brco+'">' + c + '<\/font><font color="#'+brtag+'">'; }
else if (c == ']') { bc = bc - 1; inbr -= 1; pushed=''; c = '<\/font><font color="#'+brco+'">' + c + '<\/font>'; }
else if (c == '{') { sc = sc + 1; insq += 1; pushed = '<font color="#'+sqtco+'">'; c = '<font color="#'+sqco+'">' + c + '<\/font><font color="#'+sqtag+'">'; }
else if (c == '}') { sc = sc - 1; insq -= 1; pushed='';c = '<\/font><font color="#'+sqco+'">' + c + '<\/font>'; }
else if (c == '<') { insq += 1; c = '<font color="#'+anco+'">' + c + '<\/font><font color="#'+antco+'">'; }
else if (c == '>') { insq -= 1; c = '<\/font><font color="#'+anco+'">' + c + '<\/font>'; }
else if (c == ' ')
{
if (pushed != '') { c = '<\/font>' + c + pushed; pushed = ''; }
}
else if (c == '"')
{
if (dqb == 1) { dqb = 0; } else { dqb = 1; }
if (inq == 1) { inq=0; } else { inq=1;}
if (inq == 1)
{
c = '<font color="#'+quco+'">' + c + '<\/font>';
c = c + '<font color="#'+qutco+'">';
}
else // leaving quote
{
c = '<\/font><font color="#'+quco+'">' + c + '<\/font>';
}
}
else if (c == "'")
{
c = '<font color="#'+squco+'">' + c + '<\/font>';
}
else if (0) // (c == "'")
{
if (sqb == 1) { sqb = 0; } else { sqb = 1; }
if (ins == 1) { ins=0; } else { ins=1;}
if (ins == 1)
{
c = '<font color="#'+squco+'">' + c + '<\/font>';
c = c + '<font color="#'+squtco+'">';
}
else // leaving quote
{
c = '<\/font><font color="#'+squco+'">' + c + '<\/font>';
}
}
cpcr = cpcr + c;
}
dig.innerHTML = cpcr;
var tgt = document.getElementById("xpccount");
tgt.innerHTML = cpct;
var hi = '';
var ho = ''
var hsi = '';
var hso = ''
var dqi = 'ok';
var sqi = 'ok';
if (bc != 0) { hi = '<b><font color="#ff0000">'; ho = '<\/font><\/b>';}
if (sc != 0) { hsi = '<b><font color="#ff0000">'; hso = '<\/font><\/b>';}
if (sqb != 0) { sqi = '<b><font color="#ff0000">unbalanced<\/font>'; }
if (dqb != 0) { dqi = '<b><font color="#ff0000">unbalanced<\/font>'; }
msg.innerHTML = 'Balance: []='+hi+bc.toString()+ho+' / {}='+hsi+sc.toString()+hso+ ' / "='+dqi; //+"; // '="+sqi;
}
</SCRIPT>
"""
def bailer(msg=''):
global cookiejar
pbody = ''
if msg != '':
pbody += 'Security Error:<br>'+msg+'<br>'
pbody += '<FORM ACTION="'+xprefix+xsystem+'" METHOD="POST">\n'
pbody += '<TABLE>'
pbody += '<tr> <td align="right">Enter User name:</td> <td><INPUT TYPE="text" NAME="USERNAME" VALUE=""></td> <td><i>not</i> case sensitive</td> </tr>'
pbody += '<tr> <td align="right">Enter Password:</td> <td><INPUT TYPE="PASSWORD" NAME="password" VALUE=""></td><td><b>case sensitive</b></td> </tr>'
pbody += '<tr> <td align="center" colspan=3><INPUT TYPE="submit" VALUE="Submit"></td> </tr>'
pbody += '</table>'
pbody += '</FORM>\n'
print thePage( title = 'DocSystem Security',
styles = '',
body = pbody,
valid = 1,
forhead = '',
cookiejar = cookiejar,
forbody = '',
doctype = '4.01')
raise SystemExit
def signOut():
global domain
global xprefix
global cookiejar
sheet = ''
expiration = datetime.datetime(2000,1,1)
cookie = Cookie.SimpleCookie()
cookie["pwcheck"] = 'x'
cookie["pwcheck"]["domain"] = domain
cookie["pwcheck"]["path"] = xprefix
cookie["pwcheck"]["expires"] = expiration.strftime("%a, %d-%b-%Y %H:%M:%S PST")
sheet += cookie.output()+'\n'
cookie = Cookie.SimpleCookie()
cookie["pwname"] = 'x'
cookie["pwname"]["domain"] = domain
cookie["pwname"]["path"] = xprefix
cookie["pwname"]["expires"] = expiration.strftime("%a, %d-%b-%Y %H:%M:%S PST")
sheet += cookie.output()+'\n'
cookiejar = sheet
bailer('You have been signed out.')
# capture any incoming CGI for further manipulation
# -------------------------------------------------
form = cgi.FieldStorage()
# Logout
# ------
try: una = form['logout'].value
except:
pass
else:
try:
una = int(una)
except:
pass
else:
if una == 1:
signOut()
# Security
# ========
def whitelist(string):
s = ''
for c in string: # whitelisting A-Z, a-z and 0-9
good = 1
if c < '0' or c > 'z': good = 0
if c > '9' and c < 'A': good = 0
if c > 'Z' and c < 'a': good = 0
if c == '-': good = 1
if c == '_': good = 1
if good == 1:
s += c
return s
def lighten(s,ip):
def iterw(b):
return int(b / 256)
def iterx(n,c=1):
for x in range(0,c):
n = (n * 5) % 65536
return n
def itery(h):
h = iterw(h)
h2 = random.random() * 255.0
return (int(h) ^ int(h2))
def iterz():
qq = int(random.random() * 2.999) + 1
return qq
random.seed(s)
its = len(s)
rts = 1
for c in s:
its += ord(c)
rts += 1
b = 1
its *= 5
for i in range(0,its):
b = iterx(b)
o = ''
p = iterz()
r = 0
for c in ip:
b = iterx(b)
for c in s:
b = iterx(b)
v = itery(ord(c)) ^ iterw(b)
o += '%02x' % (v)
r += 1
if r == p:
o += '%02x' % (itery(b))
p = iterz()
r = 0
return o.upper()
# IPs first:
# ----------
ip = cgi.escape(os.environ.get("REMOTE_ADDR",'127.0.0.1'))
if limitip != 'None':
if limitip.find(',') != -1:
iplist = limitip.split(',')
else:
iplist = []
iplist.append(limitip)
ipins = []
try:
for i in iplist:
a,b,c,d = i.split('.')
if d.find('-') != -1: # if a range
rlist = d.split('-')
if len(rlist) != 2:
bailer('Config file error: iplist -range error')
istart = int(rlist[0])
iend = int(rlist[1])
if istart < 0 or istart > 255 or iend < 0 or iend > 255:
bailer('Config file error: iplist value error')
if istart > iend:
istart,iend = iend,istart
for ipr in range(istart,iend+1):
ipins.append(a+'.'+b+'.'+c+'.'+str(ipr))
else: # not a range
ipins.append(i)
iplist = ipins
except Exception,e:
bailer('Config file error: iplist:: '+str(e))
hit = False
for i in iplist:
if i == ip:
hit = True
if hit == False:
bailer('Firewalled')
# bailer('"'+i+'" "'+ip+'"')
# We'll need the browser cookies:
# -------------------------------
pwcheck = ''
pwuser = ''
cookisok = False
if "HTTP_COOKIE" in os.environ:
ccc = str(os.environ)
try:
cookie = Cookie.SimpleCookie(os.environ["HTTP_COOKIE"])
except Exception,e:
bailer('Cookies not found!')
cookisok = True
upw = None
una = None
pwcheck = None
pwuser = None
cookiesmatch = False
try: una = form['USERNAME'].value
except:
pass
try: upw = form['password'].value
except:
pass
if cookisok == True:
pwcheck = whitelist(str(cookie['pwcheck'].value))
pwuser = whitelist(str(cookie['pwname'].value))
# Now user(s) and password(s)
# ---------------------------
if user.find(',') != -1:
userlist = user.split(',')
else:
userlist = []
userlist.append(user)
if password.find(',') != -1:
pwlist = password.split(',')
else:
pwlist = []
pwlist.append(password)
ulen = len(userlist)
plen = len(pwlist)
if ulen != plen:
bailer('configuration file error')
# See if cookies sufficiently ID the user
# ---------------------------------------
if pwcheck != None and pwuser != None:
for u,p in zip(userlist,pwlist):
if u == pwuser and lighten(p,ip) == pwcheck:
cookiesmatch = True
if user != 'None' and cookiesmatch != True:
okay = False
for u,p in zip(userlist,pwlist):
if u == una and p == upw:
okay = True
if okay == False:
bailer()
# bailer('Username and password do not match'+str(una)+' '+str(upw))
# we're good based on PW form input, so we're
# going to need to set the cookies:
# -------------------------------------------
expiration = datetime.datetime.now() + datetime.timedelta(seconds=logtime)
cookie = Cookie.SimpleCookie()
cookie["pwcheck"] = lighten(upw,ip)
cookie["pwcheck"]["domain"] = domain
cookie["pwcheck"]["path"] = xprefix
cookie["pwcheck"]["expires"] = expiration.strftime("%a, %d-%b-%Y %H:%M:%S "+timezone)
cookiejar += cookie.output()+'\n'
cookie = Cookie.SimpleCookie()
cookie["pwname"] = user
cookie["pwname"]["domain"] = domain
cookie["pwname"]["path"] = xprefix
cookie["pwname"]["expires"] = expiration.strftime("%a, %d-%b-%Y %H:%M:%S "+timezone)
cookiejar += cookie.output()+'\n'
# special chars
# -------------
qtard = 'j8g67f54dlll9f8f7f'
stard = 'jfjfjn76876juj54g4g'
cmd = ''
searchterm = ''
casesensitive = True
# various forms of web- and db-safety things
# ==========================================
# Prepares data, typically already text, for placement into CGI INPUT elements
# ----------------------------------------------------------------------------
def dequote(s):
s = str(s)
s = s.replace('&','&') # So we don't eat character entities on the web
s = s.replace('"','"') # So we don't put quotes inside of quote-delimited CGI elements
s = s.replace('<','<') # deactivate all of ...
s = s.replace('>','>') # ...the tag delimiters
return s
# Prepares data, typically already text, for insertion into SQLite statements
# ---------------------------------------------------------------------------
def clean(s):
s = str(s)
s = s.replace("'",qtard) # no single quotes; save a placeholder instead
s = s.replace("\\",stard) # no backslashes; save a placeholder instead
s = s.replace('\r','') # no C/Rs, this is linux. EOL is 0x0a.
return s
# When text data comes out of SQLite, replace the placeholders
# ------------------------------------------------------------
def unclean(s):
s = str(s)
s = s.replace(qtard,"'") # put the single quotes back
s = s.replace(stard,"\\") # put the backslashes back
return s
# philter() prevents characters above 127 from breaking
# the ASCII string CODEC, a common failing of
# Python. It also replaces those instances with an
# HTML-entity encoded version of themselves so that
# They will display as something visible on the web,
# and be easily visible within the context of CGI
# data entry/editing FORM elements. All CGI input comes
# here before going anywhere else; ergo, no way to
# feed illegal characters to the Python v2 CGI from
# the web. :P
# -----------------------------------------------------
def philter(rawstring):
cleanstring = ''
for rawc in rawstring:
if ord(rawc) < 128:
cleanstring += rawc
else:
cleanstring += '&#%d;' % (ord(rawc))
return cleanstring
# set up meta tags and body colors
# --------------------------------
metags = '<meta name="robots" content="noindex,nofollow">\n'
colors = 'style="color: #000000; background-color: #FFFFFF;"'
# If DB does not exist, create it
# -------------------------------
dbname = "%s%s" % (dprefix,dname)
# This is used, occasionaly, when I need to add new columns
# It's a development thing, not part of normal operation
# ---------------------------------------------------------
if 0:
# sql = "ALTER TABLE pages ADD COLUMN pageloc TEXT"
# a = dbl(dbname,sql)
# debug += str(a)
pass
# The intent is to supply a starter database, with a starter
# project in it. But in case something untoward happens with
# SQLite3's compatability, or the database is lost, or you
# just want to start fresh, this will build a new, empty
# database when it finds that there isn't one available.
# ----------------------------------------------------------
try:
fh = open(dbname)
except:
psql = 'styles TEXT' # one row, one column: global styles
a = dbl(dbname,'CREATE TABLE globals(%s)') % (psql)
psql = 'previewpath TEXT,' # path to actual HTML files are from web perspective
psql += 'extension TEXT,' # the default file extension for projects. Typically '.html'
psql += 'name TEXT,' # the name of the project
psql += 'styles TEXT,' # the styles specific to the project
psql += 'target TEXT,' # path to actual HTML files from filesystem perspective
psql += 'parentname TEXT' # parent project name
a = dbl(dbname,'CREATE TABLE projects(%s)' % (psql))
psql = 'pagename TEXT' # the name of the web page to be created
psql = 'pageloc TEXT' # the non-default location of the file to be created
psql += ',projectname TEXT' # the name of the project which the page belongs to
psql += ',pagestyle TEXT' # the style that *wraps* this page
psql += ',pagelocals TEXT' # the styles local to this page
psql += ',content TEXT' # the actual page content
psql += ',extension TEXT' # if the page has a different extension than the default
psql += ',disable INTEGER default 0' # if the page is not to be generated
psql += ',noreseq INTEGER default 0' # if the page is not to be resequenced
psql += ',sequence INTEGER' # the order in which the pages are built and linked
a = dbl(dbname,'CREATE TABLE pages(%s)' % (psql))
if do_debug == True: debug += str(a)
else:
fh.close() # it's there
# CSS used on the doc system form page
# ------------------------------------
styles = """div#docwarn
{
margin-right: 100px;
margin-left: 80px;
margin-bottom: 10px;
clear: both;
padding-left: 10px;
padding-right: 10px;
padding-top: 5px;
padding-bottom: 5px;
border: 1px solid #000000;
background: #ffddff;
color: #000000;
}
div#docnote
{
margin-right: 100px;
margin-left: 80px;
margin-bottom: 10px;
clear: both;
padding-left: 10px;
padding-right: 10px;
padding-top: 5px;
padding-bottom: 5px;
border: 1px solid #000000;
background: #ddddff;
color: #000000;
}
.tooltip
{
position: relative;
display: inline-block;
border-bottom: 1px dotted black;
}
.tooltip .tooltiptext
{
position: absolute;
visibility: hidden;
width: 600px;
top: 125%;
left: 0px;
background-color: #ffff88;
color: #000000;
text-align: left;
padding: 5px;
border-radius: 5px;
border-color: #000000;
border-style: solid;
z-index: 1;
}
.tooltip:hover .tooltiptext
{
visibility: visible;
}
"""
# command lists used to populate the cmd bars on the three form types
# -------------------------------------------------------------------
rpacmds = ['save','generate','delete']
gpacmds = ['prev','next','list','search','load','resequence']
rprcmds = ['save','generate','delete']
gprcmds = ['list','load']
rstcmds = ['save','delete']
gstcmds = ['load']
# quick links to each of the three form types
# -------------------------------------------
palinks = [ ['Project Editor','mode=project'],
['Global Style Editor','mode=style'],
['Page Editor','mode=page']
]
# Here's the reference for the page form
# --------------------------------------
thereference = """<br>
<div id="docnote">
<b>Quick Reference:</b><br>
<br>
<i>Pre-defined locals</i><br>
<pre>
[v nextpage] = page and extension of the next page in sequence, or nothing
[v prevpage] = page and extension of the previous page in sequence, or nothing
[v current_page] = web page name from top of this form
</pre>
<i>Escapes</i><br>
<pre>
[lb] [rb] = [ ]
[ls] [rs] = { }
[sp] = space
[nl] or [lf] = newline
</pre>
</div>
"""
# These are the forms
# ===================
# Page form
# ---------
pabody = """
[WARNING]
<div style="text-align: center;">Page Editor — <a href="[XPREFIX][XSYSTEM]?logout=1">Click here to Log Out</a></div>
<FORM METHOD="POST" ACTION="[XPREFIX][XSYSTEM]">
[MODE]
<table style="margin: auto; background-color: rgb(240,240,240);" width="90%" border=1>
[PROJECTNAME]
[WEBPAGENAME]
[PAGELOC]
[EXTENSION]
<tr><td align="right"><font face="Courier">Seq Control:</font></td><td><table><tr><td>[PAGESEQ]</td><td>[NORESEQ]</td></tr></table></td></tr>
[PAGEDISABLE]
[PAGEALLOW]
[PAGESTYLE]
[PAGELOCAL]
[PAGECONTENT]
</table>
<table style="margin: auto; background-color: rgb(255,128,128);" width="80%" border=1>
<tr>[RCMDS]</tr>
</table>
<table style="margin: auto; background-color: rgb(128,255,128);" width="80%" border=1>
<tr>[GCMDS]</tr>
</table>
<table style="margin: auto; background-color: rgb(220,220,255);" width="70%" border=1>
<tr>[LINKS]</tr>
</table>
</FORM>
[DEBUG]
[PREVIEWER]
[REFERENCE]
[BUGGERY]
"""
# Style form
# ----------
stbody = """
<div style="text-align: center;">Global Style Editor - These apply to <i>all</i> documents<br>
<a href="[XPREFIX][XSYSTEM]?logout=1">Click here to Log Out</a></div>
[WARNING]
<FORM METHOD="POST" ACTION="[XPREFIX][XSYSTEM]">
[MODE]
<table style="margin: auto; background-color: rgb(240,240,240);" width="90%" border=1>
[STYLEALLOW]
[GLOBALSTYLES]
</table>
<table style="margin: auto; background-color: rgb(255,128,128);" width="80%" border=1>
<tr>[RCMDS]</tr>
<table style="margin: auto; background-color: rgb(128,255,128);" width="80%" border=1>
<tr>[GCMDS]</tr>
</table>
<table style="margin: auto; background-color: rgb(220,220,255);" width="70%" border=1>
<tr>[LINKS]</tr>
</table>
</FORM>
[PREVIEWER]
<br>
<div id="docwarn">
<b>Note:</b><br>
Only the <b>global</b> style form can be used here: <tt><b>[<b style="color: red;">gstyle</b> StyleDefinition]</b></tt><br>
Only the <b>global</b> variable form can be used here: <tt><b>[<b style="color: red;">global</b> VariableDefinition]</b></tt><br>
These styles apply to <i>all</i> projects
</div>
</div>
[DEBUG]
"""
# Project form
# ------------
prbody = """
[WARNING]
<div style="text-align: center;">Project Editor — <a href="[XPREFIX][XSYSTEM]?logout=1">Click here to Log Out</a></div>
<FORM METHOD="POST" ACTION="[XPREFIX][XSYSTEM]">
[MODE]
<table style="margin: auto; background-color: rgb(240,240,240);" width="90%" border=1>
[PROJECTNAME]
[PROJECTTARGET]
[PREVIEWPATH]
[PROJECTEXT]
[PROJECTALLOW]
[PARENTNAME]
[PROJECTSTYLES]
</table>
<table style="margin: auto; background-color: rgb(255,128,128);" width="80%" border=1>
<tr>[RCMDS]</tr>
</table>
<table style="margin: auto; background-color: rgb(128,255,128);" width="80%" border=1>
<tr>[GCMDS]</tr>
</table>
<table style="margin: auto; background-color: rgb(220,220,255);" width="70%" border=1>
<tr>[LINKS]</tr>
</table>
</FORM>
[PREVIEWER]
<br>
<div id="docwarn">
<b>Note:</b><br>
Only the <b>global</b> style form can be used here: <tt><b>[<b style="color: red;">gstyle</b> StyleDefinition]</b></tt><br>
Only the <b>global</b> variable form can be used here: <tt><b>[<b style="color: red;">global</b> VariableDefinition]</b></tt><br>
These styles are specific to this project
</div>
[DEBUG]
"""
# This produces a page listing all projects
# assuming there are any. Otherwise, sets
# mode to project and returns
# -----------------------------------------
def prolist():
global xprefix
global xsystem
global dbname
global mode
global cmd
global warning
global cookiejar
sql = 'SELECT name FROM projects'
a = dbl(dbname,sql)
content = '<div style="text-align: center;"><a href="[XPREFIX][XSYSTEM]?logout=1">Click here to Log Out</a></div>'
if a.rows != 0:
b = table("Projects")
for tup in a.tuples:
content += b.line(' <a href="%s%s?mode=project&projectname=%s">%s</a> ' % (xprefix,xsystem,str(tup[0]),str(tup[0])))
content += b.finish()
content += '<br><a href="%s%s?mode=project">Open Empty, Unnamed Project</a>' % (xprefix,xsystem)
content = content.replace('[XPREFIX]',xprefix)
content = content.replace('[XSYSTEM]',xsystem)
print thePage( title = 'Proj List',
styles = '',
body = content,
valid = 1,
forhead = metags+charcounter,
forbody = colors,
cookiejar = cookiejar,
doctype = '4.01')
exit()
else:
warning += '...No Projects Found<br>'
cmd = ''
mode = 'project'
return
# This changes ? and * into SQL's (stupid) '%' and '_' wildcards
# and provides for \? and \* escapes
# --------------------------------------------------------------
def wc_convert(term):
global warning
REALLYQMARK = 'hduw7yrQMARK5gh3fr89f'
REALLYASTER = 'te453gfASTERi94gk0f67'
REALLYUNDER = 'gtfcmgvUNDERlof7567h6'
REALLYPERCE = 'kljgu45PERCE79opjdtwc'
term = term.replace('\\?',REALLYQMARK)
term = term.replace('\\*',REALLYASTER)
term = term.replace('%',REALLYPERCE)
term = term.replace('_',REALLYUNDER)
term = term.replace('?','_')
term = term.replace('*','%')
term = term.replace(REALLYQMARK,'?')
term = term.replace(REALLYASTER,'*')
term = term.replace(REALLYPERCE,'\\%')
term = term.replace(REALLYUNDER,'\\_')
# warning = '"'+term+'"'
return '%'+term+'%'
# This produces a page listing all pages in a project
# ---------------------------------------------------
def paglist(term=None):
global xprefix
global xsystem
global dbname
global projectname
global warning
global cookiejar
# a = dbl(dbname,'PRAGMA case_sensitive_like=ON')
# warning += '<pre>\n'+str(a)+'\n</pre>'
tcolors = 'style="color: #442200; background-color: #FFEEDD;"'
ssql = ''
if term != None:
term = wc_convert(term)
if casesensitive == True:
ssql = " AND (pagelocals LIKE '"+term+"' OR content LIKE '"+term+"')"
else:
ssql = " AND (lower(pagelocals) LIKE lower('"+term+"')OR lower(content) LIKE lower('"+term+"'))"
sql = "SELECT pagename||'||||'||sequence||'||||'||noreseq FROM pages WHERE projectname='%s'%s ORDER BY sequence" % (projectname,ssql)
if casesensitive == True:
a = dbl(dbname,sql,cs=True)
else:
a = dbl(dbname,sql,cs=False)
content = '<div style="margin-bottom: .5em; text-align: center;"><a href="[XPREFIX][XSYSTEM]?logout=1">Click here to Log Out</a></div>'
content = content.replace('[XPREFIX]',xprefix)
content = content.replace('[XSYSTEM]',xsystem)
content += warning
if a.rows != 0:
seqlist = []
for tup in a.tuples:
seqlist.append(str(tup[0]))
alplist = sorted(seqlist)
n = len(seqlist)
bgc = 'FFEEDD'
ccc = 'ffeedd'
b = table("#","</tt> Page Order "," "," Alpha Order ")
b.options( hparms = 'align="right"||bgcolor="#%s"|' % (bgc),
lparms = 'align="right"||width=50 bgcolor="#%s"|' % (bgc))
cpna = '%s <b><font color="#008800">==></font></b>' % (projectname)
cpnb = '%s <b><font color="#880000">==></font></b>' % (projectname)
for i in range(0,n):
tik = seqlist[i]
tup,sn,nrs = tik.split('||||')
tak = alplist[i]
tap,discard,vnrs = tak.split('||||')
if nrs == '0':
cpn = cpna
else:
cpn = cpnb
if vnrs == '0':
cpnc = cpna
else:
cpnc = cpnb
content += b.line( sn,
' <a href="%s%s?mode=page&webpagename=%s&projectname=%s"> %s %s</a> ' % (xprefix,xsystem,str(tup),projectname,cpn,str(tup)),
' ',
' <a href="%s%s?mode=page&webpagename=%s&projectname=%s"> %s %s</a> ' % (xprefix,xsystem,str(tap),projectname,cpnc,str(tap))
)
content += b.finish()
content += '<p><b><font color="#008800">==></font></b> means pages will resequence<br>'
content += '<b><font color="#880000">==></font></b> means pages will <b>not</b> resequence</p>'
else:
content += '...No Pages Found<br>'
print thePage( title = 'Pages List',
styles = '',
body = content,
valid = 1,
forhead = metags,
cookiejar = cookiejar,
forbody = tcolors,
doctype = '4.01')
exit()
# defaults prior to reading CGI input
# -----------------------------------
mytitl = 'Untitled'
mybody = '<P>eh?</P>[DEBUG]'
# CGI defaults for page mode
# --------------------------
projectname = ''
parentname = ''
projectext = ''
webpagename = ''
extension = ''
pageseq = '10'
pagedisable = ''
noreseq = ''
pagestyle = ''
pageloc = ''
pagelocal = ''
pagecontent = ''
# cgi defalts for project mode
# ----------------------------
projectstyles = ''