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

409 by mattgiuca
Moved www/conf and www/common to a new directory lib. This separates the "web"
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: common.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
984 by dcoles
Groups: Added userservice/create_project call. You can now create a project in
28
import datetime
409 by mattgiuca
Moved www/conf and www/common to a new directory lib. This separates the "web"
29
30
import conf
31
import conf.mimetypes
32
33
root_dir = conf.root_dir
34
540 by mattgiuca
Refactored error handling and reporting. Much friendlier error messages, for
35
class IVLEError(Exception):
36
    """
37
    This is the "standard" exception class for IVLE errors.
38
    It is the ONLY exception which should propagate to the top - it will then
39
    be displayed to the user as an HTTP error with the given code.
40
41
    All other exceptions are considered IVLE bugs and should not occur
42
    (they will display a traceback).
43
44
    This error should not be raised directly. Call req.throw_error.
45
    """
46
    def __init__(self, httpcode, message=None):
47
        self.httpcode = httpcode
48
        self.message = message
49
        self.args = (httpcode, message)
50
851 by wagrant
Give CGIRequest an exception handler which turns any exception into
51
class IVLEJailError(Exception):
52
    """
53
    This exception indicates an error that occurred inside an IVLE CGI script
54
    inside the jail. It should never be raised directly - only by the 
55
    interpreter.
56
57
    Information will be retrieved from it, and then treated as a normal
58
    error.
59
    """
60
    def __init__(self, type_str, message, info):
61
        self.type_str = type_str
62
        self.message = message
63
        self.info = info
64
409 by mattgiuca
Moved www/conf and www/common to a new directory lib. This separates the "web"
65
def make_path(path):
66
    """Given a path relative to the IVLE root, makes the path relative to the
67
    site root using conf.root_dir. This path can be used in URLs sent to the
68
    client."""
69
    return os.path.join(root_dir, path)
70
71
def make_local_path(path):
72
    """Given a path relative to the IVLE root, on the local file system, makes
73
    the path relative to the root using conf.ivle_install_dir. This path can
74
    be used in reading files from the local file system."""
75
    return os.path.join(conf.ivle_install_dir, 'www', path)
76
77
def unmake_path(path):
78
    """Given a path relative to the site root, makes the path relative to the
79
    IVLE root by removing conf.root_dir if it appears at the beginning. If it
80
    does not appear at the beginning, returns path unchanged. Also normalises
81
    the path."""
82
    path = os.path.normpath(path)
83
    root = os.path.normpath(root_dir)
84
85
    if path.startswith(root):
86
        path = path[len(root):]
87
        # Take out the slash as well
88
        if len(path) > 0 and path[0] == os.sep:
89
            path = path[1:]
90
91
    return path
92
93
def split_path(path):
94
    """Given a path, returns a tuple consisting of the top-level directory in
95
    the path, and the rest of the path. Note that both items in the tuple will
96
    NOT begin with a slash, regardless of whether the original path did. Also
97
    normalises the path.
98
99
    Always returns a pair of strings, except for one special case, in which
100
    the path is completely empty (or just a single slash). In this case the
101
    return value will be (None, ''). But still always returns a pair.
102
103
    Examples:
104
105
    >>> split_path("")
106
    (None, '')
107
    >>> split_path("/")
108
    (None, '')
109
    >>> split_path("home")
110
    ('home', '')
111
    >>> split_path("home/docs/files")
112
    ('home', 'docs/files')
113
    >>> split_path("//home/docs/files")
114
    ('', 'home/docs/files')
115
    """
116
    path = os.path.normpath(path)
117
    # Ignore the opening slash
118
    if path.startswith(os.sep):
119
        path = path[len(os.sep):]
120
    if path == '' or path == '.':
121
        return (None, '')
122
    splitpath = path.split(os.sep, 1)
123
    if len(splitpath) == 1:
124
        return (splitpath[0], '')
125
    else:
126
        return tuple(splitpath)
127
701 by mattgiuca
Moved "open_exercise_file" from tutorialservice to util.
128
def open_exercise_file(exercisename):
129
    """Given an exercise name, opens the corresponding XML file for reading.
130
    Returns None if the exercise file was not found.
131
    (For tutorials / worksheets).
132
    """
133
    # First normalise the path
134
    exercisename = os.path.normpath(exercisename)
135
    # Now if it begins with ".." or separator, then it's illegal
136
    if exercisename.startswith("..") or exercisename.startswith(os.sep):
137
        exercisefile = None
138
    else:
139
        exercisefile = os.path.join(conf.exercises_base, exercisename)
140
141
    try:
142
        return open(exercisefile)
143
    except (TypeError, IOError):    # TypeError if exercisefile == None
144
        return None
145
409 by mattgiuca
Moved www/conf and www/common to a new directory lib. This separates the "web"
146
# Initialise mime types library
147
mimetypes.init()
148
for (ext, mimetype) in conf.mimetypes.additional_mime_types.items():
149
    mimetypes.add_type(mimetype, ext)
150
151
def nice_filetype(filename):
152
    """Given a filename or basename, returns a "friendly" name for that
153
    file's type.
154
    eg. nice_mimetype("file.py") == "Python source code".
155
        nice_filetype("file.bzg") == "BZG file".
156
        nice_filetype("directory/") == "Directory".
157
    """
158
    if filename[-1] == os.sep:
159
        return "Directory"
160
    else:
161
        try:
162
            return conf.mimetypes.nice_mimetypes[
163
                mimetypes.guess_type(filename)[0]]
164
        except KeyError:
165
            filename = os.path.basename(filename)
166
            try:
167
                return filename[filename.rindex('.')+1:].upper() + " file"
168
            except ValueError:
169
                return "File"
673 by mattgiuca
Rebuilt the way Terms of Service are displayed:
170
171
def send_terms_of_service(req):
172
    """
173
    Sends the Terms of Service document to the req object.
174
    This consults conf to find out where the TOS is located on disk, and sends
175
    that. If it isn't found, it sends a generic message explaining to admins
176
    how to create a real one.
177
    """
178
    try:
179
        req.sendfile(conf.tos_path)
180
    except IOError:
181
        req.write(
182
"""<h1>Terms of Service</h1>
183
<p><b>*** SAMPLE ONLY ***</b></p>
184
<p>This is the text of the IVLE Terms of Service.</p>
185
<p>The administrator should create a license file with an appropriate
186
"Terms of Service" license for your organisation.</p>
187
<h2>Instructions for Administrators</h2>
188
<p>You are seeing this message because you have not configured a Terms of
189
Service document.</p>
190
<p>When you configured IVLE, you specified a path to the Terms of Service
191
document (this is found in <b><tt>lib/conf/conf.py</tt></b> under
192
"<tt>tos_path</tt>").</p>
193
<p>Create a file at this location; an HTML file with the appropriately-worded
194
license.</p>
195
<p>This should be a normal XHTML file, except it should not contain
196
<tt>html</tt>, <tt>head</tt> or <tt>body</tt> elements - it should
197
just be the contents of a body element (IVLE will wrap it accordingly).</p>
198
<p>This will automatically be used as the license text instead of this
199
placeholder text.</p>
200
""")
984 by dcoles
Groups: Added userservice/create_project call. You can now create a project in
201
202
def parse_iso8601(str):
203
    """Parses ISO8601 string into a datetime object."""
204
    # FIXME: Terrific hack that means we only accept the format that is 
205
    # produced by json.js module when it encodes date objects.
206
    return datetime.datetime.strptime(str, "%Y-%m-%dT%H:%M:%SZ")
207