MediaWiki  1.29.1
SpecialChangeContentModel.php
Go to the documentation of this file.
1 <?php
2 
4 
5  public function __construct() {
6  parent::__construct( 'ChangeContentModel', 'editcontentmodel' );
7  }
8 
9  public function doesWrites() {
10  return true;
11  }
12 
16  private $title;
17 
23  private $oldRevision;
24 
25  protected function setParameter( $par ) {
26  $par = $this->getRequest()->getVal( 'pagetitle', $par );
28  if ( $title ) {
29  $this->title = $title;
30  $this->par = $title->getPrefixedText();
31  } else {
32  $this->par = '';
33  }
34  }
35 
36  protected function postText() {
37  $text = '';
38  if ( $this->title ) {
39  $contentModelLogPage = new LogPage( 'contentmodel' );
40  $text = Xml::element( 'h2', null, $contentModelLogPage->getName()->text() );
41  $out = '';
42  LogEventsList::showLogExtract( $out, 'contentmodel', $this->title );
43  $text .= $out;
44  }
45  return $text;
46  }
47 
48  protected function getDisplayFormat() {
49  return 'ooui';
50  }
51 
52  protected function alterForm( HTMLForm $form ) {
53  if ( !$this->title ) {
54  $form->setMethod( 'GET' );
55  }
56 
57  $this->addHelpLink( 'Help:ChangeContentModel' );
58 
59  // T120576
60  $form->setSubmitTextMsg( 'changecontentmodel-submit' );
61  }
62 
63  public function validateTitle( $title ) {
64  if ( !$title ) {
65  // No form input yet
66  return true;
67  }
68 
69  // Already validated by HTMLForm, but if not, throw
70  // and exception instead of a fatal
71  $titleObj = Title::newFromTextThrow( $title );
72 
73  $this->oldRevision = Revision::newFromTitle( $titleObj ) ?: false;
74 
75  if ( $this->oldRevision ) {
76  $oldContent = $this->oldRevision->getContent();
77  if ( !$oldContent->getContentHandler()->supportsDirectEditing() ) {
78  return $this->msg( 'changecontentmodel-nodirectediting' )
79  ->params( ContentHandler::getLocalizedName( $oldContent->getModel() ) )
80  ->escaped();
81  }
82  }
83 
84  return true;
85  }
86 
87  protected function getFormFields() {
88  $fields = [
89  'pagetitle' => [
90  'type' => 'title',
91  'creatable' => true,
92  'name' => 'pagetitle',
93  'default' => $this->par,
94  'label-message' => 'changecontentmodel-title-label',
95  'validation-callback' => [ $this, 'validateTitle' ],
96  ],
97  ];
98  if ( $this->title ) {
99  $options = $this->getOptionsForTitle( $this->title );
100  if ( empty( $options ) ) {
101  throw new ErrorPageError(
102  'changecontentmodel-emptymodels-title',
103  'changecontentmodel-emptymodels-text',
104  $this->title->getPrefixedText()
105  );
106  }
107  $fields['pagetitle']['readonly'] = true;
108  $fields += [
109  'model' => [
110  'type' => 'select',
111  'name' => 'model',
112  'options' => $options,
113  'label-message' => 'changecontentmodel-model-label'
114  ],
115  'reason' => [
116  'type' => 'text',
117  'name' => 'reason',
118  'validation-callback' => function( $reason ) {
119  $match = EditPage::matchSummarySpamRegex( $reason );
120  if ( $match ) {
121  return $this->msg( 'spamprotectionmatch', $match )->parse();
122  }
123 
124  return true;
125  },
126  'label-message' => 'changecontentmodel-reason-label',
127  ],
128  ];
129  }
130 
131  return $fields;
132  }
133 
134  private function getOptionsForTitle( Title $title = null ) {
136  $options = [];
137  foreach ( $models as $model ) {
139  if ( !$handler->supportsDirectEditing() ) {
140  continue;
141  }
142  if ( $title ) {
143  if ( $title->getContentModel() === $model ) {
144  continue;
145  }
146  if ( !$handler->canBeUsedOn( $title ) ) {
147  continue;
148  }
149  }
150  $options[ContentHandler::getLocalizedName( $model )] = $model;
151  }
152 
153  return $options;
154  }
155 
156  public function onSubmit( array $data ) {
158 
159  if ( $data['pagetitle'] === '' ) {
160  // Initial form view of special page, pass
161  return false;
162  }
163 
164  // At this point, it has to be a POST request. This is enforced by HTMLForm,
165  // but lets be safe verify that.
166  if ( !$this->getRequest()->wasPosted() ) {
167  throw new RuntimeException( "Form submission was not POSTed" );
168  }
169 
170  $this->title = Title::newFromText( $data['pagetitle'] );
171  $titleWithNewContentModel = clone $this->title;
172  $titleWithNewContentModel->setContentModel( $data['model'] );
173  $user = $this->getUser();
174  // Check permissions and make sure the user has permission to:
175  $errors = wfMergeErrorArrays(
176  // edit the contentmodel of the page
177  $this->title->getUserPermissionsErrors( 'editcontentmodel', $user ),
178  // edit the page under the old content model
179  $this->title->getUserPermissionsErrors( 'edit', $user ),
180  // edit the contentmodel under the new content model
181  $titleWithNewContentModel->getUserPermissionsErrors( 'editcontentmodel', $user ),
182  // edit the page under the new content model
183  $titleWithNewContentModel->getUserPermissionsErrors( 'edit', $user )
184  );
185  if ( $errors ) {
186  $out = $this->getOutput();
187  $wikitext = $out->formatPermissionsErrorMessage( $errors );
188  // Hack to get our wikitext parsed
189  return Status::newFatal( new RawMessage( '$1', [ $wikitext ] ) );
190  }
191 
192  $page = WikiPage::factory( $this->title );
193  if ( $this->oldRevision === null ) {
194  $this->oldRevision = $page->getRevision() ?: false;
195  }
196  $oldModel = $this->title->getContentModel();
197  if ( $this->oldRevision ) {
198  $oldContent = $this->oldRevision->getContent();
199  try {
200  $newContent = ContentHandler::makeContent(
201  $oldContent->getNativeData(), $this->title, $data['model']
202  );
203  } catch ( MWException $e ) {
204  return Status::newFatal(
205  $this->msg( 'changecontentmodel-cannot-convert' )
206  ->params(
207  $this->title->getPrefixedText(),
208  ContentHandler::getLocalizedName( $data['model'] )
209  )
210  );
211  }
212  } else {
213  // Page doesn't exist, create an empty content object
214  $newContent = ContentHandler::getForModelID( $data['model'] )->makeEmptyContent();
215  }
216 
217  // All other checks have passed, let's check rate limits
218  if ( $user->pingLimiter( 'editcontentmodel' ) ) {
219  throw new ThrottledError();
220  }
221 
222  $flags = $this->oldRevision ? EDIT_UPDATE : EDIT_NEW;
224  if ( $user->isAllowed( 'bot' ) ) {
226  }
227 
228  $log = new ManualLogEntry( 'contentmodel', $this->oldRevision ? 'change' : 'new' );
229  $log->setPerformer( $user );
230  $log->setTarget( $this->title );
231  $log->setComment( $data['reason'] );
232  $log->setParameters( [
233  '4::oldmodel' => $oldModel,
234  '5::newmodel' => $data['model']
235  ] );
236 
237  $formatter = LogFormatter::newFromEntry( $log );
238  $formatter->setContext( RequestContext::newExtraneousContext( $this->title ) );
239  $reason = $formatter->getPlainActionText();
240  if ( $data['reason'] !== '' ) {
241  $reason .= $this->msg( 'colon-separator' )->inContentLanguage()->text() . $data['reason'];
242  }
243  # Truncate for whole multibyte characters.
244  $reason = $wgContLang->truncate( $reason, 255 );
245 
246  // Run edit filters
247  $derivativeContext = new DerivativeContext( $this->getContext() );
248  $derivativeContext->setTitle( $this->title );
249  $derivativeContext->setWikiPage( $page );
250  $status = new Status();
251  if ( !Hooks::run( 'EditFilterMergedContent',
252  [ $derivativeContext, $newContent, $status, $reason,
253  $user, false ] )
254  ) {
255  if ( $status->isGood() ) {
256  // TODO: extensions should really specify an error message
257  $status->fatal( 'hookaborted' );
258  }
259  return $status;
260  }
261 
262  $status = $page->doEditContent(
263  $newContent,
264  $reason,
265  $flags,
266  $this->oldRevision ? $this->oldRevision->getId() : false,
267  $user
268  );
269  if ( !$status->isOK() ) {
270  return $status;
271  }
272 
273  $logid = $log->insert();
274  $log->publish( $logid );
275 
276  return $status;
277  }
278 
279  public function onSuccess() {
280  $out = $this->getOutput();
281  $out->setPageTitle( $this->msg( 'changecontentmodel-success-title' ) );
282  $out->addWikiMsg( 'changecontentmodel-success-text', $this->title );
283  }
284 
293  public function prefixSearchSubpages( $search, $limit, $offset ) {
294  return $this->prefixSearchString( $search, $limit, $offset );
295  }
296 
297  protected function getGroupName() {
298  return 'pagetools';
299  }
300 }
ContentHandler\getForModelID
static getForModelID( $modelId)
Returns the ContentHandler singleton for the given model ID.
Definition: ContentHandler.php:293
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:265
SpecialChangeContentModel\getOptionsForTitle
getOptionsForTitle(Title $title=null)
Definition: SpecialChangeContentModel.php:134
wfMergeErrorArrays
wfMergeErrorArrays()
Merge arrays in the style of getUserPermissionsErrors, with duplicate removal e.g.
Definition: GlobalFunctions.php:242
SpecialChangeContentModel\$oldRevision
Revision bool null $oldRevision
A Revision object, false if no revision exists, null if not loaded yet.
Definition: SpecialChangeContentModel.php:23
SpecialPage\getOutput
getOutput()
Get the OutputPage being used for this instance.
Definition: SpecialPage.php:675
SpecialChangeContentModel\$title
Title null $title
Definition: SpecialChangeContentModel.php:16
EDIT_FORCE_BOT
const EDIT_FORCE_BOT
Definition: Defines.php:154
EDIT_INTERNAL
const EDIT_INTERNAL
Definition: Defines.php:157
SpecialChangeContentModel\__construct
__construct()
Definition: SpecialChangeContentModel.php:5
SpecialChangeContentModel\postText
postText()
Add post-text to the form.
Definition: SpecialChangeContentModel.php:36
$status
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist Do not use this to implement individual filters if they are compatible with the ChangesListFilter and ChangesListFilterGroup structure use sub classes of those in conjunction with the ChangesListSpecialPageStructuredFilters hook This hook can be used to implement filters that do not implement that or custom behavior that is not an individual filter e g Watchlist and Watchlist you will want to construct new ChangesListBooleanFilter or ChangesListStringOptionsFilter objects When constructing you specify which group they belong to You can reuse existing or create your you must register them with $special registerFilterGroup removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set $status
Definition: hooks.txt:1049
$user
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a account $user
Definition: hooks.txt:246
Title\getPrefixedText
getPrefixedText()
Get the prefixed title with spaces.
Definition: Title.php:1451
StatusValue\newFatal
static newFatal( $message)
Factory function for fatal errors.
Definition: StatusValue.php:63
FormSpecialPage
Special page which uses an HTMLForm to handle processing.
Definition: FormSpecialPage.php:31
RequestContext\newExtraneousContext
static newExtraneousContext(Title $title, $request=[])
Create a new extraneous context.
Definition: RequestContext.php:638
SpecialChangeContentModel\doesWrites
doesWrites()
Indicates whether this special page may perform database writes.
Definition: SpecialChangeContentModel.php:9
HTMLForm\setMethod
setMethod( $method='post')
Set the method used to submit the form.
Definition: HTMLForm.php:1587
SpecialChangeContentModel\alterForm
alterForm(HTMLForm $form)
Play with the HTMLForm if you need to more substantially.
Definition: SpecialChangeContentModel.php:52
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
SpecialChangeContentModel\prefixSearchSubpages
prefixSearchSubpages( $search, $limit, $offset)
Return an array of subpages beginning with $search that this special page will accept.
Definition: SpecialChangeContentModel.php:293
Status
Generic operation result class Has warning/error list, boolean status and arbitrary value.
Definition: Status.php:40
Revision
Definition: Revision.php:33
Revision\newFromTitle
static newFromTitle(LinkTarget $linkTarget, $id=0, $flags=0)
Load either the current, or a specified, revision that's attached to a given link target.
Definition: Revision.php:134
SpecialChangeContentModel
Definition: SpecialChangeContentModel.php:3
DerivativeContext
An IContextSource implementation which will inherit context from another source but allow individual ...
Definition: DerivativeContext.php:31
SpecialPage\addHelpLink
addHelpLink( $to, $overrideBaseUrl=false)
Adds help link with an icon via page indicators.
Definition: SpecialPage.php:785
SpecialPage\prefixSearchString
prefixSearchString( $search, $limit, $offset)
Perform a regular substring search for prefixSearchSubpages.
Definition: SpecialPage.php:448
MWException
MediaWiki exception.
Definition: MWException.php:26
WikiPage\factory
static factory(Title $title)
Create a WikiPage object of the appropriate class for the given title.
Definition: WikiPage.php:120
SpecialChangeContentModel\getFormFields
getFormFields()
Get an HTMLForm descriptor array.
Definition: SpecialChangeContentModel.php:87
SpecialChangeContentModel\getGroupName
getGroupName()
Under which header this special page is listed in Special:SpecialPages See messages 'specialpages-gro...
Definition: SpecialChangeContentModel.php:297
ContentHandler\getContentModels
static getContentModels()
Definition: ContentHandler.php:361
$page
do that in ParserLimitReportFormat instead use this to modify the parameters of the image and a DIV can begin in one section and end in another Make sure your code can handle that case gracefully See the EditSectionClearerLink extension for an example zero but section is usually empty its values are the globals values before the output is cached $page
Definition: hooks.txt:2536
SpecialChangeContentModel\onSuccess
onSuccess()
Do something exciting on successful processing of the form, most likely to show a confirmation messag...
Definition: SpecialChangeContentModel.php:279
LogPage
Class to simplify the use of log pages.
Definition: LogPage.php:31
$limit
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist Do not use this to implement individual filters if they are compatible with the ChangesListFilter and ChangesListFilterGroup structure use sub classes of those in conjunction with the ChangesListSpecialPageStructuredFilters hook This hook can be used to implement filters that do not implement that or custom behavior that is not an individual filter e g Watchlist and Watchlist you will want to construct new ChangesListBooleanFilter or ChangesListStringOptionsFilter objects When constructing you specify which group they belong to You can reuse existing or create your you must register them with $special registerFilterGroup removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content as context as context the output can only depend on parameters provided to this hook not on global state indicating whether full HTML should be generated If generation of HTML may be but other information should still be present in the ParserOutput object to manipulate or replace but no entry for that model exists in $wgContentHandlers please use GetContentModels hook to make them known to core if desired whether it is OK to use $contentModel on $title Handler functions that modify $ok should generally return false to prevent further hooks from further modifying $ok inclusive $limit
Definition: hooks.txt:1049
Xml\element
static element( $element, $attribs=null, $contents='', $allowShortTag=true)
Format an XML element with given attributes and, optionally, text content.
Definition: Xml.php:39
ThrottledError
Show an error when the user hits a rate limit.
Definition: ThrottledError.php:27
SpecialPage\getUser
getUser()
Shortcut to get the User executing this instance.
Definition: SpecialPage.php:685
global
when a variable name is used in a it is silently declared as a new masking the global
Definition: design.txt:93
LogEventsList\showLogExtract
static showLogExtract(&$out, $types=[], $page='', $user='', $param=[])
Show log extract.
Definition: LogEventsList.php:564
SpecialChangeContentModel\validateTitle
validateTitle( $title)
Definition: SpecialChangeContentModel.php:63
SpecialChangeContentModel\onSubmit
onSubmit(array $data)
Process the form on POST submission.
Definition: SpecialChangeContentModel.php:156
ContentHandler\makeContent
static makeContent( $text, Title $title=null, $modelId=null, $format=null)
Convenience function for creating a Content object from a given textual representation.
Definition: ContentHandler.php:129
SpecialPage\getContext
getContext()
Gets the context this SpecialPage is executed in.
Definition: SpecialPage.php:648
Title\newFromTextThrow
static newFromTextThrow( $text, $defaultNamespace=NS_MAIN)
Like Title::newFromText(), but throws MalformedTitleException when the title is invalid,...
Definition: Title.php:295
$e
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException' returning false will NOT prevent logging $e
Definition: hooks.txt:2122
EDIT_UPDATE
const EDIT_UPDATE
Definition: Defines.php:151
ContentHandler\getLocalizedName
static getLocalizedName( $name, Language $lang=null)
Returns the localized name for a given content model.
Definition: ContentHandler.php:348
SpecialPage\msg
msg()
Wrapper around wfMessage that sets the current context.
Definition: SpecialPage.php:746
FormSpecialPage\$par
string $par
The sub-page of the special page.
Definition: FormSpecialPage.php:36
title
title
Definition: parserTests.txt:211
EditPage\matchSummarySpamRegex
static matchSummarySpamRegex( $text)
Check given input text against $wgSummarySpamRegex, and return the text of the first match.
Definition: EditPage.php:2322
SpecialPage\getRequest
getRequest()
Get the WebRequest being used for this instance.
Definition: SpecialPage.php:665
Title\getContentModel
getContentModel( $flags=0)
Get the page's content model id, see the CONTENT_MODEL_XXX constants.
Definition: Title.php:934
$handler
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 modifiable after all normalizations have been except for the $wgMaxImageArea check set to true or false to override the $wgMaxImageArea check result gives extension the possibility to transform it themselves $handler
Definition: hooks.txt:783
SpecialChangeContentModel\getDisplayFormat
getDisplayFormat()
Get display format for the form.
Definition: SpecialChangeContentModel.php:48
HTMLForm\setSubmitTextMsg
setSubmitTextMsg( $msg)
Set the text for the submit button to a message.
Definition: HTMLForm.php:1359
EDIT_NEW
const EDIT_NEW
Definition: Defines.php:150
SpecialChangeContentModel\setParameter
setParameter( $par)
Maybe do something interesting with the subpage parameter.
Definition: SpecialChangeContentModel.php:25
Title
Represents a title within MediaWiki.
Definition: Title.php:39
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
ManualLogEntry
Class for creating log entries manually, to inject them into the database.
Definition: LogEntry.php:396
Title\setContentModel
setContentModel( $model)
Set a proposed content model for the page for permissions checking.
Definition: Title.php:972
ErrorPageError
An error page which can definitely be safely rendered using the OutputPage.
Definition: ErrorPageError.php:27
Hooks\run
static run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:131
$options
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist Do not use this to implement individual filters if they are compatible with the ChangesListFilter and ChangesListFilterGroup structure use sub classes of those in conjunction with the ChangesListSpecialPageStructuredFilters hook This hook can be used to implement filters that do not implement that or custom behavior that is not an individual filter e g Watchlist and Watchlist you will want to construct new ChangesListBooleanFilter or ChangesListStringOptionsFilter objects When constructing you specify which group they belong to You can reuse existing or create your you must register them with $special registerFilterGroup removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content as context as context $options
Definition: hooks.txt:1049
$flags
it s the revision text itself In either if gzip is the revision text is gzipped $flags
Definition: hooks.txt:2749
array
the array() calling protocol came about after MediaWiki 1.4rc1.
$wgContLang
this class mediates it Skin Encapsulates a look and feel for the wiki All of the functions that render HTML and make choices about how to render it are here and are called from various other places when and is meant to be subclassed with other skins that may override some of its functions The User object contains a reference to a and so rather than having a global skin object we just rely on the global User and get the skin with $wgUser and also has some character encoding functions and other locale stuff The current user interface language is instantiated as and the content language as $wgContLang
Definition: design.txt:56
LogFormatter\newFromEntry
static newFromEntry(LogEntry $entry)
Constructs a new formatter suitable for given entry.
Definition: LogFormatter.php:48
HTMLForm
Object handling generic submission, CSRF protection, layout and other logic for UI forms.
Definition: HTMLForm.php:128
$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:783