MediaWiki  master
SpecialChangePassword.php
Go to the documentation of this file.
1 <?php
30  protected $mUserName;
31  protected $mDomain;
32 
33  // Optional Wikitext Message to show above the password change form
34  protected $mPreTextMessage = null;
35 
36  // label for old password input
37  protected $mOldPassMsg = null;
38 
39  public function __construct() {
40  parent::__construct( 'ChangePassword', 'editmyprivateinfo' );
41  $this->listed( false );
42  }
43 
44  public function doesWrites() {
45  return true;
46  }
47 
52  function execute( $par ) {
53  $this->getOutput()->disallowUserJs();
54 
56  }
57 
58  protected function checkExecutePermissions( User $user ) {
59  parent::checkExecutePermissions( $user );
60 
61  if ( !$this->getRequest()->wasPosted() ) {
62  $this->requireLogin( 'resetpass-no-info' );
63  }
64  }
65 
71  public function setChangeMessage( Message $msg ) {
72  $this->mPreTextMessage = $msg;
73  }
74 
80  public function setOldPasswordMessage( $msg ) {
81  $this->mOldPassMsg = $msg;
82  }
83 
84  protected function getFormFields() {
85  $user = $this->getUser();
86  $request = $this->getRequest();
87 
88  $oldpassMsg = $this->mOldPassMsg;
89  if ( $oldpassMsg === null ) {
90  $oldpassMsg = $user->isLoggedIn() ? 'oldpassword' : 'resetpass-temp-password';
91  }
92 
93  $fields = [
94  'Name' => [
95  'type' => 'info',
96  'label-message' => 'username',
97  'default' => $request->getVal( 'wpName', $user->getName() ),
98  ],
99  'Password' => [
100  'type' => 'password',
101  'label-message' => $oldpassMsg,
102  ],
103  'NewPassword' => [
104  'type' => 'password',
105  'label-message' => 'newpassword',
106  ],
107  'Retype' => [
108  'type' => 'password',
109  'label-message' => 'retypenew',
110  ],
111  ];
112 
113  if ( !$this->getUser()->isLoggedIn() ) {
114  $fields['LoginOnChangeToken'] = [
115  'type' => 'hidden',
116  'label' => 'Change Password Token',
117  'default' => LoginForm::getLoginToken()->toString(),
118  ];
119  }
120 
121  $extraFields = [];
122  Hooks::run( 'ChangePasswordForm', [ &$extraFields ] );
123  foreach ( $extraFields as $extra ) {
124  list( $name, $label, $type, $default ) = $extra;
125  $fields[$name] = [
126  'type' => $type,
127  'name' => $name,
128  'label-message' => $label,
129  'default' => $default,
130  ];
131  }
132 
133  if ( !$user->isLoggedIn() ) {
134  $fields['Remember'] = [
135  'type' => 'check',
136  'label' => $this->msg( 'remembermypassword' )
137  ->numParams(
138  ceil( $this->getConfig()->get( 'CookieExpiration' ) / ( 3600 * 24 ) )
139  )->text(),
140  'default' => $request->getVal( 'wpRemember' ),
141  ];
142  }
143 
144  return $fields;
145  }
146 
147  protected function alterForm( HTMLForm $form ) {
148  $form->setId( 'mw-resetpass-form' );
149  $form->setTableId( 'mw-resetpass-table' );
150  $form->setWrapperLegendMsg( 'resetpass_header' );
151  $form->setSubmitTextMsg(
152  $this->getUser()->isLoggedIn()
153  ? 'resetpass-submit-loggedin'
154  : 'resetpass_submit'
155  );
156  $form->addButton( [
157  'name' => 'wpCancel',
158  'value' => $this->msg( 'resetpass-submit-cancel' )->text()
159  ] );
160  $form->setHeaderText( $this->msg( 'resetpass_text' )->parseAsBlock() );
161  if ( $this->mPreTextMessage instanceof Message ) {
162  $form->addPreText( $this->mPreTextMessage->parseAsBlock() );
163  }
164  $form->addHiddenFields(
165  $this->getRequest()->getValues( 'wpName', 'wpDomain', 'returnto', 'returntoquery' ) );
166  }
167 
168  public function onSubmit( array $data ) {
169  global $wgAuth;
170 
171  $request = $this->getRequest();
172 
173  if ( $request->getCheck( 'wpLoginToken' ) ) {
174  // This comes from Special:Userlogin when logging in with a temporary password
175  return false;
176  }
177 
178  if ( !$this->getUser()->isLoggedIn()
179  && !LoginForm::getLoginToken()->match( $request->getVal( 'wpLoginOnChangeToken' ) )
180  ) {
181  // Potential CSRF (bug 62497)
182  return false;
183  }
184 
185  if ( $request->getCheck( 'wpCancel' ) ) {
186  $returnto = $request->getVal( 'returnto' );
187  $titleObj = $returnto !== null ? Title::newFromText( $returnto ) : null;
188  if ( !$titleObj instanceof Title ) {
189  $titleObj = Title::newMainPage();
190  }
191  $query = $request->getVal( 'returntoquery' );
192  $this->getOutput()->redirect( $titleObj->getFullURL( $query ) );
193 
194  return true;
195  }
196 
197  $this->mUserName = $request->getVal( 'wpName', $this->getUser()->getName() );
198  $this->mDomain = $wgAuth->getDomain();
199 
200  if ( !$wgAuth->allowPasswordChange() ) {
201  throw new ErrorPageError( 'changepassword', 'resetpass_forbidden' );
202  }
203 
204  $status = $this->attemptReset( $data['Password'], $data['NewPassword'], $data['Retype'] );
205 
206  return $status;
207  }
208 
209  public function onSuccess() {
210  if ( $this->getUser()->isLoggedIn() ) {
211  $this->getOutput()->wrapWikiMsg(
212  "<div class=\"successbox\">\n$1\n</div>",
213  'changepassword-success'
214  );
215  $this->getOutput()->returnToMain();
216  } else {
217  $request = $this->getRequest();
218  LoginForm::clearLoginToken();
219  $token = LoginForm::getLoginToken()->toString();
220  $data = [
221  'action' => 'submitlogin',
222  'wpName' => $this->mUserName,
223  'wpDomain' => $this->mDomain,
224  'wpLoginToken' => $token,
225  'wpPassword' => $request->getVal( 'wpNewPassword' ),
226  ] + $request->getValues( 'wpRemember', 'returnto', 'returntoquery' );
227  $login = new LoginForm( new DerivativeRequest( $request, $data, true ) );
228  $login->setContext( $this->getContext() );
229  $login->execute( null );
230  }
231  }
232 
243  protected function attemptReset( $oldpass, $newpass, $retype ) {
244  $isSelf = ( $this->mUserName === $this->getUser()->getName() );
245  if ( $isSelf ) {
246  $user = $this->getUser();
247  } else {
248  $user = User::newFromName( $this->mUserName );
249  }
250 
251  if ( !$user || $user->isAnon() ) {
252  return Status::newFatal( $this->msg( 'nosuchusershort', $this->mUserName ) );
253  }
254 
255  if ( $newpass !== $retype ) {
256  Hooks::run( 'PrefsPasswordAudit', [ $user, $newpass, 'badretype' ] );
257  return Status::newFatal( $this->msg( 'badretype' ) );
258  }
259 
260  $throttleInfo = LoginForm::incrementLoginThrottle( $this->mUserName );
261  if ( $throttleInfo ) {
262  return Status::newFatal( $this->msg( 'changepassword-throttled' )
263  ->durationParams( $throttleInfo['wait'] )
264  );
265  }
266 
267  // @todo Make these separate messages, since the message is written for both cases
268  if ( !$user->checkTemporaryPassword( $oldpass ) && !$user->checkPassword( $oldpass ) ) {
269  Hooks::run( 'PrefsPasswordAudit', [ $user, $newpass, 'wrongpassword' ] );
270  return Status::newFatal( $this->msg( 'resetpass-wrong-oldpass' ) );
271  }
272 
273  // User is resetting their password to their old password
274  if ( $oldpass === $newpass ) {
275  return Status::newFatal( $this->msg( 'resetpass-recycled' ) );
276  }
277 
278  // Do AbortChangePassword after checking mOldpass, so we don't leak information
279  // by possibly aborting a new password before verifying the old password.
280  $abortMsg = 'resetpass-abort-generic';
281  if ( !Hooks::run( 'AbortChangePassword', [ $user, $oldpass, $newpass, &$abortMsg ] ) ) {
282  Hooks::run( 'PrefsPasswordAudit', [ $user, $newpass, 'abortreset' ] );
283  return Status::newFatal( $this->msg( $abortMsg ) );
284  }
285 
286  // Please reset throttle for successful logins, thanks!
287  LoginForm::clearLoginThrottle( $this->mUserName );
288 
289  try {
290  $user->setPassword( $newpass );
291  Hooks::run( 'PrefsPasswordAudit', [ $user, $newpass, 'success' ] );
292  } catch ( PasswordError $e ) {
293  Hooks::run( 'PrefsPasswordAudit', [ $user, $newpass, 'error' ] );
294  return Status::newFatal( new RawMessage( $e->getMessage() ) );
295  }
296 
297  if ( $isSelf ) {
298  // This is needed to keep the user connected since
299  // changing the password also modifies the user's token.
300  $remember = $this->getRequest()->getCookie( 'Token' ) !== null;
301  $user->setCookies( null, null, $remember );
302  }
303  $user->saveSettings();
304  $this->resetPasswordExpiration( $user );
305  return Status::newGood();
306  }
307 
308  public function requiresUnblock() {
309  return false;
310  }
311 
312  protected function getGroupName() {
313  return 'users';
314  }
315 
320  private function resetPasswordExpiration( User $user ) {
322  $newExpire = null;
323  if ( $wgPasswordExpirationDays ) {
324  $newExpire = wfTimestamp(
325  TS_MW,
326  time() + ( $wgPasswordExpirationDays * 24 * 3600 )
327  );
328  }
329  // Give extensions a chance to force an expiration
330  Hooks::run( 'ResetPasswordExpiration', [ $this, &$newExpire ] );
331  $dbw = wfGetDB( DB_MASTER );
332  $dbw->update(
333  'user',
334  [ 'user_password_expires' => $dbw->timestampOrNull( $newExpire ) ],
335  [ 'user_id' => $user->getId() ],
336  __METHOD__
337  );
338  }
339 
340  protected function getDisplayFormat() {
341  return 'ooui';
342  }
343 }
static newFromName($name, $validate= 'valid')
Static factory method for creation from username.
Definition: User.php:522
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
Definition: deferred.txt:11
wfGetDB($db, $groups=[], $wiki=false)
Get a Database object.
the array() calling protocol came about after MediaWiki 1.4rc1.
null for the local wiki Added should default to null in handler for backwards compatibility add a value to it if you want to add a cookie that have to vary cache options can modify $query
Definition: hooks.txt:1435
$wgPasswordExpirationDays
The number of days that a user's password is good for.
getContext()
Gets the context this SpecialPage is executed in.
$batch execute()
static newMainPage()
Create a new Title for the Main Page.
Definition: Title.php:548
resetPasswordExpiration(User $user)
For resetting user password expiration, until AuthManager comes along.
setId($id)
Definition: HTMLForm.php:1435
The Message class provides methods which fulfil two basic services:
Definition: Message.php:159
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException'returning false will NOT prevent logging $e
Definition: hooks.txt:1980
Similar to FauxRequest, but only fakes URL parameters and method (POST or GET) and use the base reque...
setOldPasswordMessage($msg)
Set a message at the top of the Change Password form.
setWrapperLegendMsg($msg)
Prompt the whole form to be wrapped in a "<fieldset>", with this message as its "<legend>" element...
Definition: HTMLForm.php:1477
msg()
Wrapper around wfMessage that sets the current context.
setChangeMessage(Message $msg)
Set a message at the top of the Change Password form.
getOutput()
Get the OutputPage being used for this instance.
$wgAuth $wgAuth
Authentication plugin.
static newFromText($text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
Definition: Title.php:256
Represents a title within MediaWiki.
Definition: Title.php:36
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
Special page which uses an HTMLForm to handle processing.
addHiddenFields(array $fields)
Add an array of hidden fields to the output.
Definition: HTMLForm.php:890
The User object encapsulates all of the user-specific settings (user_id, name, rights, email address, options, last login time).
Definition: User.php:47
wfTimestamp($outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
Let users recover their password.
An error page which can definitely be safely rendered using the OutputPage.
setTableId($id)
Set the id of the \<table\> or outermost \<div\> element.
Definition: HTMLForm.php:1424
setSubmitTextMsg($msg)
Set the text for the submit button to a message.
Definition: HTMLForm.php:1303
Object handling generic submission, CSRF protection, layout and other logic for UI forms...
Definition: HTMLForm.php:128
listed($x=null)
Get or set whether this special page is listed in Special:SpecialPages.
static run($event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:131
design txt This is a brief overview of the new design More thorough and up to date information is available on the documentation wiki at etc Handles the details of getting and saving to the user table of the and dealing with sessions and cookies OutputPage Encapsulates the entire HTML page that will be sent in response to any server request It is used by calling its functions to add text
Definition: design.txt:12
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
setHeaderText($msg, $section=null)
Set header text, inside the form.
Definition: HTMLForm.php:758
const TS_MW
MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
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
error also a ContextSource you ll probably need to make sure the header is varied on $request
Definition: hooks.txt:2458
getName()
Get the name of this Special Page.
getId()
Get the user's ID.
Definition: User.php:2114
Show an error when any operation involving passwords fails to run.
Variant of the Message class.
Definition: Message.php:1236
addPreText($msg)
Add HTML to introductory message.
Definition: HTMLForm.php:722
requireLogin($reasonMsg= 'exception-nologin-text', $titleMsg= 'exception-nologin')
If the user is not logged in, throws UserNotLoggedIn error.
getUser()
Shortcut to get the User executing this instance.
string $par
The sub-page of the special page.
getConfig()
Shortcut to get main config object.
A horrible hack to handle AuthManager's feature flag.
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:1020
addButton($data)
Add a button to the form.
Definition: HTMLForm.php:922
const DB_MASTER
Definition: Defines.php:47
attemptReset($oldpass, $newpass, $retype)
Checks the new password if it meets the requirements for passwords and set it as a current password...
getRequest()
Get the WebRequest being used for this instance.
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 incomplete & $abortMsg
Definition: hooks.txt:242
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 one of or reset my talk my contributions etc etc otherwise the built in rate limiting checks are if enabled allows for interception of redirect as a string mapping parameter names to values & $type
Definition: hooks.txt:2376
static newGood($value=null)
Factory function for good results.
Definition: Status.php:101
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:310