]>
Commit | Line | Data |
---|---|---|
181d08f3 MT |
1 | #!/usr/bin/python3 |
2 | ||
4ed1dadb | 3 | import difflib |
ef963ecb | 4 | import hashlib |
181d08f3 | 5 | import logging |
245a2e36 MT |
6 | import markdown |
7 | import markdown.extensions | |
8 | import markdown.preprocessors | |
6ac7e934 | 9 | import os.path |
181d08f3 | 10 | import re |
9e90e800 | 11 | import urllib.parse |
181d08f3 MT |
12 | |
13 | from . import misc | |
9523790a | 14 | from . import util |
181d08f3 MT |
15 | from .decorators import * |
16 | ||
181d08f3 MT |
17 | class Wiki(misc.Object): |
18 | def _get_pages(self, query, *args): | |
19 | res = self.db.query(query, *args) | |
20 | ||
21 | for row in res: | |
22 | yield Page(self.backend, row.id, data=row) | |
23 | ||
d398ca08 MT |
24 | def _get_page(self, query, *args): |
25 | res = self.db.get(query, *args) | |
26 | ||
27 | if res: | |
28 | return Page(self.backend, res.id, data=res) | |
29 | ||
86368c12 MT |
30 | def __iter__(self): |
31 | return self._get_pages( | |
32 | "SELECT wiki.* FROM wiki_current current \ | |
33 | LEFT JOIN wiki ON current.id = wiki.id \ | |
34 | WHERE current.deleted IS FALSE \ | |
35 | ORDER BY page", | |
36 | ) | |
37 | ||
c78ad26e MT |
38 | def make_path(self, page, path): |
39 | # Nothing to do for absolute links | |
40 | if path.startswith("/"): | |
41 | pass | |
42 | ||
43 | # Relative links (one-level down) | |
44 | elif path.startswith("./"): | |
45 | path = os.path.join(page, path) | |
46 | ||
47 | # All other relative links | |
48 | else: | |
49 | p = os.path.dirname(page) | |
50 | path = os.path.join(p, path) | |
51 | ||
52 | # Normalise links | |
53 | return os.path.normpath(path) | |
54 | ||
9ff59d70 MT |
55 | def page_exists(self, path): |
56 | page = self.get_page(path) | |
57 | ||
58 | # Page must have been found and not deleted | |
59 | return page and not page.was_deleted() | |
60 | ||
6ac7e934 MT |
61 | def get_page_title(self, page, default=None): |
62 | doc = self.get_page(page) | |
63 | if doc: | |
50c8dc11 MT |
64 | title = doc.title |
65 | else: | |
66 | title = os.path.basename(page) | |
6ac7e934 | 67 | |
50c8dc11 | 68 | return title |
6ac7e934 | 69 | |
181d08f3 MT |
70 | def get_page(self, page, revision=None): |
71 | page = Page.sanitise_page_name(page) | |
947224b4 MT |
72 | |
73 | # Split the path into parts | |
74 | parts = page.split("/") | |
75 | ||
76 | # Check if this is an action | |
77 | if any((part.startswith("_") for part in parts)): | |
78 | return | |
181d08f3 MT |
79 | |
80 | if revision: | |
d398ca08 | 81 | return self._get_page("SELECT * FROM wiki WHERE page = %s \ |
181d08f3 MT |
82 | AND timestamp = %s", page, revision) |
83 | else: | |
d398ca08 | 84 | return self._get_page("SELECT * FROM wiki WHERE page = %s \ |
181d08f3 MT |
85 | ORDER BY timestamp DESC LIMIT 1", page) |
86 | ||
11afe905 MT |
87 | def get_recent_changes(self, account, limit=None): |
88 | pages = self._get_pages("SELECT * FROM wiki \ | |
11afe905 MT |
89 | ORDER BY timestamp DESC") |
90 | ||
91 | for page in pages: | |
92 | if not page.check_acl(account): | |
93 | continue | |
94 | ||
95 | yield page | |
96 | ||
97 | limit -= 1 | |
98 | if not limit: | |
99 | break | |
181d08f3 | 100 | |
495e9dc4 | 101 | def create_page(self, page, author, content, changes=None, address=None): |
181d08f3 MT |
102 | page = Page.sanitise_page_name(page) |
103 | ||
aba5e58a MT |
104 | # Write page to the database |
105 | page = self._get_page("INSERT INTO wiki(page, author_uid, markdown, changes, address) \ | |
df01767e | 106 | VALUES(%s, %s, %s, %s, %s) RETURNING *", page, author.uid, content or None, changes, address) |
181d08f3 | 107 | |
aba5e58a MT |
108 | # Send email to all watchers |
109 | page._send_watcher_emails(excludes=[author]) | |
110 | ||
111 | return page | |
112 | ||
495e9dc4 | 113 | def delete_page(self, page, author, **kwargs): |
181d08f3 MT |
114 | # Do nothing if the page does not exist |
115 | if not self.get_page(page): | |
116 | return | |
117 | ||
118 | # Just creates a blank last version of the page | |
495e9dc4 | 119 | self.create_page(page, author=author, content=None, **kwargs) |
181d08f3 | 120 | |
3168788e MT |
121 | def make_breadcrumbs(self, url): |
122 | # Split and strip all empty elements (double slashes) | |
181d08f3 MT |
123 | parts = list(e for e in url.split("/") if e) |
124 | ||
3168788e | 125 | ret = [] |
b1bf7d48 | 126 | for part in ("/".join(parts[:i]) for i in range(1, len(parts))): |
3168788e | 127 | ret.append(("/%s" % part, self.get_page_title(part, os.path.basename(part)))) |
181d08f3 | 128 | |
3168788e | 129 | return ret |
181d08f3 | 130 | |
11afe905 | 131 | def search(self, query, account=None, limit=None): |
9523790a MT |
132 | res = self._get_pages("SELECT wiki.* FROM wiki_search_index search_index \ |
133 | LEFT JOIN wiki ON search_index.wiki_id = wiki.id \ | |
22e56c4a MT |
134 | WHERE search_index.document @@ websearch_to_tsquery('english', %s) \ |
135 | ORDER BY ts_rank(search_index.document, websearch_to_tsquery('english', %s)) DESC", | |
11afe905 | 136 | query, query) |
9523790a | 137 | |
df80be2c | 138 | pages = [] |
11afe905 MT |
139 | for page in res: |
140 | # Skip any pages the user doesn't have permission for | |
141 | if not page.check_acl(account): | |
142 | continue | |
143 | ||
144 | # Return any other pages | |
df80be2c | 145 | pages.append(page) |
11afe905 | 146 | |
df80be2c MT |
147 | # Break when we have found enough pages |
148 | if limit and len(pages) >= limit: | |
11afe905 | 149 | break |
9523790a | 150 | |
df80be2c MT |
151 | return pages |
152 | ||
9523790a MT |
153 | def refresh(self): |
154 | """ | |
155 | Needs to be called after a page has been changed | |
156 | """ | |
157 | self.db.execute("REFRESH MATERIALIZED VIEW wiki_search_index") | |
158 | ||
2f23c558 | 159 | def get_watchlist(self, account): |
e1d2efef MT |
160 | pages = self._get_pages(""" |
161 | WITH pages AS ( | |
162 | SELECT | |
163 | * | |
164 | FROM | |
165 | wiki_current | |
166 | LEFT JOIN | |
167 | wiki ON wiki_current.id = wiki.id | |
168 | ) | |
169 | ||
170 | SELECT | |
171 | * | |
172 | FROM | |
173 | wiki_watchlist watchlist | |
174 | JOIN | |
175 | pages ON watchlist.page = pages.page | |
176 | WHERE | |
177 | watchlist.uid = %s | |
178 | """, account.uid, | |
2f23c558 MT |
179 | ) |
180 | ||
181 | return sorted(pages) | |
182 | ||
11afe905 MT |
183 | # ACL |
184 | ||
185 | def check_acl(self, page, account): | |
186 | res = self.db.query("SELECT * FROM wiki_acls \ | |
187 | WHERE %s ILIKE (path || '%%') ORDER BY LENGTH(path) DESC LIMIT 1", page) | |
188 | ||
189 | for row in res: | |
190 | # Access not permitted when user is not logged in | |
191 | if not account: | |
192 | return False | |
193 | ||
194 | # If user is in a matching group, we grant permission | |
195 | for group in row.groups: | |
93402e56 | 196 | if account.is_member_of_group(group): |
11afe905 MT |
197 | return True |
198 | ||
199 | # Otherwise access is not permitted | |
200 | return False | |
201 | ||
202 | # If no ACLs are found, we permit access | |
203 | return True | |
204 | ||
f2cfd873 MT |
205 | # Files |
206 | ||
207 | def _get_files(self, query, *args): | |
208 | res = self.db.query(query, *args) | |
209 | ||
210 | for row in res: | |
211 | yield File(self.backend, row.id, data=row) | |
212 | ||
213 | def _get_file(self, query, *args): | |
214 | res = self.db.get(query, *args) | |
215 | ||
216 | if res: | |
217 | return File(self.backend, res.id, data=res) | |
218 | ||
219 | def get_files(self, path): | |
220 | files = self._get_files("SELECT * FROM wiki_files \ | |
221 | WHERE path = %s AND deleted_at IS NULL ORDER BY filename", path) | |
222 | ||
223 | return list(files) | |
224 | ||
ff14dea3 | 225 | def get_file_by_path(self, path, revision=None): |
f2cfd873 MT |
226 | path, filename = os.path.dirname(path), os.path.basename(path) |
227 | ||
ff14dea3 MT |
228 | if revision: |
229 | # Fetch a specific revision | |
230 | return self._get_file("SELECT * FROM wiki_files \ | |
231 | WHERE path = %s AND filename = %s AND created_at <= %s \ | |
232 | ORDER BY created_at DESC LIMIT 1", path, filename, revision) | |
233 | ||
234 | # Fetch latest version | |
235 | return self._get_file("SELECT * FROM wiki_files \ | |
236 | WHERE path = %s AND filename = %s AND deleted_at IS NULL", | |
237 | path, filename) | |
238 | ||
239 | def get_file_by_path_and_filename(self, path, filename): | |
f2cfd873 | 240 | return self._get_file("SELECT * FROM wiki_files \ |
ff14dea3 MT |
241 | WHERE path = %s AND filename = %s AND deleted_at IS NULL", |
242 | path, filename) | |
f2cfd873 MT |
243 | |
244 | def upload(self, path, filename, data, mimetype, author, address): | |
ff14dea3 MT |
245 | # Replace any existing files |
246 | file = self.get_file_by_path_and_filename(path, filename) | |
247 | if file: | |
248 | file.delete(author) | |
249 | ||
f2cfd873 | 250 | # Upload the blob first |
a3a8a163 MT |
251 | blob = self.db.get("INSERT INTO wiki_blobs(data) VALUES(%s) \ |
252 | ON CONFLICT (digest(data, %s)) DO UPDATE SET data = EXCLUDED.data \ | |
253 | RETURNING id", data, "MD5") | |
f2cfd873 MT |
254 | |
255 | # Create entry for file | |
256 | return self._get_file("INSERT INTO wiki_files(path, filename, author_uid, address, \ | |
257 | mimetype, blob_id, size) VALUES(%s, %s, %s, %s, %s, %s, %s) RETURNING *", path, | |
258 | filename, author.uid, address, mimetype, blob.id, len(data)) | |
259 | ||
2901b734 MT |
260 | def render(self, path, text): |
261 | r = WikiRenderer(self.backend, path) | |
181d08f3 | 262 | |
2901b734 | 263 | return r.render(text) |
e2205cff | 264 | |
154f6179 | 265 | |
2901b734 | 266 | class Page(misc.Object): |
181d08f3 MT |
267 | def init(self, id, data=None): |
268 | self.id = id | |
269 | self.data = data | |
270 | ||
dc847af5 MT |
271 | def __repr__(self): |
272 | return "<%s %s %s>" % (self.__class__.__name__, self.page, self.timestamp) | |
273 | ||
c21ffadb MT |
274 | def __eq__(self, other): |
275 | if isinstance(other, self.__class__): | |
276 | return self.id == other.id | |
277 | ||
0713d9ae MT |
278 | return NotImplemented |
279 | ||
181d08f3 MT |
280 | def __lt__(self, other): |
281 | if isinstance(other, self.__class__): | |
282 | if self.page == other.page: | |
283 | return self.timestamp < other.timestamp | |
284 | ||
285 | return self.page < other.page | |
286 | ||
0713d9ae MT |
287 | return NotImplemented |
288 | ||
181d08f3 MT |
289 | @staticmethod |
290 | def sanitise_page_name(page): | |
291 | if not page: | |
292 | return "/" | |
293 | ||
294 | # Make sure that the page name does NOT end with a / | |
295 | if page.endswith("/"): | |
296 | page = page[:-1] | |
297 | ||
298 | # Make sure the page name starts with a / | |
299 | if not page.startswith("/"): | |
300 | page = "/%s" % page | |
301 | ||
302 | # Remove any double slashes | |
303 | page = page.replace("//", "/") | |
304 | ||
305 | return page | |
306 | ||
307 | @property | |
308 | def url(self): | |
0805ae90 | 309 | return "/docs%s" % self.page |
181d08f3 | 310 | |
4ed1dadb MT |
311 | @property |
312 | def full_url(self): | |
0805ae90 | 313 | return "https://www.ipfire.org%s" % self.url |
4ed1dadb | 314 | |
181d08f3 MT |
315 | @property |
316 | def page(self): | |
317 | return self.data.page | |
318 | ||
319 | @property | |
320 | def title(self): | |
51e7a876 | 321 | return self._title or os.path.basename(self.page[1:]) |
181d08f3 MT |
322 | |
323 | @property | |
324 | def _title(self): | |
325 | if not self.markdown: | |
326 | return | |
327 | ||
328 | # Find first H1 headline in markdown | |
329 | markdown = self.markdown.splitlines() | |
330 | ||
0074e919 | 331 | m = re.match(r"^#\s*(.*)( #)?$", markdown[0]) |
181d08f3 MT |
332 | if m: |
333 | return m.group(1) | |
334 | ||
3b05ef6e MT |
335 | @lazy_property |
336 | def author(self): | |
337 | if self.data.author_uid: | |
338 | return self.backend.accounts.get_by_uid(self.data.author_uid) | |
339 | ||
181d08f3 MT |
340 | @property |
341 | def markdown(self): | |
c21ffadb | 342 | return self.data.markdown or "" |
181d08f3 MT |
343 | |
344 | @property | |
345 | def html(self): | |
f9e077ed MT |
346 | lines = [] |
347 | ||
348 | # Strip off the first line if it contains a heading (as it will be shown separately) | |
349 | for i, line in enumerate(self.markdown.splitlines()): | |
350 | if i == 0 and line.startswith("#"): | |
351 | continue | |
352 | ||
353 | lines.append(line) | |
354 | ||
355 | return self.backend.wiki.render(self.page, "\n".join(lines)) | |
addc18d5 | 356 | |
181d08f3 MT |
357 | @property |
358 | def timestamp(self): | |
359 | return self.data.timestamp | |
360 | ||
361 | def was_deleted(self): | |
4c13230c | 362 | return not self.markdown |
181d08f3 MT |
363 | |
364 | @lazy_property | |
365 | def breadcrumbs(self): | |
366 | return self.backend.wiki.make_breadcrumbs(self.page) | |
367 | ||
d4c68c5c MT |
368 | def is_latest_revision(self): |
369 | return self.get_latest_revision() == self | |
370 | ||
181d08f3 | 371 | def get_latest_revision(self): |
7d699684 MT |
372 | revisions = self.get_revisions() |
373 | ||
374 | # Return first object | |
375 | for rev in revisions: | |
376 | return rev | |
377 | ||
378 | def get_revisions(self): | |
379 | return self.backend.wiki._get_pages("SELECT * FROM wiki \ | |
380 | WHERE page = %s ORDER BY timestamp DESC", self.page) | |
091ac36b | 381 | |
c21ffadb MT |
382 | @lazy_property |
383 | def previous_revision(self): | |
384 | return self.backend.wiki._get_page("SELECT * FROM wiki \ | |
385 | WHERE page = %s AND timestamp < %s ORDER BY timestamp DESC \ | |
386 | LIMIT 1", self.page, self.timestamp) | |
387 | ||
d398ca08 MT |
388 | @property |
389 | def changes(self): | |
390 | return self.data.changes | |
391 | ||
11afe905 MT |
392 | # ACL |
393 | ||
394 | def check_acl(self, account): | |
395 | return self.backend.wiki.check_acl(self.page, account) | |
396 | ||
d64a1e35 MT |
397 | # Watchers |
398 | ||
4ed1dadb MT |
399 | @lazy_property |
400 | def diff(self): | |
401 | if self.previous_revision: | |
402 | diff = difflib.unified_diff( | |
403 | self.previous_revision.markdown.splitlines(), | |
404 | self.markdown.splitlines(), | |
405 | ) | |
406 | ||
407 | return "\n".join(diff) | |
408 | ||
aba5e58a MT |
409 | @property |
410 | def watchers(self): | |
411 | res = self.db.query("SELECT uid FROM wiki_watchlist \ | |
412 | WHERE page = %s", self.page) | |
413 | ||
414 | for row in res: | |
415 | # Search for account by UID and skip if none was found | |
416 | account = self.backend.accounts.get_by_uid(row.uid) | |
417 | if not account: | |
418 | continue | |
419 | ||
420 | # Return the account | |
421 | yield account | |
422 | ||
f2e25ded | 423 | def is_watched_by(self, account): |
d64a1e35 MT |
424 | res = self.db.get("SELECT 1 FROM wiki_watchlist \ |
425 | WHERE page = %s AND uid = %s", self.page, account.uid) | |
426 | ||
427 | if res: | |
428 | return True | |
429 | ||
430 | return False | |
431 | ||
432 | def add_watcher(self, account): | |
f2e25ded | 433 | if self.is_watched_by(account): |
d64a1e35 MT |
434 | return |
435 | ||
436 | self.db.execute("INSERT INTO wiki_watchlist(page, uid) \ | |
437 | VALUES(%s, %s)", self.page, account.uid) | |
438 | ||
439 | def remove_watcher(self, account): | |
440 | self.db.execute("DELETE FROM wiki_watchlist \ | |
441 | WHERE page = %s AND uid = %s", self.page, account.uid) | |
442 | ||
aba5e58a MT |
443 | def _send_watcher_emails(self, excludes=[]): |
444 | # Nothing to do if there was no previous revision | |
445 | if not self.previous_revision: | |
446 | return | |
447 | ||
448 | for watcher in self.watchers: | |
449 | # Skip everyone who is excluded | |
450 | if watcher in excludes: | |
451 | logging.debug("Excluding %s" % watcher) | |
452 | continue | |
453 | ||
516da0a9 MT |
454 | # Check permissions |
455 | if not self.backend.wiki.check_acl(self.page, watcher): | |
456 | logging.debug("Watcher %s does not have permissions" % watcher) | |
457 | continue | |
458 | ||
aba5e58a MT |
459 | logging.debug("Sending watcher email to %s" % watcher) |
460 | ||
4ed1dadb MT |
461 | # Compose message |
462 | self.backend.messages.send_template("wiki/messages/page-changed", | |
ba14044c | 463 | account=watcher, page=self, priority=-10) |
aba5e58a | 464 | |
9f1cfab7 | 465 | def restore(self, author, address, comment=None): |
d4c68c5c MT |
466 | changes = "Restore to revision from %s" % self.timestamp.isoformat() |
467 | ||
9f1cfab7 MT |
468 | # Append comment |
469 | if comment: | |
470 | changes = "%s: %s" % (changes, comment) | |
471 | ||
d4c68c5c MT |
472 | return self.backend.wiki.create_page(self.page, |
473 | author, self.markdown, changes=changes, address=address) | |
474 | ||
f2cfd873 MT |
475 | |
476 | class File(misc.Object): | |
477 | def init(self, id, data): | |
478 | self.id = id | |
479 | self.data = data | |
480 | ||
ff14dea3 MT |
481 | def __eq__(self, other): |
482 | if isinstance(other, self.__class__): | |
483 | return self.id == other.id | |
484 | ||
f2cfd873 MT |
485 | @property |
486 | def url(self): | |
a82de4b1 | 487 | return "/docs%s" % os.path.join(self.path, self.filename) |
f2cfd873 MT |
488 | |
489 | @property | |
490 | def path(self): | |
491 | return self.data.path | |
492 | ||
493 | @property | |
494 | def filename(self): | |
495 | return self.data.filename | |
496 | ||
497 | @property | |
498 | def mimetype(self): | |
499 | return self.data.mimetype | |
500 | ||
501 | @property | |
502 | def size(self): | |
503 | return self.data.size | |
504 | ||
8cb0bea4 MT |
505 | @lazy_property |
506 | def author(self): | |
507 | if self.data.author_uid: | |
508 | return self.backend.accounts.get_by_uid(self.data.author_uid) | |
509 | ||
510 | @property | |
511 | def created_at(self): | |
512 | return self.data.created_at | |
513 | ||
b26c705a MT |
514 | def delete(self, author=None): |
515 | self.db.execute("UPDATE wiki_files SET deleted_at = NOW(), deleted_by = %s \ | |
516 | WHERE id = %s", author.uid if author else None, self.id) | |
ff14dea3 MT |
517 | |
518 | @property | |
519 | def deleted_at(self): | |
520 | return self.data.deleted_at | |
521 | ||
522 | def get_latest_revision(self): | |
523 | revisions = self.get_revisions() | |
524 | ||
525 | # Return first object | |
526 | for rev in revisions: | |
527 | return rev | |
528 | ||
529 | def get_revisions(self): | |
530 | revisions = self.backend.wiki._get_files("SELECT * FROM wiki_files \ | |
2225edd9 | 531 | WHERE path = %s AND filename = %s ORDER BY created_at DESC", self.path, self.filename) |
ff14dea3 MT |
532 | |
533 | return list(revisions) | |
534 | ||
8cb0bea4 MT |
535 | def is_pdf(self): |
536 | return self.mimetype in ("application/pdf", "application/x-pdf") | |
537 | ||
f2cfd873 MT |
538 | def is_image(self): |
539 | return self.mimetype.startswith("image/") | |
540 | ||
8a62e589 MT |
541 | def is_vector_image(self): |
542 | return self.mimetype in ("image/svg+xml",) | |
543 | ||
544 | def is_bitmap_image(self): | |
545 | return self.is_image() and not self.is_vector_image() | |
546 | ||
f2cfd873 MT |
547 | @lazy_property |
548 | def blob(self): | |
549 | res = self.db.get("SELECT data FROM wiki_blobs \ | |
550 | WHERE id = %s", self.data.blob_id) | |
551 | ||
552 | if res: | |
553 | return bytes(res.data) | |
79dd9a0f | 554 | |
df4f5dfb | 555 | async def get_thumbnail(self, size): |
8a62e589 MT |
556 | assert self.is_bitmap_image() |
557 | ||
df4f5dfb MT |
558 | cache_key = "-".join(( |
559 | self.path, | |
560 | util.normalize(self.filename), | |
561 | self.created_at.isoformat(), | |
562 | "%spx" % size, | |
563 | )) | |
75d9b3da MT |
564 | |
565 | # Try to fetch the data from the cache | |
df4f5dfb | 566 | thumbnail = await self.backend.cache.get(cache_key) |
75d9b3da MT |
567 | if thumbnail: |
568 | return thumbnail | |
569 | ||
570 | # Generate the thumbnail | |
5ef115cd | 571 | thumbnail = util.generate_thumbnail(self.blob, size) |
75d9b3da MT |
572 | |
573 | # Put it into the cache for forever | |
df4f5dfb | 574 | await self.backend.cache.set(cache_key, thumbnail) |
75d9b3da MT |
575 | |
576 | return thumbnail | |
2901b734 MT |
577 | |
578 | ||
245a2e36 MT |
579 | class PrettyLinksExtension(markdown.extensions.Extension): |
580 | def extendMarkdown(self, md): | |
581 | # Create links to Bugzilla | |
582 | md.preprocessors.register(BugzillaLinksPreprocessor(md), "bugzilla", 10) | |
583 | ||
584 | # Create links to CVE | |
585 | md.preprocessors.register(CVELinksPreprocessor(md), "cve", 10) | |
586 | ||
587 | ||
588 | class BugzillaLinksPreprocessor(markdown.preprocessors.Preprocessor): | |
589 | regex = re.compile(r"(?:#(\d{5,}))", re.I) | |
590 | ||
591 | def run(self, lines): | |
592 | for line in lines: | |
593 | yield self.regex.sub(r"[#\1](https://bugzilla.ipfire.org/show_bug.cgi?id=\1)", line) | |
594 | ||
595 | ||
596 | class CVELinksPreprocessor(markdown.preprocessors.Preprocessor): | |
597 | regex = re.compile(r"(?:CVE)[\s\-](\d{4}\-\d+)") | |
598 | ||
599 | def run(self, lines): | |
600 | for line in lines: | |
601 | yield self.regex.sub(r"[CVE-\1](https://cve.mitre.org/cgi-bin/cvename.cgi?name=\1)", line) | |
602 | ||
603 | ||
2901b734 | 604 | class WikiRenderer(misc.Object): |
4ddad3e5 MT |
605 | schemas = ( |
606 | "ftp://", | |
607 | "git://", | |
608 | "http://", | |
609 | "https://", | |
610 | "rsync://", | |
611 | "sftp://", | |
612 | "ssh://", | |
613 | "webcal://", | |
614 | ) | |
615 | ||
616 | # Links | |
617 | links = re.compile(r"<a href=\"(.*?)\">(.*?)</a>") | |
2901b734 | 618 | |
c78ad26e | 619 | # Images |
e9c6d581 | 620 | images = re.compile(r"<img alt(?:=\"(.*?)\")? src=\"(.*?)\" (?:title=\"(.*?)\" )?/>") |
c78ad26e | 621 | |
245a2e36 MT |
622 | # Markdown Renderer |
623 | renderer = markdown.Markdown( | |
624 | extensions=[ | |
625 | PrettyLinksExtension(), | |
626 | "codehilite", | |
627 | "fenced_code", | |
628 | "footnotes", | |
629 | "nl2br", | |
630 | "sane_lists", | |
631 | "tables", | |
632 | "toc", | |
633 | ], | |
634 | ) | |
635 | ||
2901b734 MT |
636 | def init(self, path): |
637 | self.path = path | |
638 | ||
4ddad3e5 MT |
639 | def _render_link(self, m): |
640 | url, text = m.groups() | |
2901b734 | 641 | |
e50a437a MT |
642 | # External Links |
643 | for schema in self.schemas: | |
644 | if url.startswith(schema): | |
645 | return """<a class="link-external" href="%s">%s</a>""" % \ | |
646 | (url, text or url) | |
647 | ||
4ddad3e5 MT |
648 | # Emails |
649 | if "@" in url: | |
650 | # Strip mailto: | |
651 | if url.startswith("mailto:"): | |
652 | url = url[7:] | |
2901b734 | 653 | |
4ddad3e5 MT |
654 | return """<a class="link-external" href="mailto:%s">%s</a>""" % \ |
655 | (url, text or url) | |
2901b734 | 656 | |
4ddad3e5 MT |
657 | # Everything else must be an internal link |
658 | path = self.backend.wiki.make_path(self.path, url) | |
2901b734 | 659 | |
46b77977 | 660 | return """<a href="/docs%s">%s</a>""" % \ |
4ddad3e5 | 661 | (path, text or self.backend.wiki.get_page_title(path)) |
2901b734 | 662 | |
c78ad26e | 663 | def _render_image(self, m): |
e9c6d581 | 664 | alt_text, url, caption = m.groups() |
2901b734 | 665 | |
ef963ecb MT |
666 | # Compute a hash over the URL |
667 | h = hashlib.new("md5") | |
668 | h.update(url.encode()) | |
669 | id = h.hexdigest() | |
670 | ||
4a1bfdd5 | 671 | html = """ |
3ae53eac MT |
672 | <div class="columns is-centered"> |
673 | <div class="column is-8"> | |
ef963ecb MT |
674 | <figure class="image modal-trigger" data-target="%(id)s"> |
675 | <img src="/docs%(url)s" alt="%(caption)s"> | |
676 | ||
677 | <figcaption class="figure-caption">%(caption)s</figcaption> | |
3ae53eac | 678 | </figure> |
ef963ecb MT |
679 | |
680 | <div class="modal is-large" id="%(id)s"> | |
681 | <div class="modal-background"></div> | |
682 | ||
683 | <div class="modal-content"> | |
684 | <p class="image"> | |
685 | <img src="/docs%(plain_url)s?s=1920" alt="%(caption)s" | |
686 | loading="lazy"> | |
687 | </p> | |
688 | </div> | |
689 | ||
690 | <button class="modal-close is-large" aria-label="close"></button> | |
691 | </div> | |
3ae53eac MT |
692 | </div> |
693 | </div> | |
4a1bfdd5 MT |
694 | """ |
695 | ||
c78ad26e MT |
696 | # Skip any absolute and external URLs |
697 | if url.startswith("/") or url.startswith("https://") or url.startswith("http://"): | |
ef963ecb MT |
698 | return html % { |
699 | "caption" : caption or "", | |
700 | "id" : id, | |
701 | "plain_url" : url, | |
702 | "url" : url, | |
703 | } | |
2901b734 | 704 | |
c78ad26e MT |
705 | # Try to split query string |
706 | url, delimiter, qs = url.partition("?") | |
2901b734 | 707 | |
c78ad26e MT |
708 | # Parse query arguments |
709 | args = urllib.parse.parse_qs(qs) | |
2901b734 | 710 | |
c78ad26e | 711 | # Build absolute path |
ef963ecb | 712 | plain_url = url = self.backend.wiki.make_path(self.path, url) |
2901b734 | 713 | |
c78ad26e MT |
714 | # Find image |
715 | file = self.backend.wiki.get_file_by_path(url) | |
716 | if not file or not file.is_image(): | |
717 | return "<!-- Could not find image %s in %s -->" % (url, self.path) | |
2901b734 | 718 | |
c78ad26e MT |
719 | # Scale down the image if not already done |
720 | if not "s" in args: | |
9ce45afb | 721 | args["s"] = "920" |
2901b734 | 722 | |
4a1bfdd5 MT |
723 | # Append arguments to the URL |
724 | if args: | |
725 | url = "%s?%s" % (url, urllib.parse.urlencode(args)) | |
726 | ||
ef963ecb MT |
727 | return html % { |
728 | "caption" : caption or "", | |
729 | "id" : id, | |
730 | "plain_url" : plain_url, | |
731 | "url" : url, | |
732 | } | |
2901b734 | 733 | |
c78ad26e MT |
734 | def render(self, text): |
735 | logging.debug("Rendering %s" % self.path) | |
2901b734 | 736 | |
245a2e36 MT |
737 | # Render... |
738 | text = self.renderer.convert(text) | |
9881e9ef | 739 | |
4ddad3e5 MT |
740 | # Postprocess links |
741 | text = self.links.sub(self._render_link, text) | |
742 | ||
9881e9ef | 743 | # Postprocess images to <figure> |
c78ad26e MT |
744 | text = self.images.sub(self._render_image, text) |
745 | ||
9881e9ef | 746 | return text |