]> git.ipfire.org Git - ipfire.org.git/blame - src/backend/wiki.py
wiki: Handle external links
[ipfire.org.git] / src / backend / wiki.py
CommitLineData
181d08f3
MT
1#!/usr/bin/python3
2
4ed1dadb 3import difflib
181d08f3 4import logging
6ac7e934 5import os.path
181d08f3 6import re
addc18d5 7import tornado.gen
9e90e800 8import urllib.parse
181d08f3
MT
9
10from . import misc
9523790a 11from . import util
181d08f3
MT
12from .decorators import *
13
c683a1ff
MT
14INTERWIKIS = {
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
181d08f3
MT
20class 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
d398ca08
MT
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
6ac7e934 33 def get_page_title(self, page, default=None):
50c8dc11
MT
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
6ac7e934
MT
41 doc = self.get_page(page)
42 if doc:
50c8dc11
MT
43 title = doc.title
44 else:
45 title = os.path.basename(page)
6ac7e934 46
50c8dc11
MT
47 # Save in cache for forever
48 self.memcache.set("wiki:title:%s" % page, title)
49
50 return title
6ac7e934 51
181d08f3
MT
52 def get_page(self, page, revision=None):
53 page = Page.sanitise_page_name(page)
54 assert page
55
56 if revision:
d398ca08 57 return self._get_page("SELECT * FROM wiki WHERE page = %s \
181d08f3
MT
58 AND timestamp = %s", page, revision)
59 else:
d398ca08 60 return self._get_page("SELECT * FROM wiki WHERE page = %s \
181d08f3
MT
61 ORDER BY timestamp DESC LIMIT 1", page)
62
11afe905
MT
63 def get_recent_changes(self, account, limit=None):
64 pages = self._get_pages("SELECT * FROM wiki \
f9db574a 65 WHERE timestamp >= NOW() - INTERVAL '4 weeks' \
11afe905
MT
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
181d08f3 77
495e9dc4 78 def create_page(self, page, author, content, changes=None, address=None):
181d08f3
MT
79 page = Page.sanitise_page_name(page)
80
aba5e58a
MT
81 # Write page to the database
82 page = self._get_page("INSERT INTO wiki(page, author_uid, markdown, changes, address) \
df01767e 83 VALUES(%s, %s, %s, %s, %s) RETURNING *", page, author.uid, content or None, changes, address)
181d08f3 84
50c8dc11 85 # Update cache
980e486d 86 self.memcache.set("wiki:title:%s" % page.page, page.title)
50c8dc11 87
aba5e58a
MT
88 # Send email to all watchers
89 page._send_watcher_emails(excludes=[author])
90
91 return page
92
495e9dc4 93 def delete_page(self, page, author, **kwargs):
181d08f3
MT
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
495e9dc4 99 self.create_page(page, author=author, content=None, **kwargs)
181d08f3 100
3168788e
MT
101 def make_breadcrumbs(self, url):
102 # Split and strip all empty elements (double slashes)
181d08f3
MT
103 parts = list(e for e in url.split("/") if e)
104
3168788e 105 ret = []
b1bf7d48 106 for part in ("/".join(parts[:i]) for i in range(1, len(parts))):
3168788e 107 ret.append(("/%s" % part, self.get_page_title(part, os.path.basename(part))))
181d08f3 108
3168788e 109 return ret
181d08f3 110
11afe905 111 def search(self, query, account=None, limit=None):
9523790a
MT
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) \
11afe905
MT
117 ORDER BY ts_rank(search_index.document, to_tsquery('english', %s)) DESC",
118 query, query)
9523790a 119
df80be2c 120 pages = []
11afe905
MT
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
df80be2c 127 pages.append(page)
11afe905 128
df80be2c
MT
129 # Break when we have found enough pages
130 if limit and len(pages) >= limit:
11afe905 131 break
9523790a 132
df80be2c
MT
133 return pages
134
9523790a
MT
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
11afe905
MT
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
f2cfd873
MT
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
9e90e800
MT
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
181d08f3
MT
205
206class Page(misc.Object):
0c9bada3
MT
207 # External links
208 external_link = re.compile(r"\[\[((?:ftp|git|https?|rsync|sftp|ssh|webcal)\:\/\/.+?)(?:\|(.+?))\]\]")
209
e2205cff
MT
210 # Interwiki links e.g. [[wp>IPFire]]
211 interwiki_link = re.compile(r"\[\[(\w+)>(.+?)(?:\|(.+?))?\]\]")
212
181d08f3
MT
213 def init(self, id, data=None):
214 self.id = id
215 self.data = data
216
dc847af5
MT
217 def __repr__(self):
218 return "<%s %s %s>" % (self.__class__.__name__, self.page, self.timestamp)
219
c21ffadb
MT
220 def __eq__(self, other):
221 if isinstance(other, self.__class__):
222 return self.id == other.id
223
181d08f3
MT
224 def __lt__(self, other):
225 if isinstance(other, self.__class__):
226 if self.page == other.page:
227 return self.timestamp < other.timestamp
228
229 return self.page < other.page
230
231 @staticmethod
232 def sanitise_page_name(page):
233 if not page:
234 return "/"
235
236 # Make sure that the page name does NOT end with a /
237 if page.endswith("/"):
238 page = page[:-1]
239
240 # Make sure the page name starts with a /
241 if not page.startswith("/"):
242 page = "/%s" % page
243
244 # Remove any double slashes
245 page = page.replace("//", "/")
246
247 return page
248
249 @property
250 def url(self):
db8448d9 251 return self.page
181d08f3 252
4ed1dadb
MT
253 @property
254 def full_url(self):
255 return "https://wiki.ipfire.org%s" % self.url
256
181d08f3
MT
257 @property
258 def page(self):
259 return self.data.page
260
261 @property
262 def title(self):
51e7a876 263 return self._title or os.path.basename(self.page[1:])
181d08f3
MT
264
265 @property
266 def _title(self):
267 if not self.markdown:
268 return
269
270 # Find first H1 headline in markdown
271 markdown = self.markdown.splitlines()
272
273 m = re.match(r"^# (.*)( #)?$", markdown[0])
274 if m:
275 return m.group(1)
276
3b05ef6e
MT
277 @lazy_property
278 def author(self):
279 if self.data.author_uid:
280 return self.backend.accounts.get_by_uid(self.data.author_uid)
281
0c9bada3
MT
282 def _render_external_link(self, m):
283 url, alias = m.groups()
284
285 return """<a class="link-external" href="%s">%s</a>""" % (url, alias or url)
286
c683a1ff
MT
287 def _render_interwiki_link(self, m):
288 wiki = m.group(1)
289 if not wiki:
290 return
291
292 # Retrieve URL
293 try:
294 url, repl, icon = INTERWIKIS[wiki]
295 except KeyError:
296 logging.warning("Invalid interwiki: %s" % wiki)
297 return
298
299 # Name of the page
300 name = m.group(2)
301
302 # Expand URL
303 url = url % {
304 "name" : name,
305 "url" : urllib.parse.quote(name),
306 }
307
308 # Get alias (if present)
309 alias = m.group(3)
310
311 if not alias and repl:
312 alias = repl % name
313
314 # Put everything together
315 s = []
316
317 if icon:
318 s.append("<span class=\"%s\"></span>" % icon)
319
320 s.append("""<a class="link-external" href="%s">%s</a>""" % (url, alias or name))
321
322 return " ".join(s)
323
181d08f3
MT
324 def _render(self, text):
325 logging.debug("Rendering %s" % self)
326
9e90e800
MT
327 # Link images
328 replacements = []
df6dd1a3 329 for match in re.finditer(r"!\[(.*?)\]\((.*?)\)", text):
9e90e800
MT
330 alt_text, url = match.groups()
331
332 # Skip any absolute and external URLs
333 if url.startswith("/") or url.startswith("https://") or url.startswith("http://"):
334 continue
335
336 # Try to split query string
337 url, delimiter, qs = url.partition("?")
338
339 # Parse query arguments
340 args = urllib.parse.parse_qs(qs)
341
342 # Find image
343 file = self.backend.wiki.find_image(self.page, url)
344 if not file:
345 continue
346
347 # Scale down the image if not already done
348 if not "s" in args:
349 args["s"] = "768"
350
351 # Format URL
352 url = "%s?%s" % (file.url, urllib.parse.urlencode(args))
353
bf59e35d 354 replacements.append((match.span(), file, alt_text, url))
9e90e800
MT
355
356 # Apply all replacements
bf59e35d
MT
357 for (start, end), file, alt_text, url in reversed(replacements):
358 text = text[:start] + "[![%s](%s)](%s?action=detail)" % (alt_text, url, file.url) + text[end:]
9e90e800 359
c683a1ff 360 # Handle interwiki links
e2205cff 361 text = self.interwiki_link.sub(self._render_interwiki_link, text)
c683a1ff 362
0c9bada3
MT
363 # Handle external links
364 text = self.external_link.sub(self._render_external_link, text)
365
9e90e800 366 # Add wiki links
574794da 367 patterns = (
cc3d95d3
MT
368 (r"\[\[([\w\d\/\-\.]+)(?:\|(.+?))\]\]", r"\1", r"\2", None, True),
369 (r"\[\[([\w\d\/\-\.]+)\]\]", r"\1", r"\1", self.backend.wiki.get_page_title, True),
370
cc3d95d3
MT
371 # Mail
372 (r"\[\[([a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+)\]\]",
373 r"\1", r"\1", None, False),
574794da
MT
374 )
375
cc3d95d3 376 for pattern, link, title, repl, internal in patterns:
574794da
MT
377 replacements = []
378
379 for match in re.finditer(pattern, text):
380 l = match.expand(link)
381 t = match.expand(title)
382
cc3d95d3
MT
383 if internal:
384 # Allow relative links
385 if not l.startswith("/"):
386 l = os.path.join(self.page, l)
78738820 387
cc3d95d3
MT
388 # Normalise links
389 l = os.path.normpath(l)
78738820 390
574794da 391 if callable(repl):
78738820 392 t = repl(l) or t
574794da
MT
393
394 replacements.append((match.span(), t or l, l))
395
396 # Apply all replacements
397 for (start, end), t, l in reversed(replacements):
398 text = text[:start] + "[%s](%s)" % (t, l) + text[end:]
399
045ea3db
MT
400 # Borrow this from the blog
401 return self.backend.blog._render_text(text, lang="markdown")
181d08f3
MT
402
403 @property
404 def markdown(self):
c21ffadb 405 return self.data.markdown or ""
181d08f3
MT
406
407 @property
408 def html(self):
31834b04 409 return self._render(self.markdown)
addc18d5 410
181d08f3
MT
411 @property
412 def timestamp(self):
413 return self.data.timestamp
414
415 def was_deleted(self):
416 return self.markdown is None
417
418 @lazy_property
419 def breadcrumbs(self):
420 return self.backend.wiki.make_breadcrumbs(self.page)
421
422 def get_latest_revision(self):
7d699684
MT
423 revisions = self.get_revisions()
424
425 # Return first object
426 for rev in revisions:
427 return rev
428
429 def get_revisions(self):
430 return self.backend.wiki._get_pages("SELECT * FROM wiki \
431 WHERE page = %s ORDER BY timestamp DESC", self.page)
091ac36b 432
c21ffadb
MT
433 @lazy_property
434 def previous_revision(self):
435 return self.backend.wiki._get_page("SELECT * FROM wiki \
436 WHERE page = %s AND timestamp < %s ORDER BY timestamp DESC \
437 LIMIT 1", self.page, self.timestamp)
438
d398ca08
MT
439 @property
440 def changes(self):
441 return self.data.changes
442
11afe905
MT
443 # ACL
444
445 def check_acl(self, account):
446 return self.backend.wiki.check_acl(self.page, account)
447
091ac36b
MT
448 # Sidebar
449
450 @lazy_property
451 def sidebar(self):
452 parts = self.page.split("/")
453
454 while parts:
3cc5f666 455 sidebar = self.backend.wiki.get_page("%s/sidebar" % os.path.join(*parts))
091ac36b
MT
456 if sidebar:
457 return sidebar
458
459 parts.pop()
f2cfd873 460
d64a1e35
MT
461 # Watchers
462
4ed1dadb
MT
463 @lazy_property
464 def diff(self):
465 if self.previous_revision:
466 diff = difflib.unified_diff(
467 self.previous_revision.markdown.splitlines(),
468 self.markdown.splitlines(),
469 )
470
471 return "\n".join(diff)
472
aba5e58a
MT
473 @property
474 def watchers(self):
475 res = self.db.query("SELECT uid FROM wiki_watchlist \
476 WHERE page = %s", self.page)
477
478 for row in res:
479 # Search for account by UID and skip if none was found
480 account = self.backend.accounts.get_by_uid(row.uid)
481 if not account:
482 continue
483
484 # Return the account
485 yield account
486
f2e25ded 487 def is_watched_by(self, account):
d64a1e35
MT
488 res = self.db.get("SELECT 1 FROM wiki_watchlist \
489 WHERE page = %s AND uid = %s", self.page, account.uid)
490
491 if res:
492 return True
493
494 return False
495
496 def add_watcher(self, account):
f2e25ded 497 if self.is_watched_by(account):
d64a1e35
MT
498 return
499
500 self.db.execute("INSERT INTO wiki_watchlist(page, uid) \
501 VALUES(%s, %s)", self.page, account.uid)
502
503 def remove_watcher(self, account):
504 self.db.execute("DELETE FROM wiki_watchlist \
505 WHERE page = %s AND uid = %s", self.page, account.uid)
506
aba5e58a
MT
507 def _send_watcher_emails(self, excludes=[]):
508 # Nothing to do if there was no previous revision
509 if not self.previous_revision:
510 return
511
512 for watcher in self.watchers:
513 # Skip everyone who is excluded
514 if watcher in excludes:
515 logging.debug("Excluding %s" % watcher)
516 continue
517
518 logging.debug("Sending watcher email to %s" % watcher)
519
4ed1dadb
MT
520 # Compose message
521 self.backend.messages.send_template("wiki/messages/page-changed",
522 recipients=[watcher], page=self, priority=-10)
aba5e58a 523
f2cfd873
MT
524
525class File(misc.Object):
526 def init(self, id, data):
527 self.id = id
528 self.data = data
529
530 @property
531 def url(self):
532 return os.path.join(self.path, self.filename)
533
534 @property
535 def path(self):
536 return self.data.path
537
538 @property
539 def filename(self):
540 return self.data.filename
541
542 @property
543 def mimetype(self):
544 return self.data.mimetype
545
546 @property
547 def size(self):
548 return self.data.size
549
8cb0bea4
MT
550 @lazy_property
551 def author(self):
552 if self.data.author_uid:
553 return self.backend.accounts.get_by_uid(self.data.author_uid)
554
555 @property
556 def created_at(self):
557 return self.data.created_at
558
559 def is_pdf(self):
560 return self.mimetype in ("application/pdf", "application/x-pdf")
561
f2cfd873
MT
562 def is_image(self):
563 return self.mimetype.startswith("image/")
564
565 @lazy_property
566 def blob(self):
567 res = self.db.get("SELECT data FROM wiki_blobs \
568 WHERE id = %s", self.data.blob_id)
569
570 if res:
571 return bytes(res.data)
79dd9a0f
MT
572
573 def get_thumbnail(self, size):
75d9b3da
MT
574 cache_key = "-".join((self.path, util.normalize(self.filename), self.created_at.isoformat(), "%spx" % size))
575
576 # Try to fetch the data from the cache
577 thumbnail = self.memcache.get(cache_key)
578 if thumbnail:
579 return thumbnail
580
581 # Generate the thumbnail
5ef115cd 582 thumbnail = util.generate_thumbnail(self.blob, size)
75d9b3da
MT
583
584 # Put it into the cache for forever
585 self.memcache.set(cache_key, thumbnail)
586
587 return thumbnail