]>
git.ipfire.org Git - ipfire.org.git/blob - src/backend/wiki.py
8237da97ef6e5a18a9c8b20715bcf71a9da39e58
11 from .decorators
import *
13 class Wiki(misc
.Object
):
14 def _get_pages(self
, query
, *args
):
15 res
= self
.db
.query(query
, *args
)
18 yield Page(self
.backend
, row
.id, data
=row
)
20 def _get_page(self
, query
, *args
):
21 res
= self
.db
.get(query
, *args
)
24 return Page(self
.backend
, res
.id, data
=res
)
27 return self
._get
_pages
(
28 "SELECT wiki.* FROM wiki_current current \
29 LEFT JOIN wiki ON current.id = wiki.id \
30 WHERE current.deleted IS FALSE \
34 def make_path(self
, page
, path
):
35 # Nothing to do for absolute links
36 if path
.startswith("/"):
39 # Relative links (one-level down)
40 elif path
.startswith("./"):
41 path
= os
.path
.join(page
, path
)
43 # All other relative links
45 p
= os
.path
.dirname(page
)
46 path
= os
.path
.join(p
, path
)
49 return os
.path
.normpath(path
)
51 def page_exists(self
, path
):
52 page
= self
.get_page(path
)
54 # Page must have been found and not deleted
55 return page
and not page
.was_deleted()
57 def get_page_title(self
, page
, default
=None):
58 # Try to retrieve title from cache
59 title
= self
.memcache
.get("wiki:title:%s" % page
)
63 # If the title has not been in the cache, we will
65 doc
= self
.get_page(page
)
69 title
= os
.path
.basename(page
)
71 # Save in cache for forever
72 self
.memcache
.set("wiki:title:%s" % page
, title
)
76 def get_page(self
, page
, revision
=None):
77 page
= Page
.sanitise_page_name(page
)
81 return self
._get
_page
("SELECT * FROM wiki WHERE page = %s \
82 AND timestamp = %s", page
, revision
)
84 return self
._get
_page
("SELECT * FROM wiki WHERE page = %s \
85 ORDER BY timestamp DESC LIMIT 1", page
)
87 def get_recent_changes(self
, account
, limit
=None):
88 pages
= self
._get
_pages
("SELECT * FROM wiki \
89 ORDER BY timestamp DESC")
92 if not page
.check_acl(account
):
101 def create_page(self
, page
, author
, content
, changes
=None, address
=None):
102 page
= Page
.sanitise_page_name(page
)
104 # Write page to the database
105 page
= self
._get
_page
("INSERT INTO wiki(page, author_uid, markdown, changes, address) \
106 VALUES(%s, %s, %s, %s, %s) RETURNING *", page
, author
.uid
, content
or None, changes
, address
)
109 self
.memcache
.set("wiki:title:%s" % page
.page
, page
.title
)
111 # Send email to all watchers
112 page
._send
_watcher
_emails
(excludes
=[author
])
116 def delete_page(self
, page
, author
, **kwargs
):
117 # Do nothing if the page does not exist
118 if not self
.get_page(page
):
121 # Just creates a blank last version of the page
122 self
.create_page(page
, author
=author
, content
=None, **kwargs
)
124 def make_breadcrumbs(self
, url
):
125 # Split and strip all empty elements (double slashes)
126 parts
= list(e
for e
in url
.split("/") if e
)
129 for part
in ("/".join(parts
[:i
]) for i
in range(1, len(parts
))):
130 ret
.append(("/%s" % part
, self
.get_page_title(part
, os
.path
.basename(part
))))
134 def search(self
, query
, account
=None, limit
=None):
135 res
= self
._get
_pages
("SELECT wiki.* FROM wiki_search_index search_index \
136 LEFT JOIN wiki ON search_index.wiki_id = wiki.id \
137 WHERE search_index.document @@ websearch_to_tsquery('english', %s) \
138 ORDER BY ts_rank(search_index.document, websearch_to_tsquery('english', %s)) DESC",
143 # Skip any pages the user doesn't have permission for
144 if not page
.check_acl(account
):
147 # Return any other pages
150 # Break when we have found enough pages
151 if limit
and len(pages
) >= limit
:
158 Needs to be called after a page has been changed
160 self
.db
.execute("REFRESH MATERIALIZED VIEW wiki_search_index")
162 def get_watchlist(self
, account
):
163 pages
= self
._get
_pages
(
164 "WITH pages AS (SELECT * FROM wiki_current \
165 LEFT JOIN wiki ON wiki_current.id = wiki.id) \
166 SELECT * FROM wiki_watchlist watchlist \
167 LEFT JOIN pages ON watchlist.page = pages.page \
168 WHERE watchlist.uid = %s",
176 def check_acl(self
, page
, account
):
177 res
= self
.db
.query("SELECT * FROM wiki_acls \
178 WHERE %s ILIKE (path || '%%') ORDER BY LENGTH(path) DESC LIMIT 1", page
)
181 # Access not permitted when user is not logged in
185 # If user is in a matching group, we grant permission
186 for group
in row
.groups
:
187 if account
.is_member_of_group(group
):
190 # Otherwise access is not permitted
193 # If no ACLs are found, we permit access
198 def _get_files(self
, query
, *args
):
199 res
= self
.db
.query(query
, *args
)
202 yield File(self
.backend
, row
.id, data
=row
)
204 def _get_file(self
, query
, *args
):
205 res
= self
.db
.get(query
, *args
)
208 return File(self
.backend
, res
.id, data
=res
)
210 def get_files(self
, path
):
211 files
= self
._get
_files
("SELECT * FROM wiki_files \
212 WHERE path = %s AND deleted_at IS NULL ORDER BY filename", path
)
216 def get_file_by_path(self
, path
, revision
=None):
217 path
, filename
= os
.path
.dirname(path
), os
.path
.basename(path
)
220 # Fetch a specific revision
221 return self
._get
_file
("SELECT * FROM wiki_files \
222 WHERE path = %s AND filename = %s AND created_at <= %s \
223 ORDER BY created_at DESC LIMIT 1", path
, filename
, revision
)
225 # Fetch latest version
226 return self
._get
_file
("SELECT * FROM wiki_files \
227 WHERE path = %s AND filename = %s AND deleted_at IS NULL",
230 def get_file_by_path_and_filename(self
, path
, filename
):
231 return self
._get
_file
("SELECT * FROM wiki_files \
232 WHERE path = %s AND filename = %s AND deleted_at IS NULL",
235 def upload(self
, path
, filename
, data
, mimetype
, author
, address
):
236 # Replace any existing files
237 file = self
.get_file_by_path_and_filename(path
, filename
)
241 # Upload the blob first
242 blob
= self
.db
.get("INSERT INTO wiki_blobs(data) VALUES(%s) \
243 ON CONFLICT (digest(data, %s)) DO UPDATE SET data = EXCLUDED.data \
244 RETURNING id", data
, "MD5")
246 # Create entry for file
247 return self
._get
_file
("INSERT INTO wiki_files(path, filename, author_uid, address, \
248 mimetype, blob_id, size) VALUES(%s, %s, %s, %s, %s, %s, %s) RETURNING *", path
,
249 filename
, author
.uid
, address
, mimetype
, blob
.id, len(data
))
251 def render(self
, path
, text
):
252 r
= WikiRenderer(self
.backend
, path
)
254 return r
.render(text
)
257 class Page(misc
.Object
):
258 def init(self
, id, data
=None):
263 return "<%s %s %s>" % (self
.__class
__.__name
__, self
.page
, self
.timestamp
)
265 def __eq__(self
, other
):
266 if isinstance(other
, self
.__class
__):
267 return self
.id == other
.id
269 def __lt__(self
, other
):
270 if isinstance(other
, self
.__class
__):
271 if self
.page
== other
.page
:
272 return self
.timestamp
< other
.timestamp
274 return self
.page
< other
.page
277 def sanitise_page_name(page
):
281 # Make sure that the page name does NOT end with a /
282 if page
.endswith("/"):
285 # Make sure the page name starts with a /
286 if not page
.startswith("/"):
289 # Remove any double slashes
290 page
= page
.replace("//", "/")
300 return "https://wiki.ipfire.org%s" % self
.url
304 return self
.data
.page
308 return self
._title
or os
.path
.basename(self
.page
[1:])
312 if not self
.markdown
:
315 # Find first H1 headline in markdown
316 markdown
= self
.markdown
.splitlines()
318 m
= re
.match(r
"^#\s*(.*)( #)?$", markdown
[0])
324 if self
.data
.author_uid
:
325 return self
.backend
.accounts
.get_by_uid(self
.data
.author_uid
)
329 return self
.data
.markdown
or ""
333 return self
.backend
.wiki
.render(self
.page
, self
.markdown
)
337 return self
.data
.timestamp
339 def was_deleted(self
):
340 return not self
.markdown
343 def breadcrumbs(self
):
344 return self
.backend
.wiki
.make_breadcrumbs(self
.page
)
346 def is_latest_revision(self
):
347 return self
.get_latest_revision() == self
349 def get_latest_revision(self
):
350 revisions
= self
.get_revisions()
352 # Return first object
353 for rev
in revisions
:
356 def get_revisions(self
):
357 return self
.backend
.wiki
._get
_pages
("SELECT * FROM wiki \
358 WHERE page = %s ORDER BY timestamp DESC", self
.page
)
361 def previous_revision(self
):
362 return self
.backend
.wiki
._get
_page
("SELECT * FROM wiki \
363 WHERE page = %s AND timestamp < %s ORDER BY timestamp DESC \
364 LIMIT 1", self
.page
, self
.timestamp
)
368 return self
.data
.changes
372 def check_acl(self
, account
):
373 return self
.backend
.wiki
.check_acl(self
.page
, account
)
379 parts
= self
.page
.split("/")
382 sidebar
= self
.backend
.wiki
.get_page("%s/sidebar" % os
.path
.join(*parts
))
392 if self
.previous_revision
:
393 diff
= difflib
.unified_diff(
394 self
.previous_revision
.markdown
.splitlines(),
395 self
.markdown
.splitlines(),
398 return "\n".join(diff
)
402 res
= self
.db
.query("SELECT uid FROM wiki_watchlist \
403 WHERE page = %s", self
.page
)
406 # Search for account by UID and skip if none was found
407 account
= self
.backend
.accounts
.get_by_uid(row
.uid
)
414 def is_watched_by(self
, account
):
415 res
= self
.db
.get("SELECT 1 FROM wiki_watchlist \
416 WHERE page = %s AND uid = %s", self
.page
, account
.uid
)
423 def add_watcher(self
, account
):
424 if self
.is_watched_by(account
):
427 self
.db
.execute("INSERT INTO wiki_watchlist(page, uid) \
428 VALUES(%s, %s)", self
.page
, account
.uid
)
430 def remove_watcher(self
, account
):
431 self
.db
.execute("DELETE FROM wiki_watchlist \
432 WHERE page = %s AND uid = %s", self
.page
, account
.uid
)
434 def _send_watcher_emails(self
, excludes
=[]):
435 # Nothing to do if there was no previous revision
436 if not self
.previous_revision
:
439 for watcher
in self
.watchers
:
440 # Skip everyone who is excluded
441 if watcher
in excludes
:
442 logging
.debug("Excluding %s" % watcher
)
446 if not self
.backend
.wiki
.check_acl(self
.page
, watcher
):
447 logging
.debug("Watcher %s does not have permissions" % watcher
)
450 logging
.debug("Sending watcher email to %s" % watcher
)
453 self
.backend
.messages
.send_template("wiki/messages/page-changed",
454 account
=watcher
, page
=self
, priority
=-10)
456 def restore(self
, author
, address
, comment
=None):
457 changes
= "Restore to revision from %s" % self
.timestamp
.isoformat()
461 changes
= "%s: %s" % (changes
, comment
)
463 return self
.backend
.wiki
.create_page(self
.page
,
464 author
, self
.markdown
, changes
=changes
, address
=address
)
467 class File(misc
.Object
):
468 def init(self
, id, data
):
472 def __eq__(self
, other
):
473 if isinstance(other
, self
.__class
__):
474 return self
.id == other
.id
478 return os
.path
.join(self
.path
, self
.filename
)
482 return self
.data
.path
486 return self
.data
.filename
490 return self
.data
.mimetype
494 return self
.data
.size
498 if self
.data
.author_uid
:
499 return self
.backend
.accounts
.get_by_uid(self
.data
.author_uid
)
502 def created_at(self
):
503 return self
.data
.created_at
505 def delete(self
, author
=None):
506 self
.db
.execute("UPDATE wiki_files SET deleted_at = NOW(), deleted_by = %s \
507 WHERE id = %s", author
.uid
if author
else None, self
.id)
510 def deleted_at(self
):
511 return self
.data
.deleted_at
513 def get_latest_revision(self
):
514 revisions
= self
.get_revisions()
516 # Return first object
517 for rev
in revisions
:
520 def get_revisions(self
):
521 revisions
= self
.backend
.wiki
._get
_files
("SELECT * FROM wiki_files \
522 WHERE path = %s AND filename = %s ORDER BY created_at DESC", self
.path
, self
.filename
)
524 return list(revisions
)
527 return self
.mimetype
in ("application/pdf", "application/x-pdf")
530 return self
.mimetype
.startswith("image/")
534 res
= self
.db
.get("SELECT data FROM wiki_blobs \
535 WHERE id = %s", self
.data
.blob_id
)
538 return bytes(res
.data
)
540 def get_thumbnail(self
, size
):
541 cache_key
= "-".join((self
.path
, util
.normalize(self
.filename
), self
.created_at
.isoformat(), "%spx" % size
))
543 # Try to fetch the data from the cache
544 thumbnail
= self
.memcache
.get(cache_key
)
548 # Generate the thumbnail
549 thumbnail
= util
.generate_thumbnail(self
.blob
, size
)
551 # Put it into the cache for forever
552 self
.memcache
.set(cache_key
, thumbnail
)
557 class WikiRenderer(misc
.Object
):
570 links
= re
.compile(r
"<a href=\"(.*?
)\">(.*?
)</a
>")
573 images = re.compile(r"<img
alt(?
:=\"(.*?
)\")? src
=\"(.*?
)\" (?
:title
=\"(.*?
)\" )?
/>")
575 def init(self, path):
578 def _render_link(self, m):
579 url, text = m.groups()
584 if url.startswith("mailto
:"):
587 return """<a class="link
-external
" href="mailto
:%s">%s</a>""" % \
591 for schema in self.schemas:
592 if url.startswith(schema):
593 return """<a class="link
-external
" href="%s">%s</a>""" % \
596 # Everything else must be an internal link
597 path = self.backend.wiki.make_path(self.path, url)
599 return """<a href="%s">%s</a>""" % \
600 (path, text or self.backend.wiki.get_page_title(path))
602 def _render_image(self, m):
603 alt_text, url, caption = m.groups()
605 # Skip any absolute and external URLs
606 if url.startswith("/") or url.startswith("https
://") or url.startswith("http
://"):
607 return """<figure class="figure
"><img src="%s" class="figure
-img img
-fluid rounded
" alt="%s">
608 <figcaption class="figure
-caption
">%s</figcaption></figure>
609 """ % (url, alt_text, caption or "")
611 # Try to split query string
612 url, delimiter, qs = url.partition("?
")
614 # Parse query arguments
615 args = urllib.parse.parse_qs(qs)
617 # Build absolute path
618 url = self.backend.wiki.make_path(self.path, url)
621 file = self.backend.wiki.get_file_by_path(url)
622 if not file or not file.is_image():
623 return "<!-- Could
not find image
%s in %s -->" % (url, self.path)
625 # Scale down the image if not already done
629 return """<figure class="figure
"><img src="%s?
%s" class="figure
-img img
-fluid rounded
" alt="%s">
630 <figcaption class="figure
-caption
">%s</figcaption></figure>
631 """ % (url, urllib.parse.urlencode(args), caption, caption or "")
633 def render(self, text):
634 logging.debug("Rendering
%s" % self.path)
636 # Borrow this from the blog
637 text = self.backend.blog._render_text(text, lang="markdown
")
640 text = self.links.sub(self._render_link, text)
642 # Postprocess images to <figure>
643 text = self.images.sub(self._render_image, text)