summaryrefslogtreecommitdiffstats
path: root/Products/JRedirector/JRedirector.py
blob: fbc2cd55f261bb0c01d86daae55e7e1382623e89 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
##############################################################################
#
# JRedirector   Perform and log redirections
#
# This software is governed by a license. See
# LICENSE.txt for the terms of this license.
#
###############################################################################

__doc__     = """ JRedirector Module """
__version__='$Revision$'[11:-2]

import os, time
from DateTime.DateTime import DateTime
from Acquisition import aq_inner, aq_parent
from AccessControl.Permissions import view_management_screens, manage_properties
from AccessControl import ClassSecurityInfo
from OFS.SimpleItem import SimpleItem
from BTrees.OOBTree import OOBTree
from Globals import DTMLFile, InitializeClass, MessageDialog, \
                    PersistentMapping, package_home

_dtmldir = os.path.join(package_home(globals()), 'dtml')
addJRedirectorForm = DTMLFile('add', _dtmldir)


class JRedirector(SimpleItem):
    """ JRedirector """
    security = ClassSecurityInfo()
    meta_type = 'JRedirector'

    manage_log = DTMLFile('dtml/log', globals())
    manage_map = DTMLFile('dtml/mappings', globals())
    manage_settings = DTMLFile('dtml/settings', globals())
    manage = manage_main = manage_settings
    manage_main._setName('manage_main')
    manage_settings._setName('manage_settings')

    manage_options = ( 
                ( { 'label' : 'Properties', 'action' : 'manage_settings',
                    'help' : ('JRedirector', 'Properties.stx') }
                , { 'label' : 'Mappings', 'action' : 'manage_map',
                    'help' : ('JRedirector', 'Mappings.stx') }
                , { 'label' : 'Log', 'action' : 'manage_log',
                    'help' : ('JRedirector', 'Log.stx') }
                )
                + SimpleItem.manage_options
    )


    def __init__(self, id, title='', default_redirect='', loglevel=3):
        """ Initialize a new JRedirector instance """
        self.id = id
        self.title = title
        self._default_redirect = default_redirect
        self._redirects = PersistentMapping()
        self._log = OOBTree()
        self._loglevel = int(loglevel)


    security.declarePrivate('_getRedirectData')
    def _getRedirectData(self, REQUEST):
        """ Get the redirect URL and log """
        wildcard_match = 0
        server_url = REQUEST.get('SERVER_URL')
        referrer = REQUEST.get('HTTP_REFERER', '').strip() or 'n/a'
        full_url = REQUEST.get('PATH_INFO')

        if ( full_url.find('VirtualHostBase') != -1 or
             full_url.find('VirtualHostRoot') != -1 ):
            full_url = REQUEST.get('URL')
            trp = list(REQUEST.get('TraversalRequestNameStack'))
            vpp = REQUEST.get('VirtualRootPhysicalPath')

            if len(trp) > 0:
                trp.reverse()
                full_url = '%s/%s' % (full_url, '/'.join(trp))

            nonvirtual_path = full_url.replace(server_url, '')
            old_path = '%s%s' % ('/'.join(vpp), nonvirtual_path)
        else:
            old_path = full_url.replace(server_url, '')

        redir_handled = self._redirects.has_key(old_path)

        if not redir_handled:
            # Test if this path is to be handled case-insensitively
            lc_old_path = old_path.lower()
            if ( self._redirects.has_key(lc_old_path) and
                 self._redirects[lc_old_path].get('case_insensitive', None) ):
                redir_handled = 1
                old_path = lc_old_path

        if not redir_handled:
            # Last resort: does one of the wildcards match?
            filt = lambda x: x[1].get('is_wildcard', None) and x[0] or None
            wildcards = filter(None, map(filt, self._redirects.items()))
            for wildcard in wildcards:
                wc_dict = self._redirects.get(wildcard)
                if wc_dict.get('case_insensitive', None):
                    test_against = old_path.lower()
                else:
                    test_against = old_path

                if test_against.find(wildcard) != -1:
                    old_path = wildcard
                    redir_handled = 1
                    wildcard_match = 1
                    break

        ll = getattr(self, '_loglevel', 3)
        if ( ll == 3 or 
             (ll == 1 and redir_handled == 0) or 
             (ll == 2 and redir_handled == 1) ):
            log = self._getLogStore()
            redir_rec = log.get(old_path, {})
            redir_count = redir_rec.get('total_count', 0)
            refs = redir_rec.get('referrers', [])
            if referrer not in refs:
                refs.append(referrer)

            get_transaction().abort()
            log[old_path] = { 'total_count' : redir_count + 1
                            , 'last_access' : time.time()
                            , 'redirected' : redir_handled
                            , 'wildcard_match' : wildcard_match
                            , 'referrers' : refs
                            }
            get_transaction().note('JRedirector redirected %s' % old_path)
            get_transaction().commit()

        return self._redirects.get(old_path)


    security.declarePublic('redirect')
    def redirect(self, REQUEST):
        """ Handle a redirect for a given URL """
        redir_data = self._getRedirectData(REQUEST)

        if redir_data:
            redir_path = redir_data.get('redir_path', self._default_redirect)
            redir_status = redir_data.get('redir_status', '301')

            REQUEST.RESPONSE.redirect( redir_path
                                     , status=int(redir_status)
                                     , lock=1
                                     )

    __call__ = redirect


    security.declarePublic('getRedirectURL')
    def getRedirectURL(self, REQUEST):
        """ Get URL and status for a redirect """
        redir_path = ''
        redir_status = ''

        redir_data = self._getRedirectData(REQUEST)

        if redir_data:
            redir_path = redir_data.get('redir_path', self._default_redirect)
            redir_status = redir_data.get('redir_status', '301')

        return redir_path, redir_status


    security.declareProtected(manage_properties, 'manage_edit')
    def manage_edit( self
                   , title=''
                   , default_redirect=''
                   , loglevel=3
                   , REQUEST=None
                   ):
        """ Edit the JRedirector folder properties """
        self.title = title
        self._default_redirect = default_redirect
        self._loglevel = int(loglevel)

        if REQUEST is not None:
            msg = 'Properties changed.'
            return self.manage_settings(manage_tabs_message=msg)

    security.declareProtected(view_management_screens, 'getLoglevel')
    def getLoglevel(self):
        """ Return the level of logging """
        return getattr(self, '_loglevel', 3)


    security.declareProtected(view_management_screens, 'getMappings')
    def getMappings(self):
        """ Return the existing mappings """
        return self._redirects.items()


    security.declareProtected(view_management_screens, 'getMapping')
    def getMapping(self, old_url):
        """ Return a specific mapping """
        return self._redirects.get(old_url, {})


    security.declarePrivate('_getLogStore')
    def _getLogStore(self):
        """ Indirection to allow flexibility in backend stores """
        cur_log = self._log

        if isinstance(cur_log, PersistentMapping):
            self._log = OOBTree()

            for key, value in cur_log.items():
                self._log[key] = value

            cur_log = self._log

        return cur_log



    security.declareProtected(view_management_screens, 'getLog')
    def getLog(self):
        """ Return the log """
        log = self._getLogStore()
        log_items = list(log.items())
        sort_f = lambda a, b: cmp(b[1]['total_count'], a[1]['total_count'])
        log_items.sort(sort_f)
        
        return log_items


    security.declareProtected(view_management_screens, 'clearLog')
    def clearLog(self, REQUEST=None):
        """ Clear out the log """
        self._getLogStore().clear()

        if REQUEST is not None:
            msg = 'Log cleared'
            return self.manage_log(manage_tabs_message=msg)



    security.declareProtected(view_management_screens, 'getDefaultRedirect')
    def getDefaultRedirect(self):
        """ Return the default redirect path value """
        return self._default_redirect


    security.declareProtected(manage_properties, 'addRedirectorMapping')
    def addRedirectorMapping( self
                            , old_path
                            , new_path
                            , redir_status='301'
                            , case_insensitive=0
                            , is_wildcard=0
                            , REQUEST=None 
                            ):
        """ Add a new redirector mapping """
        if old_path.endswith('/'):
            old_path = old_path[:-1]

        if case_insensitive:
            old_path = old_path.lower()

        self._redirects[old_path] = { 'redir_path' : new_path
                                    , 'redir_status' : redir_status
                                    , 'case_insensitive' : case_insensitive
                                    , 'is_wildcard' : is_wildcard
                                    }

        if REQUEST is not None:
            msg = 'Mapping added'
            return self.manage_map(manage_tabs_message=msg)
    

    security.declareProtected(manage_properties, 'deleteRedirectorMapping')
    def deleteRedirectorMappings(self, old_paths, REQUEST=None):
        """ Delete a redirector mapping """
        for old_path in old_paths:
            if self._redirects.has_key(old_path):
                del self._redirects[old_path]

        if REQUEST is not None:
            msg = 'Mapping deleted'
            return self.manage_map(manage_tabs_message=msg)


def manage_addJRedirector( self
                         , id
                         , title=''
                         , default_redirect=''
                         , loglevel=3
                         , REQUEST=None 
                         ):
    """ Called by Zope if you create a JRedirector from the ZMI """

    if hasattr(self.this().aq_base, id) and REQUEST is not None:
        msg = 'Object already contains an item with id %s' % id
        return MessageDialog( title  = 'Item Exists'
                            , message = msg
                            , action ='%s/manage_main' % REQUEST['URL1']
                            )

    jr = JRedirector(id, title, default_redirect, loglevel)
    self._setObject(jr.getId(), jr)

    if REQUEST is not None:
        return self.manage_main(self, REQUEST)
        

InitializeClass(JRedirector)