MediaWiki  master
SpecialBotPasswords.php
Go to the documentation of this file.
1 <?php
27 
34 
36  private $userId = 0;
37 
39  private $botPassword = null;
40 
42  private $operation = null;
43 
45  private $password = null;
46 
48  private $logger;
49 
52 
55 
61  public function __construct(
65  ) {
66  parent::__construct( 'BotPasswords', 'editmyprivateinfo' );
67  $this->logger = LoggerFactory::getInstance( 'authentication' );
68  $this->passwordFactory = $passwordFactory;
69  $this->centralIdLookup = $centralIdLookup;
70  $this->setAuthManager( $authManager );
71  }
72 
76  public function isListed() {
77  return $this->getConfig()->get( MainConfigNames::EnableBotPasswords );
78  }
79 
80  protected function getLoginSecurityLevel() {
81  return $this->getName();
82  }
83 
88  public function execute( $par ) {
89  $this->getOutput()->disallowUserJs();
90  $this->requireNamedUser();
91  $this->addHelpLink( 'Manual:Bot_passwords' );
92 
93  $par = trim( $par );
94  if ( strlen( $par ) === 0 ) {
95  $par = null;
96  } elseif ( strlen( $par ) > BotPassword::APPID_MAXLENGTH ) {
97  throw new ErrorPageError( 'botpasswords', 'botpasswords-bad-appid',
98  [ htmlspecialchars( $par ) ] );
99  }
100 
101  parent::execute( $par );
102  }
103 
104  protected function checkExecutePermissions( User $user ) {
105  parent::checkExecutePermissions( $user );
106 
107  if ( !$this->getConfig()->get( MainConfigNames::EnableBotPasswords ) ) {
108  throw new ErrorPageError( 'botpasswords', 'botpasswords-disabled' );
109  }
110 
111  $this->userId = $this->centralIdLookup->centralIdFromLocalUser( $this->getUser() );
112  if ( !$this->userId ) {
113  throw new ErrorPageError( 'botpasswords', 'botpasswords-no-central-id' );
114  }
115  }
116 
117  protected function getFormFields() {
118  $fields = [];
119 
120  if ( $this->par !== null ) {
121  $this->botPassword = BotPassword::newFromCentralId( $this->userId, $this->par );
122  if ( !$this->botPassword ) {
123  $this->botPassword = BotPassword::newUnsaved( [
124  'centralId' => $this->userId,
125  'appId' => $this->par,
126  ] );
127  }
128 
129  $sep = BotPassword::getSeparator();
130  $fields[] = [
131  'type' => 'info',
132  'label-message' => 'username',
133  'default' => $this->getUser()->getName() . $sep . $this->par
134  ];
135 
136  if ( $this->botPassword->isSaved() ) {
137  $fields['resetPassword'] = [
138  'type' => 'check',
139  'label-message' => 'botpasswords-label-resetpassword',
140  ];
141  if ( $this->botPassword->isInvalid() ) {
142  $fields['resetPassword']['default'] = true;
143  }
144  }
145 
146  $lang = $this->getLanguage();
147  $showGrants = MWGrants::getValidGrants();
148  $grantLinks = array_map( [ MWGrants::class, 'getGrantsLink' ], $showGrants );
149 
150  $fields['grants'] = [
151  'type' => 'checkmatrix',
152  'label-message' => 'botpasswords-label-grants',
153  'help-message' => 'botpasswords-help-grants',
154  'columns' => [
155  $this->msg( 'botpasswords-label-grants-column' )->escaped() => 'grant'
156  ],
157  'rows' => array_combine(
158  $grantLinks,
159  $showGrants
160  ),
161  'default' => array_map(
162  static function ( $g ) {
163  return "grant-$g";
164  },
165  $this->botPassword->getGrants()
166  ),
167  'tooltips' => array_combine(
168  $grantLinks,
169  array_map(
170  static function ( $rights ) use ( $lang ) {
171  return $lang->semicolonList( array_map( [ User::class, 'getRightDescription' ], $rights ) );
172  },
173  array_intersect_key( MWGrants::getRightsByGrant(),
174  array_fill_keys( $showGrants, true ) )
175  )
176  ),
177  'force-options-on' => array_map(
178  static function ( $g ) {
179  return "grant-$g";
180  },
182  ),
183  ];
184 
185  $fields['restrictions'] = [
186  'class' => HTMLRestrictionsField::class,
187  'required' => true,
188  'default' => $this->botPassword->getRestrictions(),
189  ];
190 
191  } else {
192  $linkRenderer = $this->getLinkRenderer();
193 
195  $res = $dbr->select(
196  'bot_passwords',
197  [ 'bp_app_id', 'bp_password' ],
198  [ 'bp_user' => $this->userId ],
199  __METHOD__
200  );
201  foreach ( $res as $row ) {
202  try {
203  $password = $this->passwordFactory->newFromCiphertext( $row->bp_password );
204  $passwordInvalid = $password instanceof InvalidPassword;
205  unset( $password );
206  } catch ( PasswordError $ex ) {
207  $passwordInvalid = true;
208  }
209 
210  $text = $linkRenderer->makeKnownLink(
211  $this->getPageTitle( $row->bp_app_id ),
212  $row->bp_app_id
213  );
214  if ( $passwordInvalid ) {
215  $text .= $this->msg( 'word-separator' )->escaped()
216  . $this->msg( 'botpasswords-label-needsreset' )->parse();
217  }
218 
219  $fields[] = [
220  'section' => 'existing',
221  'type' => 'info',
222  'raw' => true,
223  'default' => $text,
224  ];
225  }
226 
227  $fields['appId'] = [
228  'section' => 'createnew',
229  'type' => 'textwithbutton',
230  'label-message' => 'botpasswords-label-appid',
231  'buttondefault' => $this->msg( 'botpasswords-label-create' )->text(),
232  'buttonflags' => [ 'progressive', 'primary' ],
233  'required' => true,
235  'maxlength' => BotPassword::APPID_MAXLENGTH,
236  'validation-callback' => static function ( $v ) {
237  $v = trim( $v );
238  return $v !== '' && strlen( $v ) <= BotPassword::APPID_MAXLENGTH;
239  },
240  ];
241 
242  $fields[] = [
243  'type' => 'hidden',
244  'default' => 'new',
245  'name' => 'op',
246  ];
247  }
248 
249  return $fields;
250  }
251 
252  protected function alterForm( HTMLForm $form ) {
253  $form->setId( 'mw-botpasswords-form' );
254  $form->setTableId( 'mw-botpasswords-table' );
255  $form->addPreText( $this->msg( 'botpasswords-summary' )->parseAsBlock() );
256  $form->suppressDefaultSubmit();
257 
258  if ( $this->par !== null ) {
259  if ( $this->botPassword->isSaved() ) {
260  $form->setWrapperLegendMsg( 'botpasswords-editexisting' );
261  $form->addButton( [
262  'name' => 'op',
263  'value' => 'update',
264  'label-message' => 'botpasswords-label-update',
265  'flags' => [ 'primary', 'progressive' ],
266  ] );
267  $form->addButton( [
268  'name' => 'op',
269  'value' => 'delete',
270  'label-message' => 'botpasswords-label-delete',
271  'flags' => [ 'destructive' ],
272  ] );
273  } else {
274  $form->setWrapperLegendMsg( 'botpasswords-createnew' );
275  $form->addButton( [
276  'name' => 'op',
277  'value' => 'create',
278  'label-message' => 'botpasswords-label-create',
279  'flags' => [ 'primary', 'progressive' ],
280  ] );
281  }
282 
283  $form->addButton( [
284  'name' => 'op',
285  'value' => 'cancel',
286  'label-message' => 'botpasswords-label-cancel'
287  ] );
288  }
289  }
290 
291  public function onSubmit( array $data ) {
292  $op = $this->getRequest()->getVal( 'op', '' );
293 
294  switch ( $op ) {
295  case 'new':
296  $this->getOutput()->redirect( $this->getPageTitle( $data['appId'] )->getFullURL() );
297  return false;
298 
299  case 'create':
300  $this->operation = 'insert';
301  return $this->save( $data );
302 
303  case 'update':
304  $this->operation = 'update';
305  return $this->save( $data );
306 
307  case 'delete':
308  $this->operation = 'delete';
309  $bp = BotPassword::newFromCentralId( $this->userId, $this->par );
310  if ( $bp ) {
311  $bp->delete();
312  $this->logger->info(
313  "Bot password {op} for {user}@{app_id}",
314  [
315  'app_id' => $this->par,
316  'user' => $this->getUser()->getName(),
317  'centralId' => $this->userId,
318  'op' => 'delete',
319  'client_ip' => $this->getRequest()->getIP()
320  ]
321  );
322  }
323  return Status::newGood();
324 
325  case 'cancel':
326  $this->getOutput()->redirect( $this->getPageTitle()->getFullURL() );
327  return false;
328  }
329 
330  return false;
331  }
332 
333  private function save( array $data ) {
334  $bp = BotPassword::newUnsaved( [
335  'centralId' => $this->userId,
336  'appId' => $this->par,
337  'restrictions' => $data['restrictions'],
338  'grants' => array_merge(
340  // @phan-suppress-next-next-line PhanTypeMismatchArgumentInternal See phan issue #3163,
341  // it's probably failing to infer the type of $data['grants']
342  preg_replace( '/^grant-/', '', $data['grants'] )
343  )
344  ] );
345 
346  if ( $bp === null ) {
347  // Messages: botpasswords-insert-failed, botpasswords-update-failed
348  return Status::newFatal( "botpasswords-{$this->operation}-failed", $this->par );
349  }
350 
351  if ( $this->operation === 'insert' || !empty( $data['resetPassword'] ) ) {
352  $this->password = BotPassword::generatePassword( $this->getConfig() );
353  $password = $this->passwordFactory->newFromPlaintext( $this->password );
354  } else {
355  $password = null;
356  }
357 
358  $res = $bp->save( $this->operation, $password );
359 
360  $success = $res->isGood();
361 
362  $this->logger->info(
363  'Bot password {op} for {user}@{app_id} ' . ( $success ? 'succeeded' : 'failed' ),
364  [
365  'op' => $this->operation,
366  'user' => $this->getUser()->getName(),
367  'app_id' => $this->par,
368  'centralId' => $this->userId,
369  'restrictions' => $data['restrictions'],
370  'grants' => $bp->getGrants(),
371  'client_ip' => $this->getRequest()->getIP(),
372  'success' => $success,
373  ]
374  );
375 
376  return $res;
377  }
378 
379  public function onSuccess() {
380  $out = $this->getOutput();
381 
382  $username = $this->getUser()->getName();
383  switch ( $this->operation ) {
384  case 'insert':
385  $out->setPageTitle( $this->msg( 'botpasswords-created-title' )->text() );
386  $out->addWikiMsg( 'botpasswords-created-body', $this->par, $username );
387  break;
388 
389  case 'update':
390  $out->setPageTitle( $this->msg( 'botpasswords-updated-title' )->text() );
391  $out->addWikiMsg( 'botpasswords-updated-body', $this->par, $username );
392  break;
393 
394  case 'delete':
395  $out->setPageTitle( $this->msg( 'botpasswords-deleted-title' )->text() );
396  $out->addWikiMsg( 'botpasswords-deleted-body', $this->par, $username );
397  $this->password = null;
398  break;
399  }
400 
401  if ( $this->password !== null ) {
402  $sep = BotPassword::getSeparator();
403  $out->addWikiMsg(
404  'botpasswords-newpassword',
405  htmlspecialchars( $username . $sep . $this->par ),
406  htmlspecialchars( $this->password ),
407  htmlspecialchars( $username ),
408  htmlspecialchars( $this->par . $sep . $this->password )
409  );
410  $this->password = null;
411  }
412 
413  $out->addReturnTo( $this->getPageTitle() );
414  }
415 
416  protected function getGroupName() {
417  return 'users';
418  }
419 
420  protected function getDisplayFormat() {
421  return 'ooui';
422  }
423 }
$success
const APPID_MAXLENGTH
Definition: BotPassword.php:36
static generatePassword( $config)
Returns a (raw, unhashed) random password string.
static getDB( $db)
Get a database connection for the bot passwords database.
Definition: BotPassword.php:99
static newFromCentralId( $centralId, $appId, $flags=self::READ_NORMAL)
Load a BotPassword from the database.
static newUnsaved(array $data, $flags=self::READ_NORMAL)
Create an unsaved BotPassword.
static getSeparator()
Get the separator for combined user name + app ID.
The CentralIdLookup service allows for connecting local users with cluster-wide IDs.
An error page which can definitely be safely rendered using the OutputPage.
Special page which uses an HTMLForm to handle processing.
string null $par
The sub-page of the special page.
Object handling generic submission, CSRF protection, layout and other logic for UI forms in a reusabl...
Definition: HTMLForm.php:150
setTableId( $id)
Set the id of the <table> or outermost <div> element.
Definition: HTMLForm.php:1743
setWrapperLegendMsg( $msg)
Prompt the whole form to be wrapped in a "<fieldset>", with this message as its "<legend>" element.
Definition: HTMLForm.php:1809
setId( $id)
Definition: HTMLForm.php:1754
addButton( $data)
Add a button to the form.
Definition: HTMLForm.php:1174
suppressDefaultSubmit( $suppressSubmit=true)
Stop a default submit button being shown for this form.
Definition: HTMLForm.php:1688
addPreText( $msg)
Add HTML to introductory message.
Definition: HTMLForm.php:848
Represents an invalid password hash.
static getHiddenGrants()
Get the list of grants that are hidden and should always be granted.
Definition: MWGrants.php:105
static getRightsByGrant()
Map all grants to corresponding user rights.
Definition: MWGrants.php:44
static getValidGrants()
List all known grants.
Definition: MWGrants.php:35
This serves as the entry point to the authentication system.
PSR-3 logger instance factory.
A class containing constants representing the names of configuration variables.
Show an error when any operation involving passwords fails to run.
Factory class for creating and checking Password objects.
Let users manage bot passwords.
BotPassword null $botPassword
Bot password being edited, if any.
onSuccess()
Do something exciting on successful processing of the form, most likely to show a confirmation messag...
alterForm(HTMLForm $form)
Play with the HTMLForm if you need to more substantially.
execute( $par)
Main execution point.
__construct(PasswordFactory $passwordFactory, AuthManager $authManager, CentralIdLookup $centralIdLookup)
string null $password
New password set, for communication between onSubmit() and onSuccess()
getFormFields()
Get an HTMLForm descriptor array.
string null $operation
Operation being performed: create, update, delete.
onSubmit(array $data)
Process the form on POST submission.
checkExecutePermissions(User $user)
Called from execute() to check if the given user can perform this action.
getDisplayFormat()
Get display format for the form.
CentralIdLookup $centralIdLookup
getLoginSecurityLevel()
Tells if the special page does something security-sensitive and needs extra defense against a stolen ...
getGroupName()
Under which header this special page is listed in Special:SpecialPages See messages 'specialpages-gro...
int $userId
Central user ID.
PasswordFactory $passwordFactory
Psr Log LoggerInterface $logger
getName()
Get the name of this Special Page.
getOutput()
Get the OutputPage being used for this instance.
getUser()
Shortcut to get the User executing this instance.
requireNamedUser( $reasonMsg='exception-nologin-text', $titleMsg='exception-nologin')
If the user is not logged in or is a temporary user, throws UserNotLoggedIn.
AuthManager null $authManager
Definition: SpecialPage.php:89
LinkRenderer null $linkRenderer
Definition: SpecialPage.php:81
msg( $key,... $params)
Wrapper around wfMessage that sets the current context.
getConfig()
Shortcut to get main config object.
getRequest()
Get the WebRequest being used for this instance.
setAuthManager(AuthManager $authManager)
Set the injected AuthManager from the special page constructor.
getPageTitle( $subpage=false)
Get a self-referential title object.
getLanguage()
Shortcut to get user's language.
addHelpLink( $to, $overrideBaseUrl=false)
Adds help link with an icon via page indicators.
static newFatal( $message,... $parameters)
Factory function for fatal errors.
Definition: StatusValue.php:70
static newGood( $value=null)
Factory function for good results.
Definition: StatusValue.php:82
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Definition: User.php:69
const DB_REPLICA
Definition: defines.php:26
if(!isset( $args[0])) $lang