MediaWiki  1.30.0
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 
58  function execute( $par ) {
59  $this->getOutput()->disallowUserJs();
60  $this->requireLogin();
61 
62  $par = trim( $par );
63  if ( strlen( $par ) === 0 ) {
64  $par = null;
65  } elseif ( strlen( $par ) > BotPassword::APPID_MAXLENGTH ) {
66  throw new ErrorPageError( 'botpasswords', 'botpasswords-bad-appid',
67  [ htmlspecialchars( $par ) ] );
68  }
69 
71  }
72 
73  protected function checkExecutePermissions( User $user ) {
74  parent::checkExecutePermissions( $user );
75 
76  if ( !$this->getConfig()->get( 'EnableBotPasswords' ) ) {
77  throw new ErrorPageError( 'botpasswords', 'botpasswords-disabled' );
78  }
79 
80  $this->userId = CentralIdLookup::factory()->centralIdFromLocalUser( $this->getUser() );
81  if ( !$this->userId ) {
82  throw new ErrorPageError( 'botpasswords', 'botpasswords-no-central-id' );
83  }
84  }
85 
86  protected function getFormFields() {
87  $fields = [];
88 
89  if ( $this->par !== null ) {
90  $this->botPassword = BotPassword::newFromCentralId( $this->userId, $this->par );
91  if ( !$this->botPassword ) {
92  $this->botPassword = BotPassword::newUnsaved( [
93  'centralId' => $this->userId,
94  'appId' => $this->par,
95  ] );
96  }
97 
99  $fields[] = [
100  'type' => 'info',
101  'label-message' => 'username',
102  'default' => $this->getUser()->getName() . $sep . $this->par
103  ];
104 
105  if ( $this->botPassword->isSaved() ) {
106  $fields['resetPassword'] = [
107  'type' => 'check',
108  'label-message' => 'botpasswords-label-resetpassword',
109  ];
110  }
111 
112  $lang = $this->getLanguage();
113  $showGrants = MWGrants::getValidGrants();
114  $fields['grants'] = [
115  'type' => 'checkmatrix',
116  'label-message' => 'botpasswords-label-grants',
117  'help-message' => 'botpasswords-help-grants',
118  'columns' => [
119  $this->msg( 'botpasswords-label-grants-column' )->escaped() => 'grant'
120  ],
121  'rows' => array_combine(
122  array_map( 'MWGrants::getGrantsLink', $showGrants ),
123  $showGrants
124  ),
125  'default' => array_map(
126  function ( $g ) {
127  return "grant-$g";
128  },
129  $this->botPassword->getGrants()
130  ),
131  'tooltips' => array_combine(
132  array_map( 'MWGrants::getGrantsLink', $showGrants ),
133  array_map(
134  function ( $rights ) use ( $lang ) {
135  return $lang->semicolonList( array_map( 'User::getRightDescription', $rights ) );
136  },
137  array_intersect_key( MWGrants::getRightsByGrant(), array_flip( $showGrants ) )
138  )
139  ),
140  'force-options-on' => array_map(
141  function ( $g ) {
142  return "grant-$g";
143  },
145  ),
146  ];
147 
148  $fields['restrictions'] = [
149  'class' => 'HTMLRestrictionsField',
150  'required' => true,
151  'default' => $this->botPassword->getRestrictions(),
152  ];
153 
154  } else {
155  $linkRenderer = $this->getLinkRenderer();
157  $res = $dbr->select(
158  'bot_passwords',
159  [ 'bp_app_id' ],
160  [ 'bp_user' => $this->userId ],
161  __METHOD__
162  );
163  foreach ( $res as $row ) {
164  $fields[] = [
165  'section' => 'existing',
166  'type' => 'info',
167  'raw' => true,
168  'default' => $linkRenderer->makeKnownLink(
169  $this->getPageTitle( $row->bp_app_id ),
170  $row->bp_app_id
171  ),
172  ];
173  }
174 
175  $fields['appId'] = [
176  'section' => 'createnew',
177  'type' => 'textwithbutton',
178  'label-message' => 'botpasswords-label-appid',
179  'buttondefault' => $this->msg( 'botpasswords-label-create' )->text(),
180  'buttonflags' => [ 'progressive', 'primary' ],
181  'required' => true,
183  'maxlength' => BotPassword::APPID_MAXLENGTH,
184  'validation-callback' => function ( $v ) {
185  $v = trim( $v );
186  return $v !== '' && strlen( $v ) <= BotPassword::APPID_MAXLENGTH;
187  },
188  ];
189 
190  $fields[] = [
191  'type' => 'hidden',
192  'default' => 'new',
193  'name' => 'op',
194  ];
195  }
196 
197  return $fields;
198  }
199 
200  protected function alterForm( HTMLForm $form ) {
201  $form->setId( 'mw-botpasswords-form' );
202  $form->setTableId( 'mw-botpasswords-table' );
203  $form->addPreText( $this->msg( 'botpasswords-summary' )->parseAsBlock() );
204  $form->suppressDefaultSubmit();
205 
206  if ( $this->par !== null ) {
207  if ( $this->botPassword->isSaved() ) {
208  $form->setWrapperLegendMsg( 'botpasswords-editexisting' );
209  $form->addButton( [
210  'name' => 'op',
211  'value' => 'update',
212  'label-message' => 'botpasswords-label-update',
213  'flags' => [ 'primary', 'progressive' ],
214  ] );
215  $form->addButton( [
216  'name' => 'op',
217  'value' => 'delete',
218  'label-message' => 'botpasswords-label-delete',
219  'flags' => [ 'destructive' ],
220  ] );
221  } else {
222  $form->setWrapperLegendMsg( 'botpasswords-createnew' );
223  $form->addButton( [
224  'name' => 'op',
225  'value' => 'create',
226  'label-message' => 'botpasswords-label-create',
227  'flags' => [ 'primary', 'progressive' ],
228  ] );
229  }
230 
231  $form->addButton( [
232  'name' => 'op',
233  'value' => 'cancel',
234  'label-message' => 'botpasswords-label-cancel'
235  ] );
236  }
237  }
238 
239  public function onSubmit( array $data ) {
240  $op = $this->getRequest()->getVal( 'op', '' );
241 
242  switch ( $op ) {
243  case 'new':
244  $this->getOutput()->redirect( $this->getPageTitle( $data['appId'] )->getFullURL() );
245  return false;
246 
247  case 'create':
248  $this->operation = 'insert';
249  return $this->save( $data );
250 
251  case 'update':
252  $this->operation = 'update';
253  return $this->save( $data );
254 
255  case 'delete':
256  $this->operation = 'delete';
257  $bp = BotPassword::newFromCentralId( $this->userId, $this->par );
258  if ( $bp ) {
259  $bp->delete();
260  }
261  return Status::newGood();
262 
263  case 'cancel':
264  $this->getOutput()->redirect( $this->getPageTitle()->getFullURL() );
265  return false;
266  }
267 
268  return false;
269  }
270 
271  private function save( array $data ) {
272  $bp = BotPassword::newUnsaved( [
273  'centralId' => $this->userId,
274  'appId' => $this->par,
275  'restrictions' => $data['restrictions'],
276  'grants' => array_merge(
278  preg_replace( '/^grant-/', '', $data['grants'] )
279  )
280  ] );
281 
282  if ( $this->operation === 'insert' || !empty( $data['resetPassword'] ) ) {
283  $this->password = BotPassword::generatePassword( $this->getConfig() );
284  $passwordFactory = new PasswordFactory();
285  $passwordFactory->init( RequestContext::getMain()->getConfig() );
286  $password = $passwordFactory->newFromPlaintext( $this->password );
287  } else {
288  $password = null;
289  }
290 
291  if ( $bp->save( $this->operation, $password ) ) {
292  return Status::newGood();
293  } else {
294  // Messages: botpasswords-insert-failed, botpasswords-update-failed
295  return Status::newFatal( "botpasswords-{$this->operation}-failed", $this->par );
296  }
297  }
298 
299  public function onSuccess() {
300  $out = $this->getOutput();
301 
302  $username = $this->getUser()->getName();
303  switch ( $this->operation ) {
304  case 'insert':
305  $out->setPageTitle( $this->msg( 'botpasswords-created-title' )->text() );
306  $out->addWikiMsg( 'botpasswords-created-body', $this->par, $username );
307  break;
308 
309  case 'update':
310  $out->setPageTitle( $this->msg( 'botpasswords-updated-title' )->text() );
311  $out->addWikiMsg( 'botpasswords-updated-body', $this->par, $username );
312  break;
313 
314  case 'delete':
315  $out->setPageTitle( $this->msg( 'botpasswords-deleted-title' )->text() );
316  $out->addWikiMsg( 'botpasswords-deleted-body', $this->par, $username );
317  $this->password = null;
318  break;
319  }
320 
321  if ( $this->password !== null ) {
322  $sep = BotPassword::getSeparator();
323  $out->addWikiMsg(
324  'botpasswords-newpassword',
325  htmlspecialchars( $username . $sep . $this->par ),
326  htmlspecialchars( $this->password ),
327  htmlspecialchars( $username ),
328  htmlspecialchars( $this->par . $sep . $this->password )
329  );
330  $this->password = null;
331  }
332 
333  $out->addReturnTo( $this->getPageTitle() );
334  }
335 
336  protected function getGroupName() {
337  return 'users';
338  }
339 
340  protected function getDisplayFormat() {
341  return 'ooui';
342  }
343 }
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:73
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:336
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:271
BotPassword\generatePassword
static generatePassword( $config)
Returns a (raw, unhashed) random password string.
Definition: BotPassword.php:397
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
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:86
$res
$res
Definition: database.txt:21
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
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:299
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:340
SpecialBotPasswords\alterForm
alterForm(HTMLForm $form)
Play with the HTMLForm if you need to more substantially.
Definition: SpecialBotPasswords.php:200
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:239
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:58
SpecialBotPasswords\$botPassword
BotPassword null $botPassword
Bot password being edited, if any.
Definition: SpecialBotPasswords.php:35
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