]>
git.ipfire.org Git - ipfire.org.git/blob - src/backend/wiki.py
15 from .decorators
import *
17 class Wiki(misc
.Object
):
18 def _get_pages(self
, query
, *args
):
19 res
= self
.db
.query(query
, *args
)
22 yield Page(self
.backend
, row
.id, data
=row
)
24 def _get_page(self
, query
, *args
):
25 res
= self
.db
.get(query
, *args
)
28 return Page(self
.backend
, res
.id, data
=res
)
30 def get_page_title(self
, page
, default
=None):
31 # Try to retrieve title from cache
32 title
= self
.memcache
.get("wiki:title:%s" % page
)
36 # If the title has not been in the cache, we will
38 doc
= self
.get_page(page
)
42 title
= os
.path
.basename(page
)
44 # Save in cache for forever
45 self
.memcache
.set("wiki:title:%s" % page
, title
)
49 def get_page(self
, page
, revision
=None):
50 page
= Page
.sanitise_page_name(page
)
54 return self
._get
_page
("SELECT * FROM wiki WHERE page = %s \
55 AND timestamp = %s", page
, revision
)
57 return self
._get
_page
("SELECT * FROM wiki WHERE page = %s \
58 ORDER BY timestamp DESC LIMIT 1", page
)
60 def get_recent_changes(self
, account
, limit
=None):
61 pages
= self
._get
_pages
("SELECT * FROM wiki \
62 WHERE timestamp >= NOW() - INTERVAL '4 weeks' \
63 ORDER BY timestamp DESC")
66 if not page
.check_acl(account
):
75 def create_page(self
, page
, author
, content
, changes
=None, address
=None):
76 page
= Page
.sanitise_page_name(page
)
78 # Write page to the database
79 page
= self
._get
_page
("INSERT INTO wiki(page, author_uid, markdown, changes, address) \
80 VALUES(%s, %s, %s, %s, %s) RETURNING *", page
, author
.uid
, content
or None, changes
, address
)
83 self
.memcache
.set("wiki:title:%s" % page
.path
, page
.title
)
85 # Send email to all watchers
86 page
._send
_watcher
_emails
(excludes
=[author
])
90 def delete_page(self
, page
, author
, **kwargs
):
91 # Do nothing if the page does not exist
92 if not self
.get_page(page
):
95 # Just creates a blank last version of the page
96 self
.create_page(page
, author
=author
, content
=None, **kwargs
)
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",
119 # Skip any pages the user doesn't have permission for
120 if not page
.check_acl(account
):
123 # Return any other pages
126 # Break when we have found enough pages
127 if limit
and len(pages
) >= limit
:
134 Needs to be called after a page has been changed
136 self
.db
.execute("REFRESH MATERIALIZED VIEW wiki_search_index")
140 def check_acl(self
, page
, account
):
141 res
= self
.db
.query("SELECT * FROM wiki_acls \
142 WHERE %s ILIKE (path || '%%') ORDER BY LENGTH(path) DESC LIMIT 1", page
)
145 # Access not permitted when user is not logged in
149 # If user is in a matching group, we grant permission
150 for group
in row
.groups
:
151 if group
in account
.groups
:
154 # Otherwise access is not permitted
157 # If no ACLs are found, we permit access
162 def _get_files(self
, query
, *args
):
163 res
= self
.db
.query(query
, *args
)
166 yield File(self
.backend
, row
.id, data
=row
)
168 def _get_file(self
, query
, *args
):
169 res
= self
.db
.get(query
, *args
)
172 return File(self
.backend
, res
.id, data
=res
)
174 def get_files(self
, path
):
175 files
= self
._get
_files
("SELECT * FROM wiki_files \
176 WHERE path = %s AND deleted_at IS NULL ORDER BY filename", path
)
180 def get_file_by_path(self
, path
):
181 path
, filename
= os
.path
.dirname(path
), os
.path
.basename(path
)
183 return self
._get
_file
("SELECT * FROM wiki_files \
184 WHERE path = %s AND filename = %s AND deleted_at IS NULL", path
, filename
)
186 def upload(self
, path
, filename
, data
, mimetype
, author
, address
):
187 # Upload the blob first
188 blob
= self
.db
.get("INSERT INTO wiki_blobs(data) VALUES(%s) RETURNING id", data
)
190 # Create entry for file
191 return self
._get
_file
("INSERT INTO wiki_files(path, filename, author_uid, address, \
192 mimetype, blob_id, size) VALUES(%s, %s, %s, %s, %s, %s, %s) RETURNING *", path
,
193 filename
, author
.uid
, address
, mimetype
, blob
.id, len(data
))
195 def find_image(self
, path
, filename
):
196 for p
in (path
, os
.path
.dirname(path
)):
197 file = self
.get_file_by_path(os
.path
.join(p
, filename
))
199 if file and file.is_image():
203 class Page(misc
.Object
):
204 def init(self
, id, data
=None):
209 return "<%s %s %s>" % (self
.__class
__.__name
__, self
.page
, self
.timestamp
)
211 def __eq__(self
, other
):
212 if isinstance(other
, self
.__class
__):
213 return self
.id == other
.id
215 def __lt__(self
, other
):
216 if isinstance(other
, self
.__class
__):
217 if self
.page
== other
.page
:
218 return self
.timestamp
< other
.timestamp
220 return self
.page
< other
.page
223 def sanitise_page_name(page
):
227 # Make sure that the page name does NOT end with a /
228 if page
.endswith("/"):
231 # Make sure the page name starts with a /
232 if not page
.startswith("/"):
235 # Remove any double slashes
236 page
= page
.replace("//", "/")
246 return "https://wiki.ipfire.org%s" % self
.url
250 return self
.data
.page
254 return self
._title
or os
.path
.basename(self
.page
[1:])
258 if not self
.markdown
:
261 # Find first H1 headline in markdown
262 markdown
= self
.markdown
.splitlines()
264 m
= re
.match(r
"^# (.*)( #)?$", markdown
[0])
270 if self
.data
.author_uid
:
271 return self
.backend
.accounts
.get_by_uid(self
.data
.author_uid
)
273 def _render(self
, text
):
274 logging
.debug("Rendering %s" % self
)
278 for match
in re
.finditer(r
"!\[(.*?)\]\((.*?)\)", text
):
279 alt_text
, url
= match
.groups()
281 # Skip any absolute and external URLs
282 if url
.startswith("/") or url
.startswith("https://") or url
.startswith("http://"):
285 # Try to split query string
286 url
, delimiter
, qs
= url
.partition("?")
288 # Parse query arguments
289 args
= urllib
.parse
.parse_qs(qs
)
292 file = self
.backend
.wiki
.find_image(self
.page
, url
)
296 # Scale down the image if not already done
301 url
= "%s?%s" % (file.url
, urllib
.parse
.urlencode(args
))
303 replacements
.append((match
.span(), file, alt_text
, url
))
305 # Apply all replacements
306 for (start
, end
), file, alt_text
, url
in reversed(replacements
):
307 text
= text
[:start
] + "[![%s](%s)](%s?action=detail)" % (alt_text
, url
, file.url
) + text
[end
:]
311 (r
"\[\[([\w\d\/\-\.]+)(?:\|(.+?))\]\]", r
"\1", r
"\2", None, True),
312 (r
"\[\[([\w\d\/\-\.]+)\]\]", r
"\1", r
"\1", self
.backend
.wiki
.get_page_title
, True),
315 (r
"\[\[((?:ftp|git|https?|rsync|sftp|ssh|webcal)\:\/\/.+?)(?:\|(.+?))\]\]",
316 r
"\1", r
"\2", None, False),
319 (r
"\[\[([a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+)\]\]",
320 r
"\1", r
"\1", None, False),
323 for pattern
, link
, title
, repl
, internal
in patterns
:
326 for match
in re
.finditer(pattern
, text
):
327 l
= match
.expand(link
)
328 t
= match
.expand(title
)
331 # Allow relative links
332 if not l
.startswith("/"):
333 l
= os
.path
.join(self
.page
, l
)
336 l
= os
.path
.normpath(l
)
341 replacements
.append((match
.span(), t
or l
, l
))
343 # Apply all replacements
344 for (start
, end
), t
, l
in reversed(replacements
):
345 text
= text
[:start
] + "[%s](%s)" % (t
, l
) + text
[end
:]
347 # Borrow this from the blog
348 return self
.backend
.blog
._render
_text
(text
, lang
="markdown")
352 return self
.data
.markdown
or ""
356 return self
._render
(self
.markdown
)
360 return self
.data
.timestamp
362 def was_deleted(self
):
363 return self
.markdown
is None
366 def breadcrumbs(self
):
367 return self
.backend
.wiki
.make_breadcrumbs(self
.page
)
369 def get_latest_revision(self
):
370 revisions
= self
.get_revisions()
372 # Return first object
373 for rev
in revisions
:
376 def get_revisions(self
):
377 return self
.backend
.wiki
._get
_pages
("SELECT * FROM wiki \
378 WHERE page = %s ORDER BY timestamp DESC", self
.page
)
381 def previous_revision(self
):
382 return self
.backend
.wiki
._get
_page
("SELECT * FROM wiki \
383 WHERE page = %s AND timestamp < %s ORDER BY timestamp DESC \
384 LIMIT 1", self
.page
, self
.timestamp
)
388 return self
.data
.changes
392 def check_acl(self
, account
):
393 return self
.backend
.wiki
.check_acl(self
.page
, account
)
399 parts
= self
.page
.split("/")
402 sidebar
= self
.backend
.wiki
.get_page("%s/sidebar" % os
.path
.join(*parts
))
412 if self
.previous_revision
:
413 diff
= difflib
.unified_diff(
414 self
.previous_revision
.markdown
.splitlines(),
415 self
.markdown
.splitlines(),
418 return "\n".join(diff
)
422 res
= self
.db
.query("SELECT uid FROM wiki_watchlist \
423 WHERE page = %s", self
.page
)
426 # Search for account by UID and skip if none was found
427 account
= self
.backend
.accounts
.get_by_uid(row
.uid
)
434 def is_watched_by(self
, account
):
435 res
= self
.db
.get("SELECT 1 FROM wiki_watchlist \
436 WHERE page = %s AND uid = %s", self
.page
, account
.uid
)
443 def add_watcher(self
, account
):
444 if self
.is_watched_by(account
):
447 self
.db
.execute("INSERT INTO wiki_watchlist(page, uid) \
448 VALUES(%s, %s)", self
.page
, account
.uid
)
450 def remove_watcher(self
, account
):
451 self
.db
.execute("DELETE FROM wiki_watchlist \
452 WHERE page = %s AND uid = %s", self
.page
, account
.uid
)
454 def _send_watcher_emails(self
, excludes
=[]):
455 # Nothing to do if there was no previous revision
456 if not self
.previous_revision
:
459 for watcher
in self
.watchers
:
460 # Skip everyone who is excluded
461 if watcher
in excludes
:
462 logging
.debug("Excluding %s" % watcher
)
465 logging
.debug("Sending watcher email to %s" % watcher
)
468 self
.backend
.messages
.send_template("wiki/messages/page-changed",
469 recipients
=[watcher
], page
=self
, priority
=-10)
472 class File(misc
.Object
):
473 def init(self
, id, data
):
479 return os
.path
.join(self
.path
, self
.filename
)
483 return self
.data
.path
487 return self
.data
.filename
491 return self
.data
.mimetype
495 return self
.data
.size
499 if self
.data
.author_uid
:
500 return self
.backend
.accounts
.get_by_uid(self
.data
.author_uid
)
503 def created_at(self
):
504 return self
.data
.created_at
507 return self
.mimetype
in ("application/pdf", "application/x-pdf")
510 return self
.mimetype
.startswith("image/")
514 res
= self
.db
.get("SELECT data FROM wiki_blobs \
515 WHERE id = %s", self
.data
.blob_id
)
518 return bytes(res
.data
)
520 def get_thumbnail(self
, size
):
521 cache_key
= "-".join((self
.path
, util
.normalize(self
.filename
), self
.created_at
.isoformat(), "%spx" % size
))
523 # Try to fetch the data from the cache
524 thumbnail
= self
.memcache
.get(cache_key
)
528 # Generate the thumbnail
529 thumbnail
= self
._generate
_thumbnail
(size
)
531 # Put it into the cache for forever
532 self
.memcache
.set(cache_key
, thumbnail
)
536 def _generate_thumbnail(self
, size
, **args
):
537 image
= PIL
.Image
.open(io
.BytesIO(self
.blob
))
539 # Remove any alpha-channels
540 if image
.format
== "JPEG" and not image
.mode
== "RGB":
541 # Make a white background
542 background
= PIL
.Image
.new("RGBA", image
.size
, (255,255,255))
544 # Flatten both images together
545 flattened_image
= PIL
.Image
.alpha_composite(background
, image
)
547 # Remove the alpha channel
548 image
= flattened_image
.convert("RGB")
550 # Resize the image to the desired resolution
551 image
.thumbnail((size
, size
), PIL
.Image
.LANCZOS
)
553 if image
.format
== "JPEG":
554 # Apply a gaussian blur to make compression easier
555 image
= image
.filter(PIL
.ImageFilter
.GaussianBlur(radius
=0.05))
557 # Arguments to optimise the compression
559 "subsampling" : "4:2:0",
563 with io
.BytesIO() as f
:
564 # If writing out the image does not work with optimization,
565 # we try to write it out without any optimization.
567 image
.save(f
, image
.format
, optimize
=True, **args
)
569 image
.save(f
, image
.format
, **args
)