]>
git.ipfire.org Git - ipfire.org.git/blob - src/backend/wiki.py
1747429ca083d5234e817595d1d1153802d3d9e7
12 from .decorators
import *
14 class Wiki(misc
.Object
):
15 def _get_pages(self
, query
, *args
):
16 res
= self
.db
.query(query
, *args
)
19 yield Page(self
.backend
, row
.id, data
=row
)
21 def _get_page(self
, query
, *args
):
22 res
= self
.db
.get(query
, *args
)
25 return Page(self
.backend
, res
.id, data
=res
)
27 def make_path(self
, page
, path
):
28 # Nothing to do for absolute links
29 if path
.startswith("/"):
32 # Relative links (one-level down)
33 elif path
.startswith("./"):
34 path
= os
.path
.join(page
, path
)
36 # All other relative links
38 p
= os
.path
.dirname(page
)
39 path
= os
.path
.join(p
, path
)
42 return os
.path
.normpath(path
)
44 def page_exists(self
, path
):
45 page
= self
.get_page(path
)
47 # Page must have been found and not deleted
48 return page
and not page
.was_deleted()
50 def get_page_title(self
, page
, default
=None):
51 # Try to retrieve title from cache
52 title
= self
.memcache
.get("wiki:title:%s" % page
)
56 # If the title has not been in the cache, we will
58 doc
= self
.get_page(page
)
62 title
= os
.path
.basename(page
)
64 # Save in cache for forever
65 self
.memcache
.set("wiki:title:%s" % page
, title
)
69 def get_page(self
, page
, revision
=None):
70 page
= Page
.sanitise_page_name(page
)
74 return self
._get
_page
("SELECT * FROM wiki WHERE page = %s \
75 AND timestamp = %s", page
, revision
)
77 return self
._get
_page
("SELECT * FROM wiki WHERE page = %s \
78 ORDER BY timestamp DESC LIMIT 1", page
)
80 def get_recent_changes(self
, account
, limit
=None):
81 pages
= self
._get
_pages
("SELECT * FROM wiki \
82 ORDER BY timestamp DESC")
85 if not page
.check_acl(account
):
94 def create_page(self
, page
, author
, content
, changes
=None, address
=None):
95 page
= Page
.sanitise_page_name(page
)
97 # Write page to the database
98 page
= self
._get
_page
("INSERT INTO wiki(page, author_uid, markdown, changes, address) \
99 VALUES(%s, %s, %s, %s, %s) RETURNING *", page
, author
.uid
, content
or None, changes
, address
)
102 self
.memcache
.set("wiki:title:%s" % page
.page
, page
.title
)
104 # Send email to all watchers
105 page
._send
_watcher
_emails
(excludes
=[author
])
109 def delete_page(self
, page
, author
, **kwargs
):
110 # Do nothing if the page does not exist
111 if not self
.get_page(page
):
114 # Just creates a blank last version of the page
115 self
.create_page(page
, author
=author
, content
=None, **kwargs
)
117 def make_breadcrumbs(self
, url
):
118 # Split and strip all empty elements (double slashes)
119 parts
= list(e
for e
in url
.split("/") if e
)
122 for part
in ("/".join(parts
[:i
]) for i
in range(1, len(parts
))):
123 ret
.append(("/%s" % part
, self
.get_page_title(part
, os
.path
.basename(part
))))
127 def search(self
, query
, account
=None, limit
=None):
128 query
= util
.parse_search_query(query
)
130 res
= self
._get
_pages
("SELECT wiki.* FROM wiki_search_index search_index \
131 LEFT JOIN wiki ON search_index.wiki_id = wiki.id \
132 WHERE search_index.document @@ to_tsquery('english', %s) \
133 ORDER BY ts_rank(search_index.document, to_tsquery('english', %s)) DESC",
138 # Skip any pages the user doesn't have permission for
139 if not page
.check_acl(account
):
142 # Return any other pages
145 # Break when we have found enough pages
146 if limit
and len(pages
) >= limit
:
153 Needs to be called after a page has been changed
155 self
.db
.execute("REFRESH MATERIALIZED VIEW wiki_search_index")
157 def get_watchlist(self
, account
):
158 pages
= self
._get
_pages
(
159 "WITH pages AS (SELECT * FROM wiki_current \
160 LEFT JOIN wiki ON wiki_current.id = wiki.id) \
161 SELECT * FROM wiki_watchlist watchlist \
162 LEFT JOIN pages ON watchlist.page = pages.page \
163 WHERE watchlist.uid = %s",
171 def check_acl(self
, page
, account
):
172 res
= self
.db
.query("SELECT * FROM wiki_acls \
173 WHERE %s ILIKE (path || '%%') ORDER BY LENGTH(path) DESC LIMIT 1", page
)
176 # Access not permitted when user is not logged in
180 # If user is in a matching group, we grant permission
181 for group
in row
.groups
:
182 if group
in account
.groups
:
185 # Otherwise access is not permitted
188 # If no ACLs are found, we permit access
193 def _get_files(self
, query
, *args
):
194 res
= self
.db
.query(query
, *args
)
197 yield File(self
.backend
, row
.id, data
=row
)
199 def _get_file(self
, query
, *args
):
200 res
= self
.db
.get(query
, *args
)
203 return File(self
.backend
, res
.id, data
=res
)
205 def get_files(self
, path
):
206 files
= self
._get
_files
("SELECT * FROM wiki_files \
207 WHERE path = %s AND deleted_at IS NULL ORDER BY filename", path
)
211 def get_file_by_path(self
, path
, revision
=None):
212 path
, filename
= os
.path
.dirname(path
), os
.path
.basename(path
)
215 # Fetch a specific revision
216 return self
._get
_file
("SELECT * FROM wiki_files \
217 WHERE path = %s AND filename = %s AND created_at <= %s \
218 ORDER BY created_at DESC LIMIT 1", path
, filename
, revision
)
220 # Fetch latest version
221 return self
._get
_file
("SELECT * FROM wiki_files \
222 WHERE path = %s AND filename = %s AND deleted_at IS NULL",
225 def get_file_by_path_and_filename(self
, path
, filename
):
226 return self
._get
_file
("SELECT * FROM wiki_files \
227 WHERE path = %s AND filename = %s AND deleted_at IS NULL",
230 def upload(self
, path
, filename
, data
, mimetype
, author
, address
):
231 # Replace any existing files
232 file = self
.get_file_by_path_and_filename(path
, filename
)
236 # Upload the blob first
237 blob
= self
.db
.get("INSERT INTO wiki_blobs(data) VALUES(%s) \
238 ON CONFLICT (digest(data, %s)) DO UPDATE SET data = EXCLUDED.data \
239 RETURNING id", data
, "MD5")
241 # Create entry for file
242 return self
._get
_file
("INSERT INTO wiki_files(path, filename, author_uid, address, \
243 mimetype, blob_id, size) VALUES(%s, %s, %s, %s, %s, %s, %s) RETURNING *", path
,
244 filename
, author
.uid
, address
, mimetype
, blob
.id, len(data
))
246 def render(self
, path
, text
):
247 r
= WikiRenderer(self
.backend
, path
)
249 return r
.render(text
)
252 class Page(misc
.Object
):
253 def init(self
, id, data
=None):
258 return "<%s %s %s>" % (self
.__class
__.__name
__, self
.page
, self
.timestamp
)
260 def __eq__(self
, other
):
261 if isinstance(other
, self
.__class
__):
262 return self
.id == other
.id
264 def __lt__(self
, other
):
265 if isinstance(other
, self
.__class
__):
266 if self
.page
== other
.page
:
267 return self
.timestamp
< other
.timestamp
269 return self
.page
< other
.page
272 def sanitise_page_name(page
):
276 # Make sure that the page name does NOT end with a /
277 if page
.endswith("/"):
280 # Make sure the page name starts with a /
281 if not page
.startswith("/"):
284 # Remove any double slashes
285 page
= page
.replace("//", "/")
295 return "https://wiki.ipfire.org%s" % self
.url
299 return self
.data
.page
303 return self
._title
or os
.path
.basename(self
.page
[1:])
307 if not self
.markdown
:
310 # Find first H1 headline in markdown
311 markdown
= self
.markdown
.splitlines()
313 m
= re
.match(r
"^#\s*(.*)( #)?$", markdown
[0])
319 if self
.data
.author_uid
:
320 return self
.backend
.accounts
.get_by_uid(self
.data
.author_uid
)
324 return self
.data
.markdown
or ""
328 return self
.backend
.wiki
.render(self
.page
, self
.markdown
)
332 return self
.data
.timestamp
334 def was_deleted(self
):
335 return self
.markdown
is None
338 def breadcrumbs(self
):
339 return self
.backend
.wiki
.make_breadcrumbs(self
.page
)
341 def get_latest_revision(self
):
342 revisions
= self
.get_revisions()
344 # Return first object
345 for rev
in revisions
:
348 def get_revisions(self
):
349 return self
.backend
.wiki
._get
_pages
("SELECT * FROM wiki \
350 WHERE page = %s ORDER BY timestamp DESC", self
.page
)
353 def previous_revision(self
):
354 return self
.backend
.wiki
._get
_page
("SELECT * FROM wiki \
355 WHERE page = %s AND timestamp < %s ORDER BY timestamp DESC \
356 LIMIT 1", self
.page
, self
.timestamp
)
360 return self
.data
.changes
364 def check_acl(self
, account
):
365 return self
.backend
.wiki
.check_acl(self
.page
, account
)
371 parts
= self
.page
.split("/")
374 sidebar
= self
.backend
.wiki
.get_page("%s/sidebar" % os
.path
.join(*parts
))
384 if self
.previous_revision
:
385 diff
= difflib
.unified_diff(
386 self
.previous_revision
.markdown
.splitlines(),
387 self
.markdown
.splitlines(),
390 return "\n".join(diff
)
394 res
= self
.db
.query("SELECT uid FROM wiki_watchlist \
395 WHERE page = %s", self
.page
)
398 # Search for account by UID and skip if none was found
399 account
= self
.backend
.accounts
.get_by_uid(row
.uid
)
406 def is_watched_by(self
, account
):
407 res
= self
.db
.get("SELECT 1 FROM wiki_watchlist \
408 WHERE page = %s AND uid = %s", self
.page
, account
.uid
)
415 def add_watcher(self
, account
):
416 if self
.is_watched_by(account
):
419 self
.db
.execute("INSERT INTO wiki_watchlist(page, uid) \
420 VALUES(%s, %s)", self
.page
, account
.uid
)
422 def remove_watcher(self
, account
):
423 self
.db
.execute("DELETE FROM wiki_watchlist \
424 WHERE page = %s AND uid = %s", self
.page
, account
.uid
)
426 def _send_watcher_emails(self
, excludes
=[]):
427 # Nothing to do if there was no previous revision
428 if not self
.previous_revision
:
431 for watcher
in self
.watchers
:
432 # Skip everyone who is excluded
433 if watcher
in excludes
:
434 logging
.debug("Excluding %s" % watcher
)
438 if not self
.backend
.wiki
.check_acl(self
.page
, watcher
):
439 logging
.debug("Watcher %s does not have permissions" % watcher
)
442 logging
.debug("Sending watcher email to %s" % watcher
)
445 self
.backend
.messages
.send_template("wiki/messages/page-changed",
446 sender
="IPFire Wiki <wiki@ipfire.org>", recipients
=[watcher
],
447 page
=self
, priority
=-10)
450 class File(misc
.Object
):
451 def init(self
, id, data
):
455 def __eq__(self
, other
):
456 if isinstance(other
, self
.__class
__):
457 return self
.id == other
.id
461 return os
.path
.join(self
.path
, self
.filename
)
465 return self
.data
.path
469 return self
.data
.filename
473 return self
.data
.mimetype
477 return self
.data
.size
481 if self
.data
.author_uid
:
482 return self
.backend
.accounts
.get_by_uid(self
.data
.author_uid
)
485 def created_at(self
):
486 return self
.data
.created_at
488 def delete(self
, author
=None):
489 self
.db
.execute("UPDATE wiki_files SET deleted_at = NOW(), deleted_by = %s \
490 WHERE id = %s", author
.uid
if author
else None, self
.id)
493 def deleted_at(self
):
494 return self
.data
.deleted_at
496 def get_latest_revision(self
):
497 revisions
= self
.get_revisions()
499 # Return first object
500 for rev
in revisions
:
503 def get_revisions(self
):
504 revisions
= self
.backend
.wiki
._get
_files
("SELECT * FROM wiki_files \
505 WHERE path = %s ORDER BY created_at DESC", self
.path
)
507 return list(revisions
)
510 return self
.mimetype
in ("application/pdf", "application/x-pdf")
513 return self
.mimetype
.startswith("image/")
517 res
= self
.db
.get("SELECT data FROM wiki_blobs \
518 WHERE id = %s", self
.data
.blob_id
)
521 return bytes(res
.data
)
523 def get_thumbnail(self
, size
):
524 cache_key
= "-".join((self
.path
, util
.normalize(self
.filename
), self
.created_at
.isoformat(), "%spx" % size
))
526 # Try to fetch the data from the cache
527 thumbnail
= self
.memcache
.get(cache_key
)
531 # Generate the thumbnail
532 thumbnail
= util
.generate_thumbnail(self
.blob
, size
)
534 # Put it into the cache for forever
535 self
.memcache
.set(cache_key
, thumbnail
)
540 class WikiRenderer(misc
.Object
):
553 links
= re
.compile(r
"<a href=\"(.*?
)\">(.*?
)</a
>")
556 images = re.compile(r"<img
alt(?
:=\"(.*?
)\")? src
=\"(.*?
)\" (?
:title
=\"(.*?
)\" )?
/>")
558 def init(self, path):
561 def _render_link(self, m):
562 url, text = m.groups()
567 if url.startswith("mailto
:"):
570 return """<a class="link
-external
" href="mailto
:%s">%s</a>""" % \
574 for schema in self.schemas:
575 if url.startswith(schema):
576 return """<a class="link
-external
" href="%s">%s</a>""" % \
579 # Everything else must be an internal link
580 path = self.backend.wiki.make_path(self.path, url)
582 return """<a href="%s">%s</a>""" % \
583 (path, text or self.backend.wiki.get_page_title(path))
585 def _render_image(self, m):
586 alt_text, url, caption = m.groups()
588 # Skip any absolute and external URLs
589 if url.startswith("/") or url.startswith("https
://") or url.startswith("http
://"):
590 return """<figure class="figure
"><img src="%s" class="figure
-img img
-fluid rounded
" alt="%s">
591 <figcaption class="figure
-caption
">%s</figcaption></figure>
592 """ % (url, alt_text, caption or "")
594 # Try to split query string
595 url, delimiter, qs = url.partition("?
")
597 # Parse query arguments
598 args = urllib.parse.parse_qs(qs)
600 # Build absolute path
601 url = self.backend.wiki.make_path(self.path, url)
604 file = self.backend.wiki.get_file_by_path(url)
605 if not file or not file.is_image():
606 return "<!-- Could
not find image
%s in %s -->" % (url, self.path)
608 # Scale down the image if not already done
612 return """<figure class="figure
"><img src="%s?
%s" class="figure
-img img
-fluid rounded
" alt="%s">
613 <figcaption class="figure
-caption
">%s</figcaption></figure>
614 """ % (url, urllib.parse.urlencode(args), caption, caption or "")
616 def render(self, text):
617 logging.debug("Rendering
%s" % self.path)
619 # Borrow this from the blog
620 text = self.backend.blog._render_text(text, lang="markdown
")
623 text = self.links.sub(self._render_link, text)
625 # Postprocess images to <figure>
626 text = self.images.sub(self._render_image, text)