summaryrefslogtreecommitdiff
blob: 136b251de0e8d0b8c9cc22768c7ba632b4842a0e (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
<?php
/**
 * Contains a helper class to help replace titles.
 * @license GPL-2.0-or-later
 */

namespace MediaWiki\Extension\Translate\Utilities;

use MessageHandle;
use Title;
use TitleArray;
use TitleArrayFromResult;
use TranslateUtils;

/**
 * Helper class that cotains utility methods to help with identifying and replace titles.
 * @since 2019.10
 */
class TranslateReplaceTitle {

	/**
	 * Returns two lists: a set of message handles that would be moved/renamed by
	 * the current text replacement, and the set of message handles that would ordinarily
	 * be moved but are not movable, due to permissions or any other reason.
	 * @param MessageHandle $sourceMessageHandle
	 * @param string $replacement
	 * @return Title[][]
	 */
	public static function getTitlesForMove(
		MessageHandle $sourceMessageHandle, $replacement
	) {
		$titlesForMove = [];
		$namespace = $sourceMessageHandle->getTitle()->getNamespace();

		$titles = self::getMatchingTitles( $sourceMessageHandle );

		foreach ( $titles as $title ) {
			$handle = new MessageHandle( $title );
			// This takes care of situations where we have two different titles
			// foo and foo/bar, both will be matched and fetched but the slash
			// does not represent a language separator
			if ( $handle->getKey() !== $sourceMessageHandle->getKey() ) {
				continue;
			}
			$targetTitle = Title::makeTitle(
				$namespace,
				TranslateUtils::title( $replacement, $handle->getCode(), $namespace )
			);
			$titlesForMove[] = [ $title, $targetTitle ];
		}

		return $titlesForMove;
	}

	/**
	 * @param MessageHandle $handle
	 * @return TitleArrayFromResult
	 */
	private static function getMatchingTitles( MessageHandle $handle ) {
		$dbr = wfGetDB( DB_MASTER );

		$tables = [ 'page' ];
		$vars = [ 'page_title', 'page_namespace', 'page_id' ];

		$comparisonCond = 'page_title ' . $dbr->buildLike(
			$handle->getTitleForBase()->getDBkey(), '/', $dbr->anyString()
		);

		$conds = [
			$comparisonCond,
			'page_namespace' => $handle->getTitle()->getNamespace(),
		];

		$result = $dbr->select( $tables, $vars, $conds, __METHOD__ );

		return TitleArray::newFromResult( $result );
	}
}

class_alias( TranslateReplaceTitle::class, '\MediaWiki\Extensions\Translate\TranslateReplaceTitle' );