]> git.ipfire.org Git - ipfire.org.git/blob - src/backend/wiki.py
wiki: Add support for relative links
[ipfire.org.git] / src / backend / wiki.py
1 #!/usr/bin/python3
2
3 import PIL
4 import difflib
5 import io
6 import logging
7 import os.path
8 import re
9 import tornado.gen
10 import urllib.parse
11
12 from . import misc
13 from . import util
14 from .decorators import *
15
16 class Wiki(misc.Object):
17 def _get_pages(self, query, *args):
18 res = self.db.query(query, *args)
19
20 for row in res:
21 yield Page(self.backend, row.id, data=row)
22
23 def _get_page(self, query, *args):
24 res = self.db.get(query, *args)
25
26 if res:
27 return Page(self.backend, res.id, data=res)
28
29 def get_page_title(self, page, default=None):
30 doc = self.get_page(page)
31 if doc:
32 return doc.title
33
34 return default or os.path.basename(page)
35
36 def get_page(self, page, revision=None):
37 page = Page.sanitise_page_name(page)
38 assert page
39
40 if revision:
41 return self._get_page("SELECT * FROM wiki WHERE page = %s \
42 AND timestamp = %s", page, revision)
43 else:
44 return self._get_page("SELECT * FROM wiki WHERE page = %s \
45 ORDER BY timestamp DESC LIMIT 1", page)
46
47 def get_recent_changes(self, account, limit=None):
48 pages = self._get_pages("SELECT * FROM wiki \
49 WHERE timestamp >= NOW() - INTERVAL '4 weeks' \
50 ORDER BY timestamp DESC")
51
52 for page in pages:
53 if not page.check_acl(account):
54 continue
55
56 yield page
57
58 limit -= 1
59 if not limit:
60 break
61
62 def create_page(self, page, author, content, changes=None, address=None):
63 page = Page.sanitise_page_name(page)
64
65 # Write page to the database
66 page = self._get_page("INSERT INTO wiki(page, author_uid, markdown, changes, address) \
67 VALUES(%s, %s, %s, %s, %s) RETURNING *", page, author.uid, content or None, changes, address)
68
69 # Render markdown
70 page.bake()
71
72 # Send email to all watchers
73 page._send_watcher_emails(excludes=[author])
74
75 return page
76
77 def delete_page(self, page, author, **kwargs):
78 # Do nothing if the page does not exist
79 if not self.get_page(page):
80 return
81
82 # Just creates a blank last version of the page
83 self.create_page(page, author=author, content=None, **kwargs)
84
85 @tornado.gen.coroutine
86 def rebake(self):
87 """
88 Re-renders all wiki pages
89 """
90 pages = self._get_pages("SELECT * FROM wiki ORDER BY timestamp DESC")
91
92 for page in pages:
93 logging.info("Baking %s from %s" % (page.page, page.timestamp))
94
95 with self.db.transaction():
96 page.bake()
97
98 def make_breadcrumbs(self, url):
99 # Split and strip all empty elements (double slashes)
100 parts = list(e for e in url.split("/") if e)
101
102 ret = []
103 for part in ("/".join(parts[:i]) for i in range(1, len(parts))):
104 ret.append(("/%s" % part, self.get_page_title(part, os.path.basename(part))))
105
106 return ret
107
108 def search(self, query, account=None, limit=None):
109 query = util.parse_search_query(query)
110
111 res = self._get_pages("SELECT wiki.* FROM wiki_search_index search_index \
112 LEFT JOIN wiki ON search_index.wiki_id = wiki.id \
113 WHERE search_index.document @@ to_tsquery('english', %s) \
114 ORDER BY ts_rank(search_index.document, to_tsquery('english', %s)) DESC",
115 query, query)
116
117 for page in res:
118 # Skip any pages the user doesn't have permission for
119 if not page.check_acl(account):
120 continue
121
122 # Return any other pages
123 yield page
124
125 limit -= 1
126 if not limit:
127 break
128
129 def refresh(self):
130 """
131 Needs to be called after a page has been changed
132 """
133 self.db.execute("REFRESH MATERIALIZED VIEW wiki_search_index")
134
135 # ACL
136
137 def check_acl(self, page, account):
138 res = self.db.query("SELECT * FROM wiki_acls \
139 WHERE %s ILIKE (path || '%%') ORDER BY LENGTH(path) DESC LIMIT 1", page)
140
141 for row in res:
142 # Access not permitted when user is not logged in
143 if not account:
144 return False
145
146 # If user is in a matching group, we grant permission
147 for group in row.groups:
148 if group in account.groups:
149 return True
150
151 # Otherwise access is not permitted
152 return False
153
154 # If no ACLs are found, we permit access
155 return True
156
157 # Files
158
159 def _get_files(self, query, *args):
160 res = self.db.query(query, *args)
161
162 for row in res:
163 yield File(self.backend, row.id, data=row)
164
165 def _get_file(self, query, *args):
166 res = self.db.get(query, *args)
167
168 if res:
169 return File(self.backend, res.id, data=res)
170
171 def get_files(self, path):
172 files = self._get_files("SELECT * FROM wiki_files \
173 WHERE path = %s AND deleted_at IS NULL ORDER BY filename", path)
174
175 return list(files)
176
177 def get_file_by_path(self, path):
178 path, filename = os.path.dirname(path), os.path.basename(path)
179
180 return self._get_file("SELECT * FROM wiki_files \
181 WHERE path = %s AND filename = %s AND deleted_at IS NULL", path, filename)
182
183 def upload(self, path, filename, data, mimetype, author, address):
184 # Upload the blob first
185 blob = self.db.get("INSERT INTO wiki_blobs(data) VALUES(%s) RETURNING id", data)
186
187 # Create entry for file
188 return self._get_file("INSERT INTO wiki_files(path, filename, author_uid, address, \
189 mimetype, blob_id, size) VALUES(%s, %s, %s, %s, %s, %s, %s) RETURNING *", path,
190 filename, author.uid, address, mimetype, blob.id, len(data))
191
192 def find_image(self, path, filename):
193 for p in (path, os.path.dirname(path)):
194 file = self.get_file_by_path(os.path.join(p, filename))
195
196 if file and file.is_image():
197 return file
198
199
200 class Page(misc.Object):
201 def init(self, id, data=None):
202 self.id = id
203 self.data = data
204
205 def __repr__(self):
206 return "<%s %s %s>" % (self.__class__.__name__, self.page, self.timestamp)
207
208 def __eq__(self, other):
209 if isinstance(other, self.__class__):
210 return self.id == other.id
211
212 def __lt__(self, other):
213 if isinstance(other, self.__class__):
214 if self.page == other.page:
215 return self.timestamp < other.timestamp
216
217 return self.page < other.page
218
219 @staticmethod
220 def sanitise_page_name(page):
221 if not page:
222 return "/"
223
224 # Make sure that the page name does NOT end with a /
225 if page.endswith("/"):
226 page = page[:-1]
227
228 # Make sure the page name starts with a /
229 if not page.startswith("/"):
230 page = "/%s" % page
231
232 # Remove any double slashes
233 page = page.replace("//", "/")
234
235 return page
236
237 @property
238 def url(self):
239 return self.page
240
241 @property
242 def full_url(self):
243 return "https://wiki.ipfire.org%s" % self.url
244
245 @property
246 def page(self):
247 return self.data.page
248
249 @property
250 def title(self):
251 return self._title or os.path.basename(self.page[1:])
252
253 @property
254 def _title(self):
255 if not self.markdown:
256 return
257
258 # Find first H1 headline in markdown
259 markdown = self.markdown.splitlines()
260
261 m = re.match(r"^# (.*)( #)?$", markdown[0])
262 if m:
263 return m.group(1)
264
265 @lazy_property
266 def author(self):
267 if self.data.author_uid:
268 return self.backend.accounts.get_by_uid(self.data.author_uid)
269
270 def _render(self, text):
271 logging.debug("Rendering %s" % self)
272
273 # Link images
274 replacements = []
275 for match in re.finditer(r"!\[(.*)\]\((.*)\)", text):
276 alt_text, url = match.groups()
277
278 # Skip any absolute and external URLs
279 if url.startswith("/") or url.startswith("https://") or url.startswith("http://"):
280 continue
281
282 # Try to split query string
283 url, delimiter, qs = url.partition("?")
284
285 # Parse query arguments
286 args = urllib.parse.parse_qs(qs)
287
288 # Find image
289 file = self.backend.wiki.find_image(self.page, url)
290 if not file:
291 continue
292
293 # Scale down the image if not already done
294 if not "s" in args:
295 args["s"] = "768"
296
297 # Format URL
298 url = "%s?%s" % (file.url, urllib.parse.urlencode(args))
299
300 replacements.append((match.span(), file, alt_text, url))
301
302 # Apply all replacements
303 for (start, end), file, alt_text, url in reversed(replacements):
304 text = text[:start] + "[![%s](%s)](%s?action=detail)" % (alt_text, url, file.url) + text[end:]
305
306 # Add wiki links
307 patterns = (
308 (r"\[\[([\w\d\/]+)(?:\|([\w\d\s]+))\]\]", r"/\1", r"\2", None),
309 (r"\[\[([\w\d\/\-\.]+)\]\]", r"\1", r"\1", self.backend.wiki.get_page_title),
310 )
311
312 for pattern, link, title, repl in patterns:
313 replacements = []
314
315 for match in re.finditer(pattern, text):
316 l = match.expand(link)
317 t = match.expand(title)
318
319 # Allow relative links
320 if not l.startswith("/"):
321 l = os.path.join(self.page, l)
322
323 # Normalise links
324 l = os.path.normpath(l)
325
326 if callable(repl):
327 t = repl(l) or t
328
329 replacements.append((match.span(), t or l, l))
330
331 # Apply all replacements
332 for (start, end), t, l in reversed(replacements):
333 text = text[:start] + "[%s](%s)" % (t, l) + text[end:]
334
335 # Borrow this from the blog
336 return self.backend.blog._render_text(text, lang="markdown")
337
338 @property
339 def markdown(self):
340 return self.data.markdown or ""
341
342 @property
343 def html(self):
344 return self.data.html or self._render(self.markdown)
345
346 def bake(self):
347 """
348 Renders the page's markdown to HTML and stores
349 it in the database.
350 """
351 self.db.execute("UPDATE wiki SET html = %s WHERE id = %s",
352 self._render(self.markdown), self.id)
353
354 @property
355 def timestamp(self):
356 return self.data.timestamp
357
358 def was_deleted(self):
359 return self.markdown is None
360
361 @lazy_property
362 def breadcrumbs(self):
363 return self.backend.wiki.make_breadcrumbs(self.page)
364
365 def get_latest_revision(self):
366 revisions = self.get_revisions()
367
368 # Return first object
369 for rev in revisions:
370 return rev
371
372 def get_revisions(self):
373 return self.backend.wiki._get_pages("SELECT * FROM wiki \
374 WHERE page = %s ORDER BY timestamp DESC", self.page)
375
376 @lazy_property
377 def previous_revision(self):
378 return self.backend.wiki._get_page("SELECT * FROM wiki \
379 WHERE page = %s AND timestamp < %s ORDER BY timestamp DESC \
380 LIMIT 1", self.page, self.timestamp)
381
382 @property
383 def changes(self):
384 return self.data.changes
385
386 # ACL
387
388 def check_acl(self, account):
389 return self.backend.wiki.check_acl(self.page, account)
390
391 # Sidebar
392
393 @lazy_property
394 def sidebar(self):
395 parts = self.page.split("/")
396
397 while parts:
398 sidebar = self.backend.wiki.get_page("%s/sidebar" % os.path.join(*parts))
399 if sidebar:
400 return sidebar
401
402 parts.pop()
403
404 # Watchers
405
406 @lazy_property
407 def diff(self):
408 if self.previous_revision:
409 diff = difflib.unified_diff(
410 self.previous_revision.markdown.splitlines(),
411 self.markdown.splitlines(),
412 )
413
414 return "\n".join(diff)
415
416 @property
417 def watchers(self):
418 res = self.db.query("SELECT uid FROM wiki_watchlist \
419 WHERE page = %s", self.page)
420
421 for row in res:
422 # Search for account by UID and skip if none was found
423 account = self.backend.accounts.get_by_uid(row.uid)
424 if not account:
425 continue
426
427 # Return the account
428 yield account
429
430 def is_watched_by(self, account):
431 res = self.db.get("SELECT 1 FROM wiki_watchlist \
432 WHERE page = %s AND uid = %s", self.page, account.uid)
433
434 if res:
435 return True
436
437 return False
438
439 def add_watcher(self, account):
440 if self.is_watched_by(account):
441 return
442
443 self.db.execute("INSERT INTO wiki_watchlist(page, uid) \
444 VALUES(%s, %s)", self.page, account.uid)
445
446 def remove_watcher(self, account):
447 self.db.execute("DELETE FROM wiki_watchlist \
448 WHERE page = %s AND uid = %s", self.page, account.uid)
449
450 def _send_watcher_emails(self, excludes=[]):
451 # Nothing to do if there was no previous revision
452 if not self.previous_revision:
453 return
454
455 for watcher in self.watchers:
456 # Skip everyone who is excluded
457 if watcher in excludes:
458 logging.debug("Excluding %s" % watcher)
459 continue
460
461 logging.debug("Sending watcher email to %s" % watcher)
462
463 # Compose message
464 self.backend.messages.send_template("wiki/messages/page-changed",
465 recipients=[watcher], page=self, priority=-10)
466
467
468 class File(misc.Object):
469 def init(self, id, data):
470 self.id = id
471 self.data = data
472
473 @property
474 def url(self):
475 return os.path.join(self.path, self.filename)
476
477 @property
478 def path(self):
479 return self.data.path
480
481 @property
482 def filename(self):
483 return self.data.filename
484
485 @property
486 def mimetype(self):
487 return self.data.mimetype
488
489 @property
490 def size(self):
491 return self.data.size
492
493 @lazy_property
494 def author(self):
495 if self.data.author_uid:
496 return self.backend.accounts.get_by_uid(self.data.author_uid)
497
498 @property
499 def created_at(self):
500 return self.data.created_at
501
502 def is_pdf(self):
503 return self.mimetype in ("application/pdf", "application/x-pdf")
504
505 def is_image(self):
506 return self.mimetype.startswith("image/")
507
508 @lazy_property
509 def blob(self):
510 res = self.db.get("SELECT data FROM wiki_blobs \
511 WHERE id = %s", self.data.blob_id)
512
513 if res:
514 return bytes(res.data)
515
516 def get_thumbnail(self, size):
517 cache_key = "-".join((self.path, util.normalize(self.filename), self.created_at.isoformat(), "%spx" % size))
518
519 # Try to fetch the data from the cache
520 thumbnail = self.memcache.get(cache_key)
521 if thumbnail:
522 return thumbnail
523
524 # Generate the thumbnail
525 thumbnail = self._generate_thumbnail(size)
526
527 # Put it into the cache for forever
528 self.memcache.set(cache_key, thumbnail)
529
530 return thumbnail
531
532 def _generate_thumbnail(self, size):
533 image = PIL.Image.open(io.BytesIO(self.blob))
534
535 # Resize the image to the desired resolution
536 image.thumbnail((size, size), PIL.Image.ANTIALIAS)
537
538 with io.BytesIO() as f:
539 # If writing out the image does not work with optimization,
540 # we try to write it out without any optimization.
541 try:
542 image.save(f, image.format, optimize=True, quality=98)
543 except:
544 image.save(f, image.format, quality=98)
545
546 return f.getvalue()