]>
Commit | Line | Data |
---|---|---|
181d08f3 MT |
1 | #!/usr/bin/python3 |
2 | ||
4ed1dadb | 3 | import difflib |
181d08f3 | 4 | import logging |
6ac7e934 | 5 | import os.path |
181d08f3 | 6 | import re |
addc18d5 | 7 | import tornado.gen |
9e90e800 | 8 | import urllib.parse |
181d08f3 MT |
9 | |
10 | from . import misc | |
9523790a | 11 | from . import util |
181d08f3 MT |
12 | from .decorators import * |
13 | ||
181d08f3 MT |
14 | class Wiki(misc.Object): |
15 | def _get_pages(self, query, *args): | |
16 | res = self.db.query(query, *args) | |
17 | ||
18 | for row in res: | |
19 | yield Page(self.backend, row.id, data=row) | |
20 | ||
d398ca08 MT |
21 | def _get_page(self, query, *args): |
22 | res = self.db.get(query, *args) | |
23 | ||
24 | if res: | |
25 | return Page(self.backend, res.id, data=res) | |
26 | ||
6ac7e934 | 27 | def get_page_title(self, page, default=None): |
50c8dc11 MT |
28 | # Try to retrieve title from cache |
29 | title = self.memcache.get("wiki:title:%s" % page) | |
30 | if title: | |
31 | return title | |
32 | ||
33 | # If the title has not been in the cache, we will | |
34 | # have to look it up | |
6ac7e934 MT |
35 | doc = self.get_page(page) |
36 | if doc: | |
50c8dc11 MT |
37 | title = doc.title |
38 | else: | |
39 | title = os.path.basename(page) | |
6ac7e934 | 40 | |
50c8dc11 MT |
41 | # Save in cache for forever |
42 | self.memcache.set("wiki:title:%s" % page, title) | |
43 | ||
44 | return title | |
6ac7e934 | 45 | |
181d08f3 MT |
46 | def get_page(self, page, revision=None): |
47 | page = Page.sanitise_page_name(page) | |
48 | assert page | |
49 | ||
50 | if revision: | |
d398ca08 | 51 | return self._get_page("SELECT * FROM wiki WHERE page = %s \ |
181d08f3 MT |
52 | AND timestamp = %s", page, revision) |
53 | else: | |
d398ca08 | 54 | return self._get_page("SELECT * FROM wiki WHERE page = %s \ |
181d08f3 MT |
55 | ORDER BY timestamp DESC LIMIT 1", page) |
56 | ||
11afe905 MT |
57 | def get_recent_changes(self, account, limit=None): |
58 | pages = self._get_pages("SELECT * FROM wiki \ | |
f9db574a | 59 | WHERE timestamp >= NOW() - INTERVAL '4 weeks' \ |
11afe905 MT |
60 | ORDER BY timestamp DESC") |
61 | ||
62 | for page in pages: | |
63 | if not page.check_acl(account): | |
64 | continue | |
65 | ||
66 | yield page | |
67 | ||
68 | limit -= 1 | |
69 | if not limit: | |
70 | break | |
181d08f3 | 71 | |
495e9dc4 | 72 | def create_page(self, page, author, content, changes=None, address=None): |
181d08f3 MT |
73 | page = Page.sanitise_page_name(page) |
74 | ||
aba5e58a MT |
75 | # Write page to the database |
76 | page = self._get_page("INSERT INTO wiki(page, author_uid, markdown, changes, address) \ | |
df01767e | 77 | VALUES(%s, %s, %s, %s, %s) RETURNING *", page, author.uid, content or None, changes, address) |
181d08f3 | 78 | |
50c8dc11 | 79 | # Update cache |
980e486d | 80 | self.memcache.set("wiki:title:%s" % page.page, page.title) |
50c8dc11 | 81 | |
aba5e58a MT |
82 | # Send email to all watchers |
83 | page._send_watcher_emails(excludes=[author]) | |
84 | ||
85 | return page | |
86 | ||
495e9dc4 | 87 | def delete_page(self, page, author, **kwargs): |
181d08f3 MT |
88 | # Do nothing if the page does not exist |
89 | if not self.get_page(page): | |
90 | return | |
91 | ||
92 | # Just creates a blank last version of the page | |
495e9dc4 | 93 | self.create_page(page, author=author, content=None, **kwargs) |
181d08f3 | 94 | |
3168788e MT |
95 | def make_breadcrumbs(self, url): |
96 | # Split and strip all empty elements (double slashes) | |
181d08f3 MT |
97 | parts = list(e for e in url.split("/") if e) |
98 | ||
3168788e | 99 | ret = [] |
b1bf7d48 | 100 | for part in ("/".join(parts[:i]) for i in range(1, len(parts))): |
3168788e | 101 | ret.append(("/%s" % part, self.get_page_title(part, os.path.basename(part)))) |
181d08f3 | 102 | |
3168788e | 103 | return ret |
181d08f3 | 104 | |
11afe905 | 105 | def search(self, query, account=None, limit=None): |
9523790a MT |
106 | query = util.parse_search_query(query) |
107 | ||
108 | res = self._get_pages("SELECT wiki.* FROM wiki_search_index search_index \ | |
109 | LEFT JOIN wiki ON search_index.wiki_id = wiki.id \ | |
110 | WHERE search_index.document @@ to_tsquery('english', %s) \ | |
11afe905 MT |
111 | ORDER BY ts_rank(search_index.document, to_tsquery('english', %s)) DESC", |
112 | query, query) | |
9523790a | 113 | |
df80be2c | 114 | pages = [] |
11afe905 MT |
115 | for page in res: |
116 | # Skip any pages the user doesn't have permission for | |
117 | if not page.check_acl(account): | |
118 | continue | |
119 | ||
120 | # Return any other pages | |
df80be2c | 121 | pages.append(page) |
11afe905 | 122 | |
df80be2c MT |
123 | # Break when we have found enough pages |
124 | if limit and len(pages) >= limit: | |
11afe905 | 125 | break |
9523790a | 126 | |
df80be2c MT |
127 | return pages |
128 | ||
9523790a MT |
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 | ||
11afe905 MT |
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 | ||
f2cfd873 MT |
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 | ||
9e90e800 MT |
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 | ||
181d08f3 MT |
199 | |
200 | class Page(misc.Object): | |
201 | def init(self, id, data=None): | |
202 | self.id = id | |
203 | self.data = data | |
204 | ||
dc847af5 MT |
205 | def __repr__(self): |
206 | return "<%s %s %s>" % (self.__class__.__name__, self.page, self.timestamp) | |
207 | ||
c21ffadb MT |
208 | def __eq__(self, other): |
209 | if isinstance(other, self.__class__): | |
210 | return self.id == other.id | |
211 | ||
181d08f3 MT |
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): | |
db8448d9 | 239 | return self.page |
181d08f3 | 240 | |
4ed1dadb MT |
241 | @property |
242 | def full_url(self): | |
243 | return "https://wiki.ipfire.org%s" % self.url | |
244 | ||
181d08f3 MT |
245 | @property |
246 | def page(self): | |
247 | return self.data.page | |
248 | ||
249 | @property | |
250 | def title(self): | |
51e7a876 | 251 | return self._title or os.path.basename(self.page[1:]) |
181d08f3 MT |
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 | ||
3b05ef6e MT |
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 | ||
181d08f3 MT |
270 | def _render(self, text): |
271 | logging.debug("Rendering %s" % self) | |
272 | ||
9e90e800 MT |
273 | # Link images |
274 | replacements = [] | |
df6dd1a3 | 275 | for match in re.finditer(r"!\[(.*?)\]\((.*?)\)", text): |
9e90e800 MT |
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 | ||
bf59e35d | 300 | replacements.append((match.span(), file, alt_text, url)) |
9e90e800 MT |
301 | |
302 | # Apply all replacements | |
bf59e35d MT |
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:] | |
9e90e800 | 305 | |
9e90e800 | 306 | # Add wiki links |
574794da | 307 | patterns = ( |
cc3d95d3 MT |
308 | (r"\[\[([\w\d\/\-\.]+)(?:\|(.+?))\]\]", r"\1", r"\2", None, True), |
309 | (r"\[\[([\w\d\/\-\.]+)\]\]", r"\1", r"\1", self.backend.wiki.get_page_title, True), | |
310 | ||
311 | # External links | |
312 | (r"\[\[((?:ftp|git|https?|rsync|sftp|ssh|webcal)\:\/\/.+?)(?:\|(.+?))\]\]", | |
313 | r"\1", r"\2", None, False), | |
314 | ||
315 | ||
316 | (r"\[\[([a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+)\]\]", | |
317 | r"\1", r"\1", None, False), | |
574794da MT |
318 | ) |
319 | ||
cc3d95d3 | 320 | for pattern, link, title, repl, internal in patterns: |
574794da MT |
321 | replacements = [] |
322 | ||
323 | for match in re.finditer(pattern, text): | |
324 | l = match.expand(link) | |
325 | t = match.expand(title) | |
326 | ||
cc3d95d3 MT |
327 | if internal: |
328 | # Allow relative links | |
329 | if not l.startswith("/"): | |
330 | l = os.path.join(self.page, l) | |
78738820 | 331 | |
cc3d95d3 MT |
332 | # Normalise links |
333 | l = os.path.normpath(l) | |
78738820 | 334 | |
574794da | 335 | if callable(repl): |
78738820 | 336 | t = repl(l) or t |
574794da MT |
337 | |
338 | replacements.append((match.span(), t or l, l)) | |
339 | ||
340 | # Apply all replacements | |
341 | for (start, end), t, l in reversed(replacements): | |
342 | text = text[:start] + "[%s](%s)" % (t, l) + text[end:] | |
343 | ||
045ea3db MT |
344 | # Borrow this from the blog |
345 | return self.backend.blog._render_text(text, lang="markdown") | |
181d08f3 MT |
346 | |
347 | @property | |
348 | def markdown(self): | |
c21ffadb | 349 | return self.data.markdown or "" |
181d08f3 MT |
350 | |
351 | @property | |
352 | def html(self): | |
31834b04 | 353 | return self._render(self.markdown) |
addc18d5 | 354 | |
181d08f3 MT |
355 | @property |
356 | def timestamp(self): | |
357 | return self.data.timestamp | |
358 | ||
359 | def was_deleted(self): | |
360 | return self.markdown is None | |
361 | ||
362 | @lazy_property | |
363 | def breadcrumbs(self): | |
364 | return self.backend.wiki.make_breadcrumbs(self.page) | |
365 | ||
366 | def get_latest_revision(self): | |
7d699684 MT |
367 | revisions = self.get_revisions() |
368 | ||
369 | # Return first object | |
370 | for rev in revisions: | |
371 | return rev | |
372 | ||
373 | def get_revisions(self): | |
374 | return self.backend.wiki._get_pages("SELECT * FROM wiki \ | |
375 | WHERE page = %s ORDER BY timestamp DESC", self.page) | |
091ac36b | 376 | |
c21ffadb MT |
377 | @lazy_property |
378 | def previous_revision(self): | |
379 | return self.backend.wiki._get_page("SELECT * FROM wiki \ | |
380 | WHERE page = %s AND timestamp < %s ORDER BY timestamp DESC \ | |
381 | LIMIT 1", self.page, self.timestamp) | |
382 | ||
d398ca08 MT |
383 | @property |
384 | def changes(self): | |
385 | return self.data.changes | |
386 | ||
11afe905 MT |
387 | # ACL |
388 | ||
389 | def check_acl(self, account): | |
390 | return self.backend.wiki.check_acl(self.page, account) | |
391 | ||
091ac36b MT |
392 | # Sidebar |
393 | ||
394 | @lazy_property | |
395 | def sidebar(self): | |
396 | parts = self.page.split("/") | |
397 | ||
398 | while parts: | |
3cc5f666 | 399 | sidebar = self.backend.wiki.get_page("%s/sidebar" % os.path.join(*parts)) |
091ac36b MT |
400 | if sidebar: |
401 | return sidebar | |
402 | ||
403 | parts.pop() | |
f2cfd873 | 404 | |
d64a1e35 MT |
405 | # Watchers |
406 | ||
4ed1dadb MT |
407 | @lazy_property |
408 | def diff(self): | |
409 | if self.previous_revision: | |
410 | diff = difflib.unified_diff( | |
411 | self.previous_revision.markdown.splitlines(), | |
412 | self.markdown.splitlines(), | |
413 | ) | |
414 | ||
415 | return "\n".join(diff) | |
416 | ||
aba5e58a MT |
417 | @property |
418 | def watchers(self): | |
419 | res = self.db.query("SELECT uid FROM wiki_watchlist \ | |
420 | WHERE page = %s", self.page) | |
421 | ||
422 | for row in res: | |
423 | # Search for account by UID and skip if none was found | |
424 | account = self.backend.accounts.get_by_uid(row.uid) | |
425 | if not account: | |
426 | continue | |
427 | ||
428 | # Return the account | |
429 | yield account | |
430 | ||
f2e25ded | 431 | def is_watched_by(self, account): |
d64a1e35 MT |
432 | res = self.db.get("SELECT 1 FROM wiki_watchlist \ |
433 | WHERE page = %s AND uid = %s", self.page, account.uid) | |
434 | ||
435 | if res: | |
436 | return True | |
437 | ||
438 | return False | |
439 | ||
440 | def add_watcher(self, account): | |
f2e25ded | 441 | if self.is_watched_by(account): |
d64a1e35 MT |
442 | return |
443 | ||
444 | self.db.execute("INSERT INTO wiki_watchlist(page, uid) \ | |
445 | VALUES(%s, %s)", self.page, account.uid) | |
446 | ||
447 | def remove_watcher(self, account): | |
448 | self.db.execute("DELETE FROM wiki_watchlist \ | |
449 | WHERE page = %s AND uid = %s", self.page, account.uid) | |
450 | ||
aba5e58a MT |
451 | def _send_watcher_emails(self, excludes=[]): |
452 | # Nothing to do if there was no previous revision | |
453 | if not self.previous_revision: | |
454 | return | |
455 | ||
456 | for watcher in self.watchers: | |
457 | # Skip everyone who is excluded | |
458 | if watcher in excludes: | |
459 | logging.debug("Excluding %s" % watcher) | |
460 | continue | |
461 | ||
462 | logging.debug("Sending watcher email to %s" % watcher) | |
463 | ||
4ed1dadb MT |
464 | # Compose message |
465 | self.backend.messages.send_template("wiki/messages/page-changed", | |
466 | recipients=[watcher], page=self, priority=-10) | |
aba5e58a | 467 | |
f2cfd873 MT |
468 | |
469 | class File(misc.Object): | |
470 | def init(self, id, data): | |
471 | self.id = id | |
472 | self.data = data | |
473 | ||
474 | @property | |
475 | def url(self): | |
476 | return os.path.join(self.path, self.filename) | |
477 | ||
478 | @property | |
479 | def path(self): | |
480 | return self.data.path | |
481 | ||
482 | @property | |
483 | def filename(self): | |
484 | return self.data.filename | |
485 | ||
486 | @property | |
487 | def mimetype(self): | |
488 | return self.data.mimetype | |
489 | ||
490 | @property | |
491 | def size(self): | |
492 | return self.data.size | |
493 | ||
8cb0bea4 MT |
494 | @lazy_property |
495 | def author(self): | |
496 | if self.data.author_uid: | |
497 | return self.backend.accounts.get_by_uid(self.data.author_uid) | |
498 | ||
499 | @property | |
500 | def created_at(self): | |
501 | return self.data.created_at | |
502 | ||
503 | def is_pdf(self): | |
504 | return self.mimetype in ("application/pdf", "application/x-pdf") | |
505 | ||
f2cfd873 MT |
506 | def is_image(self): |
507 | return self.mimetype.startswith("image/") | |
508 | ||
509 | @lazy_property | |
510 | def blob(self): | |
511 | res = self.db.get("SELECT data FROM wiki_blobs \ | |
512 | WHERE id = %s", self.data.blob_id) | |
513 | ||
514 | if res: | |
515 | return bytes(res.data) | |
79dd9a0f MT |
516 | |
517 | def get_thumbnail(self, size): | |
75d9b3da MT |
518 | cache_key = "-".join((self.path, util.normalize(self.filename), self.created_at.isoformat(), "%spx" % size)) |
519 | ||
520 | # Try to fetch the data from the cache | |
521 | thumbnail = self.memcache.get(cache_key) | |
522 | if thumbnail: | |
523 | return thumbnail | |
524 | ||
525 | # Generate the thumbnail | |
5ef115cd | 526 | thumbnail = util.generate_thumbnail(self.blob, size) |
75d9b3da MT |
527 | |
528 | # Put it into the cache for forever | |
529 | self.memcache.set(cache_key, thumbnail) | |
530 | ||
531 | return thumbnail |