MediaWiki  1.27.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 getDisplayFormat() {
37  return 'ooui';
38  }
39 
40  protected function alterForm( HTMLForm $form ) {
41  if ( !$this->title ) {
42  $form->setMethod( 'GET' );
43  }
44 
45  $this->addHelpLink( 'Help:ChangeContentModel' );
46 
47  // T120576
48  $form->setSubmitTextMsg( 'changecontentmodel-submit' );
49  }
50 
51  public function validateTitle( $title ) {
52  if ( !$title ) {
53  // No form input yet
54  return true;
55  }
56 
57  // Already validated by HTMLForm, but if not, throw
58  // and exception instead of a fatal
59  $titleObj = Title::newFromTextThrow( $title );
60 
61  $this->oldRevision = Revision::newFromTitle( $titleObj ) ?: false;
62 
63  if ( $this->oldRevision ) {
64  $oldContent = $this->oldRevision->getContent();
65  if ( !$oldContent->getContentHandler()->supportsDirectEditing() ) {
66  return $this->msg( 'changecontentmodel-nodirectediting' )
67  ->params( ContentHandler::getLocalizedName( $oldContent->getModel() ) )
68  ->escaped();
69  }
70  }
71 
72  return true;
73  }
74 
75  protected function getFormFields() {
76  $fields = [
77  'pagetitle' => [
78  'type' => 'title',
79  'creatable' => true,
80  'name' => 'pagetitle',
81  'default' => $this->par,
82  'label-message' => 'changecontentmodel-title-label',
83  'validation-callback' => [ $this, 'validateTitle' ],
84  ],
85  ];
86  if ( $this->title ) {
87  $fields['pagetitle']['readonly'] = true;
88  $fields += [
89  'model' => [
90  'type' => 'select',
91  'name' => 'model',
92  'options' => $this->getOptionsForTitle( $this->title ),
93  'label-message' => 'changecontentmodel-model-label'
94  ],
95  'reason' => [
96  'type' => 'text',
97  'name' => 'reason',
98  'validation-callback' => function( $reason ) {
99  $match = EditPage::matchSummarySpamRegex( $reason );
100  if ( $match ) {
101  return $this->msg( 'spamprotectionmatch', $match )->parse();
102  }
103 
104  return true;
105  },
106  'label-message' => 'changecontentmodel-reason-label',
107  ],
108  ];
109  }
110 
111  return $fields;
112  }
113 
114  private function getOptionsForTitle( Title $title = null ) {
116  $options = [];
117  foreach ( $models as $model ) {
119  if ( !$handler->supportsDirectEditing() ) {
120  continue;
121  }
122  if ( $title ) {
123  if ( $title->getContentModel() === $model ) {
124  continue;
125  }
126  if ( !$handler->canBeUsedOn( $title ) ) {
127  continue;
128  }
129  }
130  $options[ContentHandler::getLocalizedName( $model )] = $model;
131  }
132 
133  return $options;
134  }
135 
136  public function onSubmit( array $data ) {
138 
139  if ( $data['pagetitle'] === '' ) {
140  // Initial form view of special page, pass
141  return false;
142  }
143 
144  // At this point, it has to be a POST request. This is enforced by HTMLForm,
145  // but lets be safe verify that.
146  if ( !$this->getRequest()->wasPosted() ) {
147  throw new RuntimeException( "Form submission was not POSTed" );
148  }
149 
150  $this->title = Title::newFromText( $data['pagetitle'] );
151  $user = $this->getUser();
152  // Check permissions and make sure the user has permission to edit the specific page
153  $errors = $this->title->getUserPermissionsErrors( 'editcontentmodel', $user );
154  $errors = wfMergeErrorArrays( $errors, $this->title->getUserPermissionsErrors( 'edit', $user ) );
155  if ( $errors ) {
156  $out = $this->getOutput();
157  $wikitext = $out->formatPermissionsErrorMessage( $errors );
158  // Hack to get our wikitext parsed
159  return Status::newFatal( new RawMessage( '$1', [ $wikitext ] ) );
160  }
161 
162  $page = WikiPage::factory( $this->title );
163  if ( $this->oldRevision === null ) {
164  $this->oldRevision = $page->getRevision() ?: false;
165  }
166  $oldModel = $this->title->getContentModel();
167  if ( $this->oldRevision ) {
168  $oldContent = $this->oldRevision->getContent();
169  try {
170  $newContent = ContentHandler::makeContent(
171  $oldContent->getNativeData(), $this->title, $data['model']
172  );
173  } catch ( MWException $e ) {
174  return Status::newFatal(
175  $this->msg( 'changecontentmodel-cannot-convert' )
176  ->params(
177  $this->title->getPrefixedText(),
178  ContentHandler::getLocalizedName( $data['model'] )
179  )
180  );
181  }
182  } else {
183  // Page doesn't exist, create an empty content object
184  $newContent = ContentHandler::getForModelID( $data['model'] )->makeEmptyContent();
185  }
186  $flags = $this->oldRevision ? EDIT_UPDATE : EDIT_NEW;
187  if ( $user->isAllowed( 'bot' ) ) {
189  }
190 
191  $log = new ManualLogEntry( 'contentmodel', $this->oldRevision ? 'change' : 'new' );
192  $log->setPerformer( $user );
193  $log->setTarget( $this->title );
194  $log->setComment( $data['reason'] );
195  $log->setParameters( [
196  '4::oldmodel' => $oldModel,
197  '5::newmodel' => $data['model']
198  ] );
199 
200  $formatter = LogFormatter::newFromEntry( $log );
201  $formatter->setContext( RequestContext::newExtraneousContext( $this->title ) );
202  $reason = $formatter->getPlainActionText();
203  if ( $data['reason'] !== '' ) {
204  $reason .= $this->msg( 'colon-separator' )->inContentLanguage()->text() . $data['reason'];
205  }
206  # Truncate for whole multibyte characters.
207  $reason = $wgContLang->truncate( $reason, 255 );
208 
209  $status = $page->doEditContent(
210  $newContent,
211  $reason,
212  $flags,
213  $this->oldRevision ? $this->oldRevision->getId() : false,
214  $user
215  );
216  if ( !$status->isOK() ) {
217  return $status;
218  }
219 
220  $logid = $log->insert();
221  $log->publish( $logid );
222 
223  return $status;
224  }
225 
226  public function onSuccess() {
227  $out = $this->getOutput();
228  $out->setPageTitle( $this->msg( 'changecontentmodel-success-title' ) );
229  $out->addWikiMsg( 'changecontentmodel-success-text', $this->title );
230  }
231 
240  public function prefixSearchSubpages( $search, $limit, $offset ) {
241  return $this->prefixSearchString( $search, $limit, $offset );
242  }
243 
244  protected function getGroupName() {
245  return 'pagetools';
246  }
247 }
static factory(Title $title)
Create a WikiPage object of the appropriate class for the given title.
Definition: WikiPage.php:99
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:762
the array() calling protocol came about after MediaWiki 1.4rc1.
setMethod($method= 'post')
Set the method used to submit the form.
Definition: HTMLForm.php:1435
static getForModelID($modelId)
Returns the ContentHandler singleton for the given model ID.
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException'returning false will NOT prevent logging $e
Definition: hooks.txt:1932
static getContentModels()
static newFromEntry(LogEntry $entry)
Constructs a new formatter suitable for given entry.
it s the revision text itself In either if gzip is the revision text is gzipped $flags
Definition: hooks.txt:2548
msg()
Wrapper around wfMessage that sets the current context.
getOutput()
Get the OutputPage being used for this instance.
getPrefixedText()
Get the prefixed title with spaces.
Definition: Title.php:1449
const EDIT_UPDATE
Definition: Defines.php:180
static newFromText($text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
Definition: Title.php:277
Represents a title within MediaWiki.
Definition: Title.php:34
when a variable name is used in a it is silently declared as a new local masking the global
Definition: design.txt:93
static newFatal($message)
Factory function for fatal errors.
Definition: Status.php:89
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:117
Special page which uses an HTMLForm to handle processing.
addHelpLink($to, $overrideBaseUrl=false)
Adds help link with an icon via page indicators.
static matchSummarySpamRegex($text)
Check given input text against $wgSummarySpamRegex, and return the text of the first match...
Definition: EditPage.php:2202
static getLocalizedName($name, Language $lang=null)
Returns the localized name for a given content model.
getContentModel($flags=0)
Get the page's content model id, see the CONTENT_MODEL_XXX constants.
Definition: Title.php:944
wfMergeErrorArrays()
Merge arrays in the style of getUserPermissionsErrors, with duplicate removal e.g.
const EDIT_FORCE_BOT
Definition: Defines.php:183
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist 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:1004
setSubmitTextMsg($msg)
Set the text for the submit button to a message.
Definition: HTMLForm.php:1250
static newExtraneousContext(Title $title, $request=[])
Create a new extraneous context.
Object handling generic submission, CSRF protection, layout and other logic for UI forms...
Definition: HTMLForm.php:123
title
static makeContent($text, Title $title=null, $modelId=null, $format=null)
Convenience function for creating a Content object from a given textual representation.
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
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 local account $user
Definition: hooks.txt:242
static newFromTextThrow($text, $defaultNamespace=NS_MAIN)
Like Title::newFromText(), but throws MalformedTitleException when the title is invalid, rather than returning null.
Definition: Title.php:307
prefixSearchSubpages($search, $limit, $offset)
Return an array of subpages beginning with $search that this special page will accept.
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
Class for creating log entries manually, to inject them into the database.
Definition: LogEntry.php:394
const EDIT_NEW
Definition: Defines.php:179
Variant of the Message class.
Definition: Message.php:1232
getUser()
Shortcut to get the User executing this instance.
string $par
The sub-page of the special page.
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist 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 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:1004
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 local content language as $wgContLang
Definition: design.txt:56
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist 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:1004
Revision bool null $oldRevision
A Revision object, false if no revision exists, null if not loaded yet.
getRequest()
Get the WebRequest being used for this instance.
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:762
prefixSearchString($search, $limit, $offset)
Perform a regular substring search for prefixSearchSubpages.
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:2338