summaryrefslogtreecommitdiff
path: root/www/wiki/extensions/Translate/ffs/MediaWikiExtensionFFS.php
blob: f6aadf32e8de8de0d679f8ab974f842fc56a3622 (plain)
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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
<?php
/**
 * Support for the ugly file format that is used by MediaWiki extensions.
 *
 * @file
 * @author Niklas Laxström
 * @copyright Copyright © 2012-2013, Niklas Laxström
 * @license GPL-2.0+
 */

/**
 * Manipulates ExtensionName.i18n.php style files.
 *
 * @ingroup FFS
 * @since 2012-10-20
 */
class MediaWikiExtensionFFS extends SimpleFFS {
	public function supportsFuzzy() {
		return 'write';
	}

	public function getFileExtensions() {
		return array( '.i18n.php' );
	}

	/**
	 * To avoid parsing full files again and again when reading or exporting
	 * multiple languages, keep cache of the sections of the latest active file.
	 * @var array
	 */
	protected static $cache = array();

	/**
	 * @param string $data Full file contents
	 * @param string $filename Full path to file for debugging
	 * @return string[] Sections indexed by language code, or 0 for header section
	 * @throws MWException
	 */
	protected function splitSections( $data, $filename = 'unknown' ) {
		$data = SimpleFFS::fixNewLines( $data );

		$splitter = '$messages = array();';

		$pos = strpos( $data, $splitter );
		if ( $pos === false ) {
			throw new MWException( "MWEFFS1: File $filename: splitter not found" );
		}

		$offset = $pos + strlen( $splitter );
		$header = substr( $data, 0, $offset );

		$pattern = '(?: /\*\* .*? \*/ \n )? (?: \\$.*?  \n\);(?:\n\n|\s+\z) )';
		$regexp = "~$pattern~xsu";
		$matches = array();
		preg_match_all( $regexp, $data, $matches, PREG_SET_ORDER, $offset );

		$sections = array();
		$sections[] = $header;

		foreach ( $matches as $data ) {
			$pattern = "\\\$messages\['([a-z-]+)'\]";
			$regexp = "~$pattern~su";
			$matches = array();
			if ( !preg_match( $regexp, $data[0], $matches ) ) {
				throw new MWException( "MWEFFS2: File $filename: malformed section: {$data[0]}" );
			}
			$code = $matches[1];
			// Normalize number of newlines after each section
			$sections[$code] = rtrim( $data[0] );
		}

		return $sections;
	}

	/**
	 * @param string $code Language code.
	 * @return array|bool
	 */
	public function read( $code ) {
		$filename = $this->group->getSourceFilePath( $code );
		if ( !file_exists( $filename ) ) {
			return false;
		}

		if ( isset( self::$cache[$filename]['parsed'][$code] ) ) {
			return self::$cache[$filename]['parsed'][$code];
		}

		if ( !isset( self::$cache[$filename] ) ) {
			// Clear the cache if the filename changes to reduce memory use
			self::$cache = array();

			$contents = file_get_contents( $filename );
			self::$cache[$filename]['sections'] =
				$this->splitSections( $contents, $filename );
		}

		// Shorten
		$cache = &self::$cache[$filename];

		$value = false;
		if ( isset( $cache['sections'][$code] ) ) {
			$value = $this->readFromVariable( $cache['sections'][$code] );
		}

		$cache['parsed'][$code] = $value;

		return $value;
	}

	/**
	 * @param string $data
	 * @return array Parsed data.
	 * @throws MWException
	 */
	public function readFromVariable( $data ) {
		$messages = array();
		eval( $data );

		$c = count( $messages );
		if ( $c !== 1 ) {
			throw new MWException( "MWEFFS3: Expected 1, got $c: $data" );
		}

		$messages = array_shift( $messages );
		$mangler = $this->group->getMangler();
		$messages = $mangler->mangle( $messages );

		return array(
			'MESSAGES' => $messages,
		);
	}

	// Handled in writeReal
	protected function tryReadSource( $filename, MessageCollection $collection ) {
	}

	/**
	 * @param MessageCollection $collection
	 * @return string
	 */
	protected function writeReal( MessageCollection $collection ) {
		$mangler = $this->group->getMangler();
		$code = $collection->getLanguage();

		$block = $this->generateMessageBlock( $collection, $mangler );
		if ( $block === false ) {
			return '';
		}

		// Ugly code, relies on side effects
		// Avoid parsing stuff with fake language code
		// Premature optimization
		$this->read( 'mul' );
		$filename = $this->group->getSourceFilePath( $code );
		$cache = &self::$cache[$filename];

		// Generating authors
		if ( isset( $cache['sections'][$code] ) ) {
			// More premature optimization
			$fromFile = self::parseAuthorsFromString( $cache['sections'][$code] );
			$collection->addCollectionAuthors( $fromFile );
		}

		$authors = $collection->getAuthors();
		$authors = $this->filterAuthors( $authors, $code );

		$authorList = '';
		foreach ( $authors as $author ) {
			$authorList .= "\n * @author $author";
		}

		// And putting all together
		$name = TranslateUtils::getLanguageName( $code );
		$native = TranslateUtils::getLanguageName( $code, $code );

		$section = <<<PHP
/** $name ($native)$authorList
 */
\$messages['$code'] = array($block);
PHP;

		// Store the written part, so that when next language is called,
		// the new version will be used (instead of the old parsed version
		$cache['sections'][$code] = $section;

		// Make a copy we can alter
		$sections = $cache['sections'];
		$priority = array();

		global $wgTranslateDocumentationLanguageCode;
		$codes = array(
			0, // File header
			$this->group->getSourceLanguage(),
			$wgTranslateDocumentationLanguageCode,
		);
		foreach ( $codes as $pcode ) {
			if ( isset( $sections[$pcode] ) ) {
				$priority[] = $sections[$pcode];
				unset( $sections[$pcode] );
			}
		}

		ksort( $sections );

		return implode( "\n\n", $priority ) . "\n\n" . implode( "\n\n", $sections ) . "\n";
	}

	protected function generateMessageBlock( MessageCollection $collection, StringMatcher $mangler ) {
		$block = '';
		/**
		 * @var TMessage $m
		 */
		foreach ( $collection as $key => $m ) {
			$value = $m->translation();
			if ( $value === null ) {
				continue;
			}

			$key = $mangler->unmangle( $key );
			$value = str_replace( TRANSLATE_FUZZY, '', $value );
			$fuzzy = $m->hasTag( 'fuzzy' ) ? ' # Fuzzy' : '';

			$key = self::quote( $key );
			$value = self::quote( $value );
			$block .= "\t$key => $value,$fuzzy\n";
		}

		// Do not create empty sections
		if ( $block === '' ) {
			return false;
		}

		return "\n$block";
	}

	/**
	 * Scans for \@author tags in the string.
	 * @param string $string String containing the comments of a section
	 * @return string[] List of authors
	 */
	protected static function parseAuthorsFromString( $string ) {
		preg_match_all( '/@author (.*)/', $string, $m );

		return $m[1];
	}

	/**
	 * Tries to find optimal way to quote a string by choosing
	 * either double quotes or single quotes depending on how
	 * many escapes are needed.
	 * @param string $value The string to quote.
	 * @return string String suitable for inclusion in PHP code
	 */
	protected static function quote( $value ) {
		# Check for the appropriate apostrophe and add the value
		# Quote \ here, because it needs always escaping
		$value = addcslashes( $value, '\\' );

		# For readability
		$single = "'";
		$double = '"';
		$quote = $single; // Default

		# It is safe to use '-quoting, unless there is '-quote in the text
		if ( strpos( $value, $single ) !== false ) {
			# In case there are no variables that need to be escaped, just use "-quote
			if ( strpos( $value, $double ) === false && !preg_match( '/\$[^0-9]/', $value ) ) {
				$quote = $double;
			} else {
				# Something needs quoting, so pick the quote which causes less quoting
				$doubleEsc = substr_count( $value, $double ) + substr_count( $value, '$' );
				$singleEsc = substr_count( $value, $single );

				if ( $doubleEsc < $singleEsc ) {
					$quote = $double;
					$extra = '$';
				} else {
					$extra = '';
				}

				$value = addcslashes( $value, $quote . $extra );
			}
		}

		return $quote . $value . $quote;
	}
}