232
+        )
233
+        self.fields["state"] = forms.CharField(
234
+            required=False,
235
+            widget=autocomplete.Select2(
236
+                url=reverse_lazy("public_frontend:ac_states"),
237
+                forward=(forward.Field("country"),),
238
+                attrs={"data-minimum-input-length": 0},
239
+            ),
240
+            label=self.fields.get("state").label if self.fields.get("state") else "State/Province",
241
+        )
242
+        self.fields["city"] = forms.CharField(
243
+            required=False,
244
+            widget=autocomplete.Select2(
245
+                url=reverse_lazy("public_frontend:ac_cities"),
246
+                forward=(forward.Field("country"), forward.Field("state")),
247
+                attrs={"data-minimum-input-length": 1},
248
+            ),
249
+            label=self.fields.get("city").label if self.fields.get("city") else "City",
250
+        )
251
+
252
+        # Prepopulate initial choices so Select2 shows current values
253
+        try:
254
+            from .utils.geo import country_label, state_label
255
+            if self.instance and getattr(self.instance, "pk", None):
256
+                cval = getattr(self.instance, "country", "") or ""
257
+                sval = getattr(self.instance, "state", "") or ""
258
+                cityval = getattr(self.instance, "city", "") or ""
259
+                if cval:
260
+                    clabel = country_label(cval) or cval
261
+                    self.fields["country"].widget.choices = [(cval, clabel)]
262
+                    self.initial["country"] = cval
263
+                if cval and sval:
264
+                    slabel = state_label(cval, sval) or sval
265
+                    self.fields["state"].widget.choices = [(sval, slabel)]
266
+                    self.initial["state"] = sval
267
+                if cityval:
268
+                    self.fields["city"].widget.choices = [(cityval, cityval)]
269
+                    self.initial["city"] = cityval
270
+        except Exception:
271
+            pass
272
+
219 273
         self.helper = FormHelper()
220 274
         self.helper.form_tag = False
221 275
         self.helper.layout = Layout(
@@ -225,8 +279,8 @@ class PublicUserProfileExtraForm(forms.ModelForm):
225 279
             Field("preferred_language"),
226 280
             Field("address_line1"),
227 281
             Field("address_line2"),
228
-            Field("city"),
282
+            Field("country"),
229 283
             Field("state"),
284
+            Field("city"),
230 285
             Field("postal_code"),
231
-            Field("country"),
232 286
         )

+ 1 - 0
public_frontend/templates/public_frontend/base.html

@@ -7,6 +7,7 @@
7 7
   <meta name="viewport" content="width=device-width, initial-scale=1" />
8 8
   <title>{% if current_site %}{{ current_site.name }}{% else %}Ecoloop{% endif %} — {% block title %}{% endblock %}</title>
9 9
   {% tailwind_css %}
10
+  <script  src="{% static 'jquery/dist/jquery.min.js' %}"></script>
10 11
   <script defer src="{% static 'alpinejs/dist/cdn.min.js' %}"></script>
11 12
 </head>
12 13
 <body class="bg-gray-50 text-gray-900">

+ 23 - 2
public_frontend/templates/public_frontend/my_profile.html

@@ -1,5 +1,5 @@
1 1
 {% extends 'public_frontend/base.html' %}
2
-{% load crispy_forms_tags i18n %}
2
+{% load crispy_forms_tags i18n static %}
3 3
 {% block title %}{% trans "My Profile" %}{% endblock %}
4 4
 {% block content %}
5 5
 <div class="max-w-5xl mx-auto" x-data="{ section: 'profile' }" x-init="section = (location.hash==='\#history' ? 'history' : 'profile')">
@@ -76,7 +76,28 @@
76 76
             </div>
77 77
             <div>
78 78
               <h2 class="text-base font-semibold mb-2">{% trans "Contact & Address" %}</h2>
79
-              {{ form_extras|crispy }}
79
+              {{ form_extras.media }}
80
+              <div class="grid md:grid-cols-2 gap-4">
81
+                {{ form_extras.phone|as_crispy_field }}
82
+                {{ form_extras.job_title|as_crispy_field }}
83
+                {{ form_extras.department|as_crispy_field }}
84
+                {{ form_extras.preferred_language|as_crispy_field }}
85
+                {{ form_extras.address_line1|as_crispy_field }}
86
+                {{ form_extras.address_line2|as_crispy_field }}
87
+                <div class="md:col-span-2">
88
+                  <label class="block text-sm font-medium mb-1" for="id_country">{{ form_extras.country.label }}</label>
89
+                  {{ form_extras.country }}
90
+                </div>
91
+                <div>
92
+                  <label class="block text-sm font-medium mb-1" for="id_state">{{ form_extras.state.label }}</label>
93
+                  {{ form_extras.state }}
94
+                </div>
95
+                <div>
96
+                  <label class="block text-sm font-medium mb-1" for="id_city">{{ form_extras.city.label }}</label>
97
+                  {{ form_extras.city }}
98
+                </div>
99
+                {{ form_extras.postal_code|as_crispy_field }}
100
+              </div>
80 101
             </div>
81 102
             {% endif %}
82 103
           </div>

+ 6 - 0
public_frontend/urls.py

@@ -1,11 +1,17 @@
1 1
 from django.urls import path
2 2
 from . import views
3
+from . import views_autocomplete as ac
4
+from . import views
3 5
 from django.contrib.auth import views as auth_views
4 6
 from .views import PublicLoginView
5 7
 
6 8
 app_name = "public_frontend"
7 9
 
8 10
 urlpatterns = [
11
+    # Autocomplete endpoints for dependent selects
12
+    path('autocomplete/countries/', ac.countries_autocomplete, name='ac_countries'),
13
+    path('autocomplete/states/', ac.states_autocomplete, name='ac_states'),
14
+    path('autocomplete/cities/', ac.cities_autocomplete, name='ac_cities'),
9 15
     path("", views.home, name="home"),
10 16
     path("login/", PublicLoginView.as_view(), name="login"),
11 17
     path("logout/", auth_views.LogoutView.as_view(next_page="public_frontend:home"), name="logout"),

+ 123 - 0
public_frontend/utils/geo.py

@@ -0,0 +1,123 @@
1
+from __future__ import annotations
2
+
3
+import json
4
+import os
5
+from functools import lru_cache
6
+from typing import List, Tuple, Dict, Optional
7
+
8
+from django.conf import settings
9
+
10
+
11
+def _json_path(filename: str) -> str:
12
+    return os.path.join(settings.BASE_DIR, 'static', 'json', filename)
13
+
14
+
15
+@lru_cache(maxsize=1)
16
+def load_countries() -> List[dict]:
17
+    with open(_json_path('countries.json'), 'r', encoding='utf-8') as f:
18
+        return json.load(f)
19
+
20
+
21
+@lru_cache(maxsize=1)
22
+def load_states() -> List[dict]:
23
+    with open(_json_path('states.json'), 'r', encoding='utf-8') as f:
24
+        return json.load(f)
25
+
26
+
27
+@lru_cache(maxsize=1)
28
+def load_cities() -> List[dict]:
29
+    with open(_json_path('cities.json'), 'r', encoding='utf-8') as f:
30
+        return json.load(f)
31
+
32
+
33
+@lru_cache(maxsize=1)
34
+def _index_states_by_country() -> Dict[str, List[Tuple[str, str]]]:
35
+    idx: Dict[str, List[Tuple[str, str]]] = {}
36
+    for s in load_states():
37
+        cc = s.get('country_code')
38
+        code = s.get('iso2') or s.get('state_code')
39
+        name = s.get('name')
40
+        if not (cc and code and name):
41
+            continue
42
+        idx.setdefault(cc, []).append((str(code), name))
43
+    return idx
44
+
45
+
46
+@lru_cache(maxsize=1)
47
+def _index_cities_by_country_state() -> Dict[Tuple[str, str], List[Tuple[str, str]]]:
48
+    idx: Dict[Tuple[str, str], List[Tuple[str, str]]] = {}
49
+    for c in load_cities():
50
+        cc = c.get('country_code')
51
+        sc = (c.get('state_code') or '').upper()
52
+        name = c.get('name')
53
+        if not (cc and sc and name):
54
+            continue
55
+        key = (cc, sc)
56
+        idx.setdefault(key, []).append((name, name))
57
+    return idx
58
+
59
+
60
+def country_label(code: str) -> Optional[str]:
61
+    code = (code or '').upper()
62
+    for c in load_countries():
63
+        if c.get('iso2') == code:
64
+            return c.get('name')
65
+    return None
66
+
67
+
68
+def state_label(country_code: str, state_code: str) -> Optional[str]:
69
+    cc = (country_code or '').upper()
70
+    sc = (state_code or '').upper()
71
+    for s in load_states():
72
+        if s.get('country_code') == cc and s.get('iso2', '').upper() == sc:
73
+            return s.get('name')
74
+        if s.get('country_code') == cc and s.get('state_code', '').upper() == sc:
75
+            return s.get('name')
76
+    return None
77
+
78
+
79
+def list_countries(q: str | None = None) -> List[Tuple[str, str]]:
80
+    items: List[Tuple[str, str]] = []
81
+    ql = (q or '').strip().lower()
82
+    for c in load_countries():
83
+        code = c.get('iso2')
84
+        name = c.get('name')
85
+        if not code or not name:
86
+            continue
87
+        if ql and ql not in name.lower() and ql not in code.lower():
88
+            continue
89
+        items.append((code, name))
90
+    return items
91
+
92
+
93
+def list_states(country_code: str | None, q: str | None = None) -> List[Tuple[str, str]]:
94
+    items: List[Tuple[str, str]] = []
95
+    if not country_code:
96
+        return items
97
+    cc = country_code.upper()
98
+    ql = (q or '').strip().lower()
99
+    pool = _index_states_by_country().get(cc, [])
100
+    if not ql:
101
+        return list(pool)
102
+    for code, name in pool:
103
+        if ql and ql not in name.lower() and ql not in (code or '').lower():
104
+            continue
105
+        items.append((code, name))
106
+    return items
107
+
108
+
109
+def list_cities(country_code: str | None, state_code: str | None, q: str | None = None) -> List[Tuple[str, str]]:
110
+    items: List[Tuple[str, str]] = []
111
+    if not (country_code and state_code):
112
+        return items
113
+    cc = country_code.upper()
114
+    sc = state_code.upper()
115
+    ql = (q or '').strip().lower()
116
+    pool = _index_cities_by_country_state().get((cc, sc), [])
117
+    if not ql:
118
+        # Return first 50 to avoid huge payloads without query
119
+        return pool[:50]
120
+    for code, name in pool:
121
+        if ql in name.lower():
122
+            items.append((code, name))
123
+    return items

+ 62 - 0
public_frontend/views_autocomplete.py

@@ -0,0 +1,62 @@
1
+from __future__ import annotations
2
+
3
+from django.http import JsonResponse
4
+from django.views.decorators.http import require_GET
5
+
6
+from .utils.geo import list_countries, list_states, list_cities
7
+import json
8
+
9
+
10
+def _q(request):
11
+    return request.GET.get('q') or request.GET.get('term') or ''
12
+
13
+
14
+def _forward(request, key: str):
15
+    # Try direct param (rare) or `forward[key]`
16
+    val = request.GET.get(key)
17
+    if val:
18
+        return val
19
+    fk = request.GET.get(f'forward[{key}]')
20
+    if fk:
21
+        return fk
22
+    # DAL typically sends a JSON payload in `forward`
23
+    fjson = request.GET.get('forward')
24
+    if fjson:
25
+        try:
26
+            data = json.loads(fjson)
27
+            # Format may be dict or list of dicts
28
+            if isinstance(data, dict):
29
+                return data.get(key)
30
+            if isinstance(data, list):
31
+                for item in data:
32
+                    if isinstance(item, dict) and item.get('name') == key:
33
+                        return item.get('value')
34
+        except Exception:
35
+            pass
36
+    return None
37
+
38
+
39
+@require_GET
40
+def countries_autocomplete(request):
41
+    q = _q(request)
42
+    results = [{"id": code, "text": name} for code, name in list_countries(q)]
43
+    return JsonResponse({"results": results, "pagination": {"more": False}})
44
+
45
+
46
+@require_GET
47
+def states_autocomplete(request):
48
+    q = _q(request)
49
+    country = _forward(request, 'country')
50
+    items = list_states(country, q)
51
+    results = [{"id": code, "text": name} for code, name in items[:50]]
52
+    return JsonResponse({"results": results, "pagination": {"more": False}})
53
+
54
+
55
+@require_GET
56
+def cities_autocomplete(request):
57
+    q = _q(request)
58
+    country = _forward(request, 'country')
59
+    state = _forward(request, 'state')
60
+    items = list_cities(country, state, q)
61
+    results = [{"id": code, "text": name} for code, name in items[:50]]
62
+    return JsonResponse({"results": results, "pagination": {"more": False}})

+ 1 - 0
requirements.txt

@@ -20,3 +20,4 @@ django-extensions
20 20
 pygraphviz
21 21
 django-npm
22 22
 django-widget-tweaks
23
+django-autocomplete-light>=3.9,<4.0

File diff suppressed because it is too large
+ 2116620 - 0
static/json/cities.json


File diff suppressed because it is too large
+ 152445 - 0
static/json/countries+cities.json


File diff suppressed because it is too large
+ 1138111 - 0
static/json/countries+states+cities.json


File diff suppressed because it is too large
+ 6324 - 0
static/json/countries+states.json


File diff suppressed because it is too large
+ 14472 - 0
static/json/countries.json


+ 146 - 0
static/json/regions.json

@@ -0,0 +1,146 @@
1
+[
2
+    {
3
+        "id": 1,
4
+        "name": "Africa",
5
+        "translations": {
6
+            "br": "Afrika",
7
+            "ko": "아프리카",
8
+            "pt-BR": "África",
9
+            "pt": "África",
10
+            "nl": "Afrika",
11
+            "hr": "Afrika",
12
+            "fa": "آفریقا",
13
+            "de": "Afrika",
14
+            "es": "África",
15
+            "fr": "Afrique",
16
+            "ja": "アフリカ",
17
+            "it": "Africa",
18
+            "zh-CN": "非洲",
19
+            "tr": "Afrika",
20
+            "ru": "Африка",
21
+            "uk": "Африка",
22
+            "pl": "Afryka"
23
+        },
24
+        "wikiDataId": "Q15"
25
+    },
26
+    {
27
+        "id": 2,
28
+        "name": "Americas",
29
+        "translations": {
30
+            "br": "Amerika",
31
+            "ko": "아메리카",
32
+            "pt-BR": "América",
33
+            "pt": "América",
34
+            "nl": "Amerika",
35
+            "hr": "Amerika",
36
+            "fa": "قاره آمریکا",
37
+            "de": "Amerika",
38
+            "es": "América",
39
+            "fr": "Amérique",
40
+            "ja": "アメリカ州",
41
+            "it": "America",
42
+            "zh-CN": "美洲",
43
+            "tr": "Amerika",
44
+            "ru": "Америка",
45
+            "uk": "Америка",
46
+            "pl": "Ameryka"
47
+        },
48
+        "wikiDataId": "Q828"
49
+    },
50
+    {
51
+        "id": 3,
52
+        "name": "Asia",
53
+        "translations": {
54
+            "br": "Azia",
55
+            "ko": "아시아",
56
+            "pt-BR": "Ásia",
57
+            "pt": "Ásia",
58
+            "nl": "Azië",
59
+            "hr": "Ázsia",
60
+            "fa": "آسیا",
61
+            "de": "Asien",
62
+            "es": "Asia",
63
+            "fr": "Asie",
64
+            "ja": "アジア",
65
+            "it": "Asia",
66
+            "zh-CN": "亚洲",
67
+            "tr": "Asya",
68
+            "ru": "Азия",
69
+            "uk": "Азія",
70
+            "pl": "Azja"
71
+        },
72
+        "wikiDataId": "Q48"
73
+    },
74
+    {
75
+        "id": 4,
76
+        "name": "Europe",
77
+        "translations": {
78
+            "br": "Europa",
79
+            "ko": "유럽",
80
+            "pt-BR": "Europa",
81
+            "pt": "Europa",
82
+            "nl": "Europa",
83
+            "hr": "Európa",
84
+            "fa": "اروپا",
85
+            "de": "Europa",
86
+            "es": "Europa",
87
+            "fr": "Europe",
88
+            "ja": "ヨーロッパ",
89
+            "it": "Europa",
90
+            "zh-CN": "欧洲",
91
+            "tr": "Avrupa",
92
+            "ru": "Европа",
93
+            "uk": "Європа",
94
+            "pl": "Europa"
95
+        },
96
+        "wikiDataId": "Q46"
97
+    },
98
+    {
99
+        "id": 5,
100
+        "name": "Oceania",
101
+        "translations": {
102
+            "br": "Okeania",
103
+            "ko": "오세아니아",
104
+            "pt-BR": "Oceania",
105
+            "pt": "Oceania",
106
+            "nl": "Oceanië en Australië",
107
+            "hr": "Óceánia és Ausztrália",
108
+            "fa": "اقیانوسیه",
109
+            "de": "Ozeanien und Australien",
110
+            "es": "Oceanía",
111
+            "fr": "Océanie",
112
+            "ja": "オセアニア",
113
+            "it": "Oceania",
114
+            "zh-CN": "大洋洲",
115
+            "tr": "Okyanusya",
116
+            "ru": "Океания",
117
+            "uk": "Океанія",
118
+            "pl": "Oceania"
119
+        },
120
+        "wikiDataId": "Q55643"
121
+    },
122
+    {
123
+        "id": 6,
124
+        "name": "Polar",
125
+        "translations": {
126
+            "br": "Antartika",
127
+            "ko": "남극",
128
+            "pt-BR": "Antártida",
129
+            "pt": "Antártida",
130
+            "nl": "Antarctica",
131
+            "hr": "Antarktika",
132
+            "fa": "جنوبگان",
133
+            "de": "Antarktika",
134
+            "es": "Antártida",
135
+            "fr": "Antarctique",
136
+            "ja": "南極大陸",
137
+            "it": "Antartide",
138
+            "zh-CN": "南極洲",
139
+            "tr": "Antarktika",
140
+            "ru": "Антарктика",
141
+            "uk": "Антарктика",
142
+            "pl": "Antarktyka"
143
+        },
144
+        "wikiDataId": "Q51"
145
+    }
146
+]

File diff suppressed because it is too large
+ 955065 - 0
static/json/states+cities.json


File diff suppressed because it is too large
+ 86685 - 0
static/json/states.json


+ 507 - 0
static/json/subregions.json

@@ -0,0 +1,507 @@
1
+[
2
+    {
3
+        "id": 19,
4
+        "name": "Australia and New Zealand",
5
+        "region_id": 5,
6
+        "translations": {
7
+            "br": "Aostralia ha Zeland-Nevez",
8
+            "ko": "오스트랄라시아",
9
+            "pt": "Australásia",
10
+            "nl": "Australazië",
11
+            "hr": "Australazija",
12
+            "fa": "استرالزی",
13
+            "de": "Australasien",
14
+            "es": "Australasia",
15
+            "fr": "Australasie",
16
+            "ja": "オーストララシア",
17
+            "it": "Australasia",
18
+            "zh-CN": "澳大拉西亞",
19
+            "ru": "Австралия и Новая Зеландия",
20
+            "uk": "Австралія та Нова Зеландія",
21
+            "pl": "Australia i Nowa Zelandia"
22
+        },
23
+        "wikiDataId": "Q45256"
24
+    },
25
+    {
26
+        "id": 7,
27
+        "name": "Caribbean",
28
+        "region_id": 2,
29
+        "translations": {
30
+            "br": "Karib",
31
+            "ko": "카리브",
32
+            "pt": "Caraíbas",
33
+            "nl": "Caraïben",
34
+            "hr": "Karibi",
35
+            "fa": "کارائیب",
36
+            "de": "Karibik",
37
+            "es": "Caribe",
38
+            "fr": "Caraïbes",
39
+            "ja": "カリブ海地域",
40
+            "it": "Caraibi",
41
+            "zh-CN": "加勒比地区",
42
+            "ru": "Карибы",
43
+            "uk": "Кариби",
44
+            "pl": "Karaiby"
45
+        },
46
+        "wikiDataId": "Q664609"
47
+    },
48
+    {
49
+        "id": 9,
50
+        "name": "Central America",
51
+        "region_id": 2,
52
+        "translations": {
53
+            "br": "Kreizamerika",
54
+            "ko": "중앙아메리카",
55
+            "pt": "América Central",
56
+            "nl": "Centraal-Amerika",
57
+            "hr": "Srednja Amerika",
58
+            "fa": "آمریکای مرکزی",
59
+            "de": "Zentralamerika",
60
+            "es": "América Central",
61
+            "fr": "Amérique centrale",
62
+            "ja": "中央アメリカ",
63
+            "it": "America centrale",
64
+            "zh-CN": "中美洲",
65
+            "ru": "Центральная Америка",
66
+            "uk": "Центральна Америка",
67
+            "pl": "Ameryka Środkowa"
68
+        },
69
+        "wikiDataId": "Q27611"
70
+    },
71
+    {
72
+        "id": 10,
73
+        "name": "Central Asia",
74
+        "region_id": 3,
75
+        "translations": {
76
+            "br": "Azia ar C'hreiz",
77
+            "ko": "중앙아시아",
78
+            "pt": "Ásia Central",
79
+            "nl": "Centraal-Azië",
80
+            "hr": "Srednja Azija",
81
+            "fa": "آسیای میانه",
82
+            "de": "Zentralasien",
83
+            "es": "Asia Central",
84
+            "fr": "Asie centrale",
85
+            "ja": "中央アジア",
86
+            "it": "Asia centrale",
87
+            "zh-CN": "中亚",
88
+            "ru": "Центральная Азия",
89
+            "uk": "Центральна Азія",
90
+            "pl": "Azja Środkowa"
91
+        },
92
+        "wikiDataId": "Q27275"
93
+    },
94
+    {
95
+        "id": 4,
96
+        "name": "Eastern Africa",
97
+        "region_id": 1,
98
+        "translations": {
99
+            "br": "Afrika ar Reter",
100
+            "ko": "동아프리카",
101
+            "pt": "África Oriental",
102
+            "nl": "Oost-Afrika",
103
+            "hr": "Istočna Afrika",
104
+            "fa": "شرق آفریقا",
105
+            "de": "Ostafrika",
106
+            "es": "África Oriental",
107
+            "fr": "Afrique de l'Est",
108
+            "ja": "東アフリカ",
109
+            "it": "Africa orientale",
110
+            "zh-CN": "东部非洲",
111
+            "ru": "Восточная Африка",
112
+            "uk": "Східна Африка",
113
+            "pl": "Afryka Wschodnia"
114
+        },
115
+        "wikiDataId": "Q27407"
116
+    },
117
+    {
118
+        "id": 12,
119
+        "name": "Eastern Asia",
120
+        "region_id": 3,
121
+        "translations": {
122
+            "br": "Azia ar Reter",
123
+            "ko": "동아시아",
124
+            "pt": "Ásia Oriental",
125
+            "nl": "Oost-Azië",
126
+            "hr": "Istočna Azija",
127
+            "fa": "شرق آسیا",
128
+            "de": "Ostasien",
129
+            "es": "Asia Oriental",
130
+            "fr": "Asie de l'Est",
131
+            "ja": "東アジア",
132
+            "it": "Asia orientale",
133
+            "zh-CN": "東亞",
134
+            "ru": "Восточная Азия",
135
+            "uk": "Східна Азія",
136
+            "pl": "Azja Wschodnia"
137
+        },
138
+        "wikiDataId": "Q27231"
139
+    },
140
+    {
141
+        "id": 15,
142
+        "name": "Eastern Europe",
143
+        "region_id": 4,
144
+        "translations": {
145
+            "br": "Europa ar Reter",
146
+            "ko": "동유럽",
147
+            "pt": "Europa de Leste",
148
+            "nl": "Oost-Europa",
149
+            "hr": "Istočna Europa",
150
+            "fa": "شرق اروپا",
151
+            "de": "Osteuropa",
152
+            "es": "Europa Oriental",
153
+            "fr": "Europe de l'Est",
154
+            "ja": "東ヨーロッパ",
155
+            "it": "Europa orientale",
156
+            "zh-CN": "东欧",
157
+            "ru": "Восточная Европа",
158
+            "uk": "Східна Європа",
159
+            "pl": "Europa Wschodnia"
160
+        },
161
+        "wikiDataId": "Q27468"
162
+    },
163
+    {
164
+        "id": 20,
165
+        "name": "Melanesia",
166
+        "region_id": 5,
167
+        "translations": {
168
+            "br": "Melanezia",
169
+            "ko": "멜라네시아",
170
+            "pt": "Melanésia",
171
+            "nl": "Melanesië",
172
+            "hr": "Melanezija",
173
+            "fa": "ملانزی",
174
+            "de": "Melanesien",
175
+            "es": "Melanesia",
176
+            "fr": "Mélanésie",
177
+            "ja": "メラネシア",
178
+            "it": "Melanesia",
179
+            "zh-CN": "美拉尼西亚",
180
+            "ru": "Меланезия",
181
+            "uk": "Меланезія",
182
+            "pl": "Melanezja"
183
+        },
184
+        "wikiDataId": "Q37394"
185
+    },
186
+    {
187
+        "id": 21,
188
+        "name": "Micronesia",
189
+        "region_id": 5,
190
+        "translations": {
191
+            "br": "Mikronezia",
192
+            "ko": "미크로네시아",
193
+            "pt": "Micronésia",
194
+            "nl": "Micronesië",
195
+            "hr": "Mikronezija",
196
+            "fa": "میکرونزی",
197
+            "de": "Mikronesien",
198
+            "es": "Micronesia",
199
+            "fr": "Micronésie",
200
+            "ja": "ミクロネシア",
201
+            "it": "Micronesia",
202
+            "zh-CN": "密克罗尼西亚群岛",
203
+            "ru": "Микронезия",
204
+            "uk": "Мікронезія",
205
+            "pl": "Mikronezja"
206
+        },
207
+        "wikiDataId": "Q3359409"
208
+    },
209
+    {
210
+        "id": 2,
211
+        "name": "Middle Africa",
212
+        "region_id": 1,
213
+        "translations": {
214
+            "br": "Afrika ar C'hreiz",
215
+            "ko": "중앙아프리카",
216
+            "pt": "África Central",
217
+            "nl": "Centraal-Afrika",
218
+            "hr": "Srednja Afrika",
219
+            "fa": "مرکز آفریقا",
220
+            "de": "Zentralafrika",
221
+            "es": "África Central",
222
+            "fr": "Afrique centrale",
223
+            "ja": "中部アフリカ",
224
+            "it": "Africa centrale",
225
+            "zh-CN": "中部非洲",
226
+            "ru": "Средняя Африка",
227
+            "uk": "Середня Африка",
228
+            "pl": "Afryka Środkowa"
229
+        },
230
+        "wikiDataId": "Q27433"
231
+    },
232
+    {
233
+        "id": 1,
234
+        "name": "Northern Africa",
235
+        "region_id": 1,
236
+        "translations": {
237
+            "br": "Afrika an North",
238
+            "ko": "북아프리카",
239
+            "pt": "Norte de África",
240
+            "nl": "Noord-Afrika",
241
+            "hr": "Sjeverna Afrika",
242
+            "fa": "شمال آفریقا",
243
+            "de": "Nordafrika",
244
+            "es": "Norte de África",
245
+            "fr": "Afrique du Nord",
246
+            "ja": "北アフリカ",
247
+            "it": "Nordafrica",
248
+            "zh-CN": "北部非洲",
249
+            "ru": "Северная Африка",
250
+            "uk": "Північна Африка",
251
+            "pl": "Afryka Północna"
252
+        },
253
+        "wikiDataId": "Q27381"
254
+    },
255
+    {
256
+        "id": 6,
257
+        "name": "Northern America",
258
+        "region_id": 2,
259
+        "translations": {
260
+            "br": "Norzhamerika",
261
+            "ko": "북미",
262
+            "pt": "América Setentrional",
263
+            "nl": "Noord-Amerika",
264
+            "fa": "شمال آمریکا",
265
+            "de": "Nordamerika",
266
+            "es": "América Norteña",
267
+            "fr": "Amérique septentrionale",
268
+            "ja": "北部アメリカ",
269
+            "it": "America settentrionale",
270
+            "zh-CN": "北美地區",
271
+            "ru": "Северная Америка",
272
+            "uk": "Північна Америка",
273
+            "pl": "Ameryka Północna"
274
+        },
275
+        "wikiDataId": "Q2017699"
276
+    },
277
+    {
278
+        "id": 18,
279
+        "name": "Northern Europe",
280
+        "region_id": 4,
281
+        "translations": {
282
+            "br": "Europa an North",
283
+            "ko": "북유럽",
284
+            "pt": "Europa Setentrional",
285
+            "nl": "Noord-Europa",
286
+            "hr": "Sjeverna Europa",
287
+            "fa": "شمال اروپا",
288
+            "de": "Nordeuropa",
289
+            "es": "Europa del Norte",
290
+            "fr": "Europe du Nord",
291
+            "ja": "北ヨーロッパ",
292
+            "it": "Europa settentrionale",
293
+            "zh-CN": "北歐",
294
+            "ru": "Северная Европа",
295
+            "uk": "Північна Європа",
296
+            "pl": "Europa Północna"
297
+        },
298
+        "wikiDataId": "Q27479"
299
+    },
300
+    {
301
+        "id": 22,
302
+        "name": "Polynesia",
303
+        "region_id": 5,
304
+        "translations": {
305
+            "br": "Polisezia",
306
+            "ko": "폴리네시아",
307
+            "pt": "Polinésia",
308
+            "nl": "Polynesië",
309
+            "hr": "Polinezija",
310
+            "fa": "پلی‌نزی",
311
+            "de": "Polynesien",
312
+            "es": "Polinesia",
313
+            "fr": "Polynésie",
314
+            "ja": "ポリネシア",
315
+            "it": "Polinesia",
316
+            "zh-CN": "玻里尼西亞",
317
+            "ru": "Полинезия",
318
+            "uk": "Полінезія",
319
+            "pl": "Polinezja"
320
+        },
321
+        "wikiDataId": "Q35942"
322
+    },
323
+    {
324
+        "id": 8,
325
+        "name": "South America",
326
+        "region_id": 2,
327
+        "translations": {
328
+            "br": "Suamerika",
329
+            "ko": "남아메리카",
330
+            "pt": "América do Sul",
331
+            "nl": "Zuid-Amerika",
332
+            "hr": "Južna Amerika",
333
+            "fa": "آمریکای جنوبی",
334
+            "de": "Südamerika",
335
+            "es": "América del Sur",
336
+            "fr": "Amérique du Sud",
337
+            "ja": "南アメリカ",
338
+            "it": "America meridionale",
339
+            "zh-CN": "南美洲",
340
+            "ru": "Южная Америка",
341
+            "uk": "Південна Америка",
342
+            "pl": "Ameryka Południowa"
343
+        },
344
+        "wikiDataId": "Q18"
345
+    },
346
+    {
347
+        "id": 13,
348
+        "name": "South-Eastern Asia",
349
+        "region_id": 3,
350
+        "translations": {
351
+            "br": "Azia ar Gevred",
352
+            "ko": "동남아시아",
353
+            "pt": "Sudeste Asiático",
354
+            "nl": "Zuidoost-Azië",
355
+            "hr": "Jugoistočna Azija",
356
+            "fa": "جنوب شرق آسیا",
357
+            "de": "Südostasien",
358
+            "es": "Sudeste Asiático",
359
+            "fr": "Asie du Sud-Est",
360
+            "ja": "東南アジア",
361
+            "it": "Sud-est asiatico",
362
+            "zh-CN": "东南亚",
363
+            "ru": "Юго-Восточная Азия",
364
+            "uk": "Південно-Східна Азія",
365
+            "pl": "Azja Południowo-Wschodnia"
366
+        },
367
+        "wikiDataId": "Q11708"
368
+    },
369
+    {
370
+        "id": 5,
371
+        "name": "Southern Africa",
372
+        "region_id": 1,
373
+        "translations": {
374
+            "br": "Suafrika",
375
+            "ko": "남아프리카",
376
+            "pt": "África Austral",
377
+            "nl": "Zuidelijk Afrika",
378
+            "hr": "Južna Afrika",
379
+            "fa": "جنوب آفریقا",
380
+            "de": "Südafrika",
381
+            "es": "África austral",
382
+            "fr": "Afrique australe",
383
+            "ja": "南部アフリカ",
384
+            "it": "Africa australe",
385
+            "zh-CN": "南部非洲",
386
+            "ru": "Южная Африка",
387
+            "uk": "Південна Африка",
388
+            "pl": "Afryka Południowa"
389
+        },
390
+        "wikiDataId": "Q27394"
391
+    },
392
+    {
393
+        "id": 14,
394
+        "name": "Southern Asia",
395
+        "region_id": 3,
396
+        "translations": {
397
+            "br": "Azia ar Su",
398
+            "ko": "남아시아",
399
+            "pt": "Ásia Meridional",
400
+            "nl": "Zuid-Azië",
401
+            "hr": "Južna Azija",
402
+            "fa": "جنوب آسیا",
403
+            "de": "Südasien",
404
+            "es": "Asia del Sur",
405
+            "fr": "Asie du Sud",
406
+            "ja": "南アジア",
407
+            "it": "Asia meridionale",
408
+            "zh-CN": "南亚",
409
+            "ru": "Южная Азия",
410
+            "uk": "Південна Азія",
411
+            "pl": "Azja Południowa"
412
+        },
413
+        "wikiDataId": "Q771405"
414
+    },
415
+    {
416
+        "id": 16,
417
+        "name": "Southern Europe",
418
+        "region_id": 4,
419
+        "translations": {
420
+            "br": "Europa ar Su",
421
+            "ko": "남유럽",
422
+            "pt": "Europa meridional",
423
+            "nl": "Zuid-Europa",
424
+            "hr": "Južna Europa",
425
+            "fa": "جنوب اروپا",
426
+            "de": "Südeuropa",
427
+            "es": "Europa del Sur",
428
+            "fr": "Europe du Sud",
429
+            "ja": "南ヨーロッパ",
430
+            "it": "Europa meridionale",
431
+            "zh-CN": "南欧",
432
+            "ru": "Южная Европа",
433
+            "uk": "Південна Європа",
434
+            "pl": "Europa Południowa"
435
+        },
436
+        "wikiDataId": "Q27449"
437
+    },
438
+    {
439
+        "id": 3,
440
+        "name": "Western Africa",
441
+        "region_id": 1,
442
+        "translations": {
443
+            "br": "Afrika ar C'hornaoueg",
444
+            "ko": "서아프리카",
445
+            "pt": "África Ocidental",
446
+            "nl": "West-Afrika",
447
+            "hr": "Zapadna Afrika",
448
+            "fa": "غرب آفریقا",
449
+            "de": "Westafrika",
450
+            "es": "África Occidental",
451
+            "fr": "Afrique de l'Ouest",
452
+            "ja": "西アフリカ",
453
+            "it": "Africa occidentale",
454
+            "zh-CN": "西非",
455
+            "ru": "Западная Африка",
456
+            "uk": "Західна Африка",
457
+            "pl": "Afryka Zachodnia"
458
+        },
459
+        "wikiDataId": "Q4412"
460
+    },
461
+    {
462
+        "id": 11,
463
+        "name": "Western Asia",
464
+        "region_id": 3,
465
+        "translations": {
466
+            "br": "Azia ar Mervent",
467
+            "ko": "서아시아",
468
+            "pt": "Sudoeste Asiático",
469
+            "nl": "Zuidwest-Azië",
470
+            "hr": "Jugozapadna Azija",
471
+            "fa": "غرب آسیا",
472
+            "de": "Vorderasien",
473
+            "es": "Asia Occidental",
474
+            "fr": "Asie de l'Ouest",
475
+            "ja": "西アジア",
476
+            "it": "Asia occidentale",
477
+            "zh-CN": "西亚",
478
+            "ru": "Западная Азия",
479
+            "uk": "Західна Азія",
480
+            "pl": "Azja Zachodnia"
481
+        },
482
+        "wikiDataId": "Q27293"
483
+    },
484
+    {
485
+        "id": 17,
486
+        "name": "Western Europe",
487
+        "region_id": 4,
488
+        "translations": {
489
+            "br": "Europa ar C'hornaoueg",
490
+            "ko": "서유럽",
491
+            "pt": "Europa Ocidental",
492
+            "nl": "West-Europa",
493
+            "hr": "Zapadna Europa",
494
+            "fa": "غرب اروپا",
495
+            "de": "Westeuropa",
496
+            "es": "Europa Occidental",
497
+            "fr": "Europe de l'Ouest",
498
+            "ja": "西ヨーロッパ",
499
+            "it": "Europa occidentale",
500
+            "zh-CN": "西欧",
501
+            "ru": "Западная Европа",
502
+            "uk": "Західна Європа",
503
+            "pl": "Europa Zachodnia"
504
+        },
505
+        "wikiDataId": "Q27496"
506
+    }
507
+]

tum/whitesports - Gogs: Simplico Git Service

No Description

po.php 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510
  1. <?php
  2. /**
  3. * Class for working with PO files
  4. *
  5. * @version $Id: po.php 1158 2015-11-20 04:31:23Z dd32 $
  6. * @package pomo
  7. * @subpackage po
  8. */
  9. require_once __DIR__ . '/translations.php';
  10. if ( ! defined( 'PO_MAX_LINE_LEN' ) ) {
  11. define( 'PO_MAX_LINE_LEN', 79 );
  12. }
  13. ini_set( 'auto_detect_line_endings', 1 );
  14. /**
  15. * Routines for working with PO files
  16. */
  17. if ( ! class_exists( 'PO', false ) ) :
  18. class PO extends Gettext_Translations {
  19. public $comments_before_headers = '';
  20. /**
  21. * Exports headers to a PO entry
  22. *
  23. * @return string msgid/msgstr PO entry for this PO file headers, doesn't contain newline at the end
  24. */
  25. function export_headers() {
  26. $header_string = '';
  27. foreach ( $this->headers as $header => $value ) {
  28. $header_string .= "$header: $value\n";
  29. }
  30. $poified = PO::poify( $header_string );
  31. if ( $this->comments_before_headers ) {
  32. $before_headers = $this->prepend_each_line( rtrim( $this->comments_before_headers ) . "\n", '# ' );
  33. } else {
  34. $before_headers = '';
  35. }
  36. return rtrim( "{$before_headers}msgid \"\"\nmsgstr $poified" );
  37. }
  38. /**
  39. * Exports all entries to PO format
  40. *
  41. * @return string sequence of mgsgid/msgstr PO strings, doesn't containt newline at the end
  42. */
  43. function export_entries() {
  44. // TODO: Sorting.
  45. return implode( "\n\n", array_map( array( 'PO', 'export_entry' ), $this->entries ) );
  46. }
  47. /**
  48. * Exports the whole PO file as a string
  49. *
  50. * @param bool $include_headers whether to include the headers in the export
  51. * @return string ready for inclusion in PO file string for headers and all the enrtries
  52. */
  53. function export( $include_headers = true ) {
  54. $res = '';
  55. if ( $include_headers ) {
  56. $res .= $this->export_headers();
  57. $res .= "\n\n";
  58. }
  59. $res .= $this->export_entries();
  60. return $res;
  61. }
  62. /**
  63. * Same as {@link export}, but writes the result to a file
  64. *
  65. * @param string $filename Where to write the PO string.
  66. * @param bool $include_headers Whether to include the headers in the export.
  67. * @return bool true on success, false on error
  68. */
  69. function export_to_file( $filename, $include_headers = true ) {
  70. $fh = fopen( $filename, 'w' );
  71. if ( false === $fh ) {
  72. return false;
  73. }
  74. $export = $this->export( $include_headers );
  75. $res = fwrite( $fh, $export );
  76. if ( false === $res ) {
  77. return false;
  78. }
  79. return fclose( $fh );
  80. }
  81. /**
  82. * Text to include as a comment before the start of the PO contents
  83. *
  84. * Doesn't need to include # in the beginning of lines, these are added automatically
  85. *
  86. * @param string $text Text to include as a comment.
  87. */
  88. function set_comment_before_headers( $text ) {
  89. $this->comments_before_headers = $text;
  90. }
  91. /**
  92. * Formats a string in PO-style
  93. *
  94. * @param string $string the string to format
  95. * @return string the poified string
  96. */
  97. public static function poify( $string ) {
  98. $quote = '"';
  99. $slash = '\\';
  100. $newline = "\n";
  101. $replaces = array(
  102. "$slash" => "$slash$slash",
  103. "$quote" => "$slash$quote",
  104. "\t" => '\t',
  105. );
  106. $string = str_replace( array_keys( $replaces ), array_values( $replaces ), $string );
  107. $po = $quote . implode( "${slash}n$quote$newline$quote", explode( $newline, $string ) ) . $quote;
  108. // Add empty string on first line for readbility.
  109. if ( false !== strpos( $string, $newline ) &&
  110. ( substr_count( $string, $newline ) > 1 || substr( $string, -strlen( $newline ) ) !== $newline ) ) {
  111. $po = "$quote$quote$newline$po";
  112. }
  113. // Remove empty strings.
  114. $po = str_replace( "$newline$quote$quote", '', $po );
  115. return $po;
  116. }
  117. /**
  118. * Gives back the original string from a PO-formatted string
  119. *
  120. * @param string $string PO-formatted string
  121. * @return string enascaped string
  122. */
  123. public static function unpoify( $string ) {
  124. $escapes = array(
  125. 't' => "\t",
  126. 'n' => "\n",
  127. 'r' => "\r",
  128. '\\' => '\\',
  129. );
  130. $lines = array_map( 'trim', explode( "\n", $string ) );
  131. $lines = array_map( array( 'PO', 'trim_quotes' ), $lines );
  132. $unpoified = '';
  133. $previous_is_backslash = false;
  134. foreach ( $lines as $line ) {
  135. preg_match_all( '/./u', $line, $chars );
  136. $chars = $chars[0];
  137. foreach ( $chars as $char ) {
  138. if ( ! $previous_is_backslash ) {
  139. if ( '\\' === $char ) {
  140. $previous_is_backslash = true;
  141. } else {
  142. $unpoified .= $char;
  143. }
  144. } else {
  145. $previous_is_backslash = false;
  146. $unpoified .= isset( $escapes[ $char ] ) ? $escapes[ $char ] : $char;
  147. }
  148. }
  149. }
  150. // Standardise the line endings on imported content, technically PO files shouldn't contain \r.
  151. $unpoified = str_replace( array( "\r\n", "\r" ), "\n", $unpoified );
  152. return $unpoified;
  153. }
  154. /**
  155. * Inserts $with in the beginning of every new line of $string and
  156. * returns the modified string
  157. *
  158. * @param string $string prepend lines in this string
  159. * @param string $with prepend lines with this string
  160. */
  161. public static function prepend_each_line( $string, $with ) {
  162. $lines = explode( "\n", $string );
  163. $append = '';
  164. if ( "\n" === substr( $string, -1 ) && '' === end( $lines ) ) {
  165. /*
  166. * Last line might be empty because $string was terminated
  167. * with a newline, remove it from the $lines array,
  168. * we'll restore state by re-terminating the string at the end.
  169. */
  170. array_pop( $lines );
  171. $append = "\n";
  172. }
  173. foreach ( $lines as &$line ) {
  174. $line = $with . $line;
  175. }
  176. unset( $line );
  177. return implode( "\n", $lines ) . $append;
  178. }
  179. /**
  180. * Prepare a text as a comment -- wraps the lines and prepends #
  181. * and a special character to each line
  182. *
  183. * @access private
  184. * @param string $text the comment text
  185. * @param string $char character to denote a special PO comment,
  186. * like :, default is a space
  187. */
  188. public static function comment_block( $text, $char = ' ' ) {
  189. $text = wordwrap( $text, PO_MAX_LINE_LEN - 3 );
  190. return PO::prepend_each_line( $text, "#$char " );
  191. }
  192. /**
  193. * Builds a string from the entry for inclusion in PO file
  194. *
  195. * @param Translation_Entry $entry the entry to convert to po string.
  196. * @return string|false PO-style formatted string for the entry or
  197. * false if the entry is empty
  198. */
  199. public static function export_entry( $entry ) {
  200. if ( null === $entry->singular || '' === $entry->singular ) {
  201. return false;
  202. }
  203. $po = array();
  204. if ( ! empty( $entry->translator_comments ) ) {
  205. $po[] = PO::comment_block( $entry->translator_comments );
  206. }
  207. if ( ! empty( $entry->extracted_comments ) ) {
  208. $po[] = PO::comment_block( $entry->extracted_comments, '.' );
  209. }
  210. if ( ! empty( $entry->references ) ) {
  211. $po[] = PO::comment_block( implode( ' ', $entry->references ), ':' );
  212. }
  213. if ( ! empty( $entry->flags ) ) {
  214. $po[] = PO::comment_block( implode( ', ', $entry->flags ), ',' );
  215. }
  216. if ( $entry->context ) {
  217. $po[] = 'msgctxt ' . PO::poify( $entry->context );
  218. }
  219. $po[] = 'msgid ' . PO::poify( $entry->singular );
  220. if ( ! $entry->is_plural ) {
  221. $translation = empty( $entry->translations ) ? '' : $entry->translations[0];
  222. $translation = PO::match_begin_and_end_newlines( $translation, $entry->singular );
  223. $po[] = 'msgstr ' . PO::poify( $translation );
  224. } else {
  225. $po[] = 'msgid_plural ' . PO::poify( $entry->plural );
  226. $translations = empty( $entry->translations ) ? array( '', '' ) : $entry->translations;
  227. foreach ( $translations as $i => $translation ) {
  228. $translation = PO::match_begin_and_end_newlines( $translation, $entry->plural );
  229. $po[] = "msgstr[$i] " . PO::poify( $translation );
  230. }
  231. }
  232. return implode( "\n", $po );
  233. }
  234. public static function match_begin_and_end_newlines( $translation, $original ) {
  235. if ( '' === $translation ) {
  236. return $translation;
  237. }
  238. $original_begin = "\n" === substr( $original, 0, 1 );
  239. $original_end = "\n" === substr( $original, -1 );
  240. $translation_begin = "\n" === substr( $translation, 0, 1 );
  241. $translation_end = "\n" === substr( $translation, -1 );
  242. if ( $original_begin ) {
  243. if ( ! $translation_begin ) {
  244. $translation = "\n" . $translation;
  245. }
  246. } elseif ( $translation_begin ) {
  247. $translation = ltrim( $translation, "\n" );
  248. }
  249. if ( $original_end ) {
  250. if ( ! $translation_end ) {
  251. $translation .= "\n";
  252. }
  253. } elseif ( $translation_end ) {
  254. $translation = rtrim( $translation, "\n" );
  255. }
  256. return $translation;
  257. }
  258. /**
  259. * @param string $filename
  260. * @return bool
  261. */
  262. function import_from_file( $filename ) {
  263. $f = fopen( $filename, 'r' );
  264. if ( ! $f ) {
  265. return false;
  266. }
  267. $lineno = 0;
  268. while ( true ) {
  269. $res = $this->read_entry( $f, $lineno );
  270. if ( ! $res ) {
  271. break;
  272. }
  273. if ( '' === $res['entry']->singular ) {
  274. $this->set_headers( $this->make_headers( $res['entry']->translations[0] ) );
  275. } else {
  276. $this->add_entry( $res['entry'] );
  277. }
  278. }
  279. PO::read_line( $f, 'clear' );
  280. if ( false === $res ) {
  281. return false;
  282. }
  283. if ( ! $this->headers && ! $this->entries ) {
  284. return false;
  285. }
  286. return true;
  287. }
  288. /**
  289. * Helper function for read_entry
  290. *
  291. * @param string $context
  292. * @return bool
  293. */
  294. protected static function is_final( $context ) {
  295. return ( 'msgstr' === $context ) || ( 'msgstr_plural' === $context );
  296. }
  297. /**
  298. * @param resource $f
  299. * @param int $lineno
  300. * @return null|false|array
  301. */
  302. function read_entry( $f, $lineno = 0 ) {
  303. $entry = new Translation_Entry();
  304. // Where were we in the last step.
  305. // Can be: comment, msgctxt, msgid, msgid_plural, msgstr, msgstr_plural.
  306. $context = '';
  307. $msgstr_index = 0;
  308. while ( true ) {
  309. $lineno++;
  310. $line = PO::read_line( $f );
  311. if ( ! $line ) {
  312. if ( feof( $f ) ) {
  313. if ( self::is_final( $context ) ) {
  314. break;
  315. } elseif ( ! $context ) { // We haven't read a line and EOF came.
  316. return null;
  317. } else {
  318. return false;
  319. }
  320. } else {
  321. return false;
  322. }
  323. }
  324. if ( "\n" === $line ) {
  325. continue;
  326. }
  327. $line = trim( $line );
  328. if ( preg_match( '/^#/', $line, $m ) ) {
  329. // The comment is the start of a new entry.
  330. if ( self::is_final( $context ) ) {
  331. PO::read_line( $f, 'put-back' );
  332. $lineno--;
  333. break;
  334. }
  335. // Comments have to be at the beginning.
  336. if ( $context && 'comment' !== $context ) {
  337. return false;
  338. }
  339. // Add comment.
  340. $this->add_comment_to_entry( $entry, $line );
  341. } elseif ( preg_match( '/^msgctxt\s+(".*")/', $line, $m ) ) {
  342. if ( self::is_final( $context ) ) {
  343. PO::read_line( $f, 'put-back' );
  344. $lineno--;
  345. break;
  346. }
  347. if ( $context && 'comment' !== $context ) {
  348. return false;
  349. }
  350. $context = 'msgctxt';
  351. $entry->context .= PO::unpoify( $m[1] );
  352. } elseif ( preg_match( '/^msgid\s+(".*")/', $line, $m ) ) {
  353. if ( self::is_final( $context ) ) {
  354. PO::read_line( $f, 'put-back' );
  355. $lineno--;
  356. break;
  357. }
  358. if ( $context && 'msgctxt' !== $context && 'comment' !== $context ) {
  359. return false;
  360. }
  361. $context = 'msgid';
  362. $entry->singular .= PO::unpoify( $m[1] );
  363. } elseif ( preg_match( '/^msgid_plural\s+(".*")/', $line, $m ) ) {
  364. if ( 'msgid' !== $context ) {
  365. return false;
  366. }
  367. $context = 'msgid_plural';
  368. $entry->is_plural = true;
  369. $entry->plural .= PO::unpoify( $m[1] );
  370. } elseif ( preg_match( '/^msgstr\s+(".*")/', $line, $m ) ) {
  371. if ( 'msgid' !== $context ) {
  372. return false;
  373. }
  374. $context = 'msgstr';
  375. $entry->translations = array( PO::unpoify( $m[1] ) );
  376. } elseif ( preg_match( '/^msgstr\[(\d+)\]\s+(".*")/', $line, $m ) ) {
  377. if ( 'msgid_plural' !== $context && 'msgstr_plural' !== $context ) {
  378. return false;
  379. }
  380. $context = 'msgstr_plural';
  381. $msgstr_index = $m[1];
  382. $entry->translations[ $m[1] ] = PO::unpoify( $m[2] );
  383. } elseif ( preg_match( '/^".*"$/', $line ) ) {
  384. $unpoified = PO::unpoify( $line );
  385. switch ( $context ) {
  386. case 'msgid':
  387. $entry->singular .= $unpoified;
  388. break;
  389. case 'msgctxt':
  390. $entry->context .= $unpoified;
  391. break;
  392. case 'msgid_plural':
  393. $entry->plural .= $unpoified;
  394. break;
  395. case 'msgstr':
  396. $entry->translations[0] .= $unpoified;
  397. break;
  398. case 'msgstr_plural':
  399. $entry->translations[ $msgstr_index ] .= $unpoified;
  400. break;
  401. default:
  402. return false;
  403. }
  404. } else {
  405. return false;
  406. }
  407. }
  408. $have_translations = false;
  409. foreach ( $entry->translations as $t ) {
  410. if ( $t || ( '0' === $t ) ) {
  411. $have_translations = true;
  412. break;
  413. }
  414. }
  415. if ( false === $have_translations ) {
  416. $entry->translations = array();
  417. }
  418. return array(
  419. 'entry' => $entry,
  420. 'lineno' => $lineno,
  421. );
  422. }
  423. /**
  424. * @param resource $f
  425. * @param string $action
  426. * @return bool
  427. */
  428. function read_line( $f, $action = 'read' ) {
  429. static $last_line = '';
  430. static $use_last_line = false;
  431. if ( 'clear' === $action ) {
  432. $last_line = '';
  433. return true;
  434. }
  435. if ( 'put-back' === $action ) {
  436. $use_last_line = true;
  437. return true;
  438. }
  439. $line = $use_last_line ? $last_line : fgets( $f );
  440. $line = ( "\r\n" === substr( $line, -2 ) ) ? rtrim( $line, "\r\n" ) . "\n" : $line;
  441. $last_line = $line;
  442. $use_last_line = false;
  443. return $line;
  444. }
  445. /**
  446. * @param Translation_Entry $entry
  447. * @param string $po_comment_line
  448. */
  449. function add_comment_to_entry( &$entry, $po_comment_line ) {
  450. $first_two = substr( $po_comment_line, 0, 2 );
  451. $comment = trim( substr( $po_comment_line, 2 ) );
  452. if ( '#:' === $first_two ) {
  453. $entry->references = array_merge( $entry->references, preg_split( '/\s+/', $comment ) );
  454. } elseif ( '#.' === $first_two ) {
  455. $entry->extracted_comments = trim( $entry->extracted_comments . "\n" . $comment );
  456. } elseif ( '#,' === $first_two ) {
  457. $entry->flags = array_merge( $entry->flags, preg_split( '/,\s*/', $comment ) );
  458. } else {
  459. $entry->translator_comments = trim( $entry->translator_comments . "\n" . $comment );
  460. }
  461. }
  462. /**
  463. * @param string $s
  464. * @return string
  465. */
  466. public static function trim_quotes( $s ) {
  467. if ( '"' === substr( $s, 0, 1 ) ) {
  468. $s = substr( $s, 1 );
  469. }
  470. if ( '"' === substr( $s, -1, 1 ) ) {
  471. $s = substr( $s, 0, -1 );
  472. }
  473. return $s;
  474. }
  475. }
  476. endif;