-
Notifications
You must be signed in to change notification settings - Fork 7
/
htmldiff
executable file
·263 lines (235 loc) · 10 KB
/
htmldiff
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
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# MIT License
# © W3C® (MIT, ERCIM, Keio, Beihang).
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice (including the next paragraph) shall be included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import atexit
import html
import http_auth
import http.client
import os
import re
import surbl
import sys
import tempfile
import html5lib
import urllib.parse
from email.message import EmailMessage
from io import StringIO
from subprocess import Popen, PIPE
CONTENT_TYPE = "text/html;charset=utf-8"
Page = """
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US">
<head><title>HTML Diff service</title>
<link rel="stylesheet" href="http://www.w3.org/StyleSheets/base" />
</head>
<body>
<p><a href="http://www.w3.org/"><img src="http://www.w3.org/Icons/w3c_home" alt="W3C"/></a> <a href="http://www.w3.org/2003/Editors">W3C Editors homepage</a></p>
<h1>Create Diff between HTML pages</h1>
"""
Page2 = """
<form method="GET">
<p>Address of reference document: <input name="doc1" type="url" value="%s" style="width:100%%"/></p>
<p>Address of new document: <input name="doc2" value="%s" style="width:100%%"/></p>
<p><input type="submit" value="get Diff"/></p>
</form>
<p><strong>Tip</strong>: if the document uses the W3C convention on linking to its previous version, you can specify only the address of the new document — the previous link will be automatically detected.</p>
<h2>Diff markings</h2>
<p>This service relies on <a href="https://www.gnu.org/software/diffutils/">GNU diff</a>. The found differences are roughly marked as follow:
<ul>
<li>deleted text is shown in pink with down-arrows (as styled for a <del> element)</li>
<li>where there is replacement, it’s shown in green with bi-directional arrows,</li>
<li>where there is newly inserted text, it’s yellow with up arrows (<ins> element)</li>
</ul>
<address>
script $Revision$ of $Date$<br />
by <a href="http://www.w3.org/People/Dom/">Dominique Hazaël-Massieux</a><br />based on <a href="https://github.com/w3c/htmldiff-ui/blob/master/htmldiff.pl">Shane McCarron’ Perl script</a> wrapped in a <a href="https://github.com/w3c/htmldiff-ui/blob/master/htmldiff">Python CGI</a>
</address>
</body>
</html>
"""
def checkInputUrl(url):
checker = surbl.SurblChecker('/usr/local/share/surbl/two-level-tlds','/usr/local/etc/surbl.whitelist')
if url[:5] == 'file:' or len(urllib.parse.urlparse(url)[0])<2:
print("Status: 403")
print("Content-Type: text/plain")
print()
print("sorry, I decline to handle file: addresses")
sys.exit()
elif checker.isMarkedAsSpam(url):
print("Status: 403")
print("Content-Type: text/plain; charset=utf-8")
print()
print("sorry, this URL matches a record known in SURBL. See http://www.surbl.org/")
sys.exit()
def copyHeader(copy_func, source, key, header_name=None):
value = source.get(key)
if not value:
return False
elif header_name is None:
header_name = key
copy_func(header_name, value)
return True
def setupRequest():
opener = http_auth.ProxyAuthURLopener()
copyHeader(opener.addheader, os.environ, 'HTTP_IF_MODIFIED_SINCE', 'If-Modified-Since')
copyHeader(opener.addheader, os.environ, 'REMOTE_ADDR', 'X_Forward_IP_Addr')
return opener
def tidyFile(file):
file.seek(0)
doc = html5lib.parse(file.read())
file.close()
file = tempfile.NamedTemporaryFile(
mode='w+', prefix='htmldiff-', suffix='.html')
atexit.register(file.close)
walker = html5lib.getTreeWalker("etree")
stream = walker(doc)
s = html5lib.serializer.HTMLSerializer()
prettyhtml = s.serialize(stream)
for item in prettyhtml:
file.write(item)
file.flush()
file.seek(0)
return (file, [])
def matchPredecessorRel(rel):
return rel and "predecessor-version" in rel.lower().split(" ")
def rmfile(filename):
try:
os.unlink(filename)
except:
pass
def escapeURLQueryString(url=None):
if url is None:
return None
url_split = urllib.parse.urlsplit(url)
if url_split.query:
fields = dict(urllib.parse.parse_qsl(url_split.query))
escaped_qs = urllib.parse.urlencode(fields)
url_split = url_split._replace(query=escaped_qs)
rv = urllib.parse.urlunsplit(url_split)
else:
rv = url
return rv
def mirrorURL(url, opener):
try:
url = escapeURLQueryString(url)
filename, headers = opener.retrieve(url)
except IOError as error:
opener.error = "I/O error: %s %s" % (error.errno, error.strerror)
except http.client.InvalidURL:
opener.error = "Invalid URL submitted"
except AttributeError: # ProxyAuthURLopener returned None.
pass # There's already an error set.
else:
atexit.register(rmfile, filename)
file = open(filename)
if "content-encoding" in headers and headers["content-encoding"] == "gzip":
import gzip
data = StringIO(file.read())
file.close()
file = gzip.GzipFile(fileobj=data)
file,errors = tidyFile(file)
if len(errors) == 0:
return (file, headers)
else:
opener.error = "Tidy errors: %s" % (str(errors))
return (None, {})
def showPage(url1='', url2='', error_html='', **headers):
for name, value in list(headers.items()):
print("%s: %s" % (name.replace('_', '-'), value))
print()
print(Page)
print(error_html)
print(Page2 % (url1, url2))
sys.exit()
def serveRequest():
environ = os.environ
if 'QUERY_STRING' not in environ:
showPage(Content_Type=CONTENT_TYPE)
# Use dict(parse_qsl) so we don't get lists of values.
fields = dict(urllib.parse.parse_qsl(environ['QUERY_STRING'],
max_num_fields = 2))
if ('doc2' not in fields):
showPage(Content_Type=CONTENT_TYPE)
# if doc1 is not specified, we load doc2 to check if it has a previous version link
doc2 = fields['doc2']
checkInputUrl(doc2)
url_opener2 = setupRequest()
newdoc, newheaders = mirrorURL(doc2, url_opener2)
if 'doc1' in fields:
doc1 = fields['doc1']
elif newdoc is not None:
from bs4 import BeautifulSoup
soup = BeautifulSoup(newdoc.read(), "html.parser")
newdoc.seek(0)
try:
doc1 = soup.find(string=re.compile("Previous Version",re.IGNORECASE)).findNext(name="a", attrs={"href":True})["href"]
except:
try:
doc1 = soup.find(name=["a", "link"], attrs={"href":True, rel:matchPredecessorRel})["href"]
except:
doc1 = None
else:
doc1 = None
if (not doc1):
showPage(Content_Type=CONTENT_TYPE)
checkInputUrl(doc1)
esc1 = html.escape(doc1, True)
esc2 = html.escape(doc2, True)
urlcomponents1 = urllib.parse.urlparse(doc1)
urlcomponents2 = urllib.parse.urlparse(doc2)
# if same domain, we can use the same urlopener
# otherwise, we create a separate one
if urlcomponents2[1] == urlcomponents1[1]:
url_opener = url_opener2
else:
url_opener = setupRequest()
refdoc, refheaders = mirrorURL(doc1, url_opener)
if not (refdoc and newdoc):
http_error = ""
url = ""
if not refdoc:
http_error = url_opener.error
url = esc1
else:
http_error = url_opener2.error
url = esc2
if re.match("^[1234][0-9][0-9] ", http_error):
print("Status: %s" %(http_error))
error="<p style='color:#FF0000'>An error (%s) occured trying to get <a href='%s'>%s</a>.</p>" % (html.escape(http_error), url, url)
showPage(esc1, esc2, error, Content_Type=CONTENT_TYPE)
print("Content-Type: text/html")
if 'Content-Type' in newheaders:
msg = EmailMessage()
msg['content-type'] = newheaders["Content-Type"]
contentType = msg.get_content_type()
if 'charset' in msg['content-type'].params:
charset = msg['content-type'].params['charset'].lower()
#if charset == "iso-8859-1":
# options["char_encoding"]='latin1'
for proxy_header in ('Last-Modified', 'Expires'):
if copyHeader(lambda header, value: sys.stdout.write("%s: %s" %(header, value)), newheaders, proxy_header):
print()
print()
p = Popen(["/usr/local/bin/htmldiff", refdoc.name, newdoc.name],
stdin=PIPE, stdout=PIPE, stderr=PIPE)
sys.stdout.flush()
sys.stderr.flush()
(out, err) = p.communicate()
p.stdin.close()
if err:
error = "<p style='color:#FF0000'>An error occured when running <code>htmldiff</code> on the documents:</p><pre>%s</pre>" % (html.escape(err),)
showPage(esc1, esc2, error)
else:
# html5lib strips the doctype, so we add it manually
# cf https://github.com/w3c/htmldiff-ui/issues/4#issuecomment-642831382
print("<!doctype html>")
print(out.decode("utf-8"))
if __name__ == '__main__':
if 'SCRIPT_NAME' in os.environ:
serveRequest()