We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
REGEXP not present in PostgreSQL
Postgres [fails on Travis tests](https://travis-ci.org/dwaynebailey/pootle/jobs/50400894#L2516) because of the use of [NOT REGEXP](http://dev.mysql.com/doc/refman/5.1/en/regexp.html#operator_not-regexp)

The equivalent in Postgres is to use [POSIX Regular Expressions](http://www.postgresql.org/docs/9.3/static/functions-matching.html#FUNCTIONS-POSIX-REGEXP)


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `pootle/core/decorators.py`
Content:
```
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3 #
4 # Copyright 2013 Zuza Software Foundation
5 # Copyright 2013-2015 Evernote Corporation
6 #
7 # This file is part of Pootle.
8 #
9 # Pootle is free software; you can redistribute it and/or modify
10 # it under the terms of the GNU General Public License as published by
11 # the Free Software Foundation; either version 2 of the License, or
12 # (at your option) any later version.
13 #
14 # This program is distributed in the hope that it will be useful,
15 # but WITHOUT ANY WARRANTY; without even the implied warranty of
16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 # GNU General Public License for more details.
18 #
19 # You should have received a copy of the GNU General Public License
20 # along with this program; if not, see <http://www.gnu.org/licenses/>.
21 
22 from functools import wraps
23 
24 from django.contrib.auth import get_user_model
25 from django.core.exceptions import PermissionDenied
26 from django.core.urlresolvers import reverse
27 from django.http import Http404
28 from django.shortcuts import get_object_or_404, redirect
29 from django.utils.translation import ugettext as _
30 
31 from pootle_app.models.directory import Directory
32 from pootle_app.models.permissions import (check_permission,
33                                            get_matching_permissions)
34 from pootle_language.models import Language
35 from pootle_project.models import Project, ProjectSet, ProjectResource
36 from pootle_store.models import Store
37 from pootle_translationproject.models import TranslationProject
38 
39 from .exceptions import Http400
40 from .url_helpers import split_pootle_path
41 
42 
43 CLS2ATTR = {
44     'TranslationProject': 'translation_project',
45     'Project': 'project',
46     'Language': 'language',
47 }
48 
49 
50 def get_path_obj(func):
51     @wraps(func)
52     def wrapped(request, *args, **kwargs):
53         if request.is_ajax():
54             pootle_path = request.GET.get('path', None)
55             if pootle_path is None:
56                 raise Http400(_('Arguments missing.'))
57 
58             language_code, project_code, dir_path, filename = \
59                 split_pootle_path(pootle_path)
60             kwargs['dir_path'] = dir_path
61             kwargs['filename'] = filename
62         else:
63             language_code = kwargs.pop('language_code', None)
64             project_code = kwargs.pop('project_code', None)
65 
66         if language_code and project_code:
67             try:
68                 path_obj = TranslationProject.objects.enabled().get(
69                     language__code=language_code,
70                     project__code=project_code,
71                 )
72             except TranslationProject.DoesNotExist:
73                 path_obj = None
74 
75             if path_obj is None and not request.is_ajax():
76                 # Explicit selection via the UI: redirect either to
77                 # ``/language_code/`` or ``/projects/project_code/``
78                 user_choice = request.COOKIES.get('user-choice', None)
79                 if user_choice and user_choice in ('language', 'project',):
80                     url = {
81                         'language': reverse('pootle-language-overview',
82                                             args=[language_code]),
83                         'project': reverse('pootle-project-overview',
84                                            args=[project_code, '', '']),
85                     }
86                     response = redirect(url[user_choice])
87                     response.delete_cookie('user-choice')
88 
89                     return response
90 
91                 raise Http404
92         elif language_code:
93             user_projects = Project.accessible_by_user(request.user)
94             language = get_object_or_404(Language, code=language_code)
95             children = language.children \
96                                .filter(project__code__in=user_projects)
97             language.set_children(children)
98             path_obj = language
99         elif project_code:
100             try:
101                 path_obj = Project.objects.get_for_user(project_code,
102                                                         request.user)
103             except Project.DoesNotExist:
104                 raise Http404
105         else:  # No arguments: all user-accessible projects
106             user_projects = Project.accessible_by_user(request.user)
107             user_projects = Project.objects.for_user(request.user) \
108                                            .filter(code__in=user_projects)
109 
110             path_obj = ProjectSet(user_projects)
111 
112         request.ctx_obj = path_obj
113         request.ctx_path = path_obj.pootle_path
114         request.resource_obj = path_obj
115         request.pootle_path = path_obj.pootle_path
116 
117         return func(request, path_obj, *args, **kwargs)
118 
119     return wrapped
120 
121 
122 def set_resource(request, path_obj, dir_path, filename):
123     """Loads :cls:`pootle_app.models.Directory` and
124     :cls:`pootle_store.models.Store` models and populates the
125     request object.
126 
127     :param path_obj: A path-like object object.
128     :param dir_path: Path relative to the root of `path_obj`.
129     :param filename: Optional filename.
130     """
131     obj_directory = getattr(path_obj, 'directory', path_obj)
132     ctx_path = obj_directory.pootle_path
133     resource_path = dir_path
134     pootle_path = ctx_path + dir_path
135 
136     directory = None
137     store = None
138 
139     is_404 = False
140 
141     if filename:
142         pootle_path = pootle_path + filename
143         resource_path = resource_path + filename
144 
145         try:
146             store = Store.objects.select_related(
147                 'translation_project',
148                 'parent',
149             ).get(pootle_path=pootle_path)
150             directory = store.parent
151         except Store.DoesNotExist:
152             is_404 = True
153 
154     if directory is None and not is_404:
155         if dir_path:
156             try:
157                 directory = Directory.objects.get(pootle_path=pootle_path)
158             except Directory.DoesNotExist:
159                 is_404 = True
160         else:
161             directory = obj_directory
162 
163     if is_404:  # Try parent directory
164         language_code, project_code, dp, fn = split_pootle_path(pootle_path)
165         if not filename:
166             dir_path = dir_path[:dir_path[:-1].rfind('/') + 1]
167 
168         url = reverse('pootle-tp-overview',
169                       args=[language_code, project_code, dir_path])
170         request.redirect_url = url
171 
172         raise Http404
173 
174     request.store = store
175     request.directory = directory
176     request.pootle_path = pootle_path
177 
178     request.resource_obj = store or (directory if dir_path else path_obj)
179     request.resource_path = resource_path
180     request.ctx_obj = path_obj or request.resource_obj
181     request.ctx_path = ctx_path
182 
183 
184 def set_project_resource(request, path_obj, dir_path, filename):
185     """Loads :cls:`pootle_app.models.Directory` and
186     :cls:`pootle_store.models.Store` models and populates the
187     request object.
188 
189     This is the same as `set_resource` but operates at the project level
190     across all languages.
191 
192     :param path_obj: A :cls:`pootle_project.models.Project` object.
193     :param dir_path: Path relative to the root of `path_obj`.
194     :param filename: Optional filename.
195     """
196     query_ctx_path = ''.join(['/%/', path_obj.code, '/'])
197     query_pootle_path = query_ctx_path + dir_path
198 
199     obj_directory = getattr(path_obj, 'directory', path_obj)
200     ctx_path = obj_directory.pootle_path
201     resource_path = dir_path
202     pootle_path = ctx_path + dir_path
203 
204     # List of disabled TP paths
205     disabled_tps = TranslationProject.objects.disabled().filter(
206         project__code=path_obj.code,
207     ).values_list('pootle_path', flat=True)
208     disabled_tps = list(disabled_tps)
209     disabled_tps.append('/templates/')
210     disabled_tps_regex = '^%s' % u'|'.join(disabled_tps)
211 
212     if filename:
213         query_pootle_path = query_pootle_path + filename
214         pootle_path = pootle_path + filename
215         resource_path = resource_path + filename
216 
217         resources = Store.objects.extra(
218             where=[
219                 'pootle_store_store.pootle_path LIKE %s',
220                 'pootle_store_store.pootle_path NOT REGEXP %s',
221             ], params=[query_pootle_path, disabled_tps_regex]
222         ).select_related('translation_project__language')
223     else:
224         resources = Directory.objects.extra(
225             where=[
226                 'pootle_app_directory.pootle_path LIKE %s',
227                 'pootle_app_directory.pootle_path NOT REGEXP %s',
228             ], params=[query_pootle_path, disabled_tps_regex]
229         ).select_related('parent')
230 
231     if not resources.exists():
232         raise Http404
233 
234     request.store = None
235     request.directory = None
236     request.pootle_path = pootle_path
237 
238     request.resource_obj = ProjectResource(resources, pootle_path)
239     request.resource_path = resource_path
240     request.ctx_obj = path_obj or request.resource_obj
241     request.ctx_path = ctx_path
242 
243 
244 def get_resource(func):
245     @wraps(func)
246     def wrapped(request, path_obj, dir_path, filename):
247         """Gets resources associated to the current context."""
248         try:
249             directory = getattr(path_obj, 'directory', path_obj)
250             if directory.is_project() and (dir_path or filename):
251                 set_project_resource(request, path_obj, dir_path, filename)
252             else:
253                 set_resource(request, path_obj, dir_path, filename)
254         except Http404:
255             if not request.is_ajax():
256                 user_choice = request.COOKIES.get('user-choice', None)
257                 url = None
258 
259                 if hasattr(request, 'redirect_url'):
260                     url = request.redirect_url
261                 elif user_choice in ('language', 'resource',):
262                     project = (path_obj if isinstance(path_obj, Project)
263                                         else path_obj.project)
264                     url = reverse('pootle-project-overview',
265                                   args=[project.code, dir_path, filename])
266 
267                 if url is not None:
268                     response = redirect(url)
269 
270                     if user_choice in ('language', 'resource',):
271                         # XXX: should we rather delete this in a single place?
272                         response.delete_cookie('user-choice')
273 
274                     return response
275 
276             raise Http404
277 
278         return func(request, path_obj, dir_path, filename)
279 
280     return wrapped
281 
282 
283 def permission_required(permission_code):
284     """Checks for `permission_code` in the current context.
285 
286     To retrieve the proper context, the `get_path_obj` decorator must be
287     used along with this decorator.
288     """
289     def wrapped(func):
290         @wraps(func)
291         def _wrapped(request, *args, **kwargs):
292             path_obj = args[0]
293             directory = getattr(path_obj, 'directory', path_obj)
294 
295             # HACKISH: some old code relies on
296             # `request.translation_project`, `request.language` etc.
297             # being set, so we need to set that too.
298             attr_name = CLS2ATTR.get(path_obj.__class__.__name__,
299                                      'path_obj')
300             setattr(request, attr_name, path_obj)
301 
302             User = get_user_model()
303             request.profile = User.get(request.user)
304             request.permissions = get_matching_permissions(request.profile,
305                                                            directory)
306 
307             if not permission_code:
308                 return func(request, *args, **kwargs)
309 
310             if not check_permission(permission_code, request):
311                 raise PermissionDenied(
312                     _("Insufficient rights to access this page."),
313                 )
314 
315             return func(request, *args, **kwargs)
316         return _wrapped
317     return wrapped
318 
319 
320 def admin_required(func):
321     @wraps(func)
322     def wrapped(request, *args, **kwargs):
323         if not request.user.is_superuser:
324             raise PermissionDenied(
325                 _("You do not have rights to administer Pootle.")
326             )
327         return func(request, *args, **kwargs)
328 
329     return wrapped
330
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/pootle/core/decorators.py b/pootle/core/decorators.py
--- a/pootle/core/decorators.py
+++ b/pootle/core/decorators.py
@@ -24,6 +24,7 @@
 from django.contrib.auth import get_user_model
 from django.core.exceptions import PermissionDenied
 from django.core.urlresolvers import reverse
+from django.db import connection
 from django.http import Http404
 from django.shortcuts import get_object_or_404, redirect
 from django.utils.translation import ugettext as _
@@ -208,6 +209,9 @@
     disabled_tps = list(disabled_tps)
     disabled_tps.append('/templates/')
     disabled_tps_regex = '^%s' % u'|'.join(disabled_tps)
+    sql_not_regex = 'NOT REGEXP'
+    if connection.vendor == 'postgresql':
+        sql_not_regex = '!~'
 
     if filename:
         query_pootle_path = query_pootle_path + filename
@@ -217,14 +221,14 @@
         resources = Store.objects.extra(
             where=[
                 'pootle_store_store.pootle_path LIKE %s',
-                'pootle_store_store.pootle_path NOT REGEXP %s',
+                'pootle_store_store.pootle_path ' + sql_not_regex + ' %s',
             ], params=[query_pootle_path, disabled_tps_regex]
         ).select_related('translation_project__language')
     else:
         resources = Directory.objects.extra(
             where=[
                 'pootle_app_directory.pootle_path LIKE %s',
-                'pootle_app_directory.pootle_path NOT REGEXP %s',
+                'pootle_app_directory.pootle_path ' + sql_not_regex + ' %s',
             ], params=[query_pootle_path, disabled_tps_regex]
         ).select_related('parent')

{"golden_diff": "diff --git a/pootle/core/decorators.py b/pootle/core/decorators.py\n--- a/pootle/core/decorators.py\n+++ b/pootle/core/decorators.py\n@@ -24,6 +24,7 @@\n from django.contrib.auth import get_user_model\n from django.core.exceptions import PermissionDenied\n from django.core.urlresolvers import reverse\n+from django.db import connection\n from django.http import Http404\n from django.shortcuts import get_object_or_404, redirect\n from django.utils.translation import ugettext as _\n@@ -208,6 +209,9 @@\n     disabled_tps = list(disabled_tps)\n     disabled_tps.append('/templates/')\n     disabled_tps_regex = '^%s' % u'|'.join(disabled_tps)\n+    sql_not_regex = 'NOT REGEXP'\n+    if connection.vendor == 'postgresql':\n+        sql_not_regex = '!~'\n \n     if filename:\n         query_pootle_path = query_pootle_path + filename\n@@ -217,14 +221,14 @@\n         resources = Store.objects.extra(\n             where=[\n                 'pootle_store_store.pootle_path LIKE %s',\n-                'pootle_store_store.pootle_path NOT REGEXP %s',\n+                'pootle_store_store.pootle_path ' + sql_not_regex + ' %s',\n             ], params=[query_pootle_path, disabled_tps_regex]\n         ).select_related('translation_project__language')\n     else:\n         resources = Directory.objects.extra(\n             where=[\n                 'pootle_app_directory.pootle_path LIKE %s',\n-                'pootle_app_directory.pootle_path NOT REGEXP %s',\n+                'pootle_app_directory.pootle_path ' + sql_not_regex + ' %s',\n             ], params=[query_pootle_path, disabled_tps_regex]\n         ).select_related('parent')\n", "issue": "REGEXP not present in PostgreSQL\nPostgres [fails on Travis tests](https://travis-ci.org/dwaynebailey/pootle/jobs/50400894#L2516) because of the use of [NOT REGEXP](http://dev.mysql.com/doc/refman/5.1/en/regexp.html#operator_not-regexp)\n\nThe equivalent in Postgres is to use [POSIX Regular Expressions](http://www.postgresql.org/docs/9.3/static/functions-matching.html#FUNCTIONS-POSIX-REGEXP)\n\n", "before_files": [{"content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# Copyright 2013 Zuza Software Foundation\n# Copyright 2013-2015 Evernote Corporation\n#\n# This file is part of Pootle.\n#\n# Pootle is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; either version 2 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, see <http://www.gnu.org/licenses/>.\n\nfrom functools import wraps\n\nfrom django.contrib.auth import get_user_model\nfrom django.core.exceptions import PermissionDenied\nfrom django.core.urlresolvers import reverse\nfrom django.http import Http404\nfrom django.shortcuts import get_object_or_404, redirect\nfrom django.utils.translation import ugettext as _\n\nfrom pootle_app.models.directory import Directory\nfrom pootle_app.models.permissions import (check_permission,\n                                           get_matching_permissions)\nfrom pootle_language.models import Language\nfrom pootle_project.models import Project, ProjectSet, ProjectResource\nfrom pootle_store.models import Store\nfrom pootle_translationproject.models import TranslationProject\n\nfrom .exceptions import Http400\nfrom .url_helpers import split_pootle_path\n\n\nCLS2ATTR = {\n    'TranslationProject': 'translation_project',\n    'Project': 'project',\n    'Language': 'language',\n}\n\n\ndef get_path_obj(func):\n    @wraps(func)\n    def wrapped(request, *args, **kwargs):\n        if request.is_ajax():\n            pootle_path = request.GET.get('path', None)\n            if pootle_path is None:\n                raise Http400(_('Arguments missing.'))\n\n            language_code, project_code, dir_path, filename = \\\n                split_pootle_path(pootle_path)\n            kwargs['dir_path'] = dir_path\n            kwargs['filename'] = filename\n        else:\n            language_code = kwargs.pop('language_code', None)\n            project_code = kwargs.pop('project_code', None)\n\n        if language_code and project_code:\n            try:\n                path_obj = TranslationProject.objects.enabled().get(\n                    language__code=language_code,\n                    project__code=project_code,\n                )\n            except TranslationProject.DoesNotExist:\n                path_obj = None\n\n            if path_obj is None and not request.is_ajax():\n                # Explicit selection via the UI: redirect either to\n                # ``/language_code/`` or ``/projects/project_code/``\n                user_choice = request.COOKIES.get('user-choice', None)\n                if user_choice and user_choice in ('language', 'project',):\n                    url = {\n                        'language': reverse('pootle-language-overview',\n                                            args=[language_code]),\n                        'project': reverse('pootle-project-overview',\n                                           args=[project_code, '', '']),\n                    }\n                    response = redirect(url[user_choice])\n                    response.delete_cookie('user-choice')\n\n                    return response\n\n                raise Http404\n        elif language_code:\n            user_projects = Project.accessible_by_user(request.user)\n            language = get_object_or_404(Language, code=language_code)\n            children = language.children \\\n                               .filter(project__code__in=user_projects)\n            language.set_children(children)\n            path_obj = language\n        elif project_code:\n            try:\n                path_obj = Project.objects.get_for_user(project_code,\n                                                        request.user)\n            except Project.DoesNotExist:\n                raise Http404\n        else:  # No arguments: all user-accessible projects\n            user_projects = Project.accessible_by_user(request.user)\n            user_projects = Project.objects.for_user(request.user) \\\n                                           .filter(code__in=user_projects)\n\n            path_obj = ProjectSet(user_projects)\n\n        request.ctx_obj = path_obj\n        request.ctx_path = path_obj.pootle_path\n        request.resource_obj = path_obj\n        request.pootle_path = path_obj.pootle_path\n\n        return func(request, path_obj, *args, **kwargs)\n\n    return wrapped\n\n\ndef set_resource(request, path_obj, dir_path, filename):\n    \"\"\"Loads :cls:`pootle_app.models.Directory` and\n    :cls:`pootle_store.models.Store` models and populates the\n    request object.\n\n    :param path_obj: A path-like object object.\n    :param dir_path: Path relative to the root of `path_obj`.\n    :param filename: Optional filename.\n    \"\"\"\n    obj_directory = getattr(path_obj, 'directory', path_obj)\n    ctx_path = obj_directory.pootle_path\n    resource_path = dir_path\n    pootle_path = ctx_path + dir_path\n\n    directory = None\n    store = None\n\n    is_404 = False\n\n    if filename:\n        pootle_path = pootle_path + filename\n        resource_path = resource_path + filename\n\n        try:\n            store = Store.objects.select_related(\n                'translation_project',\n                'parent',\n            ).get(pootle_path=pootle_path)\n            directory = store.parent\n        except Store.DoesNotExist:\n            is_404 = True\n\n    if directory is None and not is_404:\n        if dir_path:\n            try:\n                directory = Directory.objects.get(pootle_path=pootle_path)\n            except Directory.DoesNotExist:\n                is_404 = True\n        else:\n            directory = obj_directory\n\n    if is_404:  # Try parent directory\n        language_code, project_code, dp, fn = split_pootle_path(pootle_path)\n        if not filename:\n            dir_path = dir_path[:dir_path[:-1].rfind('/') + 1]\n\n        url = reverse('pootle-tp-overview',\n                      args=[language_code, project_code, dir_path])\n        request.redirect_url = url\n\n        raise Http404\n\n    request.store = store\n    request.directory = directory\n    request.pootle_path = pootle_path\n\n    request.resource_obj = store or (directory if dir_path else path_obj)\n    request.resource_path = resource_path\n    request.ctx_obj = path_obj or request.resource_obj\n    request.ctx_path = ctx_path\n\n\ndef set_project_resource(request, path_obj, dir_path, filename):\n    \"\"\"Loads :cls:`pootle_app.models.Directory` and\n    :cls:`pootle_store.models.Store` models and populates the\n    request object.\n\n    This is the same as `set_resource` but operates at the project level\n    across all languages.\n\n    :param path_obj: A :cls:`pootle_project.models.Project` object.\n    :param dir_path: Path relative to the root of `path_obj`.\n    :param filename: Optional filename.\n    \"\"\"\n    query_ctx_path = ''.join(['/%/', path_obj.code, '/'])\n    query_pootle_path = query_ctx_path + dir_path\n\n    obj_directory = getattr(path_obj, 'directory', path_obj)\n    ctx_path = obj_directory.pootle_path\n    resource_path = dir_path\n    pootle_path = ctx_path + dir_path\n\n    # List of disabled TP paths\n    disabled_tps = TranslationProject.objects.disabled().filter(\n        project__code=path_obj.code,\n    ).values_list('pootle_path', flat=True)\n    disabled_tps = list(disabled_tps)\n    disabled_tps.append('/templates/')\n    disabled_tps_regex = '^%s' % u'|'.join(disabled_tps)\n\n    if filename:\n        query_pootle_path = query_pootle_path + filename\n        pootle_path = pootle_path + filename\n        resource_path = resource_path + filename\n\n        resources = Store.objects.extra(\n            where=[\n                'pootle_store_store.pootle_path LIKE %s',\n                'pootle_store_store.pootle_path NOT REGEXP %s',\n            ], params=[query_pootle_path, disabled_tps_regex]\n        ).select_related('translation_project__language')\n    else:\n        resources = Directory.objects.extra(\n            where=[\n                'pootle_app_directory.pootle_path LIKE %s',\n                'pootle_app_directory.pootle_path NOT REGEXP %s',\n            ], params=[query_pootle_path, disabled_tps_regex]\n        ).select_related('parent')\n\n    if not resources.exists():\n        raise Http404\n\n    request.store = None\n    request.directory = None\n    request.pootle_path = pootle_path\n\n    request.resource_obj = ProjectResource(resources, pootle_path)\n    request.resource_path = resource_path\n    request.ctx_obj = path_obj or request.resource_obj\n    request.ctx_path = ctx_path\n\n\ndef get_resource(func):\n    @wraps(func)\n    def wrapped(request, path_obj, dir_path, filename):\n        \"\"\"Gets resources associated to the current context.\"\"\"\n        try:\n            directory = getattr(path_obj, 'directory', path_obj)\n            if directory.is_project() and (dir_path or filename):\n                set_project_resource(request, path_obj, dir_path, filename)\n            else:\n                set_resource(request, path_obj, dir_path, filename)\n        except Http404:\n            if not request.is_ajax():\n                user_choice = request.COOKIES.get('user-choice', None)\n                url = None\n\n                if hasattr(request, 'redirect_url'):\n                    url = request.redirect_url\n                elif user_choice in ('language', 'resource',):\n                    project = (path_obj if isinstance(path_obj, Project)\n                                        else path_obj.project)\n                    url = reverse('pootle-project-overview',\n                                  args=[project.code, dir_path, filename])\n\n                if url is not None:\n                    response = redirect(url)\n\n                    if user_choice in ('language', 'resource',):\n                        # XXX: should we rather delete this in a single place?\n                        response.delete_cookie('user-choice')\n\n                    return response\n\n            raise Http404\n\n        return func(request, path_obj, dir_path, filename)\n\n    return wrapped\n\n\ndef permission_required(permission_code):\n    \"\"\"Checks for `permission_code` in the current context.\n\n    To retrieve the proper context, the `get_path_obj` decorator must be\n    used along with this decorator.\n    \"\"\"\n    def wrapped(func):\n        @wraps(func)\n        def _wrapped(request, *args, **kwargs):\n            path_obj = args[0]\n            directory = getattr(path_obj, 'directory', path_obj)\n\n            # HACKISH: some old code relies on\n            # `request.translation_project`, `request.language` etc.\n            # being set, so we need to set that too.\n            attr_name = CLS2ATTR.get(path_obj.__class__.__name__,\n                                     'path_obj')\n            setattr(request, attr_name, path_obj)\n\n            User = get_user_model()\n            request.profile = User.get(request.user)\n            request.permissions = get_matching_permissions(request.profile,\n                                                           directory)\n\n            if not permission_code:\n                return func(request, *args, **kwargs)\n\n            if not check_permission(permission_code, request):\n                raise PermissionDenied(\n                    _(\"Insufficient rights to access this page.\"),\n                )\n\n            return func(request, *args, **kwargs)\n        return _wrapped\n    return wrapped\n\n\ndef admin_required(func):\n    @wraps(func)\n    def wrapped(request, *args, **kwargs):\n        if not request.user.is_superuser:\n            raise PermissionDenied(\n                _(\"You do not have rights to administer Pootle.\")\n            )\n        return func(request, *args, **kwargs)\n\n    return wrapped\n", "path": "pootle/core/decorators.py"}], "after_files": [{"content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# Copyright 2013 Zuza Software Foundation\n# Copyright 2013-2015 Evernote Corporation\n#\n# This file is part of Pootle.\n#\n# Pootle is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; either version 2 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, see <http://www.gnu.org/licenses/>.\n\nfrom functools import wraps\n\nfrom django.contrib.auth import get_user_model\nfrom django.core.exceptions import PermissionDenied\nfrom django.core.urlresolvers import reverse\nfrom django.db import connection\nfrom django.http import Http404\nfrom django.shortcuts import get_object_or_404, redirect\nfrom django.utils.translation import ugettext as _\n\nfrom pootle_app.models.directory import Directory\nfrom pootle_app.models.permissions import (check_permission,\n                                           get_matching_permissions)\nfrom pootle_language.models import Language\nfrom pootle_project.models import Project, ProjectSet, ProjectResource\nfrom pootle_store.models import Store\nfrom pootle_translationproject.models import TranslationProject\n\nfrom .exceptions import Http400\nfrom .url_helpers import split_pootle_path\n\n\nCLS2ATTR = {\n    'TranslationProject': 'translation_project',\n    'Project': 'project',\n    'Language': 'language',\n}\n\n\ndef get_path_obj(func):\n    @wraps(func)\n    def wrapped(request, *args, **kwargs):\n        if request.is_ajax():\n            pootle_path = request.GET.get('path', None)\n            if pootle_path is None:\n                raise Http400(_('Arguments missing.'))\n\n            language_code, project_code, dir_path, filename = \\\n                split_pootle_path(pootle_path)\n            kwargs['dir_path'] = dir_path\n            kwargs['filename'] = filename\n        else:\n            language_code = kwargs.pop('language_code', None)\n            project_code = kwargs.pop('project_code', None)\n\n        if language_code and project_code:\n            try:\n                path_obj = TranslationProject.objects.enabled().get(\n                    language__code=language_code,\n                    project__code=project_code,\n                )\n            except TranslationProject.DoesNotExist:\n                path_obj = None\n\n            if path_obj is None and not request.is_ajax():\n                # Explicit selection via the UI: redirect either to\n                # ``/language_code/`` or ``/projects/project_code/``\n                user_choice = request.COOKIES.get('user-choice', None)\n                if user_choice and user_choice in ('language', 'project',):\n                    url = {\n                        'language': reverse('pootle-language-overview',\n                                            args=[language_code]),\n                        'project': reverse('pootle-project-overview',\n                                           args=[project_code, '', '']),\n                    }\n                    response = redirect(url[user_choice])\n                    response.delete_cookie('user-choice')\n\n                    return response\n\n                raise Http404\n        elif language_code:\n            user_projects = Project.accessible_by_user(request.user)\n            language = get_object_or_404(Language, code=language_code)\n            children = language.children \\\n                               .filter(project__code__in=user_projects)\n            language.set_children(children)\n            path_obj = language\n        elif project_code:\n            try:\n                path_obj = Project.objects.get_for_user(project_code,\n                                                        request.user)\n            except Project.DoesNotExist:\n                raise Http404\n        else:  # No arguments: all user-accessible projects\n            user_projects = Project.accessible_by_user(request.user)\n            user_projects = Project.objects.for_user(request.user) \\\n                                           .filter(code__in=user_projects)\n\n            path_obj = ProjectSet(user_projects)\n\n        request.ctx_obj = path_obj\n        request.ctx_path = path_obj.pootle_path\n        request.resource_obj = path_obj\n        request.pootle_path = path_obj.pootle_path\n\n        return func(request, path_obj, *args, **kwargs)\n\n    return wrapped\n\n\ndef set_resource(request, path_obj, dir_path, filename):\n    \"\"\"Loads :cls:`pootle_app.models.Directory` and\n    :cls:`pootle_store.models.Store` models and populates the\n    request object.\n\n    :param path_obj: A path-like object object.\n    :param dir_path: Path relative to the root of `path_obj`.\n    :param filename: Optional filename.\n    \"\"\"\n    obj_directory = getattr(path_obj, 'directory', path_obj)\n    ctx_path = obj_directory.pootle_path\n    resource_path = dir_path\n    pootle_path = ctx_path + dir_path\n\n    directory = None\n    store = None\n\n    is_404 = False\n\n    if filename:\n        pootle_path = pootle_path + filename\n        resource_path = resource_path + filename\n\n        try:\n            store = Store.objects.select_related(\n                'translation_project',\n                'parent',\n            ).get(pootle_path=pootle_path)\n            directory = store.parent\n        except Store.DoesNotExist:\n            is_404 = True\n\n    if directory is None and not is_404:\n        if dir_path:\n            try:\n                directory = Directory.objects.get(pootle_path=pootle_path)\n            except Directory.DoesNotExist:\n                is_404 = True\n        else:\n            directory = obj_directory\n\n    if is_404:  # Try parent directory\n        language_code, project_code, dp, fn = split_pootle_path(pootle_path)\n        if not filename:\n            dir_path = dir_path[:dir_path[:-1].rfind('/') + 1]\n\n        url = reverse('pootle-tp-overview',\n                      args=[language_code, project_code, dir_path])\n        request.redirect_url = url\n\n        raise Http404\n\n    request.store = store\n    request.directory = directory\n    request.pootle_path = pootle_path\n\n    request.resource_obj = store or (directory if dir_path else path_obj)\n    request.resource_path = resource_path\n    request.ctx_obj = path_obj or request.resource_obj\n    request.ctx_path = ctx_path\n\n\ndef set_project_resource(request, path_obj, dir_path, filename):\n    \"\"\"Loads :cls:`pootle_app.models.Directory` and\n    :cls:`pootle_store.models.Store` models and populates the\n    request object.\n\n    This is the same as `set_resource` but operates at the project level\n    across all languages.\n\n    :param path_obj: A :cls:`pootle_project.models.Project` object.\n    :param dir_path: Path relative to the root of `path_obj`.\n    :param filename: Optional filename.\n    \"\"\"\n    query_ctx_path = ''.join(['/%/', path_obj.code, '/'])\n    query_pootle_path = query_ctx_path + dir_path\n\n    obj_directory = getattr(path_obj, 'directory', path_obj)\n    ctx_path = obj_directory.pootle_path\n    resource_path = dir_path\n    pootle_path = ctx_path + dir_path\n\n    # List of disabled TP paths\n    disabled_tps = TranslationProject.objects.disabled().filter(\n        project__code=path_obj.code,\n    ).values_list('pootle_path', flat=True)\n    disabled_tps = list(disabled_tps)\n    disabled_tps.append('/templates/')\n    disabled_tps_regex = '^%s' % u'|'.join(disabled_tps)\n    sql_not_regex = 'NOT REGEXP'\n    if connection.vendor == 'postgresql':\n        sql_not_regex = '!~'\n\n    if filename:\n        query_pootle_path = query_pootle_path + filename\n        pootle_path = pootle_path + filename\n        resource_path = resource_path + filename\n\n        resources = Store.objects.extra(\n            where=[\n                'pootle_store_store.pootle_path LIKE %s',\n                'pootle_store_store.pootle_path ' + sql_not_regex + ' %s',\n            ], params=[query_pootle_path, disabled_tps_regex]\n        ).select_related('translation_project__language')\n    else:\n        resources = Directory.objects.extra(\n            where=[\n                'pootle_app_directory.pootle_path LIKE %s',\n                'pootle_app_directory.pootle_path ' + sql_not_regex + ' %s',\n            ], params=[query_pootle_path, disabled_tps_regex]\n        ).select_related('parent')\n\n    if not resources.exists():\n        raise Http404\n\n    request.store = None\n    request.directory = None\n    request.pootle_path = pootle_path\n\n    request.resource_obj = ProjectResource(resources, pootle_path)\n    request.resource_path = resource_path\n    request.ctx_obj = path_obj or request.resource_obj\n    request.ctx_path = ctx_path\n\n\ndef get_resource(func):\n    @wraps(func)\n    def wrapped(request, path_obj, dir_path, filename):\n        \"\"\"Gets resources associated to the current context.\"\"\"\n        try:\n            directory = getattr(path_obj, 'directory', path_obj)\n            if directory.is_project() and (dir_path or filename):\n                set_project_resource(request, path_obj, dir_path, filename)\n            else:\n                set_resource(request, path_obj, dir_path, filename)\n        except Http404:\n            if not request.is_ajax():\n                user_choice = request.COOKIES.get('user-choice', None)\n                url = None\n\n                if hasattr(request, 'redirect_url'):\n                    url = request.redirect_url\n                elif user_choice in ('language', 'resource',):\n                    project = (path_obj if isinstance(path_obj, Project)\n                                        else path_obj.project)\n                    url = reverse('pootle-project-overview',\n                                  args=[project.code, dir_path, filename])\n\n                if url is not None:\n                    response = redirect(url)\n\n                    if user_choice in ('language', 'resource',):\n                        # XXX: should we rather delete this in a single place?\n                        response.delete_cookie('user-choice')\n\n                    return response\n\n            raise Http404\n\n        return func(request, path_obj, dir_path, filename)\n\n    return wrapped\n\n\ndef permission_required(permission_code):\n    \"\"\"Checks for `permission_code` in the current context.\n\n    To retrieve the proper context, the `get_path_obj` decorator must be\n    used along with this decorator.\n    \"\"\"\n    def wrapped(func):\n        @wraps(func)\n        def _wrapped(request, *args, **kwargs):\n            path_obj = args[0]\n            directory = getattr(path_obj, 'directory', path_obj)\n\n            # HACKISH: some old code relies on\n            # `request.translation_project`, `request.language` etc.\n            # being set, so we need to set that too.\n            attr_name = CLS2ATTR.get(path_obj.__class__.__name__,\n                                     'path_obj')\n            setattr(request, attr_name, path_obj)\n\n            User = get_user_model()\n            request.profile = User.get(request.user)\n            request.permissions = get_matching_permissions(request.profile,\n                                                           directory)\n\n            if not permission_code:\n                return func(request, *args, **kwargs)\n\n            if not check_permission(permission_code, request):\n                raise PermissionDenied(\n                    _(\"Insufficient rights to access this page.\"),\n                )\n\n            return func(request, *args, **kwargs)\n        return _wrapped\n    return wrapped\n\n\ndef admin_required(func):\n    @wraps(func)\n    def wrapped(request, *args, **kwargs):\n        if not request.user.is_superuser:\n            raise PermissionDenied(\n                _(\"You do not have rights to administer Pootle.\")\n            )\n        return func(request, *args, **kwargs)\n\n    return wrapped\n", "path": "pootle/core/decorators.py"}]}