-
Notifications
You must be signed in to change notification settings - Fork 8
/
TranslateController.php
226 lines (210 loc) · 8.11 KB
/
TranslateController.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
<?php
declare(strict_types = 1);
namespace App\Controller;
use App\Model\Svg\SvgFile;
use App\Model\Title;
use App\Service\FileCache;
use App\Service\Uploader;
use Krinkle\Intuition\Intuition;
use OOUI\ButtonInputWidget;
use OOUI\DropdownInputWidget;
use OOUI\FieldLayout;
use OOUI\FieldsetLayout;
use OOUI\HorizontalLayout;
use OOUI\LabelWidget;
use OOUI\TextInputWidget;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\Routing\Annotation\Route;
class TranslateController extends AbstractController
{
/**
* The translate page.
*
* The 'prefix' part of this route is actually a fixed string 'File', but in order to make it
* case-insensitive we have to make it a route variable with a regex requirement. Then we can
* also check it and redirect to the canonical form when required.
* @Route( "/{prefix}:{filename}",
* name="translate",
* methods={"GET"},
* requirements={"prefix"="(?i:File)", "filename"="(.+)"}
* )
*/
public function translate(
Request $request,
Intuition $intuition,
Session $session,
FileCache $cache,
string $filename,
string $prefix = 'File'
): Response {
$normalizedFilename = Title::normalize($filename);
// Redirect to normalized URL if required.
if ('File' !== $prefix || $filename !== $normalizedFilename) {
return $this->redirectToRoute('translate', ['filename' => $normalizedFilename]);
}
// Fetch the SVG from Commons.
$path = $cache->getPath($filename);
$svgFile = new SvgFile($path);
// Upload and download buttons.
$downloadButton = new ButtonInputWidget([
'label' => $intuition->msg('download-button-label'),
'flags' => [ 'progressive' ],
'type' => 'submit',
'framed' => false,
]);
$uploadButton = new ButtonInputWidget([
'label' => $intuition->msg('upload-button-label'),
'flags' => [ 'progressive' ],
'type' => 'submit',
'icon' => 'logoWikimediaCommons',
'name' => 'upload',
]);
if (!$session->get('logged_in_user')) {
// Only logged in users can upload.
$uploadButton->setDisabled(true);
}
// Source and target language selectors.
$availableLangs = [
['data' => 'fallback', 'label' => $intuition->msg('default-language')],
];
foreach ($svgFile->getSavedLanguages() as $lang) {
$langName = $intuition->getLangName($lang);
if ($langName) {
$availableLangs[] = [
'data' => $lang,
'label' => $langName,
];
}
}
$sourceLang = new DropdownInputWidget([
'label' => $intuition->msg('source-lang-label'),
'options' => $availableLangs,
// @TODO Get this value from the session.
'value' => 'fallback',
'classes' => ['source-lang-widget'],
'infusable' => true,
]);
$targetLangDefault = $intuition->getLang();
$cookie = $request->cookies->get('svgtranslate');
if ($cookie) {
$cookieValue = json_decode($cookie);
if (isset($cookieValue->interfaceLang)) {
$targetLangDefault = $cookieValue->interfaceLang;
}
}
$targetLang = new ButtonInputWidget([
'label' => $intuition->getLangName($targetLangDefault),
'value' => $targetLangDefault,
'classes' => ['target-lang-widget'],
'indicator' => 'down',
'infusable' => true,
'name' => 'target-lang',
]);
$languageSelectorsLayout = new HorizontalLayout([
'items' => [
$sourceLang,
new LabelWidget([
'label' => $intuition->msg('source-to-target'),
'classes' => ['source-to-target-label'],
]),
$targetLang,
],
'classes' => ['language-selectors'],
]);
// Messages.
$translations = $svgFile->getInFileTranslations();
$currentFieldset = new FieldsetLayout();
$fieldsets = [$currentFieldset];
$prevTranslation = null;
foreach ($translations as $tspanId => $translation) {
// Do not display translations that are only white-space. https://stackoverflow.com/a/4167053/99667
// @TODO SvgFile should probably be handling this for us.
$whitespacePattern = '/^[\pZ\pC]+|[\pZ\pC]+$/u';
$sourceLabel = preg_replace($whitespacePattern, '', $translation[$sourceLang->getValue()]['text']);
if ('' === $sourceLabel) {
continue;
}
// Add fields for all other translations.
$fieldValue = isset($translation[$targetLang->getValue()])
? $translation[$targetLang->getValue()]['text']
: '';
$inputWidget = new TextInputWidget([
'name' => $tspanId,
'value' => $fieldValue,
'data' => ['tspan-id' => $tspanId],
]);
$field = new FieldLayout(
$inputWidget,
[
'label' => $sourceLabel,
'infusable' => true,
]
);
// Start a new fieldset if the current translation's parent is different to the previous's.
if ($prevTranslation
&& $prevTranslation['fallback']['data-parent'] !== $translation['fallback']['data-parent']) {
$currentFieldset = new FieldsetLayout();
$fieldsets[] = $currentFieldset;
}
$currentFieldset->addItems([$field]);
$prevTranslation = $translation;
}
return $this->render('translate.html.twig', [
'page_class' => 'translate',
'title' => Title::text($filename),
'filename' => $normalizedFilename,
'fieldsets' => $fieldsets,
'download_button' => $downloadButton,
'upload_button' => $uploadButton,
'language_selectors' => $languageSelectorsLayout,
'translations' => $translations,
'target_lang' => $targetLangDefault,
]);
}
/**
* @Route( "/File:{filename}", name="updownload", methods={"POST"})
*/
public function updownload(
string $filename,
Request $request,
FileCache $cache,
Uploader $uploader
): Response {
$requestParams = $request->request->all();
// Are we uploading or downloading?
$isUpload = false;
if (isset($requestParams['upload'])) {
$isUpload = true;
unset($requestParams['upload']);
}
// Target language.
$targetLang = $requestParams['target-lang'];
unset($requestParams['target-lang']);
// Add the translations to the file and save it to the filesystem.
$file = new SvgFile($cache->getPath(Title::normalize($filename)));
$file->setTranslations($targetLang, $requestParams);
$tmpFilename = $cache->fullPath($filename.uniqid().'.svg');
file_put_contents($tmpFilename, $file->saveToString());
// Download or upload.
if (!$isUpload) {
// Prompt for download.
return new BinaryFileResponse(
$tmpFilename,
200,
[],
false,
ResponseHeaderBag::DISPOSITION_ATTACHMENT
);
} else {
// Send to Commons.
$url = $uploader->upload($tmpFilename, $filename);
$this->addFlash('upload-complete', $url);
return $this->redirectToRoute('translate', ['filename' => $filename]);
}
}
}