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

« back to all changes in this revision

Viewing changes to ivle/webapp/base/xhtml.py

Allow any authenticated (even invalid) user to use the logout view.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# IVLE - Informatics Virtual Learning Environment
 
2
# Copyright (C) 2007-2009 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
# Author: Nick Chadwick
 
19
 
 
20
import inspect
 
21
import os.path
 
22
import urllib
 
23
 
 
24
import genshi.template
 
25
 
 
26
from ivle.webapp.media import media_url
 
27
from ivle.webapp.base.views import BaseView
 
28
from ivle.webapp.base.plugins import ViewPlugin, OverlayPlugin
 
29
from ivle.webapp.errors import HTTPError, Unauthorized
 
30
import ivle.conf
 
31
import ivle.util
 
32
 
 
33
class XHTMLView(BaseView):
 
34
    """
 
35
    A view which provides a base class for views which need to return XHTML
 
36
    It is expected that apps which use this view will be written using Genshi
 
37
    templates.
 
38
    """
 
39
 
 
40
    template = 'template.html'
 
41
    plugin_scripts = {}
 
42
    plugin_styles = {}
 
43
    overlay_blacklist = []
 
44
 
 
45
    def __init__(self, req, **kwargs):
 
46
        for key in kwargs:
 
47
            setattr(self, key, kwargs[key])
 
48
 
 
49
    def render(self, req):
 
50
        req.content_type = 'text/html' # TODO: Detect application/xhtml+xml
 
51
 
 
52
        # View template
 
53
        viewctx = genshi.template.Context()
 
54
        self.populate(req, viewctx)
 
55
 
 
56
        # The template is found in the directory of the module containing the
 
57
        # view.
 
58
        app_template = os.path.join(os.path.dirname(
 
59
                        inspect.getmodule(self).__file__), self.template) 
 
60
        req.write_html_head_foot = False
 
61
        loader = genshi.template.TemplateLoader(".", auto_reload=True)
 
62
        tmpl = loader.load(app_template)
 
63
        app = tmpl.generate(viewctx)
 
64
 
 
65
        for plugin in self.plugin_scripts:
 
66
            for path in self.plugin_scripts[plugin]:
 
67
                req.scripts.append(media_url(req, plugin, path))
 
68
 
 
69
        for plugin in self.plugin_styles:
 
70
            for path in self.plugin_styles[plugin]:
 
71
                req.styles.append(media_url(req, plugin, path))
 
72
 
 
73
        # Global template
 
74
        ctx = genshi.template.Context()
 
75
        # XXX: Leave this here!! (Before req.styles is read)
 
76
        ctx['overlays'] = self.render_overlays(req)
 
77
        ctx['app_styles'] = req.styles
 
78
        ctx['scripts'] = req.scripts
 
79
        ctx['scripts_init'] = req.scripts_init
 
80
        ctx['app_template'] = app
 
81
        self.populate_headings(req, ctx)
 
82
        tmpl = loader.load(os.path.join(os.path.dirname(__file__), 
 
83
                                                        'ivle-headings.html'))
 
84
        req.write(tmpl.generate(ctx).render('xhtml', doctype='xhtml'))
 
85
        
 
86
    def populate(self, req, ctx):
 
87
        raise NotImplementedError()
 
88
 
 
89
    def populate_headings(self, req, ctx):
 
90
        ctx['favicon'] = None
 
91
        ctx['root_dir'] = ivle.conf.root_dir
 
92
        ctx['public_host'] = ivle.conf.public_host
 
93
        ctx['write_javascript_settings'] = req.write_javascript_settings
 
94
        if req.user:
 
95
            ctx['login'] = req.user.login
 
96
            ctx['logged_in'] = True
 
97
            ctx['nick'] = req.user.nick
 
98
        else:
 
99
            ctx['login'] = None
 
100
            ctx['logged_in'] = False
 
101
        ctx['publicmode'] = req.publicmode
 
102
        if hasattr(self, 'help'):
 
103
            ctx['help_path'] = self.help
 
104
 
 
105
        ctx['apps_in_tabs'] = []
 
106
        for plugin in req.plugin_index[ViewPlugin]:
 
107
            if not hasattr(plugin, 'tabs'):
 
108
                continue
 
109
 
 
110
            for tab in plugin.tabs:
 
111
                # tab is a tuple: name, title, desc, icon, path
 
112
                new_app = {}
 
113
                new_app['this_app'] = hasattr(self, 'appname') \
 
114
                                      and tab[0] == self.appname
 
115
 
 
116
                # Icon name
 
117
                if tab[3] is not None:
 
118
                    new_app['has_icon'] = True
 
119
                    icon_url = media_url(req, plugin, tab[3])
 
120
                    new_app['icon_url'] = icon_url
 
121
                    if new_app['this_app']:
 
122
                        ctx['favicon'] = icon_url
 
123
                else:
 
124
                    new_app['has_icon'] = False
 
125
                new_app['path'] = ivle.util.make_path(tab[4])
 
126
                new_app['desc'] = tab[2]
 
127
                new_app['name'] = tab[1]
 
128
                new_app['weight'] = tab[5]
 
129
                ctx['apps_in_tabs'].append(new_app)
 
130
 
 
131
        ctx['apps_in_tabs'].sort(key=lambda tab: tab['weight'])
 
132
 
 
133
    def render_overlays(self, req):
 
134
        """Generate XML streams for the overlays.
 
135
        
 
136
        Returns a list of streams. Populates the scripts, styles, and 
 
137
        scripts_init.
 
138
        """
 
139
        overlays = []
 
140
        for plugin in req.plugin_index[OverlayPlugin]:
 
141
            for overclass in plugin.overlays:
 
142
                if overclass in self.overlay_blacklist:
 
143
                    continue
 
144
                overlay = overclass(req)
 
145
                #TODO: Re-factor this to look nicer
 
146
                for mplugin in overlay.plugin_scripts:
 
147
                    for path in overlay.plugin_scripts[mplugin]:
 
148
                        req.scripts.append(media_url(req, mplugin, path))
 
149
 
 
150
                for mplugin in overlay.plugin_styles:
 
151
                    for path in overlay.plugin_styles[mplugin]:
 
152
                        req.styles.append(media_url(req, mplugin, path))
 
153
 
 
154
                req.scripts_init += overlay.plugin_scripts_init
 
155
 
 
156
                overlays.append(overlay.render(req))
 
157
        return overlays
 
158
 
 
159
    @classmethod
 
160
    def get_error_view(cls, e):
 
161
        view_map = {HTTPError:    XHTMLErrorView,
 
162
                    Unauthorized: XHTMLUnauthorizedView}
 
163
        for exccls in inspect.getmro(type(e)):
 
164
            if exccls in view_map:
 
165
                return view_map[exccls]
 
166
 
 
167
class XHTMLErrorView(XHTMLView):
 
168
    template = 'xhtmlerror.html'
 
169
 
 
170
    def __init__(self, req, exception):
 
171
        self.context = exception
 
172
 
 
173
    def populate(self, req, ctx):
 
174
        ctx['exception'] = self.context
 
175
 
 
176
class XHTMLUnauthorizedView(XHTMLErrorView):
 
177
    template = 'xhtmlunauthorized.html'
 
178
 
 
179
    def __init__(self, req, exception):
 
180
        super(XHTMLUnauthorizedView, self).__init__(req, exception)
 
181
 
 
182
        if req.user is None:
 
183
            # Not logged in. Redirect to login page.
 
184
            req.throw_redirect('/+login?' + 
 
185
                               urllib.urlencode([('url', req.uri)]))
 
186
 
 
187
        req.status = 403