]>
git.ipfire.org Git - ipfire.org.git/blob - src/backend/wiki.py
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 doc
= self
.get_page(page
)
62 title
= os
.path
.basename(page
)
66 def get_page(self
, page
, revision
=None):
67 page
= Page
.sanitise_page_name(page
)
69 # Split the path into parts
70 parts
= page
.split("/")
72 # Check if this is an action
73 if any((part
.startswith("_") for part
in parts
)):
77 return self
._get
_page
("SELECT * FROM wiki WHERE page = %s \
78 AND timestamp = %s", page
, revision
)
80 return self
._get
_page
("SELECT * FROM wiki WHERE page = %s \
81 ORDER BY timestamp DESC LIMIT 1", page
)
83 def get_recent_changes(self
, account
, limit
=None):
84 pages
= self
._get
_pages
("SELECT * FROM wiki \
85 ORDER BY timestamp DESC")
88 if not page
.check_acl(account
):
97 def create_page(self
, page
, author
, content
, changes
=None, address
=None):
98 page
= Page
.sanitise_page_name(page
)
100 # Write page to the database
101 page
= self
._get
_page
("INSERT INTO wiki(page, author_uid, markdown, changes, address) \
102 VALUES(%s, %s, %s, %s, %s) RETURNING *", page
, author
.uid
, content
or None, changes
, address
)
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 res
= self
._get
_pages
("SELECT wiki.* FROM wiki_search_index search_index \
129 LEFT JOIN wiki ON search_index.wiki_id = wiki.id \
130 WHERE search_index.document @@ websearch_to_tsquery('english', %s) \
131 ORDER BY ts_rank(search_index.document, websearch_to_tsquery('english', %s)) DESC",
136 # Skip any pages the user doesn't have permission for
137 if not page
.check_acl(account
):
140 # Return any other pages
143 # Break when we have found enough pages
144 if limit
and len(pages
) >= limit
:
151 Needs to be called after a page has been changed
153 self
.db
.execute("REFRESH MATERIALIZED VIEW wiki_search_index")
155 def get_watchlist(self
, account
):
156 pages
= self
._get
_pages
("""
163 wiki ON wiki_current.id = wiki.id
169 wiki_watchlist watchlist
171 pages ON watchlist.page = pages.page
181 def check_acl(self
, page
, account
):
182 res
= self
.db
.query("SELECT * FROM wiki_acls \
183 WHERE %s ILIKE (path || '%%') ORDER BY LENGTH(path) DESC LIMIT 1", page
)
186 # Access not permitted when user is not logged in
190 # If user is in a matching group, we grant permission
191 for group
in row
.groups
:
192 if account
.is_member_of_group(group
):
195 # Otherwise access is not permitted
198 # If no ACLs are found, we permit access
203 def _get_files(self
, query
, *args
):
204 res
= self
.db
.query(query
, *args
)
207 yield File(self
.backend
, row
.id, data
=row
)
209 def _get_file(self
, query
, *args
):
210 res
= self
.db
.get(query
, *args
)
213 return File(self
.backend
, res
.id, data
=res
)
215 def get_files(self
, path
):
216 files
= self
._get
_files
("SELECT * FROM wiki_files \
217 WHERE path = %s AND deleted_at IS NULL ORDER BY filename", path
)
221 def get_file_by_path(self
, path
, revision
=None):
222 path
, filename
= os
.path
.dirname(path
), os
.path
.basename(path
)
225 # Fetch a specific revision
226 return self
._get
_file
("SELECT * FROM wiki_files \
227 WHERE path = %s AND filename = %s AND created_at <= %s \
228 ORDER BY created_at DESC LIMIT 1", path
, filename
, revision
)
230 # Fetch latest version
231 return self
._get
_file
("SELECT * FROM wiki_files \
232 WHERE path = %s AND filename = %s AND deleted_at IS NULL",
235 def get_file_by_path_and_filename(self
, path
, filename
):
236 return self
._get
_file
("SELECT * FROM wiki_files \
237 WHERE path = %s AND filename = %s AND deleted_at IS NULL",
240 def upload(self
, path
, filename
, data
, mimetype
, author
, address
):
241 # Replace any existing files
242 file = self
.get_file_by_path_and_filename(path
, filename
)
246 # Upload the blob first
247 blob
= self
.db
.get("INSERT INTO wiki_blobs(data) VALUES(%s) \
248 ON CONFLICT (digest(data, %s)) DO UPDATE SET data = EXCLUDED.data \
249 RETURNING id", data
, "MD5")
251 # Create entry for file
252 return self
._get
_file
("INSERT INTO wiki_files(path, filename, author_uid, address, \
253 mimetype, blob_id, size) VALUES(%s, %s, %s, %s, %s, %s, %s) RETURNING *", path
,
254 filename
, author
.uid
, address
, mimetype
, blob
.id, len(data
))
256 def render(self
, path
, text
):
257 r
= WikiRenderer(self
.backend
, path
)
259 return r
.render(text
)
262 class Page(misc
.Object
):
263 def init(self
, id, data
=None):
268 return "<%s %s %s>" % (self
.__class
__.__name
__, self
.page
, self
.timestamp
)
270 def __eq__(self
, other
):
271 if isinstance(other
, self
.__class
__):
272 return self
.id == other
.id
274 return NotImplemented
276 def __lt__(self
, other
):
277 if isinstance(other
, self
.__class
__):
278 if self
.page
== other
.page
:
279 return self
.timestamp
< other
.timestamp
281 return self
.page
< other
.page
283 return NotImplemented
286 def sanitise_page_name(page
):
290 # Make sure that the page name does NOT end with a /
291 if page
.endswith("/"):
294 # Make sure the page name starts with a /
295 if not page
.startswith("/"):
298 # Remove any double slashes
299 page
= page
.replace("//", "/")
305 return "/docs%s" % self
.page
309 return "https://www.ipfire.org%s" % self
.url
313 return self
.data
.page
317 return self
._title
or os
.path
.basename(self
.page
[1:])
321 if not self
.markdown
:
324 # Find first H1 headline in markdown
325 markdown
= self
.markdown
.splitlines()
327 m
= re
.match(r
"^#\s*(.*)( #)?$", markdown
[0])
333 if self
.data
.author_uid
:
334 return self
.backend
.accounts
.get_by_uid(self
.data
.author_uid
)
338 return self
.data
.markdown
or ""
344 # Strip off the first line if it contains a heading (as it will be shown separately)
345 for i
, line
in enumerate(self
.markdown
.splitlines()):
346 if i
== 0 and line
.startswith("#"):
351 return self
.backend
.wiki
.render(self
.page
, "\n".join(lines
))
355 return self
.data
.timestamp
357 def was_deleted(self
):
358 return not self
.markdown
361 def breadcrumbs(self
):
362 return self
.backend
.wiki
.make_breadcrumbs(self
.page
)
364 def is_latest_revision(self
):
365 return self
.get_latest_revision() == self
367 def get_latest_revision(self
):
368 revisions
= self
.get_revisions()
370 # Return first object
371 for rev
in revisions
:
374 def get_revisions(self
):
375 return self
.backend
.wiki
._get
_pages
("SELECT * FROM wiki \
376 WHERE page = %s ORDER BY timestamp DESC", self
.page
)
379 def previous_revision(self
):
380 return self
.backend
.wiki
._get
_page
("SELECT * FROM wiki \
381 WHERE page = %s AND timestamp < %s ORDER BY timestamp DESC \
382 LIMIT 1", self
.page
, self
.timestamp
)
386 return self
.data
.changes
390 def check_acl(self
, account
):
391 return self
.backend
.wiki
.check_acl(self
.page
, account
)
397 if self
.previous_revision
:
398 diff
= difflib
.unified_diff(
399 self
.previous_revision
.markdown
.splitlines(),
400 self
.markdown
.splitlines(),
403 return "\n".join(diff
)
407 res
= self
.db
.query("SELECT uid FROM wiki_watchlist \
408 WHERE page = %s", self
.page
)
411 # Search for account by UID and skip if none was found
412 account
= self
.backend
.accounts
.get_by_uid(row
.uid
)
419 def is_watched_by(self
, account
):
420 res
= self
.db
.get("SELECT 1 FROM wiki_watchlist \
421 WHERE page = %s AND uid = %s", self
.page
, account
.uid
)
428 def add_watcher(self
, account
):
429 if self
.is_watched_by(account
):
432 self
.db
.execute("INSERT INTO wiki_watchlist(page, uid) \
433 VALUES(%s, %s)", self
.page
, account
.uid
)
435 def remove_watcher(self
, account
):
436 self
.db
.execute("DELETE FROM wiki_watchlist \
437 WHERE page = %s AND uid = %s", self
.page
, account
.uid
)
439 def _send_watcher_emails(self
, excludes
=[]):
440 # Nothing to do if there was no previous revision
441 if not self
.previous_revision
:
444 for watcher
in self
.watchers
:
445 # Skip everyone who is excluded
446 if watcher
in excludes
:
447 logging
.debug("Excluding %s" % watcher
)
451 if not self
.backend
.wiki
.check_acl(self
.page
, watcher
):
452 logging
.debug("Watcher %s does not have permissions" % watcher
)
455 logging
.debug("Sending watcher email to %s" % watcher
)
458 self
.backend
.messages
.send_template("wiki/messages/page-changed",
459 account
=watcher
, page
=self
, priority
=-10)
461 def restore(self
, author
, address
, comment
=None):
462 changes
= "Restore to revision from %s" % self
.timestamp
.isoformat()
466 changes
= "%s: %s" % (changes
, comment
)
468 return self
.backend
.wiki
.create_page(self
.page
,
469 author
, self
.markdown
, changes
=changes
, address
=address
)
472 class File(misc
.Object
):
473 def init(self
, id, data
):
477 def __eq__(self
, other
):
478 if isinstance(other
, self
.__class
__):
479 return self
.id == other
.id
483 return os
.path
.join(self
.path
, self
.filename
)
487 return self
.data
.path
491 return self
.data
.filename
495 return self
.data
.mimetype
499 return self
.data
.size
503 if self
.data
.author_uid
:
504 return self
.backend
.accounts
.get_by_uid(self
.data
.author_uid
)
507 def created_at(self
):
508 return self
.data
.created_at
510 def delete(self
, author
=None):
511 self
.db
.execute("UPDATE wiki_files SET deleted_at = NOW(), deleted_by = %s \
512 WHERE id = %s", author
.uid
if author
else None, self
.id)
515 def deleted_at(self
):
516 return self
.data
.deleted_at
518 def get_latest_revision(self
):
519 revisions
= self
.get_revisions()
521 # Return first object
522 for rev
in revisions
:
525 def get_revisions(self
):
526 revisions
= self
.backend
.wiki
._get
_files
("SELECT * FROM wiki_files \
527 WHERE path = %s AND filename = %s ORDER BY created_at DESC", self
.path
, self
.filename
)
529 return list(revisions
)
532 return self
.mimetype
in ("application/pdf", "application/x-pdf")
535 return self
.mimetype
.startswith("image/")
537 def is_vector_image(self
):
538 return self
.mimetype
in ("image/svg+xml",)
540 def is_bitmap_image(self
):
541 return self
.is_image() and not self
.is_vector_image()
545 res
= self
.db
.get("SELECT data FROM wiki_blobs \
546 WHERE id = %s", self
.data
.blob_id
)
549 return bytes(res
.data
)
551 async def get_thumbnail(self
, size
):
552 assert self
.is_bitmap_image()
554 cache_key
= "-".join((
556 util
.normalize(self
.filename
),
557 self
.created_at
.isoformat(),
561 # Try to fetch the data from the cache
562 thumbnail
= await self
.backend
.cache
.get(cache_key
)
566 # Generate the thumbnail
567 thumbnail
= util
.generate_thumbnail(self
.blob
, size
)
569 # Put it into the cache for forever
570 await self
.backend
.cache
.set(cache_key
, thumbnail
)
575 class WikiRenderer(misc
.Object
):
588 links
= re
.compile(r
"<a href=\"(.*?
)\">(.*?
)</a
>")
591 images = re.compile(r"<img
alt(?
:=\"(.*?
)\")? src
=\"(.*?
)\" (?
:title
=\"(.*?
)\" )?
/>")
593 def init(self, path):
596 def _render_link(self, m):
597 url, text = m.groups()
600 for schema in self.schemas:
601 if url.startswith(schema):
602 return """<a class="link
-external
" href="%s">%s</a>""" % \
608 if url.startswith("mailto
:"):
611 return """<a class="link
-external
" href="mailto
:%s">%s</a>""" % \
614 # Everything else must be an internal link
615 path = self.backend.wiki.make_path(self.path, url)
617 return """<a href="/docs
%s">%s</a>""" % \
618 (path, text or self.backend.wiki.get_page_title(path))
620 def _render_image(self, m):
621 alt_text, url, caption = m.groups()
624 <div class="columns
is-centered
">
625 <div class="column
is-8">
626 <figure class="image
">
627 <img src="/docs
%s" alt="%s">
628 <figcaption class="figure
-caption
">%s</figcaption>
634 # Skip any absolute and external URLs
635 if url.startswith("/") or url.startswith("https
://") or url.startswith("http
://"):
636 return html % (url, alt_text, caption or "")
638 # Try to split query string
639 url, delimiter, qs = url.partition("?
")
641 # Parse query arguments
642 args = urllib.parse.parse_qs(qs)
644 # Build absolute path
645 url = self.backend.wiki.make_path(self.path, url)
648 file = self.backend.wiki.get_file_by_path(url)
649 if not file or not file.is_image():
650 return "<!-- Could
not find image
%s in %s -->" % (url, self.path)
652 # Scale down the image if not already done
656 # Append arguments to the URL
658 url = "%s?
%s" % (url, urllib.parse.urlencode(args))
660 return html % (url, caption, caption or "")
662 def render(self, text):
663 logging.debug("Rendering
%s" % self.path)
665 # Borrow this from the blog
666 text = self.backend.blog._render_text(text, lang="markdown
")
669 text = self.links.sub(self._render_link, text)
671 # Postprocess images to <figure>
672 text = self.images.sub(self._render_image, text)