]> git.ipfire.org Git - ipfire.org.git/blob - src/backend/wiki.py
location: Create a page that explains how to report problems
[ipfire.org.git] / src / backend / wiki.py
1 #!/usr/bin/python3
2
3 import difflib
4 import logging
5 import os.path
6 import re
7 import urllib.parse
8
9 from . import misc
10 from . import util
11 from .decorators import *
12
13 class Wiki(misc.Object):
14 def _get_pages(self, query, *args):
15 res = self.db.query(query, *args)
16
17 for row in res:
18 yield Page(self.backend, row.id, data=row)
19
20 def _get_page(self, query, *args):
21 res = self.db.get(query, *args)
22
23 if res:
24 return Page(self.backend, res.id, data=res)
25
26 def __iter__(self):
27 return self._get_pages(
28 "SELECT wiki.* FROM wiki_current current \
29 LEFT JOIN wiki ON current.id = wiki.id \
30 WHERE current.deleted IS FALSE \
31 ORDER BY page",
32 )
33
34 def make_path(self, page, path):
35 # Nothing to do for absolute links
36 if path.startswith("/"):
37 pass
38
39 # Relative links (one-level down)
40 elif path.startswith("./"):
41 path = os.path.join(page, path)
42
43 # All other relative links
44 else:
45 p = os.path.dirname(page)
46 path = os.path.join(p, path)
47
48 # Normalise links
49 return os.path.normpath(path)
50
51 def page_exists(self, path):
52 page = self.get_page(path)
53
54 # Page must have been found and not deleted
55 return page and not page.was_deleted()
56
57 def get_page_title(self, page, default=None):
58 # Try to retrieve title from cache
59 title = self.memcache.get("wiki:title:%s" % page)
60 if title:
61 return title
62
63 # If the title has not been in the cache, we will
64 # have to look it up
65 doc = self.get_page(page)
66 if doc:
67 title = doc.title
68 else:
69 title = os.path.basename(page)
70
71 # Save in cache for forever
72 self.memcache.set("wiki:title:%s" % page, title)
73
74 return title
75
76 def get_page(self, page, revision=None):
77 page = Page.sanitise_page_name(page)
78 assert page
79
80 if revision:
81 return self._get_page("SELECT * FROM wiki WHERE page = %s \
82 AND timestamp = %s", page, revision)
83 else:
84 return self._get_page("SELECT * FROM wiki WHERE page = %s \
85 ORDER BY timestamp DESC LIMIT 1", page)
86
87 def get_recent_changes(self, account, limit=None):
88 pages = self._get_pages("SELECT * FROM wiki \
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
100
101 def create_page(self, page, author, content, changes=None, address=None):
102 page = Page.sanitise_page_name(page)
103
104 # Write page to the database
105 page = self._get_page("INSERT INTO wiki(page, author_uid, markdown, changes, address) \
106 VALUES(%s, %s, %s, %s, %s) RETURNING *", page, author.uid, content or None, changes, address)
107
108 # Update cache
109 self.memcache.set("wiki:title:%s" % page.page, page.title)
110
111 # Send email to all watchers
112 page._send_watcher_emails(excludes=[author])
113
114 return page
115
116 def delete_page(self, page, author, **kwargs):
117 # Do nothing if the page does not exist
118 if not self.get_page(page):
119 return
120
121 # Just creates a blank last version of the page
122 self.create_page(page, author=author, content=None, **kwargs)
123
124 def make_breadcrumbs(self, url):
125 # Split and strip all empty elements (double slashes)
126 parts = list(e for e in url.split("/") if e)
127
128 ret = []
129 for part in ("/".join(parts[:i]) for i in range(1, len(parts))):
130 ret.append(("/%s" % part, self.get_page_title(part, os.path.basename(part))))
131
132 return ret
133
134 def search(self, query, account=None, limit=None):
135 res = self._get_pages("SELECT wiki.* FROM wiki_search_index search_index \
136 LEFT JOIN wiki ON search_index.wiki_id = wiki.id \
137 WHERE search_index.document @@ websearch_to_tsquery('english', %s) \
138 ORDER BY ts_rank(search_index.document, websearch_to_tsquery('english', %s)) DESC",
139 query, query)
140
141 pages = []
142 for page in res:
143 # Skip any pages the user doesn't have permission for
144 if not page.check_acl(account):
145 continue
146
147 # Return any other pages
148 pages.append(page)
149
150 # Break when we have found enough pages
151 if limit and len(pages) >= limit:
152 break
153
154 return pages
155
156 def refresh(self):
157 """
158 Needs to be called after a page has been changed
159 """
160 self.db.execute("REFRESH MATERIALIZED VIEW wiki_search_index")
161
162 def get_watchlist(self, account):
163 pages = self._get_pages(
164 "WITH pages AS (SELECT * FROM wiki_current \
165 LEFT JOIN wiki ON wiki_current.id = wiki.id) \
166 SELECT * FROM wiki_watchlist watchlist \
167 LEFT JOIN pages ON watchlist.page = pages.page \
168 WHERE watchlist.uid = %s",
169 account.uid,
170 )
171
172 return sorted(pages)
173
174 # ACL
175
176 def check_acl(self, page, account):
177 res = self.db.query("SELECT * FROM wiki_acls \
178 WHERE %s ILIKE (path || '%%') ORDER BY LENGTH(path) DESC LIMIT 1", page)
179
180 for row in res:
181 # Access not permitted when user is not logged in
182 if not account:
183 return False
184
185 # If user is in a matching group, we grant permission
186 for group in row.groups:
187 if account.is_member_of_group(group):
188 return True
189
190 # Otherwise access is not permitted
191 return False
192
193 # If no ACLs are found, we permit access
194 return True
195
196 # Files
197
198 def _get_files(self, query, *args):
199 res = self.db.query(query, *args)
200
201 for row in res:
202 yield File(self.backend, row.id, data=row)
203
204 def _get_file(self, query, *args):
205 res = self.db.get(query, *args)
206
207 if res:
208 return File(self.backend, res.id, data=res)
209
210 def get_files(self, path):
211 files = self._get_files("SELECT * FROM wiki_files \
212 WHERE path = %s AND deleted_at IS NULL ORDER BY filename", path)
213
214 return list(files)
215
216 def get_file_by_path(self, path, revision=None):
217 path, filename = os.path.dirname(path), os.path.basename(path)
218
219 if revision:
220 # Fetch a specific revision
221 return self._get_file("SELECT * FROM wiki_files \
222 WHERE path = %s AND filename = %s AND created_at <= %s \
223 ORDER BY created_at DESC LIMIT 1", path, filename, revision)
224
225 # Fetch latest version
226 return self._get_file("SELECT * FROM wiki_files \
227 WHERE path = %s AND filename = %s AND deleted_at IS NULL",
228 path, filename)
229
230 def get_file_by_path_and_filename(self, path, filename):
231 return self._get_file("SELECT * FROM wiki_files \
232 WHERE path = %s AND filename = %s AND deleted_at IS NULL",
233 path, filename)
234
235 def upload(self, path, filename, data, mimetype, author, address):
236 # Replace any existing files
237 file = self.get_file_by_path_and_filename(path, filename)
238 if file:
239 file.delete(author)
240
241 # Upload the blob first
242 blob = self.db.get("INSERT INTO wiki_blobs(data) VALUES(%s) \
243 ON CONFLICT (digest(data, %s)) DO UPDATE SET data = EXCLUDED.data \
244 RETURNING id", data, "MD5")
245
246 # Create entry for file
247 return self._get_file("INSERT INTO wiki_files(path, filename, author_uid, address, \
248 mimetype, blob_id, size) VALUES(%s, %s, %s, %s, %s, %s, %s) RETURNING *", path,
249 filename, author.uid, address, mimetype, blob.id, len(data))
250
251 def render(self, path, text):
252 r = WikiRenderer(self.backend, path)
253
254 return r.render(text)
255
256
257 class Page(misc.Object):
258 def init(self, id, data=None):
259 self.id = id
260 self.data = data
261
262 def __repr__(self):
263 return "<%s %s %s>" % (self.__class__.__name__, self.page, self.timestamp)
264
265 def __eq__(self, other):
266 if isinstance(other, self.__class__):
267 return self.id == other.id
268
269 def __lt__(self, other):
270 if isinstance(other, self.__class__):
271 if self.page == other.page:
272 return self.timestamp < other.timestamp
273
274 return self.page < other.page
275
276 @staticmethod
277 def sanitise_page_name(page):
278 if not page:
279 return "/"
280
281 # Make sure that the page name does NOT end with a /
282 if page.endswith("/"):
283 page = page[:-1]
284
285 # Make sure the page name starts with a /
286 if not page.startswith("/"):
287 page = "/%s" % page
288
289 # Remove any double slashes
290 page = page.replace("//", "/")
291
292 return page
293
294 @property
295 def url(self):
296 return self.page
297
298 @property
299 def full_url(self):
300 return "https://wiki.ipfire.org%s" % self.url
301
302 @property
303 def page(self):
304 return self.data.page
305
306 @property
307 def title(self):
308 return self._title or os.path.basename(self.page[1:])
309
310 @property
311 def _title(self):
312 if not self.markdown:
313 return
314
315 # Find first H1 headline in markdown
316 markdown = self.markdown.splitlines()
317
318 m = re.match(r"^#\s*(.*)( #)?$", markdown[0])
319 if m:
320 return m.group(1)
321
322 @lazy_property
323 def author(self):
324 if self.data.author_uid:
325 return self.backend.accounts.get_by_uid(self.data.author_uid)
326
327 @property
328 def markdown(self):
329 return self.data.markdown or ""
330
331 @property
332 def html(self):
333 return self.backend.wiki.render(self.page, self.markdown)
334
335 @property
336 def timestamp(self):
337 return self.data.timestamp
338
339 def was_deleted(self):
340 return not self.markdown
341
342 @lazy_property
343 def breadcrumbs(self):
344 return self.backend.wiki.make_breadcrumbs(self.page)
345
346 def is_latest_revision(self):
347 return self.get_latest_revision() == self
348
349 def get_latest_revision(self):
350 revisions = self.get_revisions()
351
352 # Return first object
353 for rev in revisions:
354 return rev
355
356 def get_revisions(self):
357 return self.backend.wiki._get_pages("SELECT * FROM wiki \
358 WHERE page = %s ORDER BY timestamp DESC", self.page)
359
360 @lazy_property
361 def previous_revision(self):
362 return self.backend.wiki._get_page("SELECT * FROM wiki \
363 WHERE page = %s AND timestamp < %s ORDER BY timestamp DESC \
364 LIMIT 1", self.page, self.timestamp)
365
366 @property
367 def changes(self):
368 return self.data.changes
369
370 # ACL
371
372 def check_acl(self, account):
373 return self.backend.wiki.check_acl(self.page, account)
374
375 # Sidebar
376
377 @lazy_property
378 def sidebar(self):
379 parts = self.page.split("/")
380
381 while parts:
382 sidebar = self.backend.wiki.get_page("%s/sidebar" % os.path.join(*parts))
383 if sidebar:
384 return sidebar
385
386 parts.pop()
387
388 # Watchers
389
390 @lazy_property
391 def diff(self):
392 if self.previous_revision:
393 diff = difflib.unified_diff(
394 self.previous_revision.markdown.splitlines(),
395 self.markdown.splitlines(),
396 )
397
398 return "\n".join(diff)
399
400 @property
401 def watchers(self):
402 res = self.db.query("SELECT uid FROM wiki_watchlist \
403 WHERE page = %s", self.page)
404
405 for row in res:
406 # Search for account by UID and skip if none was found
407 account = self.backend.accounts.get_by_uid(row.uid)
408 if not account:
409 continue
410
411 # Return the account
412 yield account
413
414 def is_watched_by(self, account):
415 res = self.db.get("SELECT 1 FROM wiki_watchlist \
416 WHERE page = %s AND uid = %s", self.page, account.uid)
417
418 if res:
419 return True
420
421 return False
422
423 def add_watcher(self, account):
424 if self.is_watched_by(account):
425 return
426
427 self.db.execute("INSERT INTO wiki_watchlist(page, uid) \
428 VALUES(%s, %s)", self.page, account.uid)
429
430 def remove_watcher(self, account):
431 self.db.execute("DELETE FROM wiki_watchlist \
432 WHERE page = %s AND uid = %s", self.page, account.uid)
433
434 def _send_watcher_emails(self, excludes=[]):
435 # Nothing to do if there was no previous revision
436 if not self.previous_revision:
437 return
438
439 for watcher in self.watchers:
440 # Skip everyone who is excluded
441 if watcher in excludes:
442 logging.debug("Excluding %s" % watcher)
443 continue
444
445 # Check permissions
446 if not self.backend.wiki.check_acl(self.page, watcher):
447 logging.debug("Watcher %s does not have permissions" % watcher)
448 continue
449
450 logging.debug("Sending watcher email to %s" % watcher)
451
452 # Compose message
453 self.backend.messages.send_template("wiki/messages/page-changed",
454 account=watcher, page=self, priority=-10)
455
456 def restore(self, author, address, comment=None):
457 changes = "Restore to revision from %s" % self.timestamp.isoformat()
458
459 # Append comment
460 if comment:
461 changes = "%s: %s" % (changes, comment)
462
463 return self.backend.wiki.create_page(self.page,
464 author, self.markdown, changes=changes, address=address)
465
466
467 class File(misc.Object):
468 def init(self, id, data):
469 self.id = id
470 self.data = data
471
472 def __eq__(self, other):
473 if isinstance(other, self.__class__):
474 return self.id == other.id
475
476 @property
477 def url(self):
478 return os.path.join(self.path, self.filename)
479
480 @property
481 def path(self):
482 return self.data.path
483
484 @property
485 def filename(self):
486 return self.data.filename
487
488 @property
489 def mimetype(self):
490 return self.data.mimetype
491
492 @property
493 def size(self):
494 return self.data.size
495
496 @lazy_property
497 def author(self):
498 if self.data.author_uid:
499 return self.backend.accounts.get_by_uid(self.data.author_uid)
500
501 @property
502 def created_at(self):
503 return self.data.created_at
504
505 def delete(self, author=None):
506 self.db.execute("UPDATE wiki_files SET deleted_at = NOW(), deleted_by = %s \
507 WHERE id = %s", author.uid if author else None, self.id)
508
509 @property
510 def deleted_at(self):
511 return self.data.deleted_at
512
513 def get_latest_revision(self):
514 revisions = self.get_revisions()
515
516 # Return first object
517 for rev in revisions:
518 return rev
519
520 def get_revisions(self):
521 revisions = self.backend.wiki._get_files("SELECT * FROM wiki_files \
522 WHERE path = %s AND filename = %s ORDER BY created_at DESC", self.path, self.filename)
523
524 return list(revisions)
525
526 def is_pdf(self):
527 return self.mimetype in ("application/pdf", "application/x-pdf")
528
529 def is_image(self):
530 return self.mimetype.startswith("image/")
531
532 def is_vector_image(self):
533 return self.mimetype in ("image/svg+xml",)
534
535 def is_bitmap_image(self):
536 return self.is_image() and not self.is_vector_image()
537
538 @lazy_property
539 def blob(self):
540 res = self.db.get("SELECT data FROM wiki_blobs \
541 WHERE id = %s", self.data.blob_id)
542
543 if res:
544 return bytes(res.data)
545
546 def get_thumbnail(self, size):
547 assert self.is_bitmap_image()
548
549 cache_key = "-".join((self.path, util.normalize(self.filename), self.created_at.isoformat(), "%spx" % size))
550
551 # Try to fetch the data from the cache
552 thumbnail = self.memcache.get(cache_key)
553 if thumbnail:
554 return thumbnail
555
556 # Generate the thumbnail
557 thumbnail = util.generate_thumbnail(self.blob, size)
558
559 # Put it into the cache for forever
560 self.memcache.set(cache_key, thumbnail)
561
562 return thumbnail
563
564
565 class WikiRenderer(misc.Object):
566 schemas = (
567 "ftp://",
568 "git://",
569 "http://",
570 "https://",
571 "rsync://",
572 "sftp://",
573 "ssh://",
574 "webcal://",
575 )
576
577 # Links
578 links = re.compile(r"<a href=\"(.*?)\">(.*?)</a>")
579
580 # Images
581 images = re.compile(r"<img alt(?:=\"(.*?)\")? src=\"(.*?)\" (?:title=\"(.*?)\" )?/>")
582
583 def init(self, path):
584 self.path = path
585
586 def _render_link(self, m):
587 url, text = m.groups()
588
589 # Emails
590 if "@" in url:
591 # Strip mailto:
592 if url.startswith("mailto:"):
593 url = url[7:]
594
595 return """<a class="link-external" href="mailto:%s">%s</a>""" % \
596 (url, text or url)
597
598 # External Links
599 for schema in self.schemas:
600 if url.startswith(schema):
601 return """<a class="link-external" href="%s">%s</a>""" % \
602 (url, text or url)
603
604 # Everything else must be an internal link
605 path = self.backend.wiki.make_path(self.path, url)
606
607 return """<a href="%s">%s</a>""" % \
608 (path, text or self.backend.wiki.get_page_title(path))
609
610 def _render_image(self, m):
611 alt_text, url, caption = m.groups()
612
613 # Skip any absolute and external URLs
614 if url.startswith("/") or url.startswith("https://") or url.startswith("http://"):
615 return """<figure class="figure"><img src="%s" class="figure-img img-fluid rounded" alt="%s">
616 <figcaption class="figure-caption">%s</figcaption></figure>
617 """ % (url, alt_text, caption or "")
618
619 # Try to split query string
620 url, delimiter, qs = url.partition("?")
621
622 # Parse query arguments
623 args = urllib.parse.parse_qs(qs)
624
625 # Build absolute path
626 url = self.backend.wiki.make_path(self.path, url)
627
628 # Find image
629 file = self.backend.wiki.get_file_by_path(url)
630 if not file or not file.is_image():
631 return "<!-- Could not find image %s in %s -->" % (url, self.path)
632
633 # Scale down the image if not already done
634 if not "s" in args:
635 args["s"] = "920"
636
637 return """<figure class="figure"><img src="%s?%s" class="figure-img img-fluid rounded" alt="%s">
638 <figcaption class="figure-caption">%s</figcaption></figure>
639 """ % (url, urllib.parse.urlencode(args), caption, caption or "")
640
641 def render(self, text):
642 logging.debug("Rendering %s" % self.path)
643
644 # Borrow this from the blog
645 text = self.backend.blog._render_text(text, lang="markdown")
646
647 # Postprocess links
648 text = self.links.sub(self._render_link, text)
649
650 # Postprocess images to <figure>
651 text = self.images.sub(self._render_image, text)
652
653 return text