MediaWiki  1.32.0
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  $options = [];
86  foreach ( $languages as $code => $name ) {
87  $options["$code - $name"] = $code;
88  }
89 
90  $page['language'] = [
91  'id' => 'mw-pl-languageselector',
92  'cssclass' => 'mw-languageselector',
93  'type' => 'select',
94  'options' => $options,
95  'label-message' => 'pagelang-language',
96  'default' => $title ?
97  $title->getPageLanguage()->getCode() :
98  $this->getConfig()->get( 'LanguageCode' ),
99  ];
100 
101  // Allow user to enter a comment explaining the change
102  $page['reason'] = [
103  'type' => 'text',
104  'label-message' => 'pagelang-reason'
105  ];
106 
107  return $page;
108  }
109 
110  protected function postText() {
111  if ( $this->par ) {
112  return $this->showLogFragment( $this->par );
113  }
114  return '';
115  }
116 
117  protected function getDisplayFormat() {
118  return 'ooui';
119  }
120 
121  public function alterForm( HTMLForm $form ) {
122  Hooks::run( 'LanguageSelector', [ $this->getOutput(), 'mw-languageselector' ] );
123  $form->setSubmitTextMsg( 'pagelang-submit' );
124  }
125 
131  public function onSubmit( array $data ) {
132  $pageName = $data['pagename'];
133 
134  // Check if user wants to use default language
135  if ( $data['selectoptions'] == 1 ) {
136  $newLanguage = 'default';
137  } else {
138  $newLanguage = $data['language'];
139  }
140 
141  try {
142  $title = Title::newFromTextThrow( $pageName );
143  } catch ( MalformedTitleException $ex ) {
144  return Status::newFatal( $ex->getMessageObject() );
145  }
146 
147  // Check permissions and make sure the user has permission to edit the page
148  $errors = $title->getUserPermissionsErrors( 'edit', $this->getUser() );
149 
150  if ( $errors ) {
151  $out = $this->getOutput();
152  $wikitext = $out->formatPermissionsErrorMessage( $errors );
153  // Hack to get our wikitext parsed
154  return Status::newFatal( new RawMessage( '$1', [ $wikitext ] ) );
155  }
156 
157  // Url to redirect to after the operation
158  $this->goToUrl = $title->getFullUrlForRedirect(
159  $title->isRedirect() ? [ 'redirect' => 'no' ] : []
160  );
161 
163  $this->getContext(),
164  $title,
165  $newLanguage,
166  $data['reason'] ?? ''
167  );
168  }
169 
179  $newLanguage, $reason, array $tags = [] ) {
180  // Get the default language for the wiki
181  $defLang = $context->getConfig()->get( 'LanguageCode' );
182 
183  $pageId = $title->getArticleID();
184 
185  // Check if article exists
186  if ( !$pageId ) {
187  return Status::newFatal(
188  'pagelang-nonexistent-page',
189  wfEscapeWikiText( $title->getPrefixedText() )
190  );
191  }
192 
193  // Load the page language from DB
194  $dbw = wfGetDB( DB_MASTER );
195  $oldLanguage = $dbw->selectField(
196  'page',
197  'page_lang',
198  [ 'page_id' => $pageId ],
199  __METHOD__
200  );
201 
202  // Check if user wants to use the default language
203  if ( $newLanguage === 'default' ) {
204  $newLanguage = null;
205  }
206 
207  // No change in language
208  if ( $newLanguage === $oldLanguage ) {
209  // Check if old language does not exist
210  if ( !$oldLanguage ) {
212  [
213  'pagelang-unchanged-language-default',
214  wfEscapeWikiText( $title->getPrefixedText() )
215  ],
216  'pagelang-unchanged-language'
217  ) );
218  }
219  return Status::newFatal(
220  'pagelang-unchanged-language',
221  wfEscapeWikiText( $title->getPrefixedText() ),
222  $oldLanguage
223  );
224  }
225 
226  // Hardcoded [def] if the language is set to null
227  $logOld = $oldLanguage ?: $defLang . '[def]';
228  $logNew = $newLanguage ?: $defLang . '[def]';
229 
230  // Writing new page language to database
231  $dbw->update(
232  'page',
233  [ 'page_lang' => $newLanguage ],
234  [
235  'page_id' => $pageId,
236  'page_lang' => $oldLanguage
237  ],
238  __METHOD__
239  );
240 
241  if ( !$dbw->affectedRows() ) {
242  return Status::newFatal( 'pagelang-db-failed' );
243  }
244 
245  // Logging change of language
246  $logParams = [
247  '4::oldlanguage' => $logOld,
248  '5::newlanguage' => $logNew
249  ];
250  $entry = new ManualLogEntry( 'pagelang', 'pagelang' );
251  $entry->setPerformer( $context->getUser() );
252  $entry->setTarget( $title );
253  $entry->setParameters( $logParams );
254  $entry->setComment( $reason );
255  $entry->setTags( $tags );
256 
257  $logid = $entry->insert();
258  $entry->publish( $logid );
259 
260  // Force re-render so that language-based content (parser functions etc.) gets updated
261  $title->invalidateCache();
262 
263  return Status::newGood( (object)[
264  'oldLanguage' => $logOld,
265  'newLanguage' => $logNew,
266  'logId' => $logid,
267  ] );
268  }
269 
270  public function onSuccess() {
271  // Success causes a redirect
272  $this->getOutput()->redirect( $this->goToUrl );
273  }
274 
275  function showLogFragment( $title ) {
276  $moveLogPage = new LogPage( 'pagelang' );
277  $out1 = Xml::element( 'h2', null, $moveLogPage->getName()->text() );
278  $out2 = '';
279  LogEventsList::showLogExtract( $out2, 'pagelang', $title );
280  return $out1 . $out2;
281  }
282 
291  public function prefixSearchSubpages( $search, $limit, $offset ) {
292  return $this->prefixSearchString( $search, $limit, $offset );
293  }
294 
295  protected function getGroupName() {
296  return 'pagetools';
297  }
298 }
Title\newFromText
static newFromText( $text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
Definition: Title.php:280
SpecialPage\msg
msg( $key)
Wrapper around wfMessage that sets the current context.
Definition: SpecialPage.php:796
$context
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:2675
SpecialPageLanguage\postText
postText()
Add post-text to the form.
Definition: SpecialPageLanguage.php:110
SpecialPage\getOutput
getOutput()
Get the OutputPage being used for this instance.
Definition: SpecialPage.php:725
$languages
switch( $options['output']) $languages
Definition: transstat.php:76
SpecialPageLanguage\getGroupName
getGroupName()
Under which header this special page is listed in Special:SpecialPages See messages 'specialpages-gro...
Definition: SpecialPageLanguage.php:295
MalformedTitleException\getMessageObject
getMessageObject()
Definition: MalformedTitleException.php:80
StatusValue\newFatal
static newFatal( $message)
Factory function for fatal errors.
Definition: StatusValue.php:68
SpecialPageLanguage\onSubmit
onSubmit(array $data)
Definition: SpecialPageLanguage.php:131
FormSpecialPage
Special page which uses an HTMLForm to handle processing.
Definition: FormSpecialPage.php:31
SpecialPageLanguage\doesWrites
doesWrites()
Indicates whether this special page may perform database writes.
Definition: SpecialPageLanguage.php:41
ContentHandler\getForTitle
static getForTitle(Title $title)
Returns the appropriate ContentHandler singleton for the given title.
Definition: ContentHandler.php:244
SpecialPage\getLanguage
getLanguage()
Shortcut to get user's language.
Definition: SpecialPage.php:755
SpecialPageLanguage\preText
preText()
Add pre-text to the form.
Definition: SpecialPageLanguage.php:45
php
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:35
SpecialPageLanguage\alterForm
alterForm(HTMLForm $form)
Play with the HTMLForm if you need to more substantially.
Definition: SpecialPageLanguage.php:121
SpecialPage\prefixSearchString
prefixSearchString( $search, $limit, $offset)
Perform a regular substring search for prefixSearchSubpages.
Definition: SpecialPage.php:495
SpecialPageLanguage\getDisplayFormat
getDisplayFormat()
Get display format for the form.
Definition: SpecialPageLanguage.php:117
SpecialPage\getConfig
getConfig()
Shortcut to get main config object.
Definition: SpecialPage.php:764
$title
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:964
wfGetDB
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
Definition: GlobalFunctions.php:2693
LogPage
Class to simplify the use of log pages.
Definition: LogPage.php:33
Xml\element
static element( $element, $attribs=null, $contents='', $allowShortTag=true)
Format an XML element with given attributes and, optionally, text content.
Definition: Xml.php:41
$code
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:813
SpecialPage\getUser
getUser()
Shortcut to get the User executing this instance.
Definition: SpecialPage.php:735
LogEventsList\showLogExtract
static showLogExtract(&$out, $types=[], $page='', $user='', $param=[])
Show log extract.
Definition: LogEventsList.php:606
DB_MASTER
const DB_MASTER
Definition: defines.php:26
ApiMessage\create
static create( $msg, $code=null, array $data=null)
Create an IApiMessage for the message.
Definition: ApiMessage.php:40
array
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))
string
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:175
SpecialPage\getContext
getContext()
Gets the context this SpecialPage is executed in.
Definition: SpecialPage.php:698
Title\newFromTextThrow
static newFromTextThrow( $text, $defaultNamespace=NS_MAIN)
Like Title::newFromText(), but throws MalformedTitleException when the title is invalid,...
Definition: Title.php:313
$name
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:302
SpecialPageLanguage\$goToUrl
string $goToUrl
URL to go to if language change successful.
Definition: SpecialPageLanguage.php:35
SpecialPageLanguage\__construct
__construct()
Definition: SpecialPageLanguage.php:37
StatusValue\newGood
static newGood( $value=null)
Factory function for good results.
Definition: StatusValue.php:81
FormSpecialPage\$par
string $par
The sub-page of the special page.
Definition: FormSpecialPage.php:36
SpecialPageLanguage\showLogFragment
showLogFragment( $title)
Definition: SpecialPageLanguage.php:275
wfEscapeWikiText
wfEscapeWikiText( $text)
Escapes the given text so that it may be output using addWikiText() without any linking,...
Definition: GlobalFunctions.php:1617
SpecialPageLanguage\prefixSearchSubpages
prefixSearchSubpages( $search, $limit, $offset)
Return an array of subpages beginning with $search that this special page will accept.
Definition: SpecialPageLanguage.php:291
SpecialPageLanguage\onSuccess
onSuccess()
Do something exciting on successful processing of the form, most likely to show a confirmation messag...
Definition: SpecialPageLanguage.php:270
IContextSource
Interface for objects which can provide a MediaWiki context on request.
Definition: IContextSource.php:53
HTMLForm\setSubmitTextMsg
setSubmitTextMsg( $msg)
Set the text for the submit button to a message.
Definition: HTMLForm.php:1376
SpecialPageLanguage\changePageLanguage
static changePageLanguage(IContextSource $context, Title $title, $newLanguage, $reason, array $tags=[])
Definition: SpecialPageLanguage.php:178
Title
Represents a title within MediaWiki.
Definition: Title.php:39
MalformedTitleException
MalformedTitleException is thrown when a TitleParser is unable to parse a title string.
Definition: MalformedTitleException.php:25
$options
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:2036
SpecialPageLanguage
Special page for changing the content language of a page.
Definition: SpecialPageLanguage.php:31
as
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
Definition: distributors.txt:9
SpecialPageLanguage\getFormFields
getFormFields()
Get an HTMLForm descriptor array.
Definition: SpecialPageLanguage.php:49
ManualLogEntry
Class for creating new log entries and inserting them into the database.
Definition: LogEntry.php:437
RawMessage
Variant of the Message class.
Definition: RawMessage.php:34
Language\fetchLanguageNames
static fetchLanguageNames( $inLanguage=self::AS_AUTONYMS, $include='mw')
Get an array of language names, indexed by code.
Definition: Language.php:843
Hooks\run
static run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:200
HTMLForm
Object handling generic submission, CSRF protection, layout and other logic for UI forms.
Definition: HTMLForm.php:136
$out
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:813