MediaWiki REL1_31
SpecialPageLanguage.php
Go to the documentation of this file.
1<?php
35 private $goToUrl;
36
37 public function __construct() {
38 parent::__construct( 'PageLanguage', 'pagelang' );
39 }
40
41 public function doesWrites() {
42 return true;
43 }
44
45 protected function preText() {
46 $this->getOutput()->addModules( 'mediawiki.special.pageLanguage' );
47 }
48
49 protected function getFormFields() {
50 // Get default from the subpage of Special page
51 $defaultName = $this->par;
52 $title = $defaultName ? Title::newFromText( $defaultName ) : null;
53 if ( $title ) {
54 $defaultPageLanguage =
55 ContentHandler::getForTitle( $title )->getPageLanguage( $title );
56 $hasCustomLanguageSet = !$defaultPageLanguage->equals( $title->getPageLanguage() );
57 } else {
58 $hasCustomLanguageSet = false;
59 }
60
61 $page = [];
62 $page['pagename'] = [
63 'type' => 'title',
64 'label-message' => 'pagelang-name',
65 'default' => $title ? $title->getPrefixedText() : $defaultName,
66 'autofocus' => $defaultName === null,
67 'exists' => true,
68 ];
69
70 // Options for whether to use the default language or select language
71 $selectoptions = [
72 (string)$this->msg( 'pagelang-use-default' )->escaped() => 1,
73 (string)$this->msg( 'pagelang-select-lang' )->escaped() => 2,
74 ];
75 $page['selectoptions'] = [
76 'id' => 'mw-pl-options',
77 'type' => 'radio',
78 'options' => $selectoptions,
79 'default' => $hasCustomLanguageSet ? 2 : 1
80 ];
81
82 // Building a language selector
83 $userLang = $this->getLanguage()->getCode();
84 $languages = Language::fetchLanguageNames( $userLang, 'mwfile' );
85 ksort( $languages );
86 $options = [];
87 foreach ( $languages as $code => $name ) {
88 $options["$code - $name"] = $code;
89 }
90
91 $page['language'] = [
92 'id' => 'mw-pl-languageselector',
93 'cssclass' => 'mw-languageselector',
94 'type' => 'select',
95 'options' => $options,
96 'label-message' => 'pagelang-language',
97 'default' => $title ?
98 $title->getPageLanguage()->getCode() :
99 $this->getConfig()->get( 'LanguageCode' ),
100 ];
101
102 // Allow user to enter a comment explaining the change
103 $page['reason'] = [
104 'type' => 'text',
105 'label-message' => 'pagelang-reason'
106 ];
107
108 return $page;
109 }
110
111 protected function postText() {
112 if ( $this->par ) {
113 return $this->showLogFragment( $this->par );
114 }
115 return '';
116 }
117
118 protected function getDisplayFormat() {
119 return 'ooui';
120 }
121
122 public function alterForm( HTMLForm $form ) {
123 Hooks::run( 'LanguageSelector', [ $this->getOutput(), 'mw-languageselector' ] );
124 $form->setSubmitTextMsg( 'pagelang-submit' );
125 }
126
132 public function onSubmit( array $data ) {
133 $pageName = $data['pagename'];
134
135 // Check if user wants to use default language
136 if ( $data['selectoptions'] == 1 ) {
137 $newLanguage = 'default';
138 } else {
139 $newLanguage = $data['language'];
140 }
141
142 try {
143 $title = Title::newFromTextThrow( $pageName );
144 } catch ( MalformedTitleException $ex ) {
145 return Status::newFatal( $ex->getMessageObject() );
146 }
147
148 // Check permissions and make sure the user has permission to edit the page
149 $errors = $title->getUserPermissionsErrors( 'edit', $this->getUser() );
150
151 if ( $errors ) {
152 $out = $this->getOutput();
153 $wikitext = $out->formatPermissionsErrorMessage( $errors );
154 // Hack to get our wikitext parsed
155 return Status::newFatal( new RawMessage( '$1', [ $wikitext ] ) );
156 }
157
158 // Url to redirect to after the operation
159 $this->goToUrl = $title->getFullUrlForRedirect(
160 $title->isRedirect() ? [ 'redirect' => 'no' ] : []
161 );
162
164 $this->getContext(),
165 $title,
166 $newLanguage,
167 $data['reason'] === null ? '' : $data['reason']
168 );
169 }
170
179 public static function changePageLanguage( IContextSource $context, Title $title,
180 $newLanguage, $reason, array $tags = [] ) {
181 // Get the default language for the wiki
182 $defLang = $context->getConfig()->get( 'LanguageCode' );
183
184 $pageId = $title->getArticleID();
185
186 // Check if article exists
187 if ( !$pageId ) {
188 return Status::newFatal(
189 'pagelang-nonexistent-page',
190 wfEscapeWikiText( $title->getPrefixedText() )
191 );
192 }
193
194 // Load the page language from DB
195 $dbw = wfGetDB( DB_MASTER );
196 $oldLanguage = $dbw->selectField(
197 'page',
198 'page_lang',
199 [ 'page_id' => $pageId ],
200 __METHOD__
201 );
202
203 // Check if user wants to use the default language
204 if ( $newLanguage === 'default' ) {
205 $newLanguage = null;
206 }
207
208 // No change in language
209 if ( $newLanguage === $oldLanguage ) {
210 // Check if old language does not exist
211 if ( !$oldLanguage ) {
212 return Status::newFatal( ApiMessage::create(
213 [
214 'pagelang-unchanged-language-default',
215 wfEscapeWikiText( $title->getPrefixedText() )
216 ],
217 'pagelang-unchanged-language'
218 ) );
219 }
220 return Status::newFatal(
221 'pagelang-unchanged-language',
222 wfEscapeWikiText( $title->getPrefixedText() ),
223 $oldLanguage
224 );
225 }
226
227 // Hardcoded [def] if the language is set to null
228 $logOld = $oldLanguage ? $oldLanguage : $defLang . '[def]';
229 $logNew = $newLanguage ? $newLanguage : $defLang . '[def]';
230
231 // Writing new page language to database
232 $dbw->update(
233 'page',
234 [ 'page_lang' => $newLanguage ],
235 [
236 'page_id' => $pageId,
237 'page_lang' => $oldLanguage
238 ],
239 __METHOD__
240 );
241
242 if ( !$dbw->affectedRows() ) {
243 return Status::newFatal( 'pagelang-db-failed' );
244 }
245
246 // Logging change of language
247 $logParams = [
248 '4::oldlanguage' => $logOld,
249 '5::newlanguage' => $logNew
250 ];
251 $entry = new ManualLogEntry( 'pagelang', 'pagelang' );
252 $entry->setPerformer( $context->getUser() );
253 $entry->setTarget( $title );
254 $entry->setParameters( $logParams );
255 $entry->setComment( $reason );
256 $entry->setTags( $tags );
257
258 $logid = $entry->insert();
259 $entry->publish( $logid );
260
261 // Force re-render so that language-based content (parser functions etc.) gets updated
262 $title->invalidateCache();
263
264 return Status::newGood( (object)[
265 'oldLanguage' => $logOld,
266 'newLanguage' => $logNew,
267 'logId' => $logid,
268 ] );
269 }
270
271 public function onSuccess() {
272 // Success causes a redirect
273 $this->getOutput()->redirect( $this->goToUrl );
274 }
275
276 function showLogFragment( $title ) {
277 $moveLogPage = new LogPage( 'pagelang' );
278 $out1 = Xml::element( 'h2', null, $moveLogPage->getName()->text() );
279 $out2 = '';
280 LogEventsList::showLogExtract( $out2, 'pagelang', $title );
281 return $out1 . $out2;
282 }
283
292 public function prefixSearchSubpages( $search, $limit, $offset ) {
293 return $this->prefixSearchString( $search, $limit, $offset );
294 }
295
296 protected function getGroupName() {
297 return 'pagetools';
298 }
299}
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
wfEscapeWikiText( $text)
Escapes the given text so that it may be output using addWikiText() without any linking,...
static create( $msg, $code=null, array $data=null)
Create an IApiMessage for the message.
Special page which uses an HTMLForm to handle processing.
string $par
The sub-page of the special page.
Object handling generic submission, CSRF protection, layout and other logic for UI forms.
Definition HTMLForm.php:130
setSubmitTextMsg( $msg)
Set the text for the submit button to a message.
static showLogExtract(&$out, $types=[], $page='', $user='', $param=[])
Show log extract.
Class to simplify the use of log pages.
Definition LogPage.php:31
MalformedTitleException is thrown when a TitleParser is unable to parse a title string.
Class for creating log entries manually, to inject them into the database.
Definition LogEntry.php:432
Variant of the Message class.
Special page for changing the content language of a page.
getFormFields()
Get an HTMLForm descriptor array.
postText()
Add post-text to the form.
prefixSearchSubpages( $search, $limit, $offset)
Return an array of subpages beginning with $search that this special page will accept.
onSuccess()
Do something exciting on successful processing of the form, most likely to show a confirmation messag...
getGroupName()
Under which header this special page is listed in Special:SpecialPages See messages 'specialpages-gro...
static changePageLanguage(IContextSource $context, Title $title, $newLanguage, $reason, array $tags=[])
alterForm(HTMLForm $form)
Play with the HTMLForm if you need to more substantially.
doesWrites()
Indicates whether this special page may perform database writes.
getDisplayFormat()
Get display format for the form.
string $goToUrl
URL to go to if language change successful.
preText()
Add pre-text to the form.
getOutput()
Get the OutputPage being used for this instance.
getUser()
Shortcut to get the User executing this instance.
getContext()
Gets the context this SpecialPage is executed in.
msg( $key)
Wrapper around wfMessage that sets the current context.
getConfig()
Shortcut to get main config object.
getLanguage()
Shortcut to get user's language.
prefixSearchString( $search, $limit, $offset)
Perform a regular substring search for prefixSearchSubpages.
Represents a title within MediaWiki.
Definition Title.php:39
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
the array() calling protocol came about after MediaWiki 1.4rc1.
This code would result in ircNotify being run twice when an article is and once for brion Hooks can return three possible true was required This is the default since MediaWiki *some string
Definition hooks.txt:181
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped & $options
Definition hooks.txt:2001
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output modifiable & $code
Definition hooks.txt:865
do that in ParserLimitReportFormat instead use this to modify the parameters of the image all existing parser cache entries will be invalid To avoid you ll need to handle that somehow(e.g. with the RejectParserCacheValue hook) because MediaWiki won 't do it for you. & $defaults also a ContextSource after deleting those rows but within the same transaction you ll probably need to make sure the header is varied on and they can depend only on the ResourceLoaderContext $context
Definition hooks.txt:2811
namespace and then decline to actually register it file or subcat img or subcat $title
Definition hooks.txt:964
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output $out
Definition hooks.txt:864
Allows to change the fields on the form that will be generated $name
Definition hooks.txt:302
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition injection.txt:37
Interface for objects which can provide a MediaWiki context on request.
const DB_MASTER
Definition defines.php:29
switch( $options['output']) $languages
Definition transstat.php:76