MediaWiki  master
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  'type' => 'textarea',
150  'label-message' => 'botpasswords-label-restrictions',
151  'required' => true,
152  'default' => $this->botPassword->getRestrictions()->toJson( true ),
153  'rows' => 5,
154  'validation-callback' => function ( $v ) {
155  try {
157  return true;
158  } catch ( InvalidArgumentException $ex ) {
159  return $ex->getMessage();
160  }
161  },
162  ];
163 
164  } else {
165  $linkRenderer = $this->getLinkRenderer();
167  $res = $dbr->select(
168  'bot_passwords',
169  [ 'bp_app_id' ],
170  [ 'bp_user' => $this->userId ],
171  __METHOD__
172  );
173  foreach ( $res as $row ) {
174  $fields[] = [
175  'section' => 'existing',
176  'type' => 'info',
177  'raw' => true,
178  'default' => $linkRenderer->makeKnownLink(
179  $this->getPageTitle( $row->bp_app_id ),
180  $row->bp_app_id
181  ),
182  ];
183  }
184 
185  $fields['appId'] = [
186  'section' => 'createnew',
187  'type' => 'textwithbutton',
188  'label-message' => 'botpasswords-label-appid',
189  'buttondefault' => $this->msg( 'botpasswords-label-create' )->text(),
190  'buttonflags' => [ 'progressive', 'primary' ],
191  'required' => true,
193  'maxlength' => BotPassword::APPID_MAXLENGTH,
194  'validation-callback' => function ( $v ) {
195  $v = trim( $v );
196  return $v !== '' && strlen( $v ) <= BotPassword::APPID_MAXLENGTH;
197  },
198  ];
199 
200  $fields[] = [
201  'type' => 'hidden',
202  'default' => 'new',
203  'name' => 'op',
204  ];
205  }
206 
207  return $fields;
208  }
209 
210  protected function alterForm( HTMLForm $form ) {
211  $form->setId( 'mw-botpasswords-form' );
212  $form->setTableId( 'mw-botpasswords-table' );
213  $form->addPreText( $this->msg( 'botpasswords-summary' )->parseAsBlock() );
214  $form->suppressDefaultSubmit();
215 
216  if ( $this->par !== null ) {
217  if ( $this->botPassword->isSaved() ) {
218  $form->setWrapperLegendMsg( 'botpasswords-editexisting' );
219  $form->addButton( [
220  'name' => 'op',
221  'value' => 'update',
222  'label-message' => 'botpasswords-label-update',
223  'flags' => [ 'primary', 'progressive' ],
224  ] );
225  $form->addButton( [
226  'name' => 'op',
227  'value' => 'delete',
228  'label-message' => 'botpasswords-label-delete',
229  'flags' => [ 'destructive' ],
230  ] );
231  } else {
232  $form->setWrapperLegendMsg( 'botpasswords-createnew' );
233  $form->addButton( [
234  'name' => 'op',
235  'value' => 'create',
236  'label-message' => 'botpasswords-label-create',
237  'flags' => [ 'primary', 'constructive' ],
238  ] );
239  }
240 
241  $form->addButton( [
242  'name' => 'op',
243  'value' => 'cancel',
244  'label-message' => 'botpasswords-label-cancel'
245  ] );
246  }
247  }
248 
249  public function onSubmit( array $data ) {
250  $op = $this->getRequest()->getVal( 'op', '' );
251 
252  switch ( $op ) {
253  case 'new':
254  $this->getOutput()->redirect( $this->getPageTitle( $data['appId'] )->getFullURL() );
255  return false;
256 
257  case 'create':
258  $this->operation = 'insert';
259  return $this->save( $data );
260 
261  case 'update':
262  $this->operation = 'update';
263  return $this->save( $data );
264 
265  case 'delete':
266  $this->operation = 'delete';
267  $bp = BotPassword::newFromCentralId( $this->userId, $this->par );
268  if ( $bp ) {
269  $bp->delete();
270  }
271  return Status::newGood();
272 
273  case 'cancel':
274  $this->getOutput()->redirect( $this->getPageTitle()->getFullURL() );
275  return false;
276  }
277 
278  return false;
279  }
280 
281  private function save( array $data ) {
282  $bp = BotPassword::newUnsaved( [
283  'centralId' => $this->userId,
284  'appId' => $this->par,
285  'restrictions' => MWRestrictions::newFromJson( $data['restrictions'] ),
286  'grants' => array_merge(
288  preg_replace( '/^grant-/', '', $data['grants'] )
289  )
290  ] );
291 
292  if ( $this->operation === 'insert' || !empty( $data['resetPassword'] ) ) {
294  max( 32, $this->getConfig()->get( 'MinimalPasswordLength' ) )
295  );
296  $passwordFactory = new PasswordFactory();
297  $passwordFactory->init( RequestContext::getMain()->getConfig() );
298  $password = $passwordFactory->newFromPlaintext( $this->password );
299  } else {
300  $password = null;
301  }
302 
303  if ( $bp->save( $this->operation, $password ) ) {
304  return Status::newGood();
305  } else {
306  // Messages: botpasswords-insert-failed, botpasswords-update-failed
307  return Status::newFatal( "botpasswords-{$this->operation}-failed", $this->par );
308  }
309  }
310 
311  public function onSuccess() {
312  $out = $this->getOutput();
313 
314  $username = $this->getUser()->getName();
315  switch ( $this->operation ) {
316  case 'insert':
317  $out->setPageTitle( $this->msg( 'botpasswords-created-title' )->text() );
318  $out->addWikiMsg( 'botpasswords-created-body', $this->par, $username );
319  break;
320 
321  case 'update':
322  $out->setPageTitle( $this->msg( 'botpasswords-updated-title' )->text() );
323  $out->addWikiMsg( 'botpasswords-updated-body', $this->par, $username );
324  break;
325 
326  case 'delete':
327  $out->setPageTitle( $this->msg( 'botpasswords-deleted-title' )->text() );
328  $out->addWikiMsg( 'botpasswords-deleted-body', $this->par, $username );
329  $this->password = null;
330  break;
331  }
332 
333  if ( $this->password !== null ) {
334  $sep = BotPassword::getSeparator();
335  $out->addWikiMsg(
336  'botpasswords-newpassword',
337  htmlspecialchars( $username . $sep . $this->par ),
338  htmlspecialchars( $this->password )
339  );
340  $this->password = null;
341  }
342 
343  $out->addReturnTo( $this->getPageTitle() );
344  }
345 
346  protected function getGroupName() {
347  return 'users';
348  }
349 
350  protected function getDisplayFormat() {
351  return 'ooui';
352  }
353 }
static getValidGrants()
List all known grants.
Definition: MWGrants.php:30
Factory class for creating and checking Password objects.
static getSeparator()
Get the separator for combined user name + app ID.
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:776
the array() calling protocol came about after MediaWiki 1.4rc1.
static getDB($db)
Get a database connection for the bot passwords database.
Definition: BotPassword.php:73
$batch execute()
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
setId($id)
Definition: HTMLForm.php:1435
if(!isset($args[0])) $lang
const APPID_MAXLENGTH
Definition: BotPassword.php:29
execute($par)
Main execution point.
static generateRandomPasswordString($minLength=10)
Generate a random string suitable for a password.
setWrapperLegendMsg($msg)
Prompt the whole form to be wrapped in a "<fieldset>", with this message as its "<legend>" element...
Definition: HTMLForm.php:1477
msg()
Wrapper around wfMessage that sets the current context.
getOutput()
Get the OutputPage being used for this instance.
static newFatal($message)
Factory function for fatal errors.
Definition: Status.php:89
Special page which uses an HTMLForm to handle processing.
static newUnsaved(array $data, $flags=self::READ_NORMAL)
Create an unsaved BotPassword.
static newFromCentralId($centralId, $appId, $flags=self::READ_NORMAL)
Load a BotPassword from the database.
The User object encapsulates all of the user-specific settings (user_id, name, rights, email address, options, last login time).
Definition: User.php:47
static getMain()
Static methods.
static getHiddenGrants()
Get the list of grants that are hidden and should always be granted.
Definition: MWGrants.php:158
An error page which can definitely be safely rendered using the OutputPage.
$res
Definition: database.txt:21
setTableId($id)
Set the id of the \<table\> or outermost \<div\> element.
Definition: HTMLForm.php:1424
Object handling generic submission, CSRF protection, layout and other logic for UI forms...
Definition: HTMLForm.php:128
const DB_SLAVE
Definition: Defines.php:46
static factory($providerId=null)
Fetch a CentralIdLookup.
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
string $operation
Operation being performed: create, update, delete.
static newFromJson($json)
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
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 local account $user
Definition: hooks.txt:242
BotPassword null $botPassword
Bot password being edited, if any.
suppressDefaultSubmit($suppressSubmit=true)
Stop a default submit button being shown for this form.
Definition: HTMLForm.php:1387
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
this hook is for auditing only or null if authentication failed before getting that far $username
Definition: hooks.txt:776
checkExecutePermissions(User $user)
static getRightsByGrant()
Map all grants to corresponding user rights.
Definition: MWGrants.php:40
addPreText($msg)
Add HTML to introductory message.
Definition: HTMLForm.php:722
requireLogin($reasonMsg= 'exception-nologin-text', $titleMsg= 'exception-nologin')
If the user is not logged in, throws UserNotLoggedIn error.
getUser()
Shortcut to get the User executing this instance.
string $par
The sub-page of the special page.
getConfig()
Shortcut to get main config object.
getLanguage()
Shortcut to get user's language.
LinkRenderer null $linkRenderer
Definition: SpecialPage.php:66
addButton($data)
Add a button to the form.
Definition: HTMLForm.php:922
getRequest()
Get the WebRequest being used for this instance.
string $password
New password set, for communication between onSubmit() and onSuccess()
Let users manage bot passwords.
static newGood($value=null)
Factory function for good results.
Definition: Status.php:101
int $userId
Central user ID.
getPageTitle($subpage=false)
Get a self-referential title object.