-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathExporter.php
262 lines (223 loc) · 7.68 KB
/
Exporter.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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
<?php
/**
* @Note We do not worry about translating "header transclusions" for non-existing articles -
* that is the responsibility of the translation manager. All titles in the project list
* now have their "dependencies" (titles it transcludes from) marked
*/
namespace ExportForTranslation;
use Config;
use MediaWiki\MediaWikiServices;
use MediaWiki\Revision\SlotRecord;
use MWException;
use Title;
use TranslationManager\TranslationManagerStatus;
use WikiPage;
class Exporter {
private const EXTENSION_NAME = 'ExportForTranslation';
/** @var Config */
private static Config $config;
/** @var string[] */
private static $textTemplates = [
'header' => '/\=\=\s*(%s)\s*\=\=/',
'header-replacement' => '== %s ==',
'header-transclusion' => '/#%s(}}|\s*\|)/',
'header-transclusion-replacement' => '#%s$1',
// A link starts with [, but can end with ], | or # - beyond either it's just text
'title' => '/\[\[\s*?%s\s*([\|\]#])/',
'title-replacement' => '[[%s$1',
'title-transclusion' => '/\{\{\s*הטמעת כותרת\s*\|\s*%s\#/',
'title-transclusion-replacement' => '{{הטמעת כותרת | %s#'
];
/** @var string[] */
private static array $linkTranslations = [];
/**
* @return string|null
* @throws MWException
*/
public static function getLanguagePreference() {
$services = MediaWikiServices::getInstance();
$userOptionsLookup = $services->getUserOptionsLookup();
$user = \RequestContext::getMain()->getUser();
$language = $userOptionsLookup->getOption( $user, 'translationmanager-language' );
$language = $language ?? self::getConfigVar( 'ExportForTranslationDefaultLanguage' );
if ( !TranslationManagerStatus::isValidLanguage( $language ) ) {
throw new MWException( "Invalid target language '$language' for translation export!" );
}
return $language;
}
/**
* @param string $name
*
* @return mixed
*/
protected static function getConfigVar( $name ) {
if ( !isset( self::$config ) ) {
self::$config = MediaWikiServices::getInstance()
->getConfigFactory()
->makeConfig( self::EXTENSION_NAME );
}
try {
$value = self::$config->get( $name );
} catch ( \ConfigException $e ) {
$value = null;
}
return $value;
}
/**
* Load the content of a given page (by name), do our misc. transformations & add metadata
*
* @param Title $title
* @param int|null $rev_id
* @param string|null $lang ISO 639-1 language code
*
* @return null|string
*/
public static function export( Title $title, $rev_id = null, $lang = null ): ?string {
$revisionStore = MediaWikiServices::getInstance()->getRevisionStore();
$targetLanguage = $lang ?? self::getLanguagePreference();
$revision = $rev_id ? $revisionStore->getRevisionById( $rev_id ) : $revisionStore->getRevisionByTitle( $title );
$wikitext = $revision->getContent( SlotRecord::MAIN )->getText();
$wikiPage = \WikiPage::factory( $title );
$linkTitles = self::getPageLinks( $wikiPage );
$linkPageIds = array_map(
static function ( Title $t ) {
return $t->getArticleID();
},
$linkTitles
);
// Also get the translation for the current page
$linkPageIds[] = $wikiPage->getId();
// Translate headers
$headersTargetMsg = wfMessage( 'exportfortranslation-headers-list-' . $targetLanguage );
if ( $headersTargetMsg->exists() ) {
$needles = explode(
"\n", wfMessage( 'exportfortranslation-headers-list-he' )->text()
);
$replacements = explode( "\n", $headersTargetMsg->text() );
// Translate regular headers
$wikitext = self::transform( $wikitext, $needles, $replacements, 'header' );
// Translate headers in transclusions
$wikitext = self::transform( $wikitext, $needles, $replacements, 'header-transclusion' );
}
// Translate regular links
self::$linkTranslations = TranslationManagerStatus::getSuggestionsByIds(
$targetLanguage, 'title', $linkPageIds
);
$needles = array_keys( self::$linkTranslations );
$replacements = array_values( self::$linkTranslations );
// Do title transformation in links
$wikitext = self::transform( $wikitext, $needles, $replacements, 'title' );
// Do title transformation in transclusions
$wikitext = self::transform( $wikitext, $needles, $replacements, 'title-transclusion' );
// Add metadata as comment
$wikitext = self::getArticleMetadata( $title ) . $wikitext;
$wikitext .= PHP_EOL . self::makeLanguageLinkToSource( $title );
return $wikitext;
}
/**
* @param WikiPage $wikiPage
*
* @return Title[]
*/
private static function getPageLinks( WikiPage $wikiPage ): array {
$pageLinks = [];
$pageCategories = [];
$title = $wikiPage->getTitle();
if ( $title->exists() ) {
$pageLinks = $title->getLinksFrom();
// Returns TitleArray
$pageCategories = iterator_to_array( $wikiPage->getCategories() );
}
return array_merge( $pageLinks, $pageCategories );
}
/**
* Make an interlanguage link back to the original page
*
* @param Title $title
*
* @return string
*/
private static function makeLanguageLinkToSource( Title $title ): string {
$hebrewName = $title->getFullText();
return '[[he:' . $hebrewName . ']]' . PHP_EOL;
}
/**
* Return the article's metadata as a template
*
* @param Title $title
*
* @return string
*/
private static function getArticleMetadata( Title $title ): string {
$hebrewName = $title->getFullText();
$metadata = '{{נתוני תרגום' . PHP_EOL;
$metadata .= '|שם=' . $hebrewName . PHP_EOL;
$targetName = self::$linkTranslations[ $hebrewName ] ?? null;
$metadata .= '|שם מתורגם=' . $targetName . PHP_EOL;
$wikipage = WikiPage::newFromID( $title->getArticleID() );
$lastmod = $wikipage->getTimestamp();
$metadata .= '|תאריך עדכון מקור=' . $lastmod . PHP_EOL;
$metadata .= '|rev_id=' . $wikipage->getLatest() . PHP_EOL;
$metadata .= '}}' . PHP_EOL;
return $metadata;
}
/**
* Do the actual replacements
*
* @param string $wikitext
* @param array $needles
* @param array $replacements
* @param string $type
*
* @return string
*/
private static function transform( string $wikitext, array $needles, array $replacements, string $type ): string {
array_walk( $needles, [ __CLASS__, 'doParamReplacement' ], $type );
array_walk( $replacements, [ __CLASS__, 'doParamReplacement' ], "$type-replacement" );
$wikitext = preg_replace( $needles, $replacements, $wikitext );
return $wikitext;
}
/**
* @param string $type
*
* @return string
*/
private static function getTemplateForType( string $type ): string {
return self::$textTemplates[ $type ];
}
/**
* @param string &$needle
* @param int|string $key
* @param string $type
*
* @return bool
*/
private static function doParamReplacement( string &$needle, $key, string $type ): bool {
$template = self::getTemplateForType( $type );
// Only for search strings
if ( strpos( $type, 'replacement' ) === false ) {
// Escape the string, including regex delimiter
$needle = preg_quote( $needle, '/' );
// Ignore extra spaces, because MW ignores them when creating links
$needle = str_replace( ' ', '\s*', $needle );
}
$needle = sprintf( $template, $needle );
return true;
}
/**
* This function expects the text we previously exported; it then tries to find the revision ID
* inside that text.
*
* It should be kept compatible with the way getArticleMetadata() adds that revision ID, and
* hopefully backwards-compatible as well.
*
* @param string $text
*
* @return int|null
*/
public static function getRevIdFromText( string $text ): ?int {
$matches = [];
preg_match( '/rev_id\s*=\s*(\d+)/', $text, $matches );
return isset( $matches[1] ) ? (int)$matches[1] : null;
}
}