]>
git.ipfire.org Git - ipfire.org.git/blob - src/backend/wiki.py
12 from .decorators
import *
15 "google" : ("https://www.google.com/search?q=%(url)s", None, "fab fa-google"),
16 "rfc" : ("https://tools.ietf.org/html/rfc%(name)s", "RFC %s", None),
17 "wp" : ("https://en.wikipedia.org/wiki/%(name)s", None, "fab fa-wikipedia-w"),
20 class Wiki(misc
.Object
):
21 def _get_pages(self
, query
, *args
):
22 res
= self
.db
.query(query
, *args
)
25 yield Page(self
.backend
, row
.id, data
=row
)
27 def _get_page(self
, query
, *args
):
28 res
= self
.db
.get(query
, *args
)
31 return Page(self
.backend
, res
.id, data
=res
)
33 def get_page_title(self
, page
, default
=None):
34 # Try to retrieve title from cache
35 title
= self
.memcache
.get("wiki:title:%s" % page
)
39 # If the title has not been in the cache, we will
41 doc
= self
.get_page(page
)
45 title
= os
.path
.basename(page
)
47 # Save in cache for forever
48 self
.memcache
.set("wiki:title:%s" % page
, title
)
52 def get_page(self
, page
, revision
=None):
53 page
= Page
.sanitise_page_name(page
)
57 return self
._get
_page
("SELECT * FROM wiki WHERE page = %s \
58 AND timestamp = %s", page
, revision
)
60 return self
._get
_page
("SELECT * FROM wiki WHERE page = %s \
61 ORDER BY timestamp DESC LIMIT 1", page
)
63 def get_recent_changes(self
, account
, limit
=None):
64 pages
= self
._get
_pages
("SELECT * FROM wiki \
65 ORDER BY timestamp DESC")
68 if not page
.check_acl(account
):
77 def create_page(self
, page
, author
, content
, changes
=None, address
=None):
78 page
= Page
.sanitise_page_name(page
)
80 # Write page to the database
81 page
= self
._get
_page
("INSERT INTO wiki(page, author_uid, markdown, changes, address) \
82 VALUES(%s, %s, %s, %s, %s) RETURNING *", page
, author
.uid
, content
or None, changes
, address
)
85 self
.memcache
.set("wiki:title:%s" % page
.page
, page
.title
)
87 # Send email to all watchers
88 page
._send
_watcher
_emails
(excludes
=[author
])
92 def delete_page(self
, page
, author
, **kwargs
):
93 # Do nothing if the page does not exist
94 if not self
.get_page(page
):
97 # Just creates a blank last version of the page
98 self
.create_page(page
, author
=author
, content
=None, **kwargs
)
100 def make_breadcrumbs(self
, url
):
101 # Split and strip all empty elements (double slashes)
102 parts
= list(e
for e
in url
.split("/") if e
)
105 for part
in ("/".join(parts
[:i
]) for i
in range(1, len(parts
))):
106 ret
.append(("/%s" % part
, self
.get_page_title(part
, os
.path
.basename(part
))))
110 def search(self
, query
, account
=None, limit
=None):
111 query
= util
.parse_search_query(query
)
113 res
= self
._get
_pages
("SELECT wiki.* FROM wiki_search_index search_index \
114 LEFT JOIN wiki ON search_index.wiki_id = wiki.id \
115 WHERE search_index.document @@ to_tsquery('english', %s) \
116 ORDER BY ts_rank(search_index.document, to_tsquery('english', %s)) DESC",
121 # Skip any pages the user doesn't have permission for
122 if not page
.check_acl(account
):
125 # Return any other pages
128 # Break when we have found enough pages
129 if limit
and len(pages
) >= limit
:
136 Needs to be called after a page has been changed
138 self
.db
.execute("REFRESH MATERIALIZED VIEW wiki_search_index")
140 def get_watchlist(self
, account
):
141 pages
= self
._get
_pages
(
142 "WITH pages AS (SELECT * FROM wiki_current \
143 LEFT JOIN wiki ON wiki_current.id = wiki.id) \
144 SELECT * FROM wiki_watchlist watchlist \
145 LEFT JOIN pages ON watchlist.page = pages.page \
146 WHERE watchlist.uid = %s",
154 def check_acl(self
, page
, account
):
155 res
= self
.db
.query("SELECT * FROM wiki_acls \
156 WHERE %s ILIKE (path || '%%') ORDER BY LENGTH(path) DESC LIMIT 1", page
)
159 # Access not permitted when user is not logged in
163 # If user is in a matching group, we grant permission
164 for group
in row
.groups
:
165 if group
in account
.groups
:
168 # Otherwise access is not permitted
171 # If no ACLs are found, we permit access
176 def _get_files(self
, query
, *args
):
177 res
= self
.db
.query(query
, *args
)
180 yield File(self
.backend
, row
.id, data
=row
)
182 def _get_file(self
, query
, *args
):
183 res
= self
.db
.get(query
, *args
)
186 return File(self
.backend
, res
.id, data
=res
)
188 def get_files(self
, path
):
189 files
= self
._get
_files
("SELECT * FROM wiki_files \
190 WHERE path = %s AND deleted_at IS NULL ORDER BY filename", path
)
194 def get_file_by_path(self
, path
):
195 path
, filename
= os
.path
.dirname(path
), os
.path
.basename(path
)
197 return self
._get
_file
("SELECT * FROM wiki_files \
198 WHERE path = %s AND filename = %s AND deleted_at IS NULL", path
, filename
)
200 def upload(self
, path
, filename
, data
, mimetype
, author
, address
):
201 # Upload the blob first
202 blob
= self
.db
.get("INSERT INTO wiki_blobs(data) VALUES(%s) RETURNING id", data
)
204 # Create entry for file
205 return self
._get
_file
("INSERT INTO wiki_files(path, filename, author_uid, address, \
206 mimetype, blob_id, size) VALUES(%s, %s, %s, %s, %s, %s, %s) RETURNING *", path
,
207 filename
, author
.uid
, address
, mimetype
, blob
.id, len(data
))
209 def find_image(self
, path
, filename
):
210 for p
in (path
, os
.path
.dirname(path
)):
211 file = self
.get_file_by_path(os
.path
.join(p
, filename
))
213 if file and file.is_image():
217 class Page(misc
.Object
):
219 wiki_link
= re
.compile(r
"\[\[([\w\d\/\-\.]+)(?:\|(.+?))?\]\]")
222 external_link
= re
.compile(r
"\[\[((?:ftp|git|https?|rsync|sftp|ssh|webcal)\:\/\/.+?)(?:\|(.+?))?\]\]")
224 # Interwiki links e.g. [[wp>IPFire]]
225 interwiki_link
= re
.compile(r
"\[\[(\w+)>(.+?)(?:\|(.+?))?\]\]")
228 email_link
= re
.compile(r
"\[\[([a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+)(?:\|(.+?))?\]\]")
230 def init(self
, id, data
=None):
235 return "<%s %s %s>" % (self
.__class
__.__name
__, self
.page
, self
.timestamp
)
237 def __eq__(self
, other
):
238 if isinstance(other
, self
.__class
__):
239 return self
.id == other
.id
241 def __lt__(self
, other
):
242 if isinstance(other
, self
.__class
__):
243 if self
.page
== other
.page
:
244 return self
.timestamp
< other
.timestamp
246 return self
.page
< other
.page
249 def sanitise_page_name(page
):
253 # Make sure that the page name does NOT end with a /
254 if page
.endswith("/"):
257 # Make sure the page name starts with a /
258 if not page
.startswith("/"):
261 # Remove any double slashes
262 page
= page
.replace("//", "/")
272 return "https://wiki.ipfire.org%s" % self
.url
276 return self
.data
.page
280 return self
._title
or os
.path
.basename(self
.page
[1:])
284 if not self
.markdown
:
287 # Find first H1 headline in markdown
288 markdown
= self
.markdown
.splitlines()
290 m
= re
.match(r
"^# (.*)( #)?$", markdown
[0])
296 if self
.data
.author_uid
:
297 return self
.backend
.accounts
.get_by_uid(self
.data
.author_uid
)
299 def _render_wiki_link(self
, m
):
300 path
, alias
= m
.groups()
302 # Allow relative links
303 if not path
.startswith("/"):
304 path
= os
.path
.join(self
.page
, path
)
307 path
= os
.path
.normpath(path
)
309 return """<a href="%s">%s</a>""" % (
311 alias
or self
.backend
.wiki
.get_page_title(path
),
314 def _render_external_link(self
, m
):
315 url
, alias
= m
.groups()
317 return """<a class="link-external" href="%s">%s</a>""" % (url
, alias
or url
)
319 def _render_interwiki_link(self
, m
):
326 url
, repl
, icon
= INTERWIKIS
[wiki
]
328 logging
.warning("Invalid interwiki: %s" % wiki
)
337 "url" : urllib
.parse
.quote(name
),
340 # Get alias (if present)
343 if not alias
and repl
:
346 # Put everything together
350 s
.append("<span class=\"%s\"></span>" % icon
)
352 s
.append("""<a class="link-external" href="%s">%s</a>""" % (url
, alias
or name
))
356 def _render_email_link(self
, m
):
357 address
, alias
= m
.groups()
359 return """<a class="link-external" href="mailto:%s">%s</a>""" \
360 % (address
, alias
or address
)
362 def _render(self
, text
):
363 logging
.debug("Rendering %s" % self
)
367 for match
in re
.finditer(r
"!\[(.*?)\]\((.*?)\)", text
):
368 alt_text
, url
= match
.groups()
370 # Skip any absolute and external URLs
371 if url
.startswith("/") or url
.startswith("https://") or url
.startswith("http://"):
374 # Try to split query string
375 url
, delimiter
, qs
= url
.partition("?")
377 # Parse query arguments
378 args
= urllib
.parse
.parse_qs(qs
)
381 file = self
.backend
.wiki
.find_image(self
.page
, url
)
385 # Scale down the image if not already done
390 url
= "%s?%s" % (file.url
, urllib
.parse
.urlencode(args
))
392 replacements
.append((match
.span(), file, alt_text
, url
))
394 # Apply all replacements
395 for (start
, end
), file, alt_text
, url
in reversed(replacements
):
396 text
= text
[:start
] + "[![%s](%s)](%s?action=detail)" % (alt_text
, url
, file.url
) + text
[end
:]
399 text
= self
.wiki_link
.sub(self
._render
_wiki
_link
, text
)
401 # Handle interwiki links
402 text
= self
.interwiki_link
.sub(self
._render
_interwiki
_link
, text
)
404 # Handle external links
405 text
= self
.external_link
.sub(self
._render
_external
_link
, text
)
408 text
= self
.email_link
.sub(self
._render
_email
_link
, text
)
410 # Borrow this from the blog
411 return self
.backend
.blog
._render
_text
(text
, lang
="markdown")
415 return self
.data
.markdown
or ""
419 return self
._render
(self
.markdown
)
423 return self
.data
.timestamp
425 def was_deleted(self
):
426 return self
.markdown
is None
429 def breadcrumbs(self
):
430 return self
.backend
.wiki
.make_breadcrumbs(self
.page
)
432 def get_latest_revision(self
):
433 revisions
= self
.get_revisions()
435 # Return first object
436 for rev
in revisions
:
439 def get_revisions(self
):
440 return self
.backend
.wiki
._get
_pages
("SELECT * FROM wiki \
441 WHERE page = %s ORDER BY timestamp DESC", self
.page
)
444 def previous_revision(self
):
445 return self
.backend
.wiki
._get
_page
("SELECT * FROM wiki \
446 WHERE page = %s AND timestamp < %s ORDER BY timestamp DESC \
447 LIMIT 1", self
.page
, self
.timestamp
)
451 return self
.data
.changes
455 def check_acl(self
, account
):
456 return self
.backend
.wiki
.check_acl(self
.page
, account
)
462 parts
= self
.page
.split("/")
465 sidebar
= self
.backend
.wiki
.get_page("%s/sidebar" % os
.path
.join(*parts
))
475 if self
.previous_revision
:
476 diff
= difflib
.unified_diff(
477 self
.previous_revision
.markdown
.splitlines(),
478 self
.markdown
.splitlines(),
481 return "\n".join(diff
)
485 res
= self
.db
.query("SELECT uid FROM wiki_watchlist \
486 WHERE page = %s", self
.page
)
489 # Search for account by UID and skip if none was found
490 account
= self
.backend
.accounts
.get_by_uid(row
.uid
)
497 def is_watched_by(self
, account
):
498 res
= self
.db
.get("SELECT 1 FROM wiki_watchlist \
499 WHERE page = %s AND uid = %s", self
.page
, account
.uid
)
506 def add_watcher(self
, account
):
507 if self
.is_watched_by(account
):
510 self
.db
.execute("INSERT INTO wiki_watchlist(page, uid) \
511 VALUES(%s, %s)", self
.page
, account
.uid
)
513 def remove_watcher(self
, account
):
514 self
.db
.execute("DELETE FROM wiki_watchlist \
515 WHERE page = %s AND uid = %s", self
.page
, account
.uid
)
517 def _send_watcher_emails(self
, excludes
=[]):
518 # Nothing to do if there was no previous revision
519 if not self
.previous_revision
:
522 for watcher
in self
.watchers
:
523 # Skip everyone who is excluded
524 if watcher
in excludes
:
525 logging
.debug("Excluding %s" % watcher
)
528 logging
.debug("Sending watcher email to %s" % watcher
)
531 self
.backend
.messages
.send_template("wiki/messages/page-changed",
532 recipients
=[watcher
], page
=self
, priority
=-10)
535 class File(misc
.Object
):
536 def init(self
, id, data
):
542 return os
.path
.join(self
.path
, self
.filename
)
546 return self
.data
.path
550 return self
.data
.filename
554 return self
.data
.mimetype
558 return self
.data
.size
562 if self
.data
.author_uid
:
563 return self
.backend
.accounts
.get_by_uid(self
.data
.author_uid
)
566 def created_at(self
):
567 return self
.data
.created_at
570 return self
.mimetype
in ("application/pdf", "application/x-pdf")
573 return self
.mimetype
.startswith("image/")
577 res
= self
.db
.get("SELECT data FROM wiki_blobs \
578 WHERE id = %s", self
.data
.blob_id
)
581 return bytes(res
.data
)
583 def get_thumbnail(self
, size
):
584 cache_key
= "-".join((self
.path
, util
.normalize(self
.filename
), self
.created_at
.isoformat(), "%spx" % size
))
586 # Try to fetch the data from the cache
587 thumbnail
= self
.memcache
.get(cache_key
)
591 # Generate the thumbnail
592 thumbnail
= util
.generate_thumbnail(self
.blob
, size
)
594 # Put it into the cache for forever
595 self
.memcache
.set(cache_key
, thumbnail
)