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