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