We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Localisation strings need to allow ordering
The following errors occur in `pootle makemessages` run via `make pot`.  These are strings where we're using multiple `%s` variables without names, thus they can't be reordered if required by the language.

```
./pootle/apps/import_export/utils.py:57: warning: 'msgid' format string with unnamed arguments cannot be properly localized:
                                                  The translator cannot reorder the arguments.
                                                  Please consider using a format string with named arguments,
                                                  and a mapping instead of a tuple for the arguments.
./pootle/apps/pootle_profile/templatetags/profile_tags.py:35: warning: 'msgid' format string with unnamed arguments cannot be properly localized:
                                                                       The translator cannot reorder the arguments.
                                                                       Please consider using a format string with named arguments,
                                                                       and a mapping instead of a tuple for the arguments.
./pootle/apps/pootle_profile/templatetags/profile_tags.py:52: warning: 'msgid' format string with unnamed arguments cannot be properly localized:
                                                                       The translator cannot reorder the arguments.
                                                                       Please consider using a format string with named arguments,
                                                                       and a mapping instead of a tuple for the arguments.
./pootle/apps/pootle_profile/templatetags/profile_tags.py:56: warning: 'msgid' format string with unnamed arguments cannot be properly localized:
                                                                       The translator cannot reorder the arguments.
                                                                       Please consider using a format string with named arguments,
                                                                       and a mapping instead of a tuple for the arguments.
```

--- 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/apps/pootle_profile/templatetags/profile_tags.py`
Content:
```
1 # -*- coding: utf-8 -*-
2 #
3 # Copyright (C) Pootle contributors.
4 #
5 # This file is a part of the Pootle project. It is distributed under the GPL3
6 # or later license. See the LICENSE file for a copy of the license and the
7 # AUTHORS file for copyright and authorship information.
8 
9 import urllib
10 
11 from django import template
12 from django.conf import settings
13 from django.core.urlresolvers import reverse
14 from django.utils.safestring import mark_safe
15 
16 from pootle.i18n.gettext import ugettext_lazy as _
17 
18 
19 register = template.Library()
20 
21 
22 @register.filter
23 def gravatar(user, size):
24     return user.gravatar_url(size)
25 
26 
27 @register.inclusion_tag("user/includes/profile_score.html")
28 def profile_score(request, profile):
29     context = dict(profile=profile)
30     top_lang = profile.scores.top_language
31     context["own_profile"] = request.user == profile.user
32     if top_lang and not top_lang[0] == -1 and top_lang[1]:
33         if context["own_profile"]:
34             score_tweet_content = _(
35                 "My current score at %s is %s"
36                 % (settings.POOTLE_TITLE,
37                    profile.scores.public_score))
38             context["score_tweet_message"] = _("Tweet this!")
39             context["score_tweet_link"] = (
40                 "https://twitter.com/share?text=%s"
41                 % urllib.quote_plus(score_tweet_content.encode("utf8")))
42     return context
43 
44 
45 @register.inclusion_tag("user/includes/profile_ranking.html")
46 def profile_ranking(request, profile):
47     context = dict(request=request, profile=profile)
48     top_lang = profile.scores.top_language
49     context["own_profile"] = request.user == profile.user
50     if top_lang and not top_lang[0] == -1 and top_lang[1]:
51         context["ranking_text"] = _(
52             "#%s contributor in %s in the last 30 days"
53             % (top_lang[0], top_lang[1].name))
54         if context["own_profile"]:
55             ranking_tweet_content = _(
56                 "I am #%s contributor in %s in the last 30 days at %s!"
57                 % (top_lang[0],
58                    top_lang[1].name,
59                    settings.POOTLE_TITLE))
60             context["ranking_tweet_link"] = (
61                 "https://twitter.com/share?text=%s"
62                 % urllib.quote_plus(ranking_tweet_content.encode("utf8")))
63             context["ranking_tweet_link_text"] = _("Tweet this!")
64     else:
65         context["no_ranking_text"] = _("No contributions in the last 30 days")
66     return context
67 
68 
69 @register.inclusion_tag("user/includes/profile_social.html")
70 def profile_social(profile):
71     links = []
72     if profile.user.website:
73         links.append(
74             dict(url=profile.user.website,
75                  icon="icon-user-website",
76                  text=_("My Website")))
77     if profile.user.twitter:
78         links.append(
79             dict(url=profile.user.twitter_url,
80                  icon="icon-user-twitter",
81                  text="@%s" % profile.user.twitter))
82     if profile.user.linkedin:
83         links.append(
84             dict(url=profile.user.linkedin,
85                  icon="icon-user-linkedin",
86                  text=_("My LinkedIn Profile")))
87     return dict(social_media_links=links)
88 
89 
90 @register.inclusion_tag("user/includes/profile_teams.html")
91 def profile_teams(request, profile):
92     teams = profile.membership.teams_and_roles
93     site_permissions = []
94     if not request.user.is_anonymous and profile.user.is_superuser:
95         site_permissions.append(_("Site administrator"))
96     for code, info in teams.items():
97         info["url"] = reverse(
98             "pootle-language-browse",
99             kwargs=dict(language_code=code))
100     teams_title = _(
101         "%s's language teams"
102         % profile.user.display_name)
103     no_teams_message = _(
104         "%s is not a member of any language teams"
105         % profile.user.display_name)
106     return dict(
107         anon_request=request.user.is_anonymous,
108         teams=teams,
109         teams_title=teams_title,
110         no_teams_message=no_teams_message,
111         site_permissions=site_permissions)
112 
113 
114 @register.inclusion_tag("user/includes/profile_user.html")
115 def profile_user(request, profile):
116     context = dict(request=request, profile=profile)
117     context['request_user_is_manager'] = (
118         request.user.has_manager_permissions())
119     if profile.user.is_anonymous:
120         context["bio"] = _(
121             "Some translations are provided by anonymous volunteers. "
122             "These are registered under this special meta-account.")
123     elif profile.user.is_system():
124         context["bio"] = _(
125             "Some translations are imported from external files. "
126             "These are registered under this special meta-account.")
127     else:
128         if request.user == profile.user:
129             context["can_edit_profile"] = True
130             context["should_edit_profile"] = (
131                 not profile.user.has_contact_details
132                 or not profile.user.bio)
133             if context["should_edit_profile"]:
134                 context["edit_profile_message"] = mark_safe(
135                     _("Show others who you are, tell about yourself<br/>"
136                       "and make your public profile look gorgeous!"))
137             context["user_title"] = _(
138                 "You can set or change your avatar image at www.gravatar.com")
139         if profile.user.bio:
140             context["bio"] = profile.user.bio
141     return context
142 
143 
144 @register.inclusion_tag("user/includes/profile_activity.html")
145 def profile_activity(profile, request_lang=None):
146     context = dict(profile=profile)
147     if profile.user.is_meta:
148         return context
149     context["user_last_event"] = (
150         context["profile"].user.last_event(locale=request_lang))
151     return context
152
```

Path: `pootle/apps/import_export/utils.py`
Content:
```
1 # -*- coding: utf-8 -*-
2 #
3 # Copyright (C) Pootle contributors.
4 #
5 # This file is a part of the Pootle project. It is distributed under the GPL3
6 # or later license. See the LICENSE file for a copy of the license and the
7 # AUTHORS file for copyright and authorship information.
8 
9 import logging
10 import os
11 from io import BytesIO
12 from zipfile import ZipFile
13 
14 from translate.storage import tmx
15 from translate.storage.factory import getclass
16 
17 from django.conf import settings
18 from django.utils.functional import cached_property
19 
20 from pootle.core.delegate import revision
21 from pootle.core.url_helpers import urljoin
22 from pootle.i18n.gettext import ugettext_lazy as _
23 from pootle_app.models.permissions import check_user_permission
24 from pootle_statistics.models import SubmissionTypes
25 from pootle_store.constants import TRANSLATED
26 from pootle_store.models import Store
27 
28 from .exceptions import (FileImportError, MissingPootlePathError,
29                          MissingPootleRevError, UnsupportedFiletypeError)
30 
31 
32 logger = logging.getLogger(__name__)
33 
34 
35 def import_file(f, user=None):
36     ttk = getclass(f)(f.read())
37     if not hasattr(ttk, "parseheader"):
38         raise UnsupportedFiletypeError(_("Unsupported filetype '%s', only PO "
39                                          "files are supported at this time\n",
40                                          f.name))
41     header = ttk.parseheader()
42     pootle_path = header.get("X-Pootle-Path")
43     if not pootle_path:
44         raise MissingPootlePathError(_("File '%s' missing X-Pootle-Path "
45                                        "header\n", f.name))
46 
47     rev = header.get("X-Pootle-Revision")
48     if not rev or not rev.isdigit():
49         raise MissingPootleRevError(_("File '%s' missing or invalid "
50                                       "X-Pootle-Revision header\n",
51                                       f.name))
52     rev = int(rev)
53 
54     try:
55         store = Store.objects.get(pootle_path=pootle_path)
56     except Store.DoesNotExist as e:
57         raise FileImportError(_("Could not create '%s'. Missing "
58                                 "Project/Language? (%s)", (f.name, e)))
59 
60     tp = store.translation_project
61     allow_add_and_obsolete = ((tp.project.checkstyle == 'terminology'
62                                or tp.is_template_project)
63                               and check_user_permission(user,
64                                                         'administrate',
65                                                         tp.directory))
66     try:
67         store.update(store=ttk, user=user,
68                      submission_type=SubmissionTypes.UPLOAD,
69                      store_revision=rev,
70                      allow_add_and_obsolete=allow_add_and_obsolete)
71     except Exception as e:
72         # This should not happen!
73         logger.error("Error importing file: %s", str(e))
74         raise FileImportError(_("There was an error uploading your file"))
75 
76 
77 class TPTMXExporter(object):
78 
79     def __init__(self, context):
80         self.context = context
81 
82     @cached_property
83     def exported_revision(self):
84         return revision.get(self.context.__class__)(
85             self.context).get(key="pootle.offline.tm")
86 
87     @cached_property
88     def revision(self):
89         return revision.get(self.context.__class__)(
90             self.context.directory).get(key="stats")[:10] or "0"
91 
92     def get_url(self):
93         if self.exported_revision:
94             relative_path = "offline_tm/%s/%s" % (
95                 self.context.language.code,
96                 self.get_filename(self.exported_revision)
97             )
98             return urljoin(settings.MEDIA_URL, relative_path)
99         return None
100 
101     def update_exported_revision(self):
102         if self.has_changes():
103             revision.get(self.context.__class__)(
104                 self.context).set(keys=["pootle.offline.tm"],
105                                   value=self.revision)
106             if "exported_revision" in self.__dict__:
107                 del self.__dict__["exported_revision"]
108 
109     def has_changes(self):
110         return self.revision != self.exported_revision
111 
112     def file_exists(self):
113         return os.path.exists(self.abs_filepath)
114 
115     @property
116     def last_exported_file_path(self):
117         if not self.exported_revision:
118             return None
119         exported_filename = self.get_filename(self.exported_revision)
120         return os.path.join(self.directory, exported_filename)
121 
122     def exported_file_exists(self):
123         if self.last_exported_file_path is None:
124             return False
125         return os.path.exists(self.last_exported_file_path)
126 
127     @property
128     def directory(self):
129         return os.path.join(settings.MEDIA_ROOT,
130                             'offline_tm',
131                             self.context.language.code)
132 
133     def get_filename(self, revision):
134         return ".".join([self.context.project.code,
135                          self.context.language.code, revision, 'tmx',
136                          'zip'])
137 
138     def check_tp(self, filename):
139         """Check if filename relates to the context TP."""
140 
141         return filename.startswith(".".join([
142             self.context.project.code,
143             self.context.language.code]))
144 
145     @property
146     def filename(self):
147         return self.get_filename(self.revision)
148 
149     @property
150     def abs_filepath(self):
151         return os.path.join(self.directory, self.filename)
152 
153     def export(self, rotate=False):
154         source_language = self.context.project.source_language.code
155         target_language = self.context.language.code
156 
157         if not os.path.exists(self.directory):
158             os.makedirs(self.directory)
159 
160         tmxfile = tmx.tmxfile()
161         for store in self.context.stores.live().iterator():
162             for unit in store.units.filter(state=TRANSLATED):
163                 tmxfile.addtranslation(unit.source, source_language,
164                                        unit.target, target_language,
165                                        unit.developer_comment)
166 
167         bs = BytesIO()
168         tmxfile.serialize(bs)
169         with open(self.abs_filepath, "wb") as f:
170             with ZipFile(f, "w") as zf:
171                 zf.writestr(self.filename.rstrip('.zip'), bs.getvalue())
172 
173         last_exported_filepath = self.last_exported_file_path
174         self.update_exported_revision()
175 
176         removed = []
177         if rotate:
178             for fn in os.listdir(self.directory):
179                 # Skip files from other projects.
180                 if not self.check_tp(fn):
181                     continue
182                 filepath = os.path.join(self.directory, fn)
183                 if filepath not in [self.abs_filepath, last_exported_filepath]:
184                     removed.append(filepath)
185                     os.remove(filepath)
186 
187         return self.abs_filepath, removed
188
```
--- 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/apps/import_export/utils.py b/pootle/apps/import_export/utils.py
--- a/pootle/apps/import_export/utils.py
+++ b/pootle/apps/import_export/utils.py
@@ -54,8 +54,10 @@
     try:
         store = Store.objects.get(pootle_path=pootle_path)
     except Store.DoesNotExist as e:
-        raise FileImportError(_("Could not create '%s'. Missing "
-                                "Project/Language? (%s)", (f.name, e)))
+        raise FileImportError(
+            _("Could not create '%(filename)s'. Missing "
+              "Project/Language? (%(error)s)",
+              dict(filename=f.name, error=e)))
 
     tp = store.translation_project
     allow_add_and_obsolete = ((tp.project.checkstyle == 'terminology'
diff --git a/pootle/apps/pootle_profile/templatetags/profile_tags.py b/pootle/apps/pootle_profile/templatetags/profile_tags.py
--- a/pootle/apps/pootle_profile/templatetags/profile_tags.py
+++ b/pootle/apps/pootle_profile/templatetags/profile_tags.py
@@ -32,9 +32,9 @@
     if top_lang and not top_lang[0] == -1 and top_lang[1]:
         if context["own_profile"]:
             score_tweet_content = _(
-                "My current score at %s is %s"
-                % (settings.POOTLE_TITLE,
-                   profile.scores.public_score))
+                "My current score at %(pootle_title)s is %(score)s",
+                dict(pootle_title=settings.POOTLE_TITLE,
+                     score=profile.scores.public_score))
             context["score_tweet_message"] = _("Tweet this!")
             context["score_tweet_link"] = (
                 "https://twitter.com/share?text=%s"
@@ -49,14 +49,15 @@
     context["own_profile"] = request.user == profile.user
     if top_lang and not top_lang[0] == -1 and top_lang[1]:
         context["ranking_text"] = _(
-            "#%s contributor in %s in the last 30 days"
-            % (top_lang[0], top_lang[1].name))
+            "#%(rank)s contributor in %(language)s in the last 30 days",
+            dict(rank=top_lang[0], language=top_lang[1].name))
         if context["own_profile"]:
             ranking_tweet_content = _(
-                "I am #%s contributor in %s in the last 30 days at %s!"
-                % (top_lang[0],
-                   top_lang[1].name,
-                   settings.POOTLE_TITLE))
+                "I am #%(rank)s contributor in %(language)s in the last 30 "
+                "days at %(pootle_title)s!",
+                dict(rank=top_lang[0],
+                     language=top_lang[1].name,
+                     pootle_title=settings.POOTLE_TITLE))
             context["ranking_tweet_link"] = (
                 "https://twitter.com/share?text=%s"
                 % urllib.quote_plus(ranking_tweet_content.encode("utf8")))

{"golden_diff": "diff --git a/pootle/apps/import_export/utils.py b/pootle/apps/import_export/utils.py\n--- a/pootle/apps/import_export/utils.py\n+++ b/pootle/apps/import_export/utils.py\n@@ -54,8 +54,10 @@\n     try:\n         store = Store.objects.get(pootle_path=pootle_path)\n     except Store.DoesNotExist as e:\n-        raise FileImportError(_(\"Could not create '%s'. Missing \"\n-                                \"Project/Language? (%s)\", (f.name, e)))\n+        raise FileImportError(\n+            _(\"Could not create '%(filename)s'. Missing \"\n+              \"Project/Language? (%(error)s)\",\n+              dict(filename=f.name, error=e)))\n \n     tp = store.translation_project\n     allow_add_and_obsolete = ((tp.project.checkstyle == 'terminology'\ndiff --git a/pootle/apps/pootle_profile/templatetags/profile_tags.py b/pootle/apps/pootle_profile/templatetags/profile_tags.py\n--- a/pootle/apps/pootle_profile/templatetags/profile_tags.py\n+++ b/pootle/apps/pootle_profile/templatetags/profile_tags.py\n@@ -32,9 +32,9 @@\n     if top_lang and not top_lang[0] == -1 and top_lang[1]:\n         if context[\"own_profile\"]:\n             score_tweet_content = _(\n-                \"My current score at %s is %s\"\n-                % (settings.POOTLE_TITLE,\n-                   profile.scores.public_score))\n+                \"My current score at %(pootle_title)s is %(score)s\",\n+                dict(pootle_title=settings.POOTLE_TITLE,\n+                     score=profile.scores.public_score))\n             context[\"score_tweet_message\"] = _(\"Tweet this!\")\n             context[\"score_tweet_link\"] = (\n                 \"https://twitter.com/share?text=%s\"\n@@ -49,14 +49,15 @@\n     context[\"own_profile\"] = request.user == profile.user\n     if top_lang and not top_lang[0] == -1 and top_lang[1]:\n         context[\"ranking_text\"] = _(\n-            \"#%s contributor in %s in the last 30 days\"\n-            % (top_lang[0], top_lang[1].name))\n+            \"#%(rank)s contributor in %(language)s in the last 30 days\",\n+            dict(rank=top_lang[0], language=top_lang[1].name))\n         if context[\"own_profile\"]:\n             ranking_tweet_content = _(\n-                \"I am #%s contributor in %s in the last 30 days at %s!\"\n-                % (top_lang[0],\n-                   top_lang[1].name,\n-                   settings.POOTLE_TITLE))\n+                \"I am #%(rank)s contributor in %(language)s in the last 30 \"\n+                \"days at %(pootle_title)s!\",\n+                dict(rank=top_lang[0],\n+                     language=top_lang[1].name,\n+                     pootle_title=settings.POOTLE_TITLE))\n             context[\"ranking_tweet_link\"] = (\n                 \"https://twitter.com/share?text=%s\"\n                 % urllib.quote_plus(ranking_tweet_content.encode(\"utf8\")))\n", "issue": "Localisation strings need to allow ordering\nThe following errors occur in `pootle makemessages` run via `make pot`.  These are strings where we're using multiple `%s` variables without names, thus they can't be reordered if required by the language.\r\n\r\n```\r\n./pootle/apps/import_export/utils.py:57: warning: 'msgid' format string with unnamed arguments cannot be properly localized:\r\n                                                  The translator cannot reorder the arguments.\r\n                                                  Please consider using a format string with named arguments,\r\n                                                  and a mapping instead of a tuple for the arguments.\r\n./pootle/apps/pootle_profile/templatetags/profile_tags.py:35: warning: 'msgid' format string with unnamed arguments cannot be properly localized:\r\n                                                                       The translator cannot reorder the arguments.\r\n                                                                       Please consider using a format string with named arguments,\r\n                                                                       and a mapping instead of a tuple for the arguments.\r\n./pootle/apps/pootle_profile/templatetags/profile_tags.py:52: warning: 'msgid' format string with unnamed arguments cannot be properly localized:\r\n                                                                       The translator cannot reorder the arguments.\r\n                                                                       Please consider using a format string with named arguments,\r\n                                                                       and a mapping instead of a tuple for the arguments.\r\n./pootle/apps/pootle_profile/templatetags/profile_tags.py:56: warning: 'msgid' format string with unnamed arguments cannot be properly localized:\r\n                                                                       The translator cannot reorder the arguments.\r\n                                                                       Please consider using a format string with named arguments,\r\n                                                                       and a mapping instead of a tuple for the arguments.\r\n```\n", "before_files": [{"content": "# -*- coding: utf-8 -*-\n#\n# Copyright (C) Pootle contributors.\n#\n# This file is a part of the Pootle project. It is distributed under the GPL3\n# or later license. See the LICENSE file for a copy of the license and the\n# AUTHORS file for copyright and authorship information.\n\nimport urllib\n\nfrom django import template\nfrom django.conf import settings\nfrom django.core.urlresolvers import reverse\nfrom django.utils.safestring import mark_safe\n\nfrom pootle.i18n.gettext import ugettext_lazy as _\n\n\nregister = template.Library()\n\n\n@register.filter\ndef gravatar(user, size):\n    return user.gravatar_url(size)\n\n\n@register.inclusion_tag(\"user/includes/profile_score.html\")\ndef profile_score(request, profile):\n    context = dict(profile=profile)\n    top_lang = profile.scores.top_language\n    context[\"own_profile\"] = request.user == profile.user\n    if top_lang and not top_lang[0] == -1 and top_lang[1]:\n        if context[\"own_profile\"]:\n            score_tweet_content = _(\n                \"My current score at %s is %s\"\n                % (settings.POOTLE_TITLE,\n                   profile.scores.public_score))\n            context[\"score_tweet_message\"] = _(\"Tweet this!\")\n            context[\"score_tweet_link\"] = (\n                \"https://twitter.com/share?text=%s\"\n                % urllib.quote_plus(score_tweet_content.encode(\"utf8\")))\n    return context\n\n\n@register.inclusion_tag(\"user/includes/profile_ranking.html\")\ndef profile_ranking(request, profile):\n    context = dict(request=request, profile=profile)\n    top_lang = profile.scores.top_language\n    context[\"own_profile\"] = request.user == profile.user\n    if top_lang and not top_lang[0] == -1 and top_lang[1]:\n        context[\"ranking_text\"] = _(\n            \"#%s contributor in %s in the last 30 days\"\n            % (top_lang[0], top_lang[1].name))\n        if context[\"own_profile\"]:\n            ranking_tweet_content = _(\n                \"I am #%s contributor in %s in the last 30 days at %s!\"\n                % (top_lang[0],\n                   top_lang[1].name,\n                   settings.POOTLE_TITLE))\n            context[\"ranking_tweet_link\"] = (\n                \"https://twitter.com/share?text=%s\"\n                % urllib.quote_plus(ranking_tweet_content.encode(\"utf8\")))\n            context[\"ranking_tweet_link_text\"] = _(\"Tweet this!\")\n    else:\n        context[\"no_ranking_text\"] = _(\"No contributions in the last 30 days\")\n    return context\n\n\n@register.inclusion_tag(\"user/includes/profile_social.html\")\ndef profile_social(profile):\n    links = []\n    if profile.user.website:\n        links.append(\n            dict(url=profile.user.website,\n                 icon=\"icon-user-website\",\n                 text=_(\"My Website\")))\n    if profile.user.twitter:\n        links.append(\n            dict(url=profile.user.twitter_url,\n                 icon=\"icon-user-twitter\",\n                 text=\"@%s\" % profile.user.twitter))\n    if profile.user.linkedin:\n        links.append(\n            dict(url=profile.user.linkedin,\n                 icon=\"icon-user-linkedin\",\n                 text=_(\"My LinkedIn Profile\")))\n    return dict(social_media_links=links)\n\n\n@register.inclusion_tag(\"user/includes/profile_teams.html\")\ndef profile_teams(request, profile):\n    teams = profile.membership.teams_and_roles\n    site_permissions = []\n    if not request.user.is_anonymous and profile.user.is_superuser:\n        site_permissions.append(_(\"Site administrator\"))\n    for code, info in teams.items():\n        info[\"url\"] = reverse(\n            \"pootle-language-browse\",\n            kwargs=dict(language_code=code))\n    teams_title = _(\n        \"%s's language teams\"\n        % profile.user.display_name)\n    no_teams_message = _(\n        \"%s is not a member of any language teams\"\n        % profile.user.display_name)\n    return dict(\n        anon_request=request.user.is_anonymous,\n        teams=teams,\n        teams_title=teams_title,\n        no_teams_message=no_teams_message,\n        site_permissions=site_permissions)\n\n\n@register.inclusion_tag(\"user/includes/profile_user.html\")\ndef profile_user(request, profile):\n    context = dict(request=request, profile=profile)\n    context['request_user_is_manager'] = (\n        request.user.has_manager_permissions())\n    if profile.user.is_anonymous:\n        context[\"bio\"] = _(\n            \"Some translations are provided by anonymous volunteers. \"\n            \"These are registered under this special meta-account.\")\n    elif profile.user.is_system():\n        context[\"bio\"] = _(\n            \"Some translations are imported from external files. \"\n            \"These are registered under this special meta-account.\")\n    else:\n        if request.user == profile.user:\n            context[\"can_edit_profile\"] = True\n            context[\"should_edit_profile\"] = (\n                not profile.user.has_contact_details\n                or not profile.user.bio)\n            if context[\"should_edit_profile\"]:\n                context[\"edit_profile_message\"] = mark_safe(\n                    _(\"Show others who you are, tell about yourself<br/>\"\n                      \"and make your public profile look gorgeous!\"))\n            context[\"user_title\"] = _(\n                \"You can set or change your avatar image at www.gravatar.com\")\n        if profile.user.bio:\n            context[\"bio\"] = profile.user.bio\n    return context\n\n\n@register.inclusion_tag(\"user/includes/profile_activity.html\")\ndef profile_activity(profile, request_lang=None):\n    context = dict(profile=profile)\n    if profile.user.is_meta:\n        return context\n    context[\"user_last_event\"] = (\n        context[\"profile\"].user.last_event(locale=request_lang))\n    return context\n", "path": "pootle/apps/pootle_profile/templatetags/profile_tags.py"}, {"content": "# -*- coding: utf-8 -*-\n#\n# Copyright (C) Pootle contributors.\n#\n# This file is a part of the Pootle project. It is distributed under the GPL3\n# or later license. See the LICENSE file for a copy of the license and the\n# AUTHORS file for copyright and authorship information.\n\nimport logging\nimport os\nfrom io import BytesIO\nfrom zipfile import ZipFile\n\nfrom translate.storage import tmx\nfrom translate.storage.factory import getclass\n\nfrom django.conf import settings\nfrom django.utils.functional import cached_property\n\nfrom pootle.core.delegate import revision\nfrom pootle.core.url_helpers import urljoin\nfrom pootle.i18n.gettext import ugettext_lazy as _\nfrom pootle_app.models.permissions import check_user_permission\nfrom pootle_statistics.models import SubmissionTypes\nfrom pootle_store.constants import TRANSLATED\nfrom pootle_store.models import Store\n\nfrom .exceptions import (FileImportError, MissingPootlePathError,\n                         MissingPootleRevError, UnsupportedFiletypeError)\n\n\nlogger = logging.getLogger(__name__)\n\n\ndef import_file(f, user=None):\n    ttk = getclass(f)(f.read())\n    if not hasattr(ttk, \"parseheader\"):\n        raise UnsupportedFiletypeError(_(\"Unsupported filetype '%s', only PO \"\n                                         \"files are supported at this time\\n\",\n                                         f.name))\n    header = ttk.parseheader()\n    pootle_path = header.get(\"X-Pootle-Path\")\n    if not pootle_path:\n        raise MissingPootlePathError(_(\"File '%s' missing X-Pootle-Path \"\n                                       \"header\\n\", f.name))\n\n    rev = header.get(\"X-Pootle-Revision\")\n    if not rev or not rev.isdigit():\n        raise MissingPootleRevError(_(\"File '%s' missing or invalid \"\n                                      \"X-Pootle-Revision header\\n\",\n                                      f.name))\n    rev = int(rev)\n\n    try:\n        store = Store.objects.get(pootle_path=pootle_path)\n    except Store.DoesNotExist as e:\n        raise FileImportError(_(\"Could not create '%s'. Missing \"\n                                \"Project/Language? (%s)\", (f.name, e)))\n\n    tp = store.translation_project\n    allow_add_and_obsolete = ((tp.project.checkstyle == 'terminology'\n                               or tp.is_template_project)\n                              and check_user_permission(user,\n                                                        'administrate',\n                                                        tp.directory))\n    try:\n        store.update(store=ttk, user=user,\n                     submission_type=SubmissionTypes.UPLOAD,\n                     store_revision=rev,\n                     allow_add_and_obsolete=allow_add_and_obsolete)\n    except Exception as e:\n        # This should not happen!\n        logger.error(\"Error importing file: %s\", str(e))\n        raise FileImportError(_(\"There was an error uploading your file\"))\n\n\nclass TPTMXExporter(object):\n\n    def __init__(self, context):\n        self.context = context\n\n    @cached_property\n    def exported_revision(self):\n        return revision.get(self.context.__class__)(\n            self.context).get(key=\"pootle.offline.tm\")\n\n    @cached_property\n    def revision(self):\n        return revision.get(self.context.__class__)(\n            self.context.directory).get(key=\"stats\")[:10] or \"0\"\n\n    def get_url(self):\n        if self.exported_revision:\n            relative_path = \"offline_tm/%s/%s\" % (\n                self.context.language.code,\n                self.get_filename(self.exported_revision)\n            )\n            return urljoin(settings.MEDIA_URL, relative_path)\n        return None\n\n    def update_exported_revision(self):\n        if self.has_changes():\n            revision.get(self.context.__class__)(\n                self.context).set(keys=[\"pootle.offline.tm\"],\n                                  value=self.revision)\n            if \"exported_revision\" in self.__dict__:\n                del self.__dict__[\"exported_revision\"]\n\n    def has_changes(self):\n        return self.revision != self.exported_revision\n\n    def file_exists(self):\n        return os.path.exists(self.abs_filepath)\n\n    @property\n    def last_exported_file_path(self):\n        if not self.exported_revision:\n            return None\n        exported_filename = self.get_filename(self.exported_revision)\n        return os.path.join(self.directory, exported_filename)\n\n    def exported_file_exists(self):\n        if self.last_exported_file_path is None:\n            return False\n        return os.path.exists(self.last_exported_file_path)\n\n    @property\n    def directory(self):\n        return os.path.join(settings.MEDIA_ROOT,\n                            'offline_tm',\n                            self.context.language.code)\n\n    def get_filename(self, revision):\n        return \".\".join([self.context.project.code,\n                         self.context.language.code, revision, 'tmx',\n                         'zip'])\n\n    def check_tp(self, filename):\n        \"\"\"Check if filename relates to the context TP.\"\"\"\n\n        return filename.startswith(\".\".join([\n            self.context.project.code,\n            self.context.language.code]))\n\n    @property\n    def filename(self):\n        return self.get_filename(self.revision)\n\n    @property\n    def abs_filepath(self):\n        return os.path.join(self.directory, self.filename)\n\n    def export(self, rotate=False):\n        source_language = self.context.project.source_language.code\n        target_language = self.context.language.code\n\n        if not os.path.exists(self.directory):\n            os.makedirs(self.directory)\n\n        tmxfile = tmx.tmxfile()\n        for store in self.context.stores.live().iterator():\n            for unit in store.units.filter(state=TRANSLATED):\n                tmxfile.addtranslation(unit.source, source_language,\n                                       unit.target, target_language,\n                                       unit.developer_comment)\n\n        bs = BytesIO()\n        tmxfile.serialize(bs)\n        with open(self.abs_filepath, \"wb\") as f:\n            with ZipFile(f, \"w\") as zf:\n                zf.writestr(self.filename.rstrip('.zip'), bs.getvalue())\n\n        last_exported_filepath = self.last_exported_file_path\n        self.update_exported_revision()\n\n        removed = []\n        if rotate:\n            for fn in os.listdir(self.directory):\n                # Skip files from other projects.\n                if not self.check_tp(fn):\n                    continue\n                filepath = os.path.join(self.directory, fn)\n                if filepath not in [self.abs_filepath, last_exported_filepath]:\n                    removed.append(filepath)\n                    os.remove(filepath)\n\n        return self.abs_filepath, removed\n", "path": "pootle/apps/import_export/utils.py"}], "after_files": [{"content": "# -*- coding: utf-8 -*-\n#\n# Copyright (C) Pootle contributors.\n#\n# This file is a part of the Pootle project. It is distributed under the GPL3\n# or later license. See the LICENSE file for a copy of the license and the\n# AUTHORS file for copyright and authorship information.\n\nimport urllib\n\nfrom django import template\nfrom django.conf import settings\nfrom django.core.urlresolvers import reverse\nfrom django.utils.safestring import mark_safe\n\nfrom pootle.i18n.gettext import ugettext_lazy as _\n\n\nregister = template.Library()\n\n\n@register.filter\ndef gravatar(user, size):\n    return user.gravatar_url(size)\n\n\n@register.inclusion_tag(\"user/includes/profile_score.html\")\ndef profile_score(request, profile):\n    context = dict(profile=profile)\n    top_lang = profile.scores.top_language\n    context[\"own_profile\"] = request.user == profile.user\n    if top_lang and not top_lang[0] == -1 and top_lang[1]:\n        if context[\"own_profile\"]:\n            score_tweet_content = _(\n                \"My current score at %(pootle_title)s is %(score)s\",\n                dict(pootle_title=settings.POOTLE_TITLE,\n                     score=profile.scores.public_score))\n            context[\"score_tweet_message\"] = _(\"Tweet this!\")\n            context[\"score_tweet_link\"] = (\n                \"https://twitter.com/share?text=%s\"\n                % urllib.quote_plus(score_tweet_content.encode(\"utf8\")))\n    return context\n\n\n@register.inclusion_tag(\"user/includes/profile_ranking.html\")\ndef profile_ranking(request, profile):\n    context = dict(request=request, profile=profile)\n    top_lang = profile.scores.top_language\n    context[\"own_profile\"] = request.user == profile.user\n    if top_lang and not top_lang[0] == -1 and top_lang[1]:\n        context[\"ranking_text\"] = _(\n            \"#%(rank)s contributor in %(language)s in the last 30 days\",\n            dict(rank=top_lang[0], language=top_lang[1].name))\n        if context[\"own_profile\"]:\n            ranking_tweet_content = _(\n                \"I am #%(rank)s contributor in %(language)s in the last 30 \"\n                \"days at %(pootle_title)s!\",\n                dict(rank=top_lang[0],\n                     language=top_lang[1].name,\n                     pootle_title=settings.POOTLE_TITLE))\n            context[\"ranking_tweet_link\"] = (\n                \"https://twitter.com/share?text=%s\"\n                % urllib.quote_plus(ranking_tweet_content.encode(\"utf8\")))\n            context[\"ranking_tweet_link_text\"] = _(\"Tweet this!\")\n    else:\n        context[\"no_ranking_text\"] = _(\"No contributions in the last 30 days\")\n    return context\n\n\n@register.inclusion_tag(\"user/includes/profile_social.html\")\ndef profile_social(profile):\n    links = []\n    if profile.user.website:\n        links.append(\n            dict(url=profile.user.website,\n                 icon=\"icon-user-website\",\n                 text=_(\"My Website\")))\n    if profile.user.twitter:\n        links.append(\n            dict(url=profile.user.twitter_url,\n                 icon=\"icon-user-twitter\",\n                 text=\"@%s\" % profile.user.twitter))\n    if profile.user.linkedin:\n        links.append(\n            dict(url=profile.user.linkedin,\n                 icon=\"icon-user-linkedin\",\n                 text=_(\"My LinkedIn Profile\")))\n    return dict(social_media_links=links)\n\n\n@register.inclusion_tag(\"user/includes/profile_teams.html\")\ndef profile_teams(request, profile):\n    teams = profile.membership.teams_and_roles\n    site_permissions = []\n    if not request.user.is_anonymous and profile.user.is_superuser:\n        site_permissions.append(_(\"Site administrator\"))\n    for code, info in teams.items():\n        info[\"url\"] = reverse(\n            \"pootle-language-browse\",\n            kwargs=dict(language_code=code))\n    teams_title = _(\n        \"%s's language teams\"\n        % profile.user.display_name)\n    no_teams_message = _(\n        \"%s is not a member of any language teams\"\n        % profile.user.display_name)\n    return dict(\n        anon_request=request.user.is_anonymous,\n        teams=teams,\n        teams_title=teams_title,\n        no_teams_message=no_teams_message,\n        site_permissions=site_permissions)\n\n\n@register.inclusion_tag(\"user/includes/profile_user.html\")\ndef profile_user(request, profile):\n    context = dict(request=request, profile=profile)\n    context['request_user_is_manager'] = (\n        request.user.has_manager_permissions())\n    if profile.user.is_anonymous:\n        context[\"bio\"] = _(\n            \"Some translations are provided by anonymous volunteers. \"\n            \"These are registered under this special meta-account.\")\n    elif profile.user.is_system():\n        context[\"bio\"] = _(\n            \"Some translations are imported from external files. \"\n            \"These are registered under this special meta-account.\")\n    else:\n        if request.user == profile.user:\n            context[\"can_edit_profile\"] = True\n            context[\"should_edit_profile\"] = (\n                not profile.user.has_contact_details\n                or not profile.user.bio)\n            if context[\"should_edit_profile\"]:\n                context[\"edit_profile_message\"] = mark_safe(\n                    _(\"Show others who you are, tell about yourself<br/>\"\n                      \"and make your public profile look gorgeous!\"))\n            context[\"user_title\"] = _(\n                \"You can set or change your avatar image at www.gravatar.com\")\n        if profile.user.bio:\n            context[\"bio\"] = profile.user.bio\n    return context\n\n\n@register.inclusion_tag(\"user/includes/profile_activity.html\")\ndef profile_activity(profile, request_lang=None):\n    context = dict(profile=profile)\n    if profile.user.is_meta:\n        return context\n    context[\"user_last_event\"] = (\n        context[\"profile\"].user.last_event(locale=request_lang))\n    return context\n", "path": "pootle/apps/pootle_profile/templatetags/profile_tags.py"}, {"content": "# -*- coding: utf-8 -*-\n#\n# Copyright (C) Pootle contributors.\n#\n# This file is a part of the Pootle project. It is distributed under the GPL3\n# or later license. See the LICENSE file for a copy of the license and the\n# AUTHORS file for copyright and authorship information.\n\nimport logging\nimport os\nfrom io import BytesIO\nfrom zipfile import ZipFile\n\nfrom translate.storage import tmx\nfrom translate.storage.factory import getclass\n\nfrom django.conf import settings\nfrom django.utils.functional import cached_property\n\nfrom pootle.core.delegate import revision\nfrom pootle.core.url_helpers import urljoin\nfrom pootle.i18n.gettext import ugettext_lazy as _\nfrom pootle_app.models.permissions import check_user_permission\nfrom pootle_statistics.models import SubmissionTypes\nfrom pootle_store.constants import TRANSLATED\nfrom pootle_store.models import Store\n\nfrom .exceptions import (FileImportError, MissingPootlePathError,\n                         MissingPootleRevError, UnsupportedFiletypeError)\n\n\nlogger = logging.getLogger(__name__)\n\n\ndef import_file(f, user=None):\n    ttk = getclass(f)(f.read())\n    if not hasattr(ttk, \"parseheader\"):\n        raise UnsupportedFiletypeError(_(\"Unsupported filetype '%s', only PO \"\n                                         \"files are supported at this time\\n\",\n                                         f.name))\n    header = ttk.parseheader()\n    pootle_path = header.get(\"X-Pootle-Path\")\n    if not pootle_path:\n        raise MissingPootlePathError(_(\"File '%s' missing X-Pootle-Path \"\n                                       \"header\\n\", f.name))\n\n    rev = header.get(\"X-Pootle-Revision\")\n    if not rev or not rev.isdigit():\n        raise MissingPootleRevError(_(\"File '%s' missing or invalid \"\n                                      \"X-Pootle-Revision header\\n\",\n                                      f.name))\n    rev = int(rev)\n\n    try:\n        store = Store.objects.get(pootle_path=pootle_path)\n    except Store.DoesNotExist as e:\n        raise FileImportError(\n            _(\"Could not create '%(filename)s'. Missing \"\n              \"Project/Language? (%(error)s)\",\n              dict(filename=f.name, error=e)))\n\n    tp = store.translation_project\n    allow_add_and_obsolete = ((tp.project.checkstyle == 'terminology'\n                               or tp.is_template_project)\n                              and check_user_permission(user,\n                                                        'administrate',\n                                                        tp.directory))\n    try:\n        store.update(store=ttk, user=user,\n                     submission_type=SubmissionTypes.UPLOAD,\n                     store_revision=rev,\n                     allow_add_and_obsolete=allow_add_and_obsolete)\n    except Exception as e:\n        # This should not happen!\n        logger.error(\"Error importing file: %s\", str(e))\n        raise FileImportError(_(\"There was an error uploading your file\"))\n\n\nclass TPTMXExporter(object):\n\n    def __init__(self, context):\n        self.context = context\n\n    @cached_property\n    def exported_revision(self):\n        return revision.get(self.context.__class__)(\n            self.context).get(key=\"pootle.offline.tm\")\n\n    @cached_property\n    def revision(self):\n        return revision.get(self.context.__class__)(\n            self.context.directory).get(key=\"stats\")[:10] or \"0\"\n\n    def get_url(self):\n        if self.exported_revision:\n            relative_path = \"offline_tm/%s/%s\" % (\n                self.context.language.code,\n                self.get_filename(self.exported_revision)\n            )\n            return urljoin(settings.MEDIA_URL, relative_path)\n        return None\n\n    def update_exported_revision(self):\n        if self.has_changes():\n            revision.get(self.context.__class__)(\n                self.context).set(keys=[\"pootle.offline.tm\"],\n                                  value=self.revision)\n            if \"exported_revision\" in self.__dict__:\n                del self.__dict__[\"exported_revision\"]\n\n    def has_changes(self):\n        return self.revision != self.exported_revision\n\n    def file_exists(self):\n        return os.path.exists(self.abs_filepath)\n\n    @property\n    def last_exported_file_path(self):\n        if not self.exported_revision:\n            return None\n        exported_filename = self.get_filename(self.exported_revision)\n        return os.path.join(self.directory, exported_filename)\n\n    def exported_file_exists(self):\n        if self.last_exported_file_path is None:\n            return False\n        return os.path.exists(self.last_exported_file_path)\n\n    @property\n    def directory(self):\n        return os.path.join(settings.MEDIA_ROOT,\n                            'offline_tm',\n                            self.context.language.code)\n\n    def get_filename(self, revision):\n        return \".\".join([self.context.project.code,\n                         self.context.language.code, revision, 'tmx',\n                         'zip'])\n\n    def check_tp(self, filename):\n        \"\"\"Check if filename relates to the context TP.\"\"\"\n\n        return filename.startswith(\".\".join([\n            self.context.project.code,\n            self.context.language.code]))\n\n    @property\n    def filename(self):\n        return self.get_filename(self.revision)\n\n    @property\n    def abs_filepath(self):\n        return os.path.join(self.directory, self.filename)\n\n    def export(self, rotate=False):\n        source_language = self.context.project.source_language.code\n        target_language = self.context.language.code\n\n        if not os.path.exists(self.directory):\n            os.makedirs(self.directory)\n\n        tmxfile = tmx.tmxfile()\n        for store in self.context.stores.live().iterator():\n            for unit in store.units.filter(state=TRANSLATED):\n                tmxfile.addtranslation(unit.source, source_language,\n                                       unit.target, target_language,\n                                       unit.developer_comment)\n\n        bs = BytesIO()\n        tmxfile.serialize(bs)\n        with open(self.abs_filepath, \"wb\") as f:\n            with ZipFile(f, \"w\") as zf:\n                zf.writestr(self.filename.rstrip('.zip'), bs.getvalue())\n\n        last_exported_filepath = self.last_exported_file_path\n        self.update_exported_revision()\n\n        removed = []\n        if rotate:\n            for fn in os.listdir(self.directory):\n                # Skip files from other projects.\n                if not self.check_tp(fn):\n                    continue\n                filepath = os.path.join(self.directory, fn)\n                if filepath not in [self.abs_filepath, last_exported_filepath]:\n                    removed.append(filepath)\n                    os.remove(filepath)\n\n        return self.abs_filepath, removed\n", "path": "pootle/apps/import_export/utils.py"}]}