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

« back to all changes in this revision

Viewing changes to lib/common/util.py

Drop serve, download from ivle.conf.apps.

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