MediaWiki  master
SpecialChangeCredentials.php
Go to the documentation of this file.
1 <?php
2 
9 
16  protected static $allowedActions = [ AuthManager::ACTION_CHANGE ];
17 
18  protected static $messagePrefix = 'changecredentials';
19 
21  protected static $loadUserData = true;
22 
26  public function __construct( AuthManager $authManager ) {
27  parent::__construct( 'ChangeCredentials', 'editmyprivateinfo' );
28  $this->setAuthManager( $authManager );
29  }
30 
31  protected function getGroupName() {
32  return 'users';
33  }
34 
35  public function isListed() {
36  $this->loadAuth( '' );
37  return (bool)$this->authRequests;
38  }
39 
40  public function doesWrites() {
41  return true;
42  }
43 
44  protected function getDefaultAction( $subPage ) {
45  return AuthManager::ACTION_CHANGE;
46  }
47 
48  protected function getPreservedParams( $withToken = false ) {
49  $request = $this->getRequest();
50  $params = parent::getPreservedParams( $withToken );
51  $params += [
52  'returnto' => $request->getVal( 'returnto' ),
53  'returntoquery' => $request->getVal( 'returntoquery' ),
54  ];
55  return $params;
56  }
57 
58  public function execute( $subPage ) {
59  $this->setHeaders();
60  $this->outputHeader();
61 
62  $this->loadAuth( $subPage );
63 
64  if ( !$subPage ) {
65  $this->showSubpageList();
66  return;
67  }
68 
69  if ( !$this->authRequests ) {
70  // messages used: changecredentials-invalidsubpage, removecredentials-invalidsubpage
71  $this->showSubpageList( $this->msg( static::$messagePrefix . '-invalidsubpage', $subPage ) );
72  return;
73  }
74 
75  $out = $this->getOutput();
76  $out->addModules( 'mediawiki.special.changecredentials' );
77  $out->addBacklinkSubtitle( $this->getPageTitle() );
78  $status = $this->trySubmit();
79 
80  if ( $status === false || !$status->isOK() ) {
81  $this->displayForm( $status );
82  return;
83  }
84 
85  $response = $status->getValue();
86 
87  switch ( $response->status ) {
88  case AuthenticationResponse::PASS:
89  $this->success();
90  break;
91  case AuthenticationResponse::FAIL:
92  $this->displayForm( Status::newFatal( $response->message ) );
93  break;
94  default:
95  throw new LogicException( 'invalid AuthenticationResponse' );
96  }
97  }
98 
99  protected function loadAuth( $subPage, $authAction = null, $reset = false ) {
100  parent::loadAuth( $subPage, $authAction );
101  if ( $subPage ) {
102  $foundReqs = [];
103  foreach ( $this->authRequests as $req ) {
104  if ( $req->getUniqueId() === $subPage ) {
105  $foundReqs[] = $req;
106  }
107  }
108  if ( count( $foundReqs ) > 1 ) {
109  throw new LogicException( 'Multiple AuthenticationRequest objects with same ID!' );
110  }
111  $this->authRequests = $foundReqs;
112  }
113  }
114 
116  public function onAuthChangeFormFields(
117  array $requests, array $fieldInfo, array &$formDescriptor, $action
118  ) {
119  parent::onAuthChangeFormFields( $requests, $fieldInfo, $formDescriptor, $action );
120 
121  // Add some UI flair for password changes, the most common use case for this page.
122  if ( AuthenticationRequest::getRequestByClass( $this->authRequests,
123  PasswordAuthenticationRequest::class )
124  ) {
125  $formDescriptor = self::mergeDefaultFormDescriptor( $fieldInfo, $formDescriptor, [
126  'password' => [
127  'autocomplete' => 'new-password',
128  'placeholder-message' => 'createacct-yourpassword-ph',
129  'help-message' => 'createacct-useuniquepass',
130  ],
131  'retype' => [
132  'autocomplete' => 'new-password',
133  'placeholder-message' => 'createacct-yourpasswordagain-ph',
134  ],
135  // T263927 - the Chromium password form guide recommends always having a username field
136  'username' => [
137  'type' => 'text',
138  'baseField' => 'password',
139  'autocomplete' => 'username',
140  'nodata' => true,
141  'readonly' => true,
142  'cssclass' => 'mw-htmlform-hidden-field',
143  'label-message' => 'userlogin-yourname',
144  'placeholder-message' => 'userlogin-yourname-ph',
145  ],
146  ] );
147  }
148  }
149 
150  protected function getAuthFormDescriptor( $requests, $action ) {
151  if ( !static::$loadUserData ) {
152  return [];
153  } else {
154  $descriptor = parent::getAuthFormDescriptor( $requests, $action );
155 
156  $any = false;
157  foreach ( $descriptor as &$field ) {
158  if ( $field['type'] === 'password' && $field['name'] !== 'retype' ) {
159  $any = true;
160  if ( isset( $field['cssclass'] ) ) {
161  $field['cssclass'] .= ' mw-changecredentials-validate-password';
162  } else {
163  $field['cssclass'] = 'mw-changecredentials-validate-password';
164  }
165  }
166  }
167 
168  if ( $any ) {
169  $this->getOutput()->addModules( 'mediawiki.misc-authed-ooui' );
170  }
171 
172  return $descriptor;
173  }
174  }
175 
176  protected function getAuthForm( array $requests, $action ) {
177  $form = parent::getAuthForm( $requests, $action );
178  $req = reset( $requests );
179  $info = $req->describeCredentials();
180 
181  $form->addPreText(
182  Html::openElement( 'dl' )
183  . Html::element( 'dt', [], $this->msg( 'credentialsform-provider' )->text() )
184  . Html::element( 'dd', [], $info['provider']->text() )
185  . Html::element( 'dt', [], $this->msg( 'credentialsform-account' )->text() )
186  . Html::element( 'dd', [], $info['account']->text() )
187  . Html::closeElement( 'dl' )
188  );
189 
190  // messages used: changecredentials-submit removecredentials-submit
191  $form->setSubmitTextMsg( static::$messagePrefix . '-submit' );
192  $form->showCancel()->setCancelTarget( $this->getReturnUrl() ?: Title::newMainPage() );
193  $form->setSubmitID( 'change_credentials_submit' );
194  return $form;
195  }
196 
197  protected function needsSubmitButton( array $requests ) {
198  // Change/remove forms show are built from a single AuthenticationRequest and do not allow
199  // for redirect flow; they always need a submit button.
200  return true;
201  }
202 
203  public function handleFormSubmit( $data ) {
204  // remove requests do not accept user input
205  $requests = $this->authRequests;
206  if ( static::$loadUserData ) {
207  $requests = AuthenticationRequest::loadRequestsFromSubmission( $this->authRequests, $data );
208  }
209 
210  $response = $this->performAuthenticationStep( $this->authAction, $requests );
211 
212  // we can't handle FAIL or similar as failure here since it might require changing the form
213  return Status::newGood( $response );
214  }
215 
219  protected function showSubpageList( $error = null ) {
220  $out = $this->getOutput();
221 
222  if ( $error ) {
223  $out->addHTML( $error->parse() );
224  }
225 
226  $groupedRequests = [];
227  foreach ( $this->authRequests as $req ) {
228  $info = $req->describeCredentials();
229  $groupedRequests[$info['provider']->text()][] = $req;
230  }
231 
232  $linkRenderer = $this->getLinkRenderer();
233  $out->addHTML( Html::openElement( 'dl' ) );
234  foreach ( $groupedRequests as $group => $members ) {
235  $out->addHTML( Html::element( 'dt', [], $group ) );
236  foreach ( $members as $req ) {
238  $info = $req->describeCredentials();
239  $out->addHTML( Html::rawElement( 'dd', [],
240  $linkRenderer->makeLink(
241  $this->getPageTitle( $req->getUniqueId() ),
242  $info['account']->text()
243  )
244  ) );
245  }
246  }
247  $out->addHTML( Html::closeElement( 'dl' ) );
248  }
249 
250  protected function success() {
251  $session = $this->getRequest()->getSession();
252  $user = $this->getUser();
253  $out = $this->getOutput();
254  $returnUrl = $this->getReturnUrl();
255 
256  // change user token and update the session
257  SessionManager::singleton()->invalidateSessionsForUser( $user );
258  $session->setUser( $user );
259  $session->resetId();
260 
261  if ( $returnUrl ) {
262  $out->redirect( $returnUrl );
263  } else {
264  // messages used: changecredentials-success removecredentials-success
265  $out->addHtml(
267  $out->msg( static::$messagePrefix . '-success' )->parse()
268  )
269  );
270  $out->returnToMain();
271  }
272  }
273 
277  protected function getReturnUrl() {
278  $request = $this->getRequest();
279  $returnTo = $request->getText( 'returnto' );
280  $returnToQuery = $request->getText( 'returntoquery', '' );
281 
282  if ( !$returnTo ) {
283  return null;
284  }
285 
286  $title = Title::newFromText( $returnTo );
287  return $title->getFullUrlForRedirect( $returnToQuery );
288  }
289 
290  protected function getRequestBlacklist() {
291  return $this->getConfig()->get( MainConfigNames::ChangeCredentialsBlacklist );
292  }
293 }
A special page subclass for authentication-related special pages.
string $authAction
one of the AuthManager::ACTION_* constants.
performAuthenticationStep( $action, array $requests)
displayForm( $status)
Display the form.
AuthenticationRequest[] $authRequests
string $subPage
Subpage of the special page.
static mergeDefaultFormDescriptor(array $fieldInfo, array $formDescriptor, array $defaultFormDescriptor)
Apply defaults to a form descriptor, without creating non-existent fields.
getRequest()
Get the WebRequest being used for this instance.
trySubmit()
Attempts to do an authentication step with the submitted data.
static element( $element, $attribs=[], $contents='')
Identical to rawElement(), but HTML-escapes $contents (like Xml::element()).
Definition: Html.php:236
static rawElement( $element, $attribs=[], $contents='')
Returns an HTML element in a string.
Definition: Html.php:214
static openElement( $element, $attribs=[])
Identical to rawElement(), but has no third parameter and omits the end tag (and the self-closing '/'...
Definition: Html.php:256
static successBox( $html, $className='')
Return a success box.
Definition: Html.php:800
static closeElement( $element)
Returns "</$element>".
Definition: Html.php:320
This serves as the entry point to the authentication system.
This is a value object for authentication requests.
This is a value object to hold authentication response data.
This is a value object for authentication requests with a username and password.
A class containing constants representing the names of configuration variables.
This serves as the entry point to the MediaWiki session handling system.
Special change to change credentials (such as the password).
getGroupName()
Under which header this special page is listed in Special:SpecialPages See messages 'specialpages-gro...
getAuthForm(array $requests, $action)
doesWrites()
Indicates whether this special page may perform database writes.
handleFormSubmit( $data)
Submit handler callback for HTMLForm.
getPreservedParams( $withToken=false)
Returns URL query parameters which can be used to reload the page (or leave and return) while preserv...
isListed()
Whether this special page is listed in Special:SpecialPages.
getRequestBlacklist()
Allows blacklisting certain request types.
getAuthFormDescriptor( $requests, $action)
Generates a HTMLForm descriptor array from a set of authentication requests.
loadAuth( $subPage, $authAction=null, $reset=false)
Load or initialize $authAction, $authRequests and $subPage.
getDefaultAction( $subPage)
Get the default action for this special page, if none is given via URL/POST data.
__construct(AuthManager $authManager)
needsSubmitButton(array $requests)
Returns true if the form built from the given AuthenticationRequests needs a submit button.
static $loadUserData
Change action needs user data; remove action does not.
execute( $subPage)
Default execute method Checks user permissions.
onAuthChangeFormFields(array $requests, array $fieldInfo, array &$formDescriptor, $action)
Change the form descriptor that determines how a field will look in the authentication form....
outputHeader( $summaryMessageKey='')
Outputs a summary message on top of special pages Per default the message key is the canonical name o...
setHeaders()
Sets headers - this should be called from the execute() method of all derived classes!
getOutput()
Get the OutputPage being used for this instance.
getUser()
Shortcut to get the User executing this instance.
msg( $key,... $params)
Wrapper around wfMessage that sets the current context.
getConfig()
Shortcut to get main config object.
setAuthManager(AuthManager $authManager)
Set the injected AuthManager from the special page constructor.
getPageTitle( $subpage=false)
Get a self-referential title object.
static newFatal( $message,... $parameters)
Factory function for fatal errors.
Definition: StatusValue.php:73
static newGood( $value=null)
Factory function for good results.
Definition: StatusValue.php:85
static newMainPage(MessageLocalizer $localizer=null)
Create a new Title for the Main Page.
Definition: Title.php:703
static newFromText( $text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
Definition: Title.php:373