]>
git.ipfire.org Git - ipfire.org.git/blob - src/backend/wiki.py
13 from .decorators
import *
15 class Wiki(misc
.Object
):
16 def _get_pages(self
, query
, *args
):
17 res
= self
.db
.query(query
, *args
)
20 yield Page(self
.backend
, row
.id, data
=row
)
22 def _get_page(self
, query
, *args
):
23 res
= self
.db
.get(query
, *args
)
26 return Page(self
.backend
, res
.id, data
=res
)
28 def get_page_title(self
, page
, default
=None):
29 doc
= self
.get_page(page
)
33 return default
or os
.path
.basename(page
)
35 def get_page(self
, page
, revision
=None):
36 page
= Page
.sanitise_page_name(page
)
40 return self
._get
_page
("SELECT * FROM wiki WHERE page = %s \
41 AND timestamp = %s", page
, revision
)
43 return self
._get
_page
("SELECT * FROM wiki WHERE page = %s \
44 ORDER BY timestamp DESC LIMIT 1", page
)
46 def get_recent_changes(self
, account
, limit
=None):
47 pages
= self
._get
_pages
("SELECT * FROM wiki \
48 WHERE timestamp >= NOW() - INTERVAL '4 weeks' \
49 ORDER BY timestamp DESC")
52 if not page
.check_acl(account
):
61 def create_page(self
, page
, author
, content
, changes
=None, address
=None):
62 page
= Page
.sanitise_page_name(page
)
64 # Write page to the database
65 page
= self
._get
_page
("INSERT INTO wiki(page, author_uid, markdown, changes, address) \
66 VALUES(%s, %s, %s, %s, %s) RETURNING *", page
, author
.uid
, content
or None, changes
, address
)
68 # Send email to all watchers
69 page
._send
_watcher
_emails
(excludes
=[author
])
73 def delete_page(self
, page
, author
, **kwargs
):
74 # Do nothing if the page does not exist
75 if not self
.get_page(page
):
78 # Just creates a blank last version of the page
79 self
.create_page(page
, author
=author
, content
=None, **kwargs
)
81 def make_breadcrumbs(self
, url
):
82 # Split and strip all empty elements (double slashes)
83 parts
= list(e
for e
in url
.split("/") if e
)
86 for part
in ("/".join(parts
[:i
]) for i
in range(1, len(parts
))):
87 ret
.append(("/%s" % part
, self
.get_page_title(part
, os
.path
.basename(part
))))
91 def search(self
, query
, account
=None, limit
=None):
92 query
= util
.parse_search_query(query
)
94 res
= self
._get
_pages
("SELECT wiki.* FROM wiki_search_index search_index \
95 LEFT JOIN wiki ON search_index.wiki_id = wiki.id \
96 WHERE search_index.document @@ to_tsquery('english', %s) \
97 ORDER BY ts_rank(search_index.document, to_tsquery('english', %s)) DESC",
101 # Skip any pages the user doesn't have permission for
102 if not page
.check_acl(account
):
105 # Return any other pages
114 Needs to be called after a page has been changed
116 self
.db
.execute("REFRESH MATERIALIZED VIEW wiki_search_index")
120 def check_acl(self
, page
, account
):
121 res
= self
.db
.query("SELECT * FROM wiki_acls \
122 WHERE %s ILIKE (path || '%%') ORDER BY LENGTH(path) DESC LIMIT 1", page
)
125 # Access not permitted when user is not logged in
129 # If user is in a matching group, we grant permission
130 for group
in row
.groups
:
131 if group
in account
.groups
:
134 # Otherwise access is not permitted
137 # If no ACLs are found, we permit access
142 def _get_files(self
, query
, *args
):
143 res
= self
.db
.query(query
, *args
)
146 yield File(self
.backend
, row
.id, data
=row
)
148 def _get_file(self
, query
, *args
):
149 res
= self
.db
.get(query
, *args
)
152 return File(self
.backend
, res
.id, data
=res
)
154 def get_files(self
, path
):
155 files
= self
._get
_files
("SELECT * FROM wiki_files \
156 WHERE path = %s AND deleted_at IS NULL ORDER BY filename", path
)
160 def get_file_by_path(self
, path
):
161 path
, filename
= os
.path
.dirname(path
), os
.path
.basename(path
)
163 return self
._get
_file
("SELECT * FROM wiki_files \
164 WHERE path = %s AND filename = %s AND deleted_at IS NULL", path
, filename
)
166 def upload(self
, path
, filename
, data
, mimetype
, author
, address
):
167 # Upload the blob first
168 blob
= self
.db
.get("INSERT INTO wiki_blobs(data) VALUES(%s) RETURNING id", data
)
170 # Create entry for file
171 return self
._get
_file
("INSERT INTO wiki_files(path, filename, author_uid, address, \
172 mimetype, blob_id, size) VALUES(%s, %s, %s, %s, %s, %s, %s) RETURNING *", path
,
173 filename
, author
.uid
, address
, mimetype
, blob
.id, len(data
))
175 def find_image(self
, path
, filename
):
176 for p
in (path
, os
.path
.dirname(path
)):
177 file = self
.get_file_by_path(os
.path
.join(p
, filename
))
179 if file and file.is_image():
183 class Page(misc
.Object
):
184 def init(self
, id, data
=None):
189 return "<%s %s %s>" % (self
.__class
__.__name
__, self
.page
, self
.timestamp
)
191 def __eq__(self
, other
):
192 if isinstance(other
, self
.__class
__):
193 return self
.id == other
.id
195 def __lt__(self
, other
):
196 if isinstance(other
, self
.__class
__):
197 if self
.page
== other
.page
:
198 return self
.timestamp
< other
.timestamp
200 return self
.page
< other
.page
203 def sanitise_page_name(page
):
207 # Make sure that the page name does NOT end with a /
208 if page
.endswith("/"):
211 # Make sure the page name starts with a /
212 if not page
.startswith("/"):
215 # Remove any double slashes
216 page
= page
.replace("//", "/")
226 return "https://wiki.ipfire.org%s" % self
.url
230 return self
.data
.page
234 return self
._title
or os
.path
.basename(self
.page
[1:])
238 if not self
.markdown
:
241 # Find first H1 headline in markdown
242 markdown
= self
.markdown
.splitlines()
244 m
= re
.match(r
"^# (.*)( #)?$", markdown
[0])
250 if self
.data
.author_uid
:
251 return self
.backend
.accounts
.get_by_uid(self
.data
.author_uid
)
253 def _render(self
, text
):
254 logging
.debug("Rendering %s" % self
)
258 for match
in re
.finditer(r
"!\[(.*)\]\((.*)\)", text
):
259 alt_text
, url
= match
.groups()
261 # Skip any absolute and external URLs
262 if url
.startswith("/") or url
.startswith("https://") or url
.startswith("http://"):
265 # Try to split query string
266 url
, delimiter
, qs
= url
.partition("?")
268 # Parse query arguments
269 args
= urllib
.parse
.parse_qs(qs
)
272 file = self
.backend
.wiki
.find_image(self
.page
, url
)
276 # Scale down the image if not already done
281 url
= "%s?%s" % (file.url
, urllib
.parse
.urlencode(args
))
283 replacements
.append((match
.span(), file, alt_text
, url
))
285 # Apply all replacements
286 for (start
, end
), file, alt_text
, url
in reversed(replacements
):
287 text
= text
[:start
] + "[![%s](%s)](%s?action=detail)" % (alt_text
, url
, file.url
) + text
[end
:]
291 (r
"\[\[([\w\d\/]+)(?:\|([\w\d\s]+))\]\]", r
"/\1", r
"\2", None, None),
292 (r
"\[\[([\w\d\/\-]+)\]\]", r
"/\1", r
"\1", self
.backend
.wiki
.get_page_title
, r
"\1"),
295 for pattern
, link
, title
, repl
, args
in patterns
:
298 for match
in re
.finditer(pattern
, text
):
299 l
= match
.expand(link
)
300 t
= match
.expand(title
)
303 t
= repl(match
.expand(args
)) or t
305 replacements
.append((match
.span(), t
or l
, l
))
307 # Apply all replacements
308 for (start
, end
), t
, l
in reversed(replacements
):
309 text
= text
[:start
] + "[%s](%s)" % (t
, l
) + text
[end
:]
311 # Borrow this from the blog
312 return self
.backend
.blog
._render
_text
(text
, lang
="markdown")
316 return self
.data
.markdown
or ""
320 return self
.data
.html
or self
._render
(self
.markdown
)
324 return self
.data
.timestamp
326 def was_deleted(self
):
327 return self
.markdown
is None
330 def breadcrumbs(self
):
331 return self
.backend
.wiki
.make_breadcrumbs(self
.page
)
333 def get_latest_revision(self
):
334 revisions
= self
.get_revisions()
336 # Return first object
337 for rev
in revisions
:
340 def get_revisions(self
):
341 return self
.backend
.wiki
._get
_pages
("SELECT * FROM wiki \
342 WHERE page = %s ORDER BY timestamp DESC", self
.page
)
345 def previous_revision(self
):
346 return self
.backend
.wiki
._get
_page
("SELECT * FROM wiki \
347 WHERE page = %s AND timestamp < %s ORDER BY timestamp DESC \
348 LIMIT 1", self
.page
, self
.timestamp
)
352 return self
.data
.changes
356 def check_acl(self
, account
):
357 return self
.backend
.wiki
.check_acl(self
.page
, account
)
363 parts
= self
.page
.split("/")
366 sidebar
= self
.backend
.wiki
.get_page("%s/sidebar" % os
.path
.join(*parts
))
376 if self
.previous_revision
:
377 diff
= difflib
.unified_diff(
378 self
.previous_revision
.markdown
.splitlines(),
379 self
.markdown
.splitlines(),
382 return "\n".join(diff
)
386 res
= self
.db
.query("SELECT uid FROM wiki_watchlist \
387 WHERE page = %s", self
.page
)
390 # Search for account by UID and skip if none was found
391 account
= self
.backend
.accounts
.get_by_uid(row
.uid
)
398 def is_watched_by(self
, account
):
399 res
= self
.db
.get("SELECT 1 FROM wiki_watchlist \
400 WHERE page = %s AND uid = %s", self
.page
, account
.uid
)
407 def add_watcher(self
, account
):
408 if self
.is_watched_by(account
):
411 self
.db
.execute("INSERT INTO wiki_watchlist(page, uid) \
412 VALUES(%s, %s)", self
.page
, account
.uid
)
414 def remove_watcher(self
, account
):
415 self
.db
.execute("DELETE FROM wiki_watchlist \
416 WHERE page = %s AND uid = %s", self
.page
, account
.uid
)
418 def _send_watcher_emails(self
, excludes
=[]):
419 # Nothing to do if there was no previous revision
420 if not self
.previous_revision
:
423 for watcher
in self
.watchers
:
424 # Skip everyone who is excluded
425 if watcher
in excludes
:
426 logging
.debug("Excluding %s" % watcher
)
429 logging
.debug("Sending watcher email to %s" % watcher
)
432 self
.backend
.messages
.send_template("wiki/messages/page-changed",
433 recipients
=[watcher
], page
=self
, priority
=-10)
436 class File(misc
.Object
):
437 def init(self
, id, data
):
443 return os
.path
.join(self
.path
, self
.filename
)
447 return self
.data
.path
451 return self
.data
.filename
455 return self
.data
.mimetype
459 return self
.data
.size
463 if self
.data
.author_uid
:
464 return self
.backend
.accounts
.get_by_uid(self
.data
.author_uid
)
467 def created_at(self
):
468 return self
.data
.created_at
471 return self
.mimetype
in ("application/pdf", "application/x-pdf")
474 return self
.mimetype
.startswith("image/")
478 res
= self
.db
.get("SELECT data FROM wiki_blobs \
479 WHERE id = %s", self
.data
.blob_id
)
482 return bytes(res
.data
)
484 def get_thumbnail(self
, size
):
485 cache_key
= "-".join((self
.path
, util
.normalize(self
.filename
), self
.created_at
.isoformat(), "%spx" % size
))
487 # Try to fetch the data from the cache
488 thumbnail
= self
.memcache
.get(cache_key
)
492 # Generate the thumbnail
493 thumbnail
= self
._generate
_thumbnail
(size
)
495 # Put it into the cache for forever
496 self
.memcache
.set(cache_key
, thumbnail
)
500 def _generate_thumbnail(self
, size
):
501 image
= PIL
.Image
.open(io
.BytesIO(self
.blob
))
503 # Resize the image to the desired resolution
504 image
.thumbnail((size
, size
), PIL
.Image
.ANTIALIAS
)
506 with io
.BytesIO() as f
:
507 # If writing out the image does not work with optimization,
508 # we try to write it out without any optimization.
510 image
.save(f
, image
.format
, optimize
=True, quality
=98)
512 image
.save(f
, image
.format
, quality
=98)