summaryrefslogtreecommitdiff
path: root/www/wiki/languages/ConverterRule.php
blob: 8dfe00f88c15aed874cf8bd73f1731176b737504 (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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
<?php
/**
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 * http://www.gnu.org/copyleft/gpl.html
 *
 * @file
 * @ingroup Language
 */

/**
 * Parser for rules of language conversion , parse rules in -{ }- tag.
 * @ingroup Language
 * @author fdcn <fdcn64@gmail.com>, PhiLiP <philip.npc@gmail.com>
 */
class ConverterRule {
	public $mText; // original text in -{text}-
	public $mConverter; // LanguageConverter object
	public $mRuleDisplay = '';
	public $mRuleTitle = false;
	public $mRules = '';// string : the text of the rules
	public $mRulesAction = 'none';
	public $mFlags = [];
	public $mVariantFlags = [];
	public $mConvTable = [];
	public $mBidtable = [];// array of the translation in each variant
	public $mUnidtable = [];// array of the translation in each variant

	/**
	 * @param string $text The text between -{ and }-
	 * @param LanguageConverter $converter
	 */
	public function __construct( $text, $converter ) {
		$this->mText = $text;
		$this->mConverter = $converter;
	}

	/**
	 * Check if variants array in convert array.
	 *
	 * @param array|string $variants Variant language code
	 * @return string Translated text
	 */
	public function getTextInBidtable( $variants ) {
		$variants = (array)$variants;
		if ( !$variants ) {
			return false;
		}
		foreach ( $variants as $variant ) {
			if ( isset( $this->mBidtable[$variant] ) ) {
				return $this->mBidtable[$variant];
			}
		}
		return false;
	}

	/**
	 * Parse flags with syntax -{FLAG| ... }-
	 * @private
	 */
	function parseFlags() {
		$text = $this->mText;
		$flags = [];
		$variantFlags = [];

		$sepPos = strpos( $text, '|' );
		if ( $sepPos !== false ) {
			$validFlags = $this->mConverter->mFlags;
			$f = StringUtils::explode( ';', substr( $text, 0, $sepPos ) );
			foreach ( $f as $ff ) {
				$ff = trim( $ff );
				if ( isset( $validFlags[$ff] ) ) {
					$flags[$validFlags[$ff]] = true;
				}
			}
			$text = strval( substr( $text, $sepPos + 1 ) );
		}

		if ( !$flags ) {
			$flags['S'] = true;
		} elseif ( isset( $flags['R'] ) ) {
			$flags = [ 'R' => true ];// remove other flags
		} elseif ( isset( $flags['N'] ) ) {
			$flags = [ 'N' => true ];// remove other flags
		} elseif ( isset( $flags['-'] ) ) {
			$flags = [ '-' => true ];// remove other flags
		} elseif ( count( $flags ) == 1 && isset( $flags['T'] ) ) {
			$flags['H'] = true;
		} elseif ( isset( $flags['H'] ) ) {
			// replace A flag, and remove other flags except T
			$temp = [ '+' => true, 'H' => true ];
			if ( isset( $flags['T'] ) ) {
				$temp['T'] = true;
			}
			if ( isset( $flags['D'] ) ) {
				$temp['D'] = true;
			}
			$flags = $temp;
		} else {
			if ( isset( $flags['A'] ) ) {
				$flags['+'] = true;
				$flags['S'] = true;
			}
			if ( isset( $flags['D'] ) ) {
				unset( $flags['S'] );
			}
			// try to find flags like "zh-hans", "zh-hant"
			// allow syntaxes like "-{zh-hans;zh-hant|XXXX}-"
			$variantFlags = array_intersect( array_keys( $flags ), $this->mConverter->mVariants );
			if ( $variantFlags ) {
				$variantFlags = array_flip( $variantFlags );
				$flags = [];
			}
		}
		$this->mVariantFlags = $variantFlags;
		$this->mRules = $text;
		$this->mFlags = $flags;
	}

	/**
	 * Generate conversion table.
	 * @private
	 */
	function parseRules() {
		$rules = $this->mRules;
		$bidtable = [];
		$unidtable = [];
		$variants = $this->mConverter->mVariants;
		$varsep_pattern = $this->mConverter->getVarSeparatorPattern();

		// Split according to $varsep_pattern, but ignore semicolons from HTML entities
		$rules = preg_replace( '/(&[#a-zA-Z0-9]+);/', "$1\x01", $rules );
		$choice = preg_split( $varsep_pattern, $rules );
		$choice = str_replace( "\x01", ';', $choice );

		foreach ( $choice as $c ) {
			$v = explode( ':', $c, 2 );
			if ( count( $v ) != 2 ) {
				// syntax error, skip
				continue;
			}
			$to = trim( $v[1] );
			$v = trim( $v[0] );
			$u = explode( '=>', $v, 2 );
			// if $to is empty (which is also used as $from in bidtable),
			// strtr() could return a wrong result.
			if ( count( $u ) == 1 && $to !== '' && in_array( $v, $variants ) ) {
				$bidtable[$v] = $to;
			} elseif ( count( $u ) == 2 ) {
				$from = trim( $u[0] );
				$v = trim( $u[1] );
				// if $from is empty, strtr() could return a wrong result.
				if ( array_key_exists( $v, $unidtable )
					&& !is_array( $unidtable[$v] )
					&& $from !== ''
					&& in_array( $v, $variants ) ) {
					$unidtable[$v] = [ $from => $to ];
				} elseif ( $from !== '' && in_array( $v, $variants ) ) {
					$unidtable[$v][$from] = $to;
				}
			}
			// syntax error, pass
			if ( !isset( $this->mConverter->mVariantNames[$v] ) ) {
				$bidtable = [];
				$unidtable = [];
				break;
			}
		}
		$this->mBidtable = $bidtable;
		$this->mUnidtable = $unidtable;
	}

	/**
	 * @private
	 *
	 * @return string
	 */
	function getRulesDesc() {
		$codesep = $this->mConverter->mDescCodeSep;
		$varsep = $this->mConverter->mDescVarSep;
		$text = '';
		foreach ( $this->mBidtable as $k => $v ) {
			$text .= $this->mConverter->mVariantNames[$k] . "$codesep$v$varsep";
		}
		foreach ( $this->mUnidtable as $k => $a ) {
			foreach ( $a as $from => $to ) {
				$text .= $from . '⇒' . $this->mConverter->mVariantNames[$k] .
					"$codesep$to$varsep";
			}
		}
		return $text;
	}

	/**
	 * Parse rules conversion.
	 * @private
	 *
	 * @param string $variant
	 *
	 * @return string
	 */
	function getRuleConvertedStr( $variant ) {
		$bidtable = $this->mBidtable;
		$unidtable = $this->mUnidtable;

		if ( count( $bidtable ) + count( $unidtable ) == 0 ) {
			return $this->mRules;
		} else {
			// display current variant in bidirectional array
			$disp = $this->getTextInBidtable( $variant );
			// or display current variant in fallbacks
			if ( $disp === false ) {
				$disp = $this->getTextInBidtable(
					$this->mConverter->getVariantFallbacks( $variant ) );
			}
			// or display current variant in unidirectional array
			if ( $disp === false && array_key_exists( $variant, $unidtable ) ) {
				$disp = array_values( $unidtable[$variant] )[0];
			}
			// or display first text under disable manual convert
			if ( $disp === false && $this->mConverter->mManualLevel[$variant] == 'disable' ) {
				if ( count( $bidtable ) > 0 ) {
					$disp = array_values( $bidtable )[0];
				} else {
					$disp = array_values( array_values( $unidtable )[0] )[0];
				}
			}
			return $disp;
		}
	}

	/**
	 * Similar to getRuleConvertedStr(), but this prefers to use original
	 * page title if $variant === $this->mConverter->mMainLanguageCode
	 * and may return false in this case (so this title conversion rule
	 * will be ignored and the original title is shown).
	 *
	 * @since 1.22
	 * @param string $variant The variant code to display page title in
	 * @return string|bool The converted title or false if just page name
	 */
	function getRuleConvertedTitle( $variant ) {
		if ( $variant === $this->mConverter->mMainLanguageCode ) {
			// If a string targeting exactly this variant is set,
			// use it. Otherwise, just return false, so the real
			// page name can be shown (and because variant === main,
			// there'll be no further automatic conversion).
			$disp = $this->getTextInBidtable( $variant );
			if ( $disp ) {
				return $disp;
			}
			if ( array_key_exists( $variant, $this->mUnidtable ) ) {
				$disp = array_values( $this->mUnidtable[$variant] )[0];
			}
			// Assigned above or still false.
			return $disp;
		} else {
			return $this->getRuleConvertedStr( $variant );
		}
	}

	/**
	 * Generate conversion table for all text.
	 * @private
	 */
	function generateConvTable() {
		// Special case optimisation
		if ( !$this->mBidtable && !$this->mUnidtable ) {
			$this->mConvTable = [];
			return;
		}

		$bidtable = $this->mBidtable;
		$unidtable = $this->mUnidtable;
		$manLevel = $this->mConverter->mManualLevel;

		$vmarked = [];
		foreach ( $this->mConverter->mVariants as $v ) {
			/* for bidirectional array
				fill in the missing variants, if any,
				with fallbacks */
			if ( !isset( $bidtable[$v] ) ) {
				$variantFallbacks =
					$this->mConverter->getVariantFallbacks( $v );
				$vf = $this->getTextInBidtable( $variantFallbacks );
				if ( $vf ) {
					$bidtable[$v] = $vf;
				}
			}

			if ( isset( $bidtable[$v] ) ) {
				foreach ( $vmarked as $vo ) {
					// use syntax: -{A|zh:WordZh;zh-tw:WordTw}-
					// or -{H|zh:WordZh;zh-tw:WordTw}-
					// or -{-|zh:WordZh;zh-tw:WordTw}-
					// to introduce a custom mapping between
					// words WordZh and WordTw in the whole text
					if ( $manLevel[$v] == 'bidirectional' ) {
						$this->mConvTable[$v][$bidtable[$vo]] = $bidtable[$v];
					}
					if ( $manLevel[$vo] == 'bidirectional' ) {
						$this->mConvTable[$vo][$bidtable[$v]] = $bidtable[$vo];
					}
				}
				$vmarked[] = $v;
			}
			/* for unidirectional array fill to convert tables */
			if ( ( $manLevel[$v] == 'bidirectional' || $manLevel[$v] == 'unidirectional' )
				&& isset( $unidtable[$v] )
			) {
				if ( isset( $this->mConvTable[$v] ) ) {
					$this->mConvTable[$v] = $unidtable[$v] + $this->mConvTable[$v];
				} else {
					$this->mConvTable[$v] = $unidtable[$v];
				}
			}
		}
	}

	/**
	 * Parse rules and flags.
	 * @param string $variant Variant language code
	 */
	public function parse( $variant = null ) {
		if ( !$variant ) {
			$variant = $this->mConverter->getPreferredVariant();
		}

		$this->parseFlags();
		$flags = $this->mFlags;

		// convert to specified variant
		// syntax: -{zh-hans;zh-hant[;...]|<text to convert>}-
		if ( $this->mVariantFlags ) {
			// check if current variant in flags
			if ( isset( $this->mVariantFlags[$variant] ) ) {
				// then convert <text to convert> to current language
				$this->mRules = $this->mConverter->autoConvert( $this->mRules,
					$variant );
			} else {
				// if current variant no in flags,
				// then we check its fallback variants.
				$variantFallbacks =
					$this->mConverter->getVariantFallbacks( $variant );
				if ( is_array( $variantFallbacks ) ) {
					foreach ( $variantFallbacks as $variantFallback ) {
						// if current variant's fallback exist in flags
						if ( isset( $this->mVariantFlags[$variantFallback] ) ) {
							// then convert <text to convert> to fallback language
							$this->mRules =
								$this->mConverter->autoConvert( $this->mRules,
									$variantFallback );
							break;
						}
					}
				}
			}
			$this->mFlags = $flags = [ 'R' => true ];
		}

		if ( !isset( $flags['R'] ) && !isset( $flags['N'] ) ) {
			// decode => HTML entities modified by Sanitizer::removeHTMLtags
			$this->mRules = str_replace( '=&gt;', '=>', $this->mRules );
			$this->parseRules();
		}
		$rules = $this->mRules;

		if ( !$this->mBidtable && !$this->mUnidtable ) {
			if ( isset( $flags['+'] ) || isset( $flags['-'] ) ) {
				// fill all variants if text in -{A/H/-|text}- is non-empty but without rules
				if ( $rules !== '' ) {
					foreach ( $this->mConverter->mVariants as $v ) {
						$this->mBidtable[$v] = $rules;
					}
				}
			} elseif ( !isset( $flags['N'] ) && !isset( $flags['T'] ) ) {
				$this->mFlags = $flags = [ 'R' => true ];
			}
		}

		$this->mRuleDisplay = false;
		foreach ( $flags as $flag => $unused ) {
			switch ( $flag ) {
				case 'R':
					// if we don't do content convert, still strip the -{}- tags
					$this->mRuleDisplay = $rules;
					break;
				case 'N':
					// process N flag: output current variant name
					$ruleVar = trim( $rules );
					if ( isset( $this->mConverter->mVariantNames[$ruleVar] ) ) {
						$this->mRuleDisplay = $this->mConverter->mVariantNames[$ruleVar];
					} else {
						$this->mRuleDisplay = '';
					}
					break;
				case 'D':
					// process D flag: output rules description
					$this->mRuleDisplay = $this->getRulesDesc();
					break;
				case 'H':
					// process H,- flag or T only: output nothing
					$this->mRuleDisplay = '';
					break;
				case '-':
					$this->mRulesAction = 'remove';
					$this->mRuleDisplay = '';
					break;
				case '+':
					$this->mRulesAction = 'add';
					$this->mRuleDisplay = '';
					break;
				case 'S':
					$this->mRuleDisplay = $this->getRuleConvertedStr( $variant );
					break;
				case 'T':
					$this->mRuleTitle = $this->getRuleConvertedTitle( $variant );
					$this->mRuleDisplay = '';
					break;
				default:
					// ignore unknown flags (but see error case below)
			}
		}
		if ( $this->mRuleDisplay === false ) {
			$this->mRuleDisplay = '<span class="error">'
				. wfMessage( 'converter-manual-rule-error' )->inContentLanguage()->escaped()
				. '</span>';
		}

		$this->generateConvTable();
	}

	/**
	 * Checks if there are conversion rules.
	 * @return bool
	 */
	public function hasRules() {
		return $this->mRules !== '';
	}

	/**
	 * Get display text on markup -{...}-
	 * @return string
	 */
	public function getDisplay() {
		return $this->mRuleDisplay;
	}

	/**
	 * Get converted title.
	 * @return string
	 */
	public function getTitle() {
		return $this->mRuleTitle;
	}

	/**
	 * Return how deal with conversion rules.
	 * @return string
	 */
	public function getRulesAction() {
		return $this->mRulesAction;
	}

	/**
	 * Get conversion table. (bidirectional and unidirectional
	 * conversion table)
	 * @return array
	 */
	public function getConvTable() {
		return $this->mConvTable;
	}

	/**
	 * Get conversion rules string.
	 * @return string
	 */
	public function getRules() {
		return $this->mRules;
	}

	/**
	 * Get conversion flags.
	 * @return array
	 */
	public function getFlags() {
		return $this->mFlags;
	}
}