~azzar1/unity/add-show-desktop-key

« back to all changes in this revision

Viewing changes to ivle/util.py

  • Committer: William Grant
  • Date: 2009-04-28 05:10:36 UTC
  • Revision ID: grantw@unimelb.edu.au-20090428051036-f0teat0qpex7xlul
XHTMLView no longer uses ivle.conf.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# IVLE - Informatics Virtual Learning Environment
 
2
# Copyright (C) 2007-2008 The University of Melbourne
 
3
#
 
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.
 
8
#
 
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.
 
13
#
 
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
 
17
 
 
18
# Module: util
 
19
# Author: Matt Giuca
 
20
# Date: 12/12/2007
 
21
 
 
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.
 
25
 
 
26
import os
 
27
import mimetypes
 
28
import datetime
 
29
 
 
30
import ivle.conf
 
31
import ivle.conf.mimetypes
 
32
 
 
33
class IVLEError(Exception):
 
34
    """
 
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.
 
38
 
 
39
    All other exceptions are considered IVLE bugs and should not occur
 
40
    (they will display a traceback).
 
41
 
 
42
    This error should not be raised directly. Call req.throw_error.
 
43
    """
 
44
    def __init__(self, httpcode, message=None):
 
45
        self.httpcode = httpcode
 
46
        self.message = message
 
47
        self.args = (httpcode, message)
 
48
 
 
49
class IVLEJailError(Exception):
 
50
    """
 
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 
 
53
    interpreter.
 
54
 
 
55
    Information will be retrieved from it, and then treated as a normal
 
56
    error.
 
57
    """
 
58
    def __init__(self, type_str, message, info):
 
59
        self.type_str = type_str
 
60
        self.message = message
 
61
        self.info = info
 
62
 
 
63
class FakeObject(object):
 
64
    """ A representation of an object that can't be Pickled """
 
65
    def __init__(self, type, name, attrib={}):
 
66
        self.type = type
 
67
        self.name = name
 
68
        self.attrib = attrib
 
69
 
 
70
    def __repr__(self):
 
71
        return "<Fake %s %s>"%(self.type, self.name)
 
72
 
 
73
def make_path(path):
 
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
 
76
    the client."""
 
77
    return os.path.join(ivle.conf.root_dir, path)
 
78
 
 
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)
 
86
 
 
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:
 
91
            path = path[1:]
 
92
 
 
93
    return path
 
94
 
 
95
def split_path(path):
 
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
 
99
    normalises the path.
 
100
 
 
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.
 
104
 
 
105
    Examples:
 
106
 
 
107
    >>> split_path("")
 
108
    (None, '')
 
109
    >>> split_path("/")
 
110
    (None, '')
 
111
    >>> split_path("home")
 
112
    ('home', '')
 
113
    >>> split_path("home/docs/files")
 
114
    ('home', 'docs/files')
 
115
    >>> split_path("//home/docs/files")
 
116
    ('', 'home/docs/files')
 
117
    """
 
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 == '.':
 
123
        return (None, '')
 
124
    splitpath = path.split(os.sep, 1)
 
125
    if len(splitpath) == 1:
 
126
        return (splitpath[0], '')
 
127
    else:
 
128
        return tuple(splitpath)
 
129
 
 
130
# Initialise mime types library
 
131
mimetypes.init()
 
132
for (ext, mimetype) in ivle.conf.mimetypes.additional_mime_types.items():
 
133
    mimetypes.add_type(mimetype, ext)
 
134
 
 
135
def nice_filetype(filename):
 
136
    """Given a filename or basename, returns a "friendly" name for that
 
137
    file's type.
 
138
    eg. nice_mimetype("file.py") == "Python source code".
 
139
        nice_filetype("file.bzg") == "BZG file".
 
140
        nice_filetype("directory/") == "Directory".
 
141
    """
 
142
    if filename[-1] == os.sep:
 
143
        return "Directory"
 
144
    else:
 
145
        try:
 
146
            return ivle.conf.mimetypes.nice_mimetypes[
 
147
                mimetypes.guess_type(filename)[0]]
 
148
        except KeyError:
 
149
            filename = os.path.basename(filename)
 
150
            try:
 
151
                return filename[filename.rindex('.')+1:].upper() + " file"
 
152
            except ValueError:
 
153
                return "File"
 
154
 
 
155
def incomplete_utf8_sequence(byteseq):
 
156
    """
 
157
    str -> int
 
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
 
160
    sequence.
 
161
 
 
162
    If the string is empty or ends with a complete character OR INVALID
 
163
    sequence, returns 0.
 
164
    Otherwise, returns 1-3 indicating the number of bytes in the final
 
165
    incomplete (but valid) character sequence.
 
166
 
 
167
    Does not check any bytes before the final sequence for correctness.
 
168
 
 
169
    >>> incomplete_utf8_sequence("")
 
170
    0
 
171
    >>> incomplete_utf8_sequence("xy")
 
172
    0
 
173
    >>> incomplete_utf8_sequence("xy\xc3\xbc")
 
174
    0
 
175
    >>> incomplete_utf8_sequence("\xc3")
 
176
    1
 
177
    >>> incomplete_utf8_sequence("\xbc\xc3")
 
178
    1
 
179
    >>> incomplete_utf8_sequence("xy\xbc\xc3")
 
180
    1
 
181
    >>> incomplete_utf8_sequence("xy\xe0\xa0")
 
182
    2
 
183
    >>> incomplete_utf8_sequence("xy\xf4")
 
184
    1
 
185
    >>> incomplete_utf8_sequence("xy\xf4\x8f")
 
186
    2
 
187
    >>> incomplete_utf8_sequence("xy\xf4\x8f\xa0")
 
188
    3
 
189
    """
 
190
    count = 0
 
191
    expect = None
 
192
    for b in byteseq[::-1]:
 
193
        b = ord(b)
 
194
        count += 1
 
195
        if b & 0x80 == 0x0:
 
196
            # 0xxxxxxx (single-byte character)
 
197
            expect = 1
 
198
            break
 
199
        elif b & 0xc0 == 0x80:
 
200
            # 10xxxxxx (subsequent byte)
 
201
            pass
 
202
        elif b & 0xe0 == 0xc0:
 
203
            # 110xxxxx (start of 2-byte sequence)
 
204
            expect = 2
 
205
            break
 
206
        elif b & 0xf0 == 0xe0:
 
207
            # 1110xxxx (start of 3-byte sequence)
 
208
            expect = 3
 
209
            break
 
210
        elif b & 0xf8 == 0xf0:
 
211
            # 11110xxx (start of 4-byte sequence)
 
212
            expect = 4
 
213
            break
 
214
        else:
 
215
            # Invalid byte
 
216
            return 0
 
217
 
 
218
        if count >= 4:
 
219
            # Seen too many "subsequent bytes", invalid
 
220
            return 0
 
221
 
 
222
    if expect is None:
 
223
        # We never saw a "first byte", invalid
 
224
        return 0
 
225
 
 
226
    # We now know expect and count
 
227
    if count >= expect:
 
228
        # Complete, or we saw an invalid sequence
 
229
        return 0
 
230
    elif count < expect:
 
231
        # Incomplete
 
232
        return count
 
233
 
 
234
def object_to_dict(attrnames, obj):
 
235
    """
 
236
    Convert an object into a dictionary. This takes a shallow copy of the
 
237
    object.
 
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).
 
241
    """
 
242
    return dict((k, getattr(obj, k))
 
243
        for k in attrnames if not k.startswith('_'))