MediaWiki  1.33.0
SpecialBotPasswords.php
Go to the documentation of this file.
1 <?php
26 
33 
35  private $userId = 0;
36 
38  private $botPassword = null;
39 
41  private $operation = null;
42 
44  private $password = null;
45 
47  private $logger = null;
48 
49  public function __construct() {
50  parent::__construct( 'BotPasswords', 'editmyprivateinfo' );
51  $this->logger = LoggerFactory::getInstance( 'authentication' );
52  }
53 
57  public function isListed() {
58  return $this->getConfig()->get( 'EnableBotPasswords' );
59  }
60 
61  protected function getLoginSecurityLevel() {
62  return $this->getName();
63  }
64 
69  function execute( $par ) {
70  $this->getOutput()->disallowUserJs();
71  $this->requireLogin();
72 
73  $par = trim( $par );
74  if ( strlen( $par ) === 0 ) {
75  $par = null;
76  } elseif ( strlen( $par ) > BotPassword::APPID_MAXLENGTH ) {
77  throw new ErrorPageError( 'botpasswords', 'botpasswords-bad-appid',
78  [ htmlspecialchars( $par ) ] );
79  }
80 
82  }
83 
84  protected function checkExecutePermissions( User $user ) {
85  parent::checkExecutePermissions( $user );
86 
87  if ( !$this->getConfig()->get( 'EnableBotPasswords' ) ) {
88  throw new ErrorPageError( 'botpasswords', 'botpasswords-disabled' );
89  }
90 
91  $this->userId = CentralIdLookup::factory()->centralIdFromLocalUser( $this->getUser() );
92  if ( !$this->userId ) {
93  throw new ErrorPageError( 'botpasswords', 'botpasswords-no-central-id' );
94  }
95  }
96 
97  protected function getFormFields() {
98  $fields = [];
99 
100  if ( $this->par !== null ) {
101  $this->botPassword = BotPassword::newFromCentralId( $this->userId, $this->par );
102  if ( !$this->botPassword ) {
103  $this->botPassword = BotPassword::newUnsaved( [
104  'centralId' => $this->userId,
105  'appId' => $this->par,
106  ] );
107  }
108 
109  $sep = BotPassword::getSeparator();
110  $fields[] = [
111  'type' => 'info',
112  'label-message' => 'username',
113  'default' => $this->getUser()->getName() . $sep . $this->par
114  ];
115 
116  if ( $this->botPassword->isSaved() ) {
117  $fields['resetPassword'] = [
118  'type' => 'check',
119  'label-message' => 'botpasswords-label-resetpassword',
120  ];
121  if ( $this->botPassword->isInvalid() ) {
122  $fields['resetPassword']['default'] = true;
123  }
124  }
125 
126  $lang = $this->getLanguage();
127  $showGrants = MWGrants::getValidGrants();
128  $fields['grants'] = [
129  'type' => 'checkmatrix',
130  'label-message' => 'botpasswords-label-grants',
131  'help-message' => 'botpasswords-help-grants',
132  'columns' => [
133  $this->msg( 'botpasswords-label-grants-column' )->escaped() => 'grant'
134  ],
135  'rows' => array_combine(
136  array_map( 'MWGrants::getGrantsLink', $showGrants ),
137  $showGrants
138  ),
139  'default' => array_map(
140  function ( $g ) {
141  return "grant-$g";
142  },
143  $this->botPassword->getGrants()
144  ),
145  'tooltips' => array_combine(
146  array_map( 'MWGrants::getGrantsLink', $showGrants ),
147  array_map(
148  function ( $rights ) use ( $lang ) {
149  return $lang->semicolonList( array_map( 'User::getRightDescription', $rights ) );
150  },
151  array_intersect_key( MWGrants::getRightsByGrant(), array_flip( $showGrants ) )
152  )
153  ),
154  'force-options-on' => array_map(
155  function ( $g ) {
156  return "grant-$g";
157  },
159  ),
160  ];
161 
162  $fields['restrictions'] = [
163  'class' => HTMLRestrictionsField::class,
164  'required' => true,
165  'default' => $this->botPassword->getRestrictions(),
166  ];
167 
168  } else {
169  $linkRenderer = $this->getLinkRenderer();
170  $passwordFactory = MediaWikiServices::getInstance()->getPasswordFactory();
171 
173  $res = $dbr->select(
174  'bot_passwords',
175  [ 'bp_app_id', 'bp_password' ],
176  [ 'bp_user' => $this->userId ],
177  __METHOD__
178  );
179  foreach ( $res as $row ) {
180  try {
181  $password = $passwordFactory->newFromCiphertext( $row->bp_password );
182  $passwordInvalid = $password instanceof InvalidPassword;
183  unset( $password );
184  } catch ( PasswordError $ex ) {
185  $passwordInvalid = true;
186  }
187 
188  $text = $linkRenderer->makeKnownLink(
189  $this->getPageTitle( $row->bp_app_id ),
190  $row->bp_app_id
191  );
192  if ( $passwordInvalid ) {
193  $text .= $this->msg( 'word-separator' )->escaped()
194  . $this->msg( 'botpasswords-label-needsreset' )->parse();
195  }
196 
197  $fields[] = [
198  'section' => 'existing',
199  'type' => 'info',
200  'raw' => true,
201  'default' => $text,
202  ];
203  }
204 
205  $fields['appId'] = [
206  'section' => 'createnew',
207  'type' => 'textwithbutton',
208  'label-message' => 'botpasswords-label-appid',
209  'buttondefault' => $this->msg( 'botpasswords-label-create' )->text(),
210  'buttonflags' => [ 'progressive', 'primary' ],
211  'required' => true,
213  'maxlength' => BotPassword::APPID_MAXLENGTH,
214  'validation-callback' => function ( $v ) {
215  $v = trim( $v );
216  return $v !== '' && strlen( $v ) <= BotPassword::APPID_MAXLENGTH;
217  },
218  ];
219 
220  $fields[] = [
221  'type' => 'hidden',
222  'default' => 'new',
223  'name' => 'op',
224  ];
225  }
226 
227  return $fields;
228  }
229 
230  protected function alterForm( HTMLForm $form ) {
231  $form->setId( 'mw-botpasswords-form' );
232  $form->setTableId( 'mw-botpasswords-table' );
233  $form->addPreText( $this->msg( 'botpasswords-summary' )->parseAsBlock() );
234  $form->suppressDefaultSubmit();
235 
236  if ( $this->par !== null ) {
237  if ( $this->botPassword->isSaved() ) {
238  $form->setWrapperLegendMsg( 'botpasswords-editexisting' );
239  $form->addButton( [
240  'name' => 'op',
241  'value' => 'update',
242  'label-message' => 'botpasswords-label-update',
243  'flags' => [ 'primary', 'progressive' ],
244  ] );
245  $form->addButton( [
246  'name' => 'op',
247  'value' => 'delete',
248  'label-message' => 'botpasswords-label-delete',
249  'flags' => [ 'destructive' ],
250  ] );
251  } else {
252  $form->setWrapperLegendMsg( 'botpasswords-createnew' );
253  $form->addButton( [
254  'name' => 'op',
255  'value' => 'create',
256  'label-message' => 'botpasswords-label-create',
257  'flags' => [ 'primary', 'progressive' ],
258  ] );
259  }
260 
261  $form->addButton( [
262  'name' => 'op',
263  'value' => 'cancel',
264  'label-message' => 'botpasswords-label-cancel'
265  ] );
266  }
267  }
268 
269  public function onSubmit( array $data ) {
270  $op = $this->getRequest()->getVal( 'op', '' );
271 
272  switch ( $op ) {
273  case 'new':
274  $this->getOutput()->redirect( $this->getPageTitle( $data['appId'] )->getFullURL() );
275  return false;
276 
277  case 'create':
278  $this->operation = 'insert';
279  return $this->save( $data );
280 
281  case 'update':
282  $this->operation = 'update';
283  return $this->save( $data );
284 
285  case 'delete':
286  $this->operation = 'delete';
287  $bp = BotPassword::newFromCentralId( $this->userId, $this->par );
288  if ( $bp ) {
289  $bp->delete();
290  $this->logger->info(
291  "Bot password {op} for {user}@{app_id}",
292  [
293  'app_id' => $this->par,
294  'user' => $this->getUser()->getName(),
295  'centralId' => $this->userId,
296  'op' => 'delete',
297  'client_ip' => $this->getRequest()->getIP()
298  ]
299  );
300  }
301  return Status::newGood();
302 
303  case 'cancel':
304  $this->getOutput()->redirect( $this->getPageTitle()->getFullURL() );
305  return false;
306  }
307 
308  return false;
309  }
310 
311  private function save( array $data ) {
312  $bp = BotPassword::newUnsaved( [
313  'centralId' => $this->userId,
314  'appId' => $this->par,
315  'restrictions' => $data['restrictions'],
316  'grants' => array_merge(
318  preg_replace( '/^grant-/', '', $data['grants'] )
319  )
320  ] );
321 
322  if ( $this->operation === 'insert' || !empty( $data['resetPassword'] ) ) {
323  $this->password = BotPassword::generatePassword( $this->getConfig() );
324  $passwordFactory = MediaWikiServices::getInstance()->getPasswordFactory();
325  $password = $passwordFactory->newFromPlaintext( $this->password );
326  } else {
327  $password = null;
328  }
329 
330  if ( $bp->save( $this->operation, $password ) ) {
331  $this->logger->info(
332  "Bot password {op} for {user}@{app_id}",
333  [
334  'op' => $this->operation,
335  'user' => $this->getUser()->getName(),
336  'app_id' => $this->par,
337  'centralId' => $this->userId,
338  'restrictions' => $data['restrictions'],
339  'grants' => $bp->getGrants(),
340  'client_ip' => $this->getRequest()->getIP()
341  ]
342  );
343  return Status::newGood();
344  } else {
345  // Messages: botpasswords-insert-failed, botpasswords-update-failed
346  return Status::newFatal( "botpasswords-{$this->operation}-failed", $this->par );
347  }
348  }
349 
350  public function onSuccess() {
351  $out = $this->getOutput();
352 
353  $username = $this->getUser()->getName();
354  switch ( $this->operation ) {
355  case 'insert':
356  $out->setPageTitle( $this->msg( 'botpasswords-created-title' )->text() );
357  $out->addWikiMsg( 'botpasswords-created-body', $this->par, $username );
358  break;
359 
360  case 'update':
361  $out->setPageTitle( $this->msg( 'botpasswords-updated-title' )->text() );
362  $out->addWikiMsg( 'botpasswords-updated-body', $this->par, $username );
363  break;
364 
365  case 'delete':
366  $out->setPageTitle( $this->msg( 'botpasswords-deleted-title' )->text() );
367  $out->addWikiMsg( 'botpasswords-deleted-body', $this->par, $username );
368  $this->password = null;
369  break;
370  }
371 
372  if ( $this->password !== null ) {
373  $sep = BotPassword::getSeparator();
374  $out->addWikiMsg(
375  'botpasswords-newpassword',
376  htmlspecialchars( $username . $sep . $this->par ),
377  htmlspecialchars( $this->password ),
378  htmlspecialchars( $username ),
379  htmlspecialchars( $this->par . $sep . $this->password )
380  );
381  $this->password = null;
382  }
383 
384  $out->addReturnTo( $this->getPageTitle() );
385  }
386 
387  protected function getGroupName() {
388  return 'users';
389  }
390 
391  protected function getDisplayFormat() {
392  return 'ooui';
393  }
394 }
SpecialPage\getPageTitle
getPageTitle( $subpage=false)
Get a self-referential title object.
Definition: SpecialPage.php:678
SpecialBotPasswords
Let users manage bot passwords.
Definition: SpecialBotPasswords.php:32
$user
return true to allow those checks to and false if checking is done & $user
Definition: hooks.txt:1476
SpecialPage\msg
msg( $key)
Wrapper around wfMessage that sets the current context.
Definition: SpecialPage.php:796
HTMLForm\suppressDefaultSubmit
suppressDefaultSubmit( $suppressSubmit=true)
Stop a default submit button being shown for this form.
Definition: HTMLForm.php:1455
SpecialPage\getOutput
getOutput()
Get the OutputPage being used for this instance.
Definition: SpecialPage.php:725
$lang
if(!isset( $args[0])) $lang
Definition: testCompression.php:33
SpecialBotPasswords\checkExecutePermissions
checkExecutePermissions(User $user)
Called from execute() to check if the given user can perform this action.
Definition: SpecialBotPasswords.php:84
BotPassword
Utility class for bot passwords.
Definition: BotPassword.php:30
SpecialBotPasswords\getGroupName
getGroupName()
Under which header this special page is listed in Special:SpecialPages See messages 'specialpages-gro...
Definition: SpecialBotPasswords.php:387
BotPassword\getSeparator
static getSeparator()
Get the separator for combined user name + app ID.
Definition: BotPassword.php:231
$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 When $user is not it can be in the form of< username >< more info > e g for bot passwords intended to be added to log contexts Fields it might only if the login was with a bot password 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:780
SpecialBotPasswords\save
save(array $data)
Definition: SpecialBotPasswords.php:311
BotPassword\generatePassword
static generatePassword( $config)
Returns a (raw, unhashed) random password string.
Definition: BotPassword.php:406
StatusValue\newFatal
static newFatal( $message)
Factory function for fatal errors.
Definition: StatusValue.php:68
PasswordError
Show an error when any operation involving passwords fails to run.
Definition: PasswordError.php:26
FormSpecialPage
Special page which uses an HTMLForm to handle processing.
Definition: FormSpecialPage.php:31
SpecialBotPasswords\getFormFields
getFormFields()
Get an HTMLForm descriptor array.
Definition: SpecialBotPasswords.php:97
$res
$res
Definition: database.txt:21
InvalidPassword
Represents an invalid password hash.
Definition: InvalidPassword.php:32
BotPassword\getDB
static getDB( $db)
Get a database connection for the bot passwords database.
Definition: BotPassword.php:76
SpecialPage\getLanguage
getLanguage()
Shortcut to get user's language.
Definition: SpecialPage.php:755
BotPassword\APPID_MAXLENGTH
const APPID_MAXLENGTH
Definition: BotPassword.php:32
SpecialPage\getName
getName()
Get the name of this Special Page.
Definition: SpecialPage.php:152
MWGrants\getHiddenGrants
static getHiddenGrants()
Get the list of grants that are hidden and should always be granted.
Definition: MWGrants.php:157
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
$dbr
$dbr
Definition: testCompression.php:50
$data
$data
Utility to generate mapping file used in mw.Title (phpCharToUpper.json)
Definition: generatePhpCharToUpperMappings.php:13
SpecialPage\getConfig
getConfig()
Shortcut to get main config object.
Definition: SpecialPage.php:764
HTMLForm\addButton
addButton( $data)
Add a button to the form.
Definition: HTMLForm.php:958
BotPassword\newUnsaved
static newUnsaved(array $data, $flags=self::READ_NORMAL)
Create an unsaved BotPassword.
Definition: BotPassword.php:138
SpecialBotPasswords\onSuccess
onSuccess()
Do something exciting on successful processing of the form, most likely to show a confirmation messag...
Definition: SpecialBotPasswords.php:350
use
as see the revision history and available at free of to any person obtaining a copy of this software and associated documentation to deal in the Software without including without limitation the rights to use
Definition: MIT-LICENSE.txt:10
SpecialPage\getUser
getUser()
Shortcut to get the User executing this instance.
Definition: SpecialPage.php:735
DB_REPLICA
const DB_REPLICA
Definition: defines.php:25
array
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))
SpecialBotPasswords\$logger
Psr Log LoggerInterface $logger
Definition: SpecialBotPasswords.php:47
MWGrants\getValidGrants
static getValidGrants()
List all known grants.
Definition: MWGrants.php:31
SpecialBotPasswords\getDisplayFormat
getDisplayFormat()
Get display format for the form.
Definition: SpecialBotPasswords.php:391
SpecialBotPasswords\alterForm
alterForm(HTMLForm $form)
Play with the HTMLForm if you need to more substantially.
Definition: SpecialBotPasswords.php:230
FormSpecialPage\$par
string null $par
The sub-page of the special page.
Definition: FormSpecialPage.php:36
SpecialPage\requireLogin
requireLogin( $reasonMsg='exception-nologin-text', $titleMsg='exception-nologin')
If the user is not logged in, throws UserNotLoggedIn error.
Definition: SpecialPage.php:339
execute
$batch execute()
SpecialBotPasswords\$password
string $password
New password set, for communication between onSubmit() and onSuccess()
Definition: SpecialBotPasswords.php:44
StatusValue\newGood
static newGood( $value=null)
Factory function for good results.
Definition: StatusValue.php:81
HTMLForm\setId
setId( $id)
Definition: HTMLForm.php:1503
SpecialPage\getRequest
getRequest()
Get the WebRequest being used for this instance.
Definition: SpecialPage.php:715
BotPassword\newFromCentralId
static newFromCentralId( $centralId, $appId, $flags=self::READ_NORMAL)
Load a BotPassword from the database.
Definition: BotPassword.php:107
SpecialPage\getLinkRenderer
getLinkRenderer()
Definition: SpecialPage.php:908
text
This list may contain false positives That usually means there is additional text with links below the first Each row contains links to the first and second as well as the first line of the second redirect text
Definition: All_system_messages.txt:1267
SpecialBotPasswords\isListed
isListed()
Definition: SpecialBotPasswords.php:57
SpecialBotPasswords\$userId
int $userId
Central user ID.
Definition: SpecialBotPasswords.php:35
HTMLForm\setWrapperLegendMsg
setWrapperLegendMsg( $msg)
Prompt the whole form to be wrapped in a "<fieldset>", with this message as its "<legend>" element.
Definition: HTMLForm.php:1545
MWGrants\getRightsByGrant
static getRightsByGrant()
Map all grants to corresponding user rights.
Definition: MWGrants.php:41
SpecialBotPasswords\__construct
__construct()
Definition: SpecialBotPasswords.php:49
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
HTMLForm\setTableId
setTableId( $id)
Set the id of the <table> or outermost <div> element.
Definition: HTMLForm.php:1492
SpecialBotPasswords\onSubmit
onSubmit(array $data)
Process the form on POST submission.
Definition: SpecialBotPasswords.php:269
LoggerFactory
MediaWiki Logger LoggerFactory implements a PSR[0] compatible message logging system Named Psr Log LoggerInterface instances can be obtained from the MediaWiki Logger LoggerFactory::getInstance() static method. MediaWiki\Logger\LoggerFactory expects a class implementing the MediaWiki\Logger\Spi interface to act as a factory for new Psr\Log\LoggerInterface instances. The "Spi" in MediaWiki\Logger\Spi stands for "service provider interface". An SPI is an API intended to be implemented or extended by a third party. This software design pattern is intended to enable framework extension and replaceable components. It is specifically used in the MediaWiki\Logger\LoggerFactory service to allow alternate PSR-3 logging implementations to be easily integrated with MediaWiki. The service provider interface allows the backend logging library to be implemented in multiple ways. The $wgMWLoggerDefaultSpi global provides the classname of the default MediaWiki\Logger\Spi implementation to be loaded at runtime. This can either be the name of a class implementing the MediaWiki\Logger\Spi with a zero argument const ructor or a callable that will return an MediaWiki\Logger\Spi instance. Alternately the MediaWiki\Logger\LoggerFactory MediaWiki Logger LoggerFactory
Definition: logger.txt:5
HTMLForm\addPreText
addPreText( $msg)
Add HTML to introductory message.
Definition: HTMLForm.php:747
class
you have access to all of the normal MediaWiki so you can get a DB use the etc For full docs on the Maintenance class
Definition: maintenance.txt:52
SpecialPage\$linkRenderer
MediaWiki Linker LinkRenderer null $linkRenderer
Definition: SpecialPage.php:66
MediaWikiServices
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 MediaWikiServices
Definition: injection.txt:23
SpecialBotPasswords\$operation
string $operation
Operation being performed: create, update, delete.
Definition: SpecialBotPasswords.php:41
ErrorPageError
An error page which can definitely be safely rendered using the OutputPage.
Definition: ErrorPageError.php:27
CentralIdLookup\factory
static factory( $providerId=null)
Fetch a CentralIdLookup.
Definition: CentralIdLookup.php:46
User
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Definition: User.php:48
$username
this hook is for auditing only or null if authentication failed before getting that far $username
Definition: hooks.txt:780
SpecialBotPasswords\execute
execute( $par)
Main execution point.
Definition: SpecialBotPasswords.php:69
SpecialBotPasswords\$botPassword
BotPassword null $botPassword
Bot password being edited, if any.
Definition: SpecialBotPasswords.php:38
SpecialBotPasswords\getLoginSecurityLevel
getLoginSecurityLevel()
Tells if the special page does something security-sensitive and needs extra defense against a stolen ...
Definition: SpecialBotPasswords.php:61
HTMLForm
Object handling generic submission, CSRF protection, layout and other logic for UI forms.
Definition: HTMLForm.php:133