MediaWiki REL1_27
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
74 parent::execute( $par );
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 'type' => 'textarea',
157 'label-message' => 'botpasswords-label-restrictions',
158 'required' => true,
159 'default' => $this->botPassword->getRestrictions()->toJson( true ),
160 'rows' => 5,
161 'validation-callback' => function ( $v ) {
162 try {
164 return true;
165 } catch ( InvalidArgumentException $ex ) {
166 return $ex->getMessage();
167 }
168 },
169 ];
170
171 } else {
172 $passwordFactory = new PasswordFactory();
173 $passwordFactory->init( $this->getConfig() );
174
175 $dbr = BotPassword::getDB( DB_REPLICA );
176 $res = $dbr->select(
177 'bot_passwords',
178 [ 'bp_app_id', 'bp_password' ],
179 [ 'bp_user' => $this->userId ],
180 __METHOD__
181 );
182 foreach ( $res as $row ) {
183 try {
184 $password = $passwordFactory->newFromCiphertext( $row->bp_password );
185 $passwordInvalid = $password instanceof InvalidPassword;
186 unset( $password );
187 } catch ( PasswordError $ex ) {
188 $passwordInvalid = true;
189 }
190
191 $text = Linker::link(
192 $this->getPageTitle( $row->bp_app_id ),
193 htmlspecialchars( $row->bp_app_id ),
194 [],
195 [],
196 [ 'known' ]
197 );
198 if ( $passwordInvalid ) {
199 $text .= $this->msg( 'word-separator' )->escaped()
200 . $this->msg( 'botpasswords-label-needsreset' )->parse();
201 }
202
203 $fields[] = [
204 'section' => 'existing',
205 'type' => 'info',
206 'raw' => true,
207 'default' => $text,
208 ];
209 }
210
211 $fields['appId'] = [
212 'section' => 'createnew',
213 'type' => 'textwithbutton',
214 'label-message' => 'botpasswords-label-appid',
215 'buttondefault' => $this->msg( 'botpasswords-label-create' )->text(),
216 'buttonflags' => [ 'progressive', 'primary' ],
217 'required' => true,
218 'size' => BotPassword::APPID_MAXLENGTH,
219 'maxlength' => BotPassword::APPID_MAXLENGTH,
220 'validation-callback' => function ( $v ) {
221 $v = trim( $v );
222 return $v !== '' && strlen( $v ) <= BotPassword::APPID_MAXLENGTH;
223 },
224 ];
225
226 $fields[] = [
227 'type' => 'hidden',
228 'default' => 'new',
229 'name' => 'op',
230 ];
231 }
232
233 return $fields;
234 }
235
236 protected function alterForm( HTMLForm $form ) {
237 $form->setId( 'mw-botpasswords-form' );
238 $form->setTableId( 'mw-botpasswords-table' );
239 $form->addPreText( $this->msg( 'botpasswords-summary' )->parseAsBlock() );
240 $form->suppressDefaultSubmit();
241
242 if ( $this->par !== null ) {
243 if ( $this->botPassword->isSaved() ) {
244 $form->setWrapperLegendMsg( 'botpasswords-editexisting' );
245 $form->addButton( [
246 'name' => 'op',
247 'value' => 'update',
248 'label-message' => 'botpasswords-label-update',
249 'flags' => [ 'primary', 'progressive' ],
250 ] );
251 $form->addButton( [
252 'name' => 'op',
253 'value' => 'delete',
254 'label-message' => 'botpasswords-label-delete',
255 'flags' => [ 'destructive' ],
256 ] );
257 } else {
258 $form->setWrapperLegendMsg( 'botpasswords-createnew' );
259 $form->addButton( [
260 'name' => 'op',
261 'value' => 'create',
262 'label-message' => 'botpasswords-label-create',
263 'flags' => [ 'primary', 'constructive' ],
264 ] );
265 }
266
267 $form->addButton( [
268 'name' => 'op',
269 'value' => 'cancel',
270 'label-message' => 'botpasswords-label-cancel'
271 ] );
272 }
273 }
274
275 public function onSubmit( array $data ) {
276 $op = $this->getRequest()->getVal( 'op', '' );
277
278 switch ( $op ) {
279 case 'new':
280 $this->getOutput()->redirect( $this->getPageTitle( $data['appId'] )->getFullURL() );
281 return false;
282
283 case 'create':
284 $this->operation = 'insert';
285 return $this->save( $data );
286
287 case 'update':
288 $this->operation = 'update';
289 return $this->save( $data );
290
291 case 'delete':
292 $this->operation = 'delete';
293 $bp = BotPassword::newFromCentralId( $this->userId, $this->par );
294 if ( $bp ) {
295 $bp->delete();
296 }
297 return Status::newGood();
298
299 case 'cancel':
300 $this->getOutput()->redirect( $this->getPageTitle()->getFullURL() );
301 return false;
302 }
303
304 return false;
305 }
306
307 private function save( array $data ) {
308 $bp = BotPassword::newUnsaved( [
309 'centralId' => $this->userId,
310 'appId' => $this->par,
311 'restrictions' => MWRestrictions::newFromJson( $data['restrictions'] ),
312 'grants' => array_merge(
314 preg_replace( '/^grant-/', '', $data['grants'] )
315 )
316 ] );
317
318 if ( $this->operation === 'insert' || !empty( $data['resetPassword'] ) ) {
319 $this->password = BotPassword::generatePassword( $this->getConfig() );
320 $passwordFactory = new PasswordFactory();
321 $passwordFactory->init( RequestContext::getMain()->getConfig() );
322 $password = $passwordFactory->newFromPlaintext( $this->password );
323 } else {
324 $password = null;
325 }
326
327 if ( $bp->save( $this->operation, $password ) ) {
328 return Status::newGood();
329 } else {
330 // Messages: botpasswords-insert-failed, botpasswords-update-failed
331 return Status::newFatal( "botpasswords-{$this->operation}-failed", $this->par );
332 }
333 }
334
335 public function onSuccess() {
336 $out = $this->getOutput();
337
338 $username = $this->getUser()->getName();
339 switch ( $this->operation ) {
340 case 'insert':
341 $out->setPageTitle( $this->msg( 'botpasswords-created-title' )->text() );
342 $out->addWikiMsg( 'botpasswords-created-body', $this->par, $username );
343 break;
344
345 case 'update':
346 $out->setPageTitle( $this->msg( 'botpasswords-updated-title' )->text() );
347 $out->addWikiMsg( 'botpasswords-updated-body', $this->par, $username );
348 break;
349
350 case 'delete':
351 $out->setPageTitle( $this->msg( 'botpasswords-deleted-title' )->text() );
352 $out->addWikiMsg( 'botpasswords-deleted-body', $this->par, $username );
353 $this->password = null;
354 break;
355 }
356
357 if ( $this->password !== null ) {
358 $sep = BotPassword::getSeparator();
359 $out->addWikiMsg(
360 'botpasswords-newpassword',
361 htmlspecialchars( $username . $sep . $this->par ),
362 htmlspecialchars( $this->password ),
363 htmlspecialchars( $username ),
364 htmlspecialchars( $this->par . $sep . $this->password )
365 );
366 $this->password = null;
367 }
368
369 $out->addReturnTo( $this->getPageTitle() );
370 }
371
372 protected function getGroupName() {
373 return 'users';
374 }
375
376 protected function getDisplayFormat() {
377 return 'ooui';
378 }
379}
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
Utility class for bot passwords.
static factory( $providerId=null)
Fetch a CentralIdLookup.
An error page which can definitely be safely rendered using the OutputPage.
Special page which uses an HTMLForm to handle processing.
string $par
The sub-page of the special page.
Object handling generic submission, CSRF protection, layout and other logic for UI forms.
Definition HTMLForm.php:123
setTableId( $id)
Set the id of the <table> or outermost <div> element.
setWrapperLegendMsg( $msg)
Prompt the whole form to be wrapped in a "<fieldset>", with this message as its "<legend>" element.
setId( $id)
addButton( $data)
Add a button to the form.
Definition HTMLForm.php:899
suppressDefaultSubmit( $suppressSubmit=true)
Stop a default submit button being shown for this form.
addPreText( $msg)
Add HTML to introductory message.
Definition HTMLForm.php:700
Represents an invalid password hash.
static link( $target, $html=null, $customAttribs=[], $query=[], $options=[])
This function returns an HTML link to the given target.
Definition Linker.php:195
static getHiddenGrants()
Get the list of grants that are hidden and should always be granted.
Definition MWGrants.php:158
static getRightsByGrant()
Map all grants to corresponding user rights.
Definition MWGrants.php:40
static getValidGrants()
List all known grants.
Definition MWGrants.php:30
static newFromJson( $json)
Show an error when any operation involving passwords fails to run.
Factory class for creating and checking Password objects.
static getMain()
Static methods.
Let users manage bot passwords.
string $password
New password set, for communication between onSubmit() and onSuccess()
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.
getFormFields()
Get an HTMLForm descriptor array.
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.
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.
string $operation
Operation being performed: create, update, delete.
getName()
Get the name of this Special Page.
getOutput()
Get the OutputPage being used for this instance.
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.
getConfig()
Shortcut to get main config object.
getRequest()
Get the WebRequest being used for this instance.
getPageTitle( $subpage=false)
Get a self-referential title object.
getLanguage()
Shortcut to get user's language.
msg()
Wrapper around wfMessage that sets the current context.
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Definition User.php:47
$res
Definition database.txt:21
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a save
Definition deferred.txt:5
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:18
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
const DB_REPLICA
Definition Defines.php:46
the array() calling protocol came about after MediaWiki 1.4rc1.
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:249
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:846
this hook is for auditing only or null if authentication failed before getting that far $username
Definition hooks.txt:767
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:37
if(!isset( $args[0])) $lang