]>
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
)
69 # Send email to all watchers
70 page
._send
_watcher
_emails
(excludes
=[author
])
74 def delete_page(self
, page
, author
, **kwargs
):
75 # Do nothing if the page does not exist
76 if not self
.get_page(page
):
79 # Just creates a blank last version of the page
80 self
.create_page(page
, author
=author
, content
=None, **kwargs
)
82 def make_breadcrumbs(self
, url
):
83 # Split and strip all empty elements (double slashes)
84 parts
= list(e
for e
in url
.split("/") if e
)
87 for part
in ("/".join(parts
[:i
]) for i
in range(1, len(parts
))):
88 ret
.append(("/%s" % part
, self
.get_page_title(part
, os
.path
.basename(part
))))
92 def search(self
, query
, account
=None, limit
=None):
93 query
= util
.parse_search_query(query
)
95 res
= self
._get
_pages
("SELECT wiki.* FROM wiki_search_index search_index \
96 LEFT JOIN wiki ON search_index.wiki_id = wiki.id \
97 WHERE search_index.document @@ to_tsquery('english', %s) \
98 ORDER BY ts_rank(search_index.document, to_tsquery('english', %s)) DESC",
102 # Skip any pages the user doesn't have permission for
103 if not page
.check_acl(account
):
106 # Return any other pages
115 Needs to be called after a page has been changed
117 self
.db
.execute("REFRESH MATERIALIZED VIEW wiki_search_index")
121 def check_acl(self
, page
, account
):
122 res
= self
.db
.query("SELECT * FROM wiki_acls \
123 WHERE %s ILIKE (path || '%%') ORDER BY LENGTH(path) DESC LIMIT 1", page
)
126 # Access not permitted when user is not logged in
130 # If user is in a matching group, we grant permission
131 for group
in row
.groups
:
132 if group
in account
.groups
:
135 # Otherwise access is not permitted
138 # If no ACLs are found, we permit access
143 def _get_files(self
, query
, *args
):
144 res
= self
.db
.query(query
, *args
)
147 yield File(self
.backend
, row
.id, data
=row
)
149 def _get_file(self
, query
, *args
):
150 res
= self
.db
.get(query
, *args
)
153 return File(self
.backend
, res
.id, data
=res
)
155 def get_files(self
, path
):
156 files
= self
._get
_files
("SELECT * FROM wiki_files \
157 WHERE path = %s AND deleted_at IS NULL ORDER BY filename", path
)
161 def get_file_by_path(self
, path
):
162 path
, filename
= os
.path
.dirname(path
), os
.path
.basename(path
)
164 return self
._get
_file
("SELECT * FROM wiki_files \
165 WHERE path = %s AND filename = %s AND deleted_at IS NULL", path
, filename
)
167 def upload(self
, path
, filename
, data
, mimetype
, author
, address
):
168 # Upload the blob first
169 blob
= self
.db
.get("INSERT INTO wiki_blobs(data) VALUES(%s) RETURNING id", data
)
171 # Create entry for file
172 return self
._get
_file
("INSERT INTO wiki_files(path, filename, author_uid, address, \
173 mimetype, blob_id, size) VALUES(%s, %s, %s, %s, %s, %s, %s) RETURNING *", path
,
174 filename
, author
.uid
, address
, mimetype
, blob
.id, len(data
))
176 def find_image(self
, path
, filename
):
177 for p
in (path
, os
.path
.dirname(path
)):
178 file = self
.get_file_by_path(os
.path
.join(p
, filename
))
180 if file and file.is_image():
184 class Page(misc
.Object
):
185 def init(self
, id, data
=None):
190 return "<%s %s %s>" % (self
.__class
__.__name
__, self
.page
, self
.timestamp
)
192 def __eq__(self
, other
):
193 if isinstance(other
, self
.__class
__):
194 return self
.id == other
.id
196 def __lt__(self
, other
):
197 if isinstance(other
, self
.__class
__):
198 if self
.page
== other
.page
:
199 return self
.timestamp
< other
.timestamp
201 return self
.page
< other
.page
204 def sanitise_page_name(page
):
208 # Make sure that the page name does NOT end with a /
209 if page
.endswith("/"):
212 # Make sure the page name starts with a /
213 if not page
.startswith("/"):
216 # Remove any double slashes
217 page
= page
.replace("//", "/")
227 return "https://wiki.ipfire.org%s" % self
.url
231 return self
.data
.page
235 return self
._title
or os
.path
.basename(self
.page
[1:])
239 if not self
.markdown
:
242 # Find first H1 headline in markdown
243 markdown
= self
.markdown
.splitlines()
245 m
= re
.match(r
"^# (.*)( #)?$", markdown
[0])
251 if self
.data
.author_uid
:
252 return self
.backend
.accounts
.get_by_uid(self
.data
.author_uid
)
254 def _render(self
, text
):
255 logging
.debug("Rendering %s" % self
)
259 for match
in re
.finditer(r
"!\[(.*?)\]\((.*?)\)", text
):
260 alt_text
, url
= match
.groups()
262 # Skip any absolute and external URLs
263 if url
.startswith("/") or url
.startswith("https://") or url
.startswith("http://"):
266 # Try to split query string
267 url
, delimiter
, qs
= url
.partition("?")
269 # Parse query arguments
270 args
= urllib
.parse
.parse_qs(qs
)
273 file = self
.backend
.wiki
.find_image(self
.page
, url
)
277 # Scale down the image if not already done
282 url
= "%s?%s" % (file.url
, urllib
.parse
.urlencode(args
))
284 replacements
.append((match
.span(), file, alt_text
, url
))
286 # Apply all replacements
287 for (start
, end
), file, alt_text
, url
in reversed(replacements
):
288 text
= text
[:start
] + "[![%s](%s)](%s?action=detail)" % (alt_text
, url
, file.url
) + text
[end
:]
292 (r
"\[\[([\w\d\/\-\.]+)(?:\|(.+?))\]\]", r
"\1", r
"\2", None, True),
293 (r
"\[\[([\w\d\/\-\.]+)\]\]", r
"\1", r
"\1", self
.backend
.wiki
.get_page_title
, True),
296 (r
"\[\[((?:ftp|git|https?|rsync|sftp|ssh|webcal)\:\/\/.+?)(?:\|(.+?))\]\]",
297 r
"\1", r
"\2", None, False),
300 (r
"\[\[([a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+)\]\]",
301 r
"\1", r
"\1", None, False),
304 for pattern
, link
, title
, repl
, internal
in patterns
:
307 for match
in re
.finditer(pattern
, text
):
308 l
= match
.expand(link
)
309 t
= match
.expand(title
)
312 # Allow relative links
313 if not l
.startswith("/"):
314 l
= os
.path
.join(self
.page
, l
)
317 l
= os
.path
.normpath(l
)
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
._render
(self
.markdown
)
341 return self
.data
.timestamp
343 def was_deleted(self
):
344 return self
.markdown
is None
347 def breadcrumbs(self
):
348 return self
.backend
.wiki
.make_breadcrumbs(self
.page
)
350 def get_latest_revision(self
):
351 revisions
= self
.get_revisions()
353 # Return first object
354 for rev
in revisions
:
357 def get_revisions(self
):
358 return self
.backend
.wiki
._get
_pages
("SELECT * FROM wiki \
359 WHERE page = %s ORDER BY timestamp DESC", self
.page
)
362 def previous_revision(self
):
363 return self
.backend
.wiki
._get
_page
("SELECT * FROM wiki \
364 WHERE page = %s AND timestamp < %s ORDER BY timestamp DESC \
365 LIMIT 1", self
.page
, self
.timestamp
)
369 return self
.data
.changes
373 def check_acl(self
, account
):
374 return self
.backend
.wiki
.check_acl(self
.page
, account
)
380 parts
= self
.page
.split("/")
383 sidebar
= self
.backend
.wiki
.get_page("%s/sidebar" % os
.path
.join(*parts
))
393 if self
.previous_revision
:
394 diff
= difflib
.unified_diff(
395 self
.previous_revision
.markdown
.splitlines(),
396 self
.markdown
.splitlines(),
399 return "\n".join(diff
)
403 res
= self
.db
.query("SELECT uid FROM wiki_watchlist \
404 WHERE page = %s", self
.page
)
407 # Search for account by UID and skip if none was found
408 account
= self
.backend
.accounts
.get_by_uid(row
.uid
)
415 def is_watched_by(self
, account
):
416 res
= self
.db
.get("SELECT 1 FROM wiki_watchlist \
417 WHERE page = %s AND uid = %s", self
.page
, account
.uid
)
424 def add_watcher(self
, account
):
425 if self
.is_watched_by(account
):
428 self
.db
.execute("INSERT INTO wiki_watchlist(page, uid) \
429 VALUES(%s, %s)", self
.page
, account
.uid
)
431 def remove_watcher(self
, account
):
432 self
.db
.execute("DELETE FROM wiki_watchlist \
433 WHERE page = %s AND uid = %s", self
.page
, account
.uid
)
435 def _send_watcher_emails(self
, excludes
=[]):
436 # Nothing to do if there was no previous revision
437 if not self
.previous_revision
:
440 for watcher
in self
.watchers
:
441 # Skip everyone who is excluded
442 if watcher
in excludes
:
443 logging
.debug("Excluding %s" % watcher
)
446 logging
.debug("Sending watcher email to %s" % watcher
)
449 self
.backend
.messages
.send_template("wiki/messages/page-changed",
450 recipients
=[watcher
], page
=self
, priority
=-10)
453 class File(misc
.Object
):
454 def init(self
, id, data
):
460 return os
.path
.join(self
.path
, self
.filename
)
464 return self
.data
.path
468 return self
.data
.filename
472 return self
.data
.mimetype
476 return self
.data
.size
480 if self
.data
.author_uid
:
481 return self
.backend
.accounts
.get_by_uid(self
.data
.author_uid
)
484 def created_at(self
):
485 return self
.data
.created_at
488 return self
.mimetype
in ("application/pdf", "application/x-pdf")
491 return self
.mimetype
.startswith("image/")
495 res
= self
.db
.get("SELECT data FROM wiki_blobs \
496 WHERE id = %s", self
.data
.blob_id
)
499 return bytes(res
.data
)
501 def get_thumbnail(self
, size
):
502 cache_key
= "-".join((self
.path
, util
.normalize(self
.filename
), self
.created_at
.isoformat(), "%spx" % size
))
504 # Try to fetch the data from the cache
505 thumbnail
= self
.memcache
.get(cache_key
)
509 # Generate the thumbnail
510 thumbnail
= self
._generate
_thumbnail
(size
)
512 # Put it into the cache for forever
513 self
.memcache
.set(cache_key
, thumbnail
)
517 def _generate_thumbnail(self
, size
):
518 image
= PIL
.Image
.open(io
.BytesIO(self
.blob
))
520 # Resize the image to the desired resolution
521 image
.thumbnail((size
, size
), PIL
.Image
.ANTIALIAS
)
523 with io
.BytesIO() as f
:
524 # If writing out the image does not work with optimization,
525 # we try to write it out without any optimization.
527 image
.save(f
, image
.format
, optimize
=True, quality
=98)
529 image
.save(f
, image
.format
, quality
=98)