MediaWiki  1.30.1
SpecialBotPasswords.php
Go to the documentation of this file.
1 <?php
30 
32  private $userId = 0;
33 
35  private $botPassword = null;
36 
38  private $operation = null;
39 
41  private $password = null;
42 
43  public function __construct() {
44  parent::__construct( 'BotPasswords', 'editmyprivateinfo' );
45  }
46 
50  public function isListed() {
51  return $this->getConfig()->get( 'EnableBotPasswords' );
52  }
53 
54  protected function getLoginSecurityLevel() {
55  return $this->getName();
56  }
57 
62  function execute( $par ) {
63  $this->getOutput()->disallowUserJs();
64  $this->requireLogin();
65 
66  $par = trim( $par );
67  if ( strlen( $par ) === 0 ) {
68  $par = null;
69  } elseif ( strlen( $par ) > BotPassword::APPID_MAXLENGTH ) {
70  throw new ErrorPageError( 'botpasswords', 'botpasswords-bad-appid',
71  [ htmlspecialchars( $par ) ] );
72  }
73 
75  }
76 
77  protected function checkExecutePermissions( User $user ) {
78  parent::checkExecutePermissions( $user );
79 
80  if ( !$this->getConfig()->get( 'EnableBotPasswords' ) ) {
81  throw new ErrorPageError( 'botpasswords', 'botpasswords-disabled' );
82  }
83 
84  $this->userId = CentralIdLookup::factory()->centralIdFromLocalUser( $this->getUser() );
85  if ( !$this->userId ) {
86  throw new ErrorPageError( 'botpasswords', 'botpasswords-no-central-id' );
87  }
88  }
89 
90  protected function getFormFields() {
91  $fields = [];
92 
93  if ( $this->par !== null ) {
94  $this->botPassword = BotPassword::newFromCentralId( $this->userId, $this->par );
95  if ( !$this->botPassword ) {
96  $this->botPassword = BotPassword::newUnsaved( [
97  'centralId' => $this->userId,
98  'appId' => $this->par,
99  ] );
100  }
101 
102  $sep = BotPassword::getSeparator();
103  $fields[] = [
104  'type' => 'info',
105  'label-message' => 'username',
106  'default' => $this->getUser()->getName() . $sep . $this->par
107  ];
108 
109  if ( $this->botPassword->isSaved() ) {
110  $fields['resetPassword'] = [
111  'type' => 'check',
112  'label-message' => 'botpasswords-label-resetpassword',
113  ];
114  if ( $this->botPassword->isInvalid() ) {
115  $fields['resetPassword']['default'] = true;
116  }
117  }
118 
119  $lang = $this->getLanguage();
120  $showGrants = MWGrants::getValidGrants();
121  $fields['grants'] = [
122  'type' => 'checkmatrix',
123  'label-message' => 'botpasswords-label-grants',
124  'help-message' => 'botpasswords-help-grants',
125  'columns' => [
126  $this->msg( 'botpasswords-label-grants-column' )->escaped() => 'grant'
127  ],
128  'rows' => array_combine(
129  array_map( 'MWGrants::getGrantsLink', $showGrants ),
130  $showGrants
131  ),
132  'default' => array_map(
133  function ( $g ) {
134  return "grant-$g";
135  },
136  $this->botPassword->getGrants()
137  ),
138  'tooltips' => array_combine(
139  array_map( 'MWGrants::getGrantsLink', $showGrants ),
140  array_map(
141  function ( $rights ) use ( $lang ) {
142  return $lang->semicolonList( array_map( 'User::getRightDescription', $rights ) );
143  },
144  array_intersect_key( MWGrants::getRightsByGrant(), array_flip( $showGrants ) )
145  )
146  ),
147  'force-options-on' => array_map(
148  function ( $g ) {
149  return "grant-$g";
150  },
152  ),
153  ];
154 
155  $fields['restrictions'] = [
156  'class' => 'HTMLRestrictionsField',
157  'required' => true,
158  'default' => $this->botPassword->getRestrictions(),
159  ];
160 
161  } else {
162  $linkRenderer = $this->getLinkRenderer();
163  $passwordFactory = new PasswordFactory();
164  $passwordFactory->init( $this->getConfig() );
165 
167  $res = $dbr->select(
168  'bot_passwords',
169  [ 'bp_app_id', 'bp_password' ],
170  [ 'bp_user' => $this->userId ],
171  __METHOD__
172  );
173  foreach ( $res as $row ) {
174  try {
175  $password = $passwordFactory->newFromCiphertext( $row->bp_password );
176  $passwordInvalid = $password instanceof InvalidPassword;
177  unset( $password );
178  } catch ( PasswordError $ex ) {
179  $passwordInvalid = true;
180  }
181 
182  $text = $linkRenderer->makeKnownLink(
183  $this->getPageTitle( $row->bp_app_id ),
184  $row->bp_app_id
185  );
186  if ( $passwordInvalid ) {
187  $text .= $this->msg( 'word-separator' )->escaped()
188  . $this->msg( 'botpasswords-label-needsreset' )->parse();
189  }
190 
191  $fields[] = [
192  'section' => 'existing',
193  'type' => 'info',
194  'raw' => true,
195  'default' => $text,
196  ];
197  }
198 
199  $fields['appId'] = [
200  'section' => 'createnew',
201  'type' => 'textwithbutton',
202  'label-message' => 'botpasswords-label-appid',
203  'buttondefault' => $this->msg( 'botpasswords-label-create' )->text(),
204  'buttonflags' => [ 'progressive', 'primary' ],
205  'required' => true,
207  'maxlength' => BotPassword::APPID_MAXLENGTH,
208  'validation-callback' => function ( $v ) {
209  $v = trim( $v );
210  return $v !== '' && strlen( $v ) <= BotPassword::APPID_MAXLENGTH;
211  },
212  ];
213 
214  $fields[] = [
215  'type' => 'hidden',
216  'default' => 'new',
217  'name' => 'op',
218  ];
219  }
220 
221  return $fields;
222  }
223 
224  protected function alterForm( HTMLForm $form ) {
225  $form->setId( 'mw-botpasswords-form' );
226  $form->setTableId( 'mw-botpasswords-table' );
227  $form->addPreText( $this->msg( 'botpasswords-summary' )->parseAsBlock() );
228  $form->suppressDefaultSubmit();
229 
230  if ( $this->par !== null ) {
231  if ( $this->botPassword->isSaved() ) {
232  $form->setWrapperLegendMsg( 'botpasswords-editexisting' );
233  $form->addButton( [
234  'name' => 'op',
235  'value' => 'update',
236  'label-message' => 'botpasswords-label-update',
237  'flags' => [ 'primary', 'progressive' ],
238  ] );
239  $form->addButton( [
240  'name' => 'op',
241  'value' => 'delete',
242  'label-message' => 'botpasswords-label-delete',
243  'flags' => [ 'destructive' ],
244  ] );
245  } else {
246  $form->setWrapperLegendMsg( 'botpasswords-createnew' );
247  $form->addButton( [
248  'name' => 'op',
249  'value' => 'create',
250  'label-message' => 'botpasswords-label-create',
251  'flags' => [ 'primary', 'progressive' ],
252  ] );
253  }
254 
255  $form->addButton( [
256  'name' => 'op',
257  'value' => 'cancel',
258  'label-message' => 'botpasswords-label-cancel'
259  ] );
260  }
261  }
262 
263  public function onSubmit( array $data ) {
264  $op = $this->getRequest()->getVal( 'op', '' );
265 
266  switch ( $op ) {
267  case 'new':
268  $this->getOutput()->redirect( $this->getPageTitle( $data['appId'] )->getFullURL() );
269  return false;
270 
271  case 'create':
272  $this->operation = 'insert';
273  return $this->save( $data );
274 
275  case 'update':
276  $this->operation = 'update';
277  return $this->save( $data );
278 
279  case 'delete':
280  $this->operation = 'delete';
281  $bp = BotPassword::newFromCentralId( $this->userId, $this->par );
282  if ( $bp ) {
283  $bp->delete();
284  }
285  return Status::newGood();
286 
287  case 'cancel':
288  $this->getOutput()->redirect( $this->getPageTitle()->getFullURL() );
289  return false;
290  }
291 
292  return false;
293  }
294 
295  private function save( array $data ) {
296  $bp = BotPassword::newUnsaved( [
297  'centralId' => $this->userId,
298  'appId' => $this->par,
299  'restrictions' => $data['restrictions'],
300  'grants' => array_merge(
302  preg_replace( '/^grant-/', '', $data['grants'] )
303  )
304  ] );
305 
306  if ( $this->operation === 'insert' || !empty( $data['resetPassword'] ) ) {
307  $this->password = BotPassword::generatePassword( $this->getConfig() );
308  $passwordFactory = new PasswordFactory();
309  $passwordFactory->init( RequestContext::getMain()->getConfig() );
310  $password = $passwordFactory->newFromPlaintext( $this->password );
311  } else {
312  $password = null;
313  }
314 
315  if ( $bp->save( $this->operation, $password ) ) {
316  return Status::newGood();
317  } else {
318  // Messages: botpasswords-insert-failed, botpasswords-update-failed
319  return Status::newFatal( "botpasswords-{$this->operation}-failed", $this->par );
320  }
321  }
322 
323  public function onSuccess() {
324  $out = $this->getOutput();
325 
326  $username = $this->getUser()->getName();
327  switch ( $this->operation ) {
328  case 'insert':
329  $out->setPageTitle( $this->msg( 'botpasswords-created-title' )->text() );
330  $out->addWikiMsg( 'botpasswords-created-body', $this->par, $username );
331  break;
332 
333  case 'update':
334  $out->setPageTitle( $this->msg( 'botpasswords-updated-title' )->text() );
335  $out->addWikiMsg( 'botpasswords-updated-body', $this->par, $username );
336  break;
337 
338  case 'delete':
339  $out->setPageTitle( $this->msg( 'botpasswords-deleted-title' )->text() );
340  $out->addWikiMsg( 'botpasswords-deleted-body', $this->par, $username );
341  $this->password = null;
342  break;
343  }
344 
345  if ( $this->password !== null ) {
346  $sep = BotPassword::getSeparator();
347  $out->addWikiMsg(
348  'botpasswords-newpassword',
349  htmlspecialchars( $username . $sep . $this->par ),
350  htmlspecialchars( $this->password ),
351  htmlspecialchars( $username ),
352  htmlspecialchars( $this->par . $sep . $this->password )
353  );
354  $this->password = null;
355  }
356 
357  $out->addReturnTo( $this->getPageTitle() );
358  }
359 
360  protected function getGroupName() {
361  return 'users';
362  }
363 
364  protected function getDisplayFormat() {
365  return 'ooui';
366  }
367 }
SpecialPage\getPageTitle
getPageTitle( $subpage=false)
Get a self-referential title object.
Definition: SpecialPage.php:628
SpecialBotPasswords
Let users manage bot passwords.
Definition: SpecialBotPasswords.php:29
$user
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 account $user
Definition: hooks.txt:244
SpecialPage\msg
msg( $key)
Wrapper around wfMessage that sets the current context.
Definition: SpecialPage.php:746
HTMLForm\suppressDefaultSubmit
suppressDefaultSubmit( $suppressSubmit=true)
Stop a default submit button being shown for this form.
Definition: HTMLForm.php:1449
SpecialPage\getOutput
getOutput()
Get the OutputPage being used for this instance.
Definition: SpecialPage.php:675
$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:77
BotPassword
Utility class for bot passwords.
Definition: BotPassword.php:28
text
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
SpecialBotPasswords\getGroupName
getGroupName()
Under which header this special page is listed in Special:SpecialPages See messages 'specialpages-gro...
Definition: SpecialBotPasswords.php:360
BotPassword\getSeparator
static getSeparator()
Get the separator for combined user name + app ID.
Definition: BotPassword.php:230
SpecialBotPasswords\save
save(array $data)
Definition: SpecialBotPasswords.php:295
BotPassword\generatePassword
static generatePassword( $config)
Returns a (raw, unhashed) random password string.
Definition: BotPassword.php:406
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
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:90
$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:74
SpecialPage\getLanguage
getLanguage()
Shortcut to get user's language.
Definition: SpecialPage.php:705
BotPassword\APPID_MAXLENGTH
const APPID_MAXLENGTH
Definition: BotPassword.php:30
SpecialPage\getName
getName()
Get the name of this Special Page.
Definition: SpecialPage.php:150
MWGrants\getHiddenGrants
static getHiddenGrants()
Get the list of grants that are hidden and should always be granted.
Definition: MWGrants.php:159
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
SpecialPage\getConfig
getConfig()
Shortcut to get main config object.
Definition: SpecialPage.php:714
HTMLForm\addButton
addButton( $data)
Add a button to the form.
Definition: HTMLForm.php:956
BotPassword\newUnsaved
static newUnsaved(array $data, $flags=self::READ_NORMAL)
Create an unsaved BotPassword.
Definition: BotPassword.php:135
SpecialBotPasswords\onSuccess
onSuccess()
Do something exciting on successful processing of the form, most likely to show a confirmation messag...
Definition: SpecialBotPasswords.php:323
SpecialPage\getUser
getUser()
Shortcut to get the User executing this instance.
Definition: SpecialPage.php:685
DB_REPLICA
const DB_REPLICA
Definition: defines.php:25
MWGrants\getValidGrants
static getValidGrants()
List all known grants.
Definition: MWGrants.php:31
SpecialBotPasswords\getDisplayFormat
getDisplayFormat()
Get display format for the form.
Definition: SpecialBotPasswords.php:364
SpecialBotPasswords\alterForm
alterForm(HTMLForm $form)
Play with the HTMLForm if you need to more substantially.
Definition: SpecialBotPasswords.php:224
SpecialPage\requireLogin
requireLogin( $reasonMsg='exception-nologin-text', $titleMsg='exception-nologin')
If the user is not logged in, throws UserNotLoggedIn error.
Definition: SpecialPage.php:336
execute
$batch execute()
SpecialBotPasswords\$password
string $password
New password set, for communication between onSubmit() and onSuccess()
Definition: SpecialBotPasswords.php:41
StatusValue\newGood
static newGood( $value=null)
Factory function for good results.
Definition: StatusValue.php:81
HTMLForm\setId
setId( $id)
Definition: HTMLForm.php:1497
FormSpecialPage\$par
string $par
The sub-page of the special page.
Definition: FormSpecialPage.php:36
SpecialPage\getRequest
getRequest()
Get the WebRequest being used for this instance.
Definition: SpecialPage.php:665
RequestContext\getMain
static getMain()
Static methods.
Definition: RequestContext.php:470
BotPassword\newFromCentralId
static newFromCentralId( $centralId, $appId, $flags=self::READ_NORMAL)
Load a BotPassword from the database.
Definition: BotPassword.php:104
SpecialPage\getLinkRenderer
getLinkRenderer()
Definition: SpecialPage.php:860
SpecialBotPasswords\isListed
isListed()
Definition: SpecialBotPasswords.php:50
$dbr
if(! $regexes) $dbr
Definition: cleanup.php:94
SpecialBotPasswords\$userId
int $userId
Central user ID.
Definition: SpecialBotPasswords.php:32
HTMLForm\setWrapperLegendMsg
setWrapperLegendMsg( $msg)
Prompt the whole form to be wrapped in a "<fieldset>", with this message as its "<legend>" element.
Definition: HTMLForm.php:1539
MWGrants\getRightsByGrant
static getRightsByGrant()
Map all grants to corresponding user rights.
Definition: MWGrants.php:41
SpecialBotPasswords\__construct
__construct()
Definition: SpecialBotPasswords.php:43
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:1486
SpecialBotPasswords\onSubmit
onSubmit(array $data)
Process the form on POST submission.
Definition: SpecialBotPasswords.php:263
HTMLForm\addPreText
addPreText( $msg)
Add HTML to introductory message.
Definition: HTMLForm.php:756
PasswordFactory
Factory class for creating and checking Password objects.
Definition: PasswordFactory.php:28
SpecialPage\$linkRenderer
MediaWiki Linker LinkRenderer null $linkRenderer
Definition: SpecialPage.php:66
SpecialBotPasswords\$operation
string $operation
Operation being performed: create, update, delete.
Definition: SpecialBotPasswords.php:38
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:45
User
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Definition: User.php:51
$username
this hook is for auditing only or null if authentication failed before getting that far $username
Definition: hooks.txt:781
SpecialBotPasswords\execute
execute( $par)
Main execution point.
Definition: SpecialBotPasswords.php:62
SpecialBotPasswords\$botPassword
BotPassword null $botPassword
Bot password being edited, if any.
Definition: SpecialBotPasswords.php:35
SpecialBotPasswords\getLoginSecurityLevel
getLoginSecurityLevel()
Tells if the special page does something security-sensitive and needs extra defense against a stolen ...
Definition: SpecialBotPasswords.php:54
array
the array() calling protocol came about after MediaWiki 1.4rc1.
HTMLForm
Object handling generic submission, CSRF protection, layout and other logic for UI forms.
Definition: HTMLForm.php:128
$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 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:781