]>
git.ipfire.org Git - ipfire.org.git/blob - src/backend/wiki.py
14 from .decorators
import *
16 class Wiki(misc
.Object
):
17 def _get_pages(self
, query
, *args
):
18 res
= self
.db
.query(query
, *args
)
21 yield Page(self
.backend
, row
.id, data
=row
)
23 def _get_page(self
, query
, *args
):
24 res
= self
.db
.get(query
, *args
)
27 return Page(self
.backend
, res
.id, data
=res
)
29 def get_page_title(self
, page
, default
=None):
30 doc
= self
.get_page(page
)
34 return default
or os
.path
.basename(page
)
36 def get_page(self
, page
, revision
=None):
37 page
= Page
.sanitise_page_name(page
)
41 return self
._get
_page
("SELECT * FROM wiki WHERE page = %s \
42 AND timestamp = %s", page
, revision
)
44 return self
._get
_page
("SELECT * FROM wiki WHERE page = %s \
45 ORDER BY timestamp DESC LIMIT 1", page
)
47 def get_recent_changes(self
, account
, limit
=None):
48 pages
= self
._get
_pages
("SELECT * FROM wiki \
49 WHERE timestamp >= NOW() - INTERVAL '4 weeks' \
50 ORDER BY timestamp DESC")
53 if not page
.check_acl(account
):
62 def create_page(self
, page
, author
, content
, changes
=None, address
=None):
63 page
= Page
.sanitise_page_name(page
)
65 # Write page to the database
66 page
= self
._get
_page
("INSERT INTO wiki(page, author_uid, markdown, changes, address) \
67 VALUES(%s, %s, %s, %s, %s) RETURNING *", page
, author
.uid
, content
or None, changes
, address
)
72 # Send email to all watchers
73 page
._send
_watcher
_emails
(excludes
=[author
])
77 def delete_page(self
, page
, author
, **kwargs
):
78 # Do nothing if the page does not exist
79 if not self
.get_page(page
):
82 # Just creates a blank last version of the page
83 self
.create_page(page
, author
=author
, content
=None, **kwargs
)
85 @tornado.gen
.coroutine
88 Re-renders all wiki pages
90 pages
= self
._get
_pages
("SELECT * FROM wiki ORDER BY timestamp DESC")
93 logging
.info("Baking %s from %s" % (page
.page
, page
.timestamp
))
95 with self
.db
.transaction():
98 def make_breadcrumbs(self
, url
):
99 # Split and strip all empty elements (double slashes)
100 parts
= list(e
for e
in url
.split("/") if e
)
103 for part
in ("/".join(parts
[:i
]) for i
in range(1, len(parts
))):
104 ret
.append(("/%s" % part
, self
.get_page_title(part
, os
.path
.basename(part
))))
108 def search(self
, query
, account
=None, limit
=None):
109 query
= util
.parse_search_query(query
)
111 res
= self
._get
_pages
("SELECT wiki.* FROM wiki_search_index search_index \
112 LEFT JOIN wiki ON search_index.wiki_id = wiki.id \
113 WHERE search_index.document @@ to_tsquery('english', %s) \
114 ORDER BY ts_rank(search_index.document, to_tsquery('english', %s)) DESC",
118 # Skip any pages the user doesn't have permission for
119 if not page
.check_acl(account
):
122 # Return any other pages
131 Needs to be called after a page has been changed
133 self
.db
.execute("REFRESH MATERIALIZED VIEW wiki_search_index")
137 def check_acl(self
, page
, account
):
138 res
= self
.db
.query("SELECT * FROM wiki_acls \
139 WHERE %s ILIKE (path || '%%') ORDER BY LENGTH(path) DESC LIMIT 1", page
)
142 # Access not permitted when user is not logged in
146 # If user is in a matching group, we grant permission
147 for group
in row
.groups
:
148 if group
in account
.groups
:
151 # Otherwise access is not permitted
154 # If no ACLs are found, we permit access
159 def _get_files(self
, query
, *args
):
160 res
= self
.db
.query(query
, *args
)
163 yield File(self
.backend
, row
.id, data
=row
)
165 def _get_file(self
, query
, *args
):
166 res
= self
.db
.get(query
, *args
)
169 return File(self
.backend
, res
.id, data
=res
)
171 def get_files(self
, path
):
172 files
= self
._get
_files
("SELECT * FROM wiki_files \
173 WHERE path = %s AND deleted_at IS NULL ORDER BY filename", path
)
177 def get_file_by_path(self
, path
):
178 path
, filename
= os
.path
.dirname(path
), os
.path
.basename(path
)
180 return self
._get
_file
("SELECT * FROM wiki_files \
181 WHERE path = %s AND filename = %s AND deleted_at IS NULL", path
, filename
)
183 def upload(self
, path
, filename
, data
, mimetype
, author
, address
):
184 # Upload the blob first
185 blob
= self
.db
.get("INSERT INTO wiki_blobs(data) VALUES(%s) RETURNING id", data
)
187 # Create entry for file
188 return self
._get
_file
("INSERT INTO wiki_files(path, filename, author_uid, address, \
189 mimetype, blob_id, size) VALUES(%s, %s, %s, %s, %s, %s, %s) RETURNING *", path
,
190 filename
, author
.uid
, address
, mimetype
, blob
.id, len(data
))
192 def find_image(self
, path
, filename
):
193 for p
in (path
, os
.path
.dirname(path
)):
194 file = self
.get_file_by_path(os
.path
.join(p
, filename
))
196 if file and file.is_image():
200 class Page(misc
.Object
):
201 def init(self
, id, data
=None):
206 return "<%s %s %s>" % (self
.__class
__.__name
__, self
.page
, self
.timestamp
)
208 def __eq__(self
, other
):
209 if isinstance(other
, self
.__class
__):
210 return self
.id == other
.id
212 def __lt__(self
, other
):
213 if isinstance(other
, self
.__class
__):
214 if self
.page
== other
.page
:
215 return self
.timestamp
< other
.timestamp
217 return self
.page
< other
.page
220 def sanitise_page_name(page
):
224 # Make sure that the page name does NOT end with a /
225 if page
.endswith("/"):
228 # Make sure the page name starts with a /
229 if not page
.startswith("/"):
232 # Remove any double slashes
233 page
= page
.replace("//", "/")
243 return "https://wiki.ipfire.org%s" % self
.url
247 return self
.data
.page
251 return self
._title
or os
.path
.basename(self
.page
[1:])
255 if not self
.markdown
:
258 # Find first H1 headline in markdown
259 markdown
= self
.markdown
.splitlines()
261 m
= re
.match(r
"^# (.*)( #)?$", markdown
[0])
267 if self
.data
.author_uid
:
268 return self
.backend
.accounts
.get_by_uid(self
.data
.author_uid
)
270 def _render(self
, text
):
271 logging
.debug("Rendering %s" % self
)
275 for match
in re
.finditer(r
"!\[(.*)\]\((.*)\)", text
):
276 alt_text
, url
= match
.groups()
278 # Skip any absolute and external URLs
279 if url
.startswith("/") or url
.startswith("https://") or url
.startswith("http://"):
282 # Try to split query string
283 url
, delimiter
, qs
= url
.partition("?")
285 # Parse query arguments
286 args
= urllib
.parse
.parse_qs(qs
)
289 file = self
.backend
.wiki
.find_image(self
.page
, url
)
293 # Scale down the image if not already done
298 url
= "%s?%s" % (file.url
, urllib
.parse
.urlencode(args
))
300 replacements
.append((match
.span(), file, alt_text
, url
))
302 # Apply all replacements
303 for (start
, end
), file, alt_text
, url
in reversed(replacements
):
304 text
= text
[:start
] + "[![%s](%s)](%s?action=detail)" % (alt_text
, url
, file.url
) + text
[end
:]
308 (r
"\[\[([\w\d\/]+)(?:\|([\w\d\s]+))\]\]", r
"/\1", r
"\2", None, None),
309 (r
"\[\[([\w\d\/\-]+)\]\]", r
"/\1", r
"\1", self
.backend
.wiki
.get_page_title
, r
"\1"),
312 for pattern
, link
, title
, repl
, args
in patterns
:
315 for match
in re
.finditer(pattern
, text
):
316 l
= match
.expand(link
)
317 t
= match
.expand(title
)
320 t
= repl(match
.expand(args
)) or t
322 replacements
.append((match
.span(), t
or l
, l
))
324 # Apply all replacements
325 for (start
, end
), t
, l
in reversed(replacements
):
326 text
= text
[:start
] + "[%s](%s)" % (t
, l
) + text
[end
:]
328 # Borrow this from the blog
329 return self
.backend
.blog
._render
_text
(text
, lang
="markdown")
333 return self
.data
.markdown
or ""
337 return self
.data
.html
or self
._render
(self
.markdown
)
341 Renders the page's markdown to HTML and stores
344 self
.db
.execute("UPDATE wiki SET html = %s WHERE id = %s",
345 self
._render
(self
.markdown
), self
.id)
349 return self
.data
.timestamp
351 def was_deleted(self
):
352 return self
.markdown
is None
355 def breadcrumbs(self
):
356 return self
.backend
.wiki
.make_breadcrumbs(self
.page
)
358 def get_latest_revision(self
):
359 revisions
= self
.get_revisions()
361 # Return first object
362 for rev
in revisions
:
365 def get_revisions(self
):
366 return self
.backend
.wiki
._get
_pages
("SELECT * FROM wiki \
367 WHERE page = %s ORDER BY timestamp DESC", self
.page
)
370 def previous_revision(self
):
371 return self
.backend
.wiki
._get
_page
("SELECT * FROM wiki \
372 WHERE page = %s AND timestamp < %s ORDER BY timestamp DESC \
373 LIMIT 1", self
.page
, self
.timestamp
)
377 return self
.data
.changes
381 def check_acl(self
, account
):
382 return self
.backend
.wiki
.check_acl(self
.page
, account
)
388 parts
= self
.page
.split("/")
391 sidebar
= self
.backend
.wiki
.get_page("%s/sidebar" % os
.path
.join(*parts
))
401 if self
.previous_revision
:
402 diff
= difflib
.unified_diff(
403 self
.previous_revision
.markdown
.splitlines(),
404 self
.markdown
.splitlines(),
407 return "\n".join(diff
)
411 res
= self
.db
.query("SELECT uid FROM wiki_watchlist \
412 WHERE page = %s", self
.page
)
415 # Search for account by UID and skip if none was found
416 account
= self
.backend
.accounts
.get_by_uid(row
.uid
)
423 def is_watched_by(self
, account
):
424 res
= self
.db
.get("SELECT 1 FROM wiki_watchlist \
425 WHERE page = %s AND uid = %s", self
.page
, account
.uid
)
432 def add_watcher(self
, account
):
433 if self
.is_watched_by(account
):
436 self
.db
.execute("INSERT INTO wiki_watchlist(page, uid) \
437 VALUES(%s, %s)", self
.page
, account
.uid
)
439 def remove_watcher(self
, account
):
440 self
.db
.execute("DELETE FROM wiki_watchlist \
441 WHERE page = %s AND uid = %s", self
.page
, account
.uid
)
443 def _send_watcher_emails(self
, excludes
=[]):
444 # Nothing to do if there was no previous revision
445 if not self
.previous_revision
:
448 for watcher
in self
.watchers
:
449 # Skip everyone who is excluded
450 if watcher
in excludes
:
451 logging
.debug("Excluding %s" % watcher
)
454 logging
.debug("Sending watcher email to %s" % watcher
)
457 self
.backend
.messages
.send_template("wiki/messages/page-changed",
458 recipients
=[watcher
], page
=self
, priority
=-10)
461 class File(misc
.Object
):
462 def init(self
, id, data
):
468 return os
.path
.join(self
.path
, self
.filename
)
472 return self
.data
.path
476 return self
.data
.filename
480 return self
.data
.mimetype
484 return self
.data
.size
488 if self
.data
.author_uid
:
489 return self
.backend
.accounts
.get_by_uid(self
.data
.author_uid
)
492 def created_at(self
):
493 return self
.data
.created_at
496 return self
.mimetype
in ("application/pdf", "application/x-pdf")
499 return self
.mimetype
.startswith("image/")
503 res
= self
.db
.get("SELECT data FROM wiki_blobs \
504 WHERE id = %s", self
.data
.blob_id
)
507 return bytes(res
.data
)
509 def get_thumbnail(self
, size
):
510 cache_key
= "-".join((self
.path
, util
.normalize(self
.filename
), self
.created_at
.isoformat(), "%spx" % size
))
512 # Try to fetch the data from the cache
513 thumbnail
= self
.memcache
.get(cache_key
)
517 # Generate the thumbnail
518 thumbnail
= self
._generate
_thumbnail
(size
)
520 # Put it into the cache for forever
521 self
.memcache
.set(cache_key
, thumbnail
)
525 def _generate_thumbnail(self
, size
):
526 image
= PIL
.Image
.open(io
.BytesIO(self
.blob
))
528 # Resize the image to the desired resolution
529 image
.thumbnail((size
, size
), PIL
.Image
.ANTIALIAS
)
531 with io
.BytesIO() as f
:
532 # If writing out the image does not work with optimization,
533 # we try to write it out without any optimization.
535 image
.save(f
, image
.format
, optimize
=True, quality
=98)
537 image
.save(f
, image
.format
, quality
=98)