1
# IVLE - Informatics Virtual Learning Environment
2
# Copyright (C) 2007-2008 The University of Melbourne
4
# This program is free software; you can redistribute it and/or modify
5
# it under the terms of the GNU General Public License as published by
6
# the Free Software Foundation; either version 2 of the License, or
7
# (at your option) any later version.
9
# This program is distributed in the hope that it will be useful,
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
# GNU General Public License for more details.
14
# You should have received a copy of the GNU General Public License
15
# along with this program; if not, write to the Free Software
16
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
22
# Contains common utility functions.
23
# Also initialises mime types library. You must import util before using
24
# Python's builtin mimetypes module to make sure local settings are applied.
31
import ivle.conf.mimetypes
33
class IVLEError(Exception):
35
This is the "standard" exception class for IVLE errors.
36
It is the ONLY exception which should propagate to the top - it will then
37
be displayed to the user as an HTTP error with the given code.
39
All other exceptions are considered IVLE bugs and should not occur
40
(they will display a traceback).
42
This error should not be raised directly. Call req.throw_error.
44
def __init__(self, httpcode, message=None):
45
self.httpcode = httpcode
46
self.message = message
47
self.args = (httpcode, message)
49
class IVLEJailError(Exception):
51
This exception indicates an error that occurred inside an IVLE CGI script
52
inside the jail. It should never be raised directly - only by the
55
Information will be retrieved from it, and then treated as a normal
58
def __init__(self, type_str, message, info):
59
self.type_str = type_str
60
self.message = message
63
class FakeObject(object):
64
""" A representation of an object that can't be Pickled """
65
def __init__(self, type, name, attrib={}):
71
return "<Fake %s %s>"%(self.type, self.name)
74
"""Given a path relative to the IVLE root, makes the path relative to the
75
site root using ivle.conf.root_dir. This path can be used in URLs sent to
77
return os.path.join(ivle.conf.root_dir, path)
79
def unmake_path(path):
80
"""Given a path relative to the site root, makes the path relative to the
81
IVLE root by removing ivle.conf.root_dir if it appears at the beginning. If
82
it does not appear at the beginning, returns path unchanged. Also
83
normalises the path."""
84
path = os.path.normpath(path)
85
root = os.path.normpath(ivle.conf.root_dir)
87
if path.startswith(root):
88
path = path[len(root):]
89
# Take out the slash as well
90
if len(path) > 0 and path[0] == os.sep:
96
"""Given a path, returns a tuple consisting of the top-level directory in
97
the path, and the rest of the path. Note that both items in the tuple will
98
NOT begin with a slash, regardless of whether the original path did. Also
101
Always returns a pair of strings, except for one special case, in which
102
the path is completely empty (or just a single slash). In this case the
103
return value will be (None, ''). But still always returns a pair.
111
>>> split_path("home")
113
>>> split_path("home/docs/files")
114
('home', 'docs/files')
115
>>> split_path("//home/docs/files")
116
('', 'home/docs/files')
118
path = os.path.normpath(path)
119
# Ignore the opening slash
120
if path.startswith(os.sep):
121
path = path[len(os.sep):]
122
if path == '' or path == '.':
124
splitpath = path.split(os.sep, 1)
125
if len(splitpath) == 1:
126
return (splitpath[0], '')
128
return tuple(splitpath)
130
# Initialise mime types library
132
for (ext, mimetype) in ivle.conf.mimetypes.additional_mime_types.items():
133
mimetypes.add_type(mimetype, ext)
135
def nice_filetype(filename):
136
"""Given a filename or basename, returns a "friendly" name for that
138
eg. nice_mimetype("file.py") == "Python source code".
139
nice_filetype("file.bzg") == "BZG file".
140
nice_filetype("directory/") == "Directory".
142
if filename[-1] == os.sep:
146
return ivle.conf.mimetypes.nice_mimetypes[
147
mimetypes.guess_type(filename)[0]]
149
filename = os.path.basename(filename)
151
return filename[filename.rindex('.')+1:].upper() + " file"
155
def incomplete_utf8_sequence(byteseq):
158
Given a UTF-8-encoded byte sequence (str), returns the number of bytes at
159
the end of the string which comprise an incomplete UTF-8 character
162
If the string is empty or ends with a complete character OR INVALID
164
Otherwise, returns 1-3 indicating the number of bytes in the final
165
incomplete (but valid) character sequence.
167
Does not check any bytes before the final sequence for correctness.
169
>>> incomplete_utf8_sequence("")
171
>>> incomplete_utf8_sequence("xy")
173
>>> incomplete_utf8_sequence("xy\xc3\xbc")
175
>>> incomplete_utf8_sequence("\xc3")
177
>>> incomplete_utf8_sequence("\xbc\xc3")
179
>>> incomplete_utf8_sequence("xy\xbc\xc3")
181
>>> incomplete_utf8_sequence("xy\xe0\xa0")
183
>>> incomplete_utf8_sequence("xy\xf4")
185
>>> incomplete_utf8_sequence("xy\xf4\x8f")
187
>>> incomplete_utf8_sequence("xy\xf4\x8f\xa0")
192
for b in byteseq[::-1]:
196
# 0xxxxxxx (single-byte character)
199
elif b & 0xc0 == 0x80:
200
# 10xxxxxx (subsequent byte)
202
elif b & 0xe0 == 0xc0:
203
# 110xxxxx (start of 2-byte sequence)
206
elif b & 0xf0 == 0xe0:
207
# 1110xxxx (start of 3-byte sequence)
210
elif b & 0xf8 == 0xf0:
211
# 11110xxx (start of 4-byte sequence)
219
# Seen too many "subsequent bytes", invalid
223
# We never saw a "first byte", invalid
226
# We now know expect and count
228
# Complete, or we saw an invalid sequence
234
def object_to_dict(attrnames, obj):
236
Convert an object into a dictionary. This takes a shallow copy of the
238
attrnames: Set (or iterable) of names of attributes to be copied into the
239
dictionary. (We don't auto-lookup, because this function needs to be
240
used on magical objects).
242
return dict((k, getattr(obj, k))
243
for k in attrnames if not k.startswith('_'))