summaryrefslogtreecommitdiffstats
path: root/Tools/faqwiz/faqmain.py
blob: c3d9c7d3fc6a19a5a192a685a804934e6ca79191 (plain)
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
#! /depot/sundry/plat/bin/python1.4

"""Interactive FAQ project.

XXX TO DO

- generic error handler
- should have files containing section headers
- customize rcs command pathnames
- recognize urls and email addresses and turn them into <A> tags
- use cookies to keep Name/email the same
- explanation of editing somewhere
- various embellishments, GIFs, crosslinks, hints, etc.
- create new sections
- rearrange entries
- delete entries
- send email on changes
- optional staging of entries until reviewed?
- freeze entries
- username/password for editors
- Change references to other Q's and whole sections
- Browse should display menu of 7 sections & let you pick
  (or frontpage should have the option to browse a section or all)
- support adding annotations, too

"""

NAMEPAT = "faq??.???.htp"
NAMEREG = "^faq\([0-9][0-9]\)\.\([0-9][0-9][0-9]\)\.htp$"

class FAQServer:

    def __init__(self):
	pass

    def main(self):
	self.form = cgi.FieldStorage()
	req = self.req or 'frontpage'
	try:
	    method = getattr(self, 'do_%s' % req)
	except AttributeError:
	    print "Unrecognized request type", req
	else:
	    method()
	    self.epilogue()

    KEYS = ['req', 'query', 'name', 'text', 'commit', 'title',
	    'author', 'email', 'log', 'section', 'number', 'add',
	    'version']

    def __getattr__(self, key):
	if key not in self.KEYS:
	    raise AttributeError
	try:
	    value = self.form[key].value
	    setattr(self, key, value)
	    return value
	except KeyError:
	    return ''

    def do_frontpage(self):
	self.prologue("Python FAQ (alpha) Front Page")
	print """
	<UL>
	<LI><A HREF="faq.py?req=index">FAQ index</A>
	<LI><A HREF="faq.py?req=all">The whole FAQ</A>
	<LI><A HREF="faq.py?req=roulette">FAQ roulette</A>
	<LI><A HREF="faq.py?req=recent">Recently changed FAQ entries</A>
	<LI><A HREF="faq.py?req=add">Add a new FAQ entry</A>
	</UL>

	<H2>Search the FAQ</H2>

	<FORM ACTION="faq.py?req=query">
	<INPUT TYPE=text NAME=query>
	<INPUT TYPE=submit VALUE="Search">
	<INPUT TYPE=hidden NAME=req VALUE=query>
	</FORM>

	Disclaimer: these pages are intended to be edited by anyone.
	Please exercise discretion when editing, don't be rude, etc.
	"""

    def do_index(self):
	self.prologue("Python FAQ Index")
	names = os.listdir(os.curdir)
	names.sort()
	section = None
	for name in names:
	    headers, text = self.read(name)
	    if headers:
		title = headers['title']
		i = string.find(title, '.')
		nsec = title[:i]
		if nsec != section:
		    if section:
			print """
			<P>
			<LI><A HREF="faq.py?req=add&amp;section=%s"
			>Add new entry</A> (at this point)
			</UL>
			""" % section
		    section = nsec
		    print "<H2>Section %s</H2>" % section
		    print "<UL>"
		print '<LI><A HREF="faq.py?req=show&name=%s">%s</A>' % (
		    name, cgi.escape(title))
	if section:
	    print """
	    <P>
	    <LI><A HREF="faq.py?req=add&amp;section=%s">Add new entry</A>
	    (at this point)
	    </UL>
	    """ % section
	else:
	    print "No FAQ entries?!?!"

    def do_show(self):
	name = self.name
	headers, text = self.read(name)
	if not headers:
	    print "Invalid file name", name
	    return
	self.show(name, headers['title'], text, 1)

    def do_all(self):
	self.prologue("The Whole Python FAQ")
	print "<HR>"
	names = os.listdir(os.curdir)
	names.sort()
	section = None
	for name in names:
	    headers, text = self.read(name)
	    if headers:
		title = headers['title']
		i = string.find(title, '.')
		nsec = title[:i]
		if nsec != section:
		    section = nsec
		    print "<H1>Section %s</H1>" % section
		    print "<HR>"
		self.show(name, title, text, 1)
	if not section:
	    print "No FAQ entries?!?!"

    def do_roulette(self):
	import whrandom
	self.prologue("Python FAQ Roulette")
	print """
	Please check the correctness of the entry below.
	If you find any problems, please edit the entry.
	<P>
	<HR>
	"""
	names = os.listdir(os.curdir)
	while names:
	    name = whrandom.choice(names)
	    headers, text = self.read(name)
	    if headers:
		self.show(name, headers['title'], text, 1)
		print '<P><A HREF="faq.py?req=roulette">Show another one</A>'
		break
	    else:
		names.remove(name)
	else:
	    print "No FAQ entries?!?!"

    def do_recent(self):
	import fnmatch, stat
	names = os.listdir(os.curdir)
	now = time.time()
	list = []
	for name in names:
	    if not fnmatch.fnmatch(name, NAMEPAT):
		continue
	    try:
		st = os.stat(name)
	    except os.error:
		continue
	    tuple = (st[stat.ST_MTIME], name)
	    list.append(tuple)
	list.sort()
	list.reverse()
	self.prologue("Python FAQ, Most Recently Modified First")
	print "<HR>"
	n = 0
	for (mtime, name) in list:
	    headers, text = self.read(name)
	    if headers:
		self.show(name, headers['title'], text, 1)
		n = n+1
	if not n:
	    print "No FAQ entries?!?!"

    def do_query(self):
	import regex
	self.prologue("Python FAQ Query Results")
	query = self.query
	if not query:
	    print "No query string"
	    return
	p = regex.compile(query, regex.casefold)
	names = os.listdir(os.curdir)
	names.sort()
	print "<HR>"
	n = 0
	for name in names:
	    headers, text = self.read(name)
	    if headers:
		title = headers['title']
		if p.search(title) >= 0 or p.search(text) >= 0:
		    self.show(name, title, text, 1)
		    n = n+1
	if not n:
	    print "No hits."

    def do_add(self):
	section = self.section
	if not section:
	    self.prologue("How to add a new FAQ entry")
	    print """
	    Go to the <A HREF="faq.py?req=index">FAQ index</A>
	    and click on the "Add new entry" link at the end
	    of the section to which you want to add the entry.
	    """
	    return
	try:
	    nsec = string.atoi(section)
	except ValueError:
	    print "Bad section number", nsec
	names = os.listdir(os.curdir)
	max = 0
	import regex
	prog = regex.compile(NAMEREG)
	for name in names:
	    if prog.match(name) >= 0:
		s1, s2 = prog.group(1, 2)
		n1, n2 = string.atoi(s1), string.atoi(s2)
		if n1 == nsec:
		    if n2 > max:
			max = n2
	if not max:
	    print "Can't add new sections yet."
	    return
	num = max+1
	name = "faq%02d.%03d.htp" % (nsec, num)
	self.name = name
	self.add = "yes"
	self.number = str(num)
	self.do_edit()

    def do_edit(self):
	name = self.name
	headers, text = self.read(name)
	if not headers:
	    print "Invalid file name", name
	    return
	self.prologue("Python FAQ Edit Form")
	title = headers['title']
	version = self.getversion(name)
	print "<FORM METHOD=POST ACTION=faq.py>"
	self.showedit(name, title, text)
	if self.add:
	    print """
	    <INPUT TYPE=hidden NAME=add VALUE=%s>
	    <INPUT TYPE=hidden NAME=section VALUE=%s>
	    <INPUT TYPE=hidden NAME=number VALUE=%s>
	    """ % (self.add, self.section, self.number)
	print """
	<INPUT TYPE=submit VALUE="Review Edit">
	<INPUT TYPE=hidden NAME=req VALUE=review>
	<INPUT TYPE=hidden NAME=name VALUE=%s>
	<INPUT TYPE=hidden NAME=version VALUE=%s>
	</FORM>
	<HR>
	""" % (name, version)
	self.show(name, title, text)

    def do_review(self):
	if self.commit:
	    self.checkin()
	    return
	name = self.name
	text = self.text
	title = self.title
	headers, oldtext = self.read(name)
	if not headers:
	    print "Invalid file name", name
	    return
	self.prologue("Python FAQ Review Form")
	print "<HR>"
	self.show(name, title, text)
	print "<FORM METHOD=POST ACTION=faq.py>"
	if self.log and self.author and '@' in self.email:
	    print """
	    <INPUT TYPE=submit NAME=commit VALUE="Commit">
	    Click this button to commit the change.
	    <P>
	    <HR>
	    <P>
	    """
	else:
	    print """
	    To commit this change, please enter your name,
	    email and a log message in the form below.
	    <P>
	    <HR>
	    <P>
	    """
	self.showedit(name, title, text)
	if self.add:
	    print """
	    <INPUT TYPE=hidden NAME=add VALUE=%s>
	    <INPUT TYPE=hidden NAME=section VALUE=%s>
	    <INPUT TYPE=hidden NAME=number VALUE=%s>
	    """ % (self.add, self.section, self.number)
	print """
	<BR>
	<INPUT TYPE=submit VALUE="Review Edit">
	<INPUT TYPE=hidden NAME=req VALUE=review>
	<INPUT TYPE=hidden NAME=name VALUE=%s>
	<INPUT TYPE=hidden NAME=version VALUE=%s>
	</FORM>
	<HR>
	""" % (name, self.version)

    def do_info(self):
	name = self.name
	headers, text = self.read(name)
	if not headers:
	    print "Invalid file name", name
	    return
	print '<PRE>'
	sys.stdout.flush()
	os.system("/depot/gnu/plat/bin/rlog -r %s </dev/null 2>&1" % self.name)
	print '</PRE>'
	print '<A HREF="faq.py?req=rlog&name=%s">View full rcs log</A>' % name

    def do_rlog(self):
	name = self.name
	headers, text = self.read(name)
	if not headers:
	    print "Invalid file name", name
	    return
	print '<PRE>'
	sys.stdout.flush()
	os.system("/depot/gnu/plat/bin/rlog %s </dev/null 2>&1" % self.name)
	print '</PRE>'

    def checkin(self):
	import regsub, time, tempfile
	name = self.name

	headers, oldtext = self.read(name)
	if not headers:
	    print "Invalid file name", name
	    return
	version = self.version
	curversion = self.getversion(name)
	if version != curversion:
	    print "Version conflict."
	    print "You edited version %s but current version is %s." % (
		version, curversion)
	    print '<A HREF="faq.py?req=show&name=%s">Reload.</A>' % name
	    return
	text = self.text
	title = self.title
	author = self.author
	email = self.email
	log = self.log
	text = regsub.gsub("\r\n", "\n", text)
	log = regsub.gsub("\r\n", "\n", log)
	author = string.join(string.split(author))
	email = string.join(string.split(email))
	title = string.join(string.split(title))
	oldtitle = headers['title']
	oldtitle = string.join(string.split(oldtitle))
	text = string.strip(text)
	oldtext = string.strip(oldtext)
	if text == oldtext and title == oldtitle:
	    print "No changes."
	    # XXX Should exit more ceremoniously
	    return
	# Check that the FAQ entry number didn't change
	if string.split(title)[:1] != string.split(oldtitle)[:1]:
	    print "Don't change the FAQ entry number please."
	    # XXX Should exit more ceremoniously
	    return
	remhost = os.environ["REMOTE_HOST"]
	remaddr = os.environ["REMOTE_ADDR"]
	try:
	    os.unlink(name + "~")
	except os.error:
	    pass
	try:
	    os.rename(name, name + "~")
	except os.error:
	    pass
	try:
	    os.unlink(name)
	except os.error:
	    pass
	try:
	    f = open(name, "w")
	except IOError, msg:
	    print "Can't open", name, "for writing:", cgi.escape(str(msg))
	    # XXX Should exit more ceremoniously
	    return
	now = time.ctime(time.time())
	f.write("Title: %s\n" % title)
	f.write("Last-Changed-Date: %s\n" % now)
	f.write("Last-Changed-Author: %s\n" % author)
	f.write("Last-Changed-Email: %s\n" % email)
	f.write("Last-Changed-Remote-Host: %s\n" % remhost)
	f.write("Last-Changed-Remote-Address: %s\n" % remaddr)
	keys = headers.keys()
	keys.sort()
	keys.remove('title')
	for key in keys:
	    if key[:13] != 'last-changed-':
		f.write("%s: %s\n" % (string.capwords(key, '-'),
				      headers[key]))
	f.write("\n")
	f.write(text)
	f.write("\n")
	f.close()

	tfn = tempfile.mktemp()
	f = open(tfn, "w")
	f.write("Last-Changed-Date: %s\n" % now)
	f.write("Last-Changed-Author: %s\n" % author)
	f.write("Last-Changed-Email: %s\n" % email)
	f.write("Last-Changed-Remote-Host: %s\n" % remhost)
	f.write("Last-Changed-Remote-Address: %s\n" % remaddr)
	f.write("\n")
	f.write(log)
	f.write("\n")
	f.close()
	
	p = os.popen("""
	/depot/gnu/plat/bin/rcs -l %s </dev/null 2>&1
	/depot/gnu/plat/bin/ci -u %s <%s 2>&1
	rm -f %s
	""" % (name, name, tfn, tfn))
	output = p.read()
	sts = p.close()
	if not sts:
	    self.prologue("Python FAQ Entry Edited")
	    print "<HR>"
	    self.show(name, title, text, 1)
	    if output:
		print "<PRE>%s</PRE>" % cgi.escape(output)
	else:
	    print """
	    <H1>Python FAQ Entry Commit Failed</H1>
	    Exit status 0x%04x
	    """ % sts
	    if output:
		print "<PRE>%s</PRE>" % cgi.escape(output)

    def showedit(self, name, title, text):
	print """
	Title: <INPUT TYPE=text SIZE=70 NAME=title VALUE="%s"<BR>
	<TEXTAREA COLS=80 ROWS=20 NAME=text>""" % title
	print cgi.escape(string.strip(text))
	print """</TEXTAREA>
	<BR>
	Please provide the following information for logging purposes:
	<BR>
	<CODE>Name : </CODE><INPUT TYPE=text SIZE=70 NAME=author VALUE="%s"<BR>
	<CODE>Email: </CODE><INPUT TYPE=text SIZE=70 NAME=email VALUE="%s"<BR>
	Log message (reason for the change):<BR>
	<TEXTAREA COLS=80 ROWS=5 NAME=log>\n%s\n</TEXTAREA>
	""" % (self.author, self.email, self.log)

    def showheaders(self, headers):
	print "<UL>"
	keys = map(string.lower, headers.keys())
	keys.sort()
	for key in keys:
	    print "<LI><B>%s:</B> %s" % (string.capwords(key, '-'),
					 headers[key] or '')
	print "</UL>"

    def read(self, name):
	import fnmatch, rfc822
	if not fnmatch.fnmatch(name, NAMEPAT):
	    return None, None
	if self.add:
	    try:
		fname = "faq%02d.%03d.htp" % (string.atoi(self.section),
					      string.atoi(self.number))
	    except ValueError:
		return None, None
	    if fname != name:
		return None, None
	    headers = {'title': "%s.%s. " % (self.section, self.number)}
	    text = ""
	    return headers, text
	f = open(name)
	headers = rfc822.Message(f)
	text = f.read()
	f.close()
	return headers, text

    def show(self, name, title, text, edit=0):
	# XXX Should put <A> tags around recognizable URLs
	# XXX Should also turn "see section N" into hyperlinks
	print "<H2>%s</H2>" % cgi.escape(title)
	pre = 0
	for line in string.split(text, '\n'):
	    if not string.strip(line):
		if pre:
		    print '</PRE>'
		    pre = 0
		else:
		    print '<P>'
	    else:
		if line == string.lstrip(line):	# I.e., no leading whitespace
		    if pre:
			print '</PRE>'
			pre = 0
		else:
		    if not pre:
			print '<PRE>'
			pre = 1
		print cgi.escape(line)
	if pre:
	    print '</PRE>'
	    pre = 0
	print '<P>'
	if edit:
	    print """
	    <A HREF="faq.py?req=edit&name=%s">Edit this entry</A> /
	    <A HREF="faq.py?req=info&name=%s" TARGET=_blank>Log info</A>
	    """ % (name, name)
	    print '<P>'
	print "<HR>"

    def getversion(self, name):
	p = os.popen("/depot/gnu/plat/bin/rlog -h %s </dev/null 2>&1" % name)
	head = ""
	while 1:
	    line = p.readline()
	    if not line:
		break
	    if line[:5] == 'head:':
		head = string.strip(line[5:])
	p.close()
	return head

    def prologue(self, title):
	title = cgi.escape(title)
	print '''\
	<HTML>
	<HEAD>
	<TITLE>%s</TITLE>
	</HEAD>
	<BODY BACKGROUND="http://www.python.org/pics/RedShort.gif"
	      BGCOLOR="#FFFFFF"
	      TEXT="#000000"
	      LINK="#AA0000"
	      VLINK="#906A6A">
	<H1>%s</H1>
	''' % (title, title)

    def epilogue(self):
	print '''
	<P>
	<HR>
	<A HREF="mailto:guido@python.org">GvR</A>
	</BODY>
	</HTML>
	'''

print "Content-type: text/html\n"
dt = 0
try:
    import time
    t1 = time.time()
    import cgi, string, os, sys
    x = FAQServer()
    x.main()
    t2 = time.time()
    dt = t2-t1
except:
    print "<HR>Sorry, an error occurred"
    cgi.print_exception()
print "<P>(running time = %s seconds)" % str(round(dt, 3))