MediaWiki REL1_28
BotPassword.php
Go to the documentation of this file.
1<?php
22
27class BotPassword implements IDBAccessObject {
28
29 const APPID_MAXLENGTH = 32;
30
32 private $isSaved;
33
35 private $centralId;
36
38 private $appId;
39
41 private $token;
42
45
47 private $grants;
48
50 private $flags = self::READ_NORMAL;
51
57 protected function __construct( $row, $isSaved, $flags = self::READ_NORMAL ) {
58 $this->isSaved = $isSaved;
59 $this->flags = $flags;
60
61 $this->centralId = (int)$row->bp_user;
62 $this->appId = $row->bp_app_id;
63 $this->token = $row->bp_token;
64 $this->restrictions = MWRestrictions::newFromJson( $row->bp_restrictions );
65 $this->grants = FormatJson::decode( $row->bp_grants );
66 }
67
73 public static function getDB( $db ) {
75
77 ? wfGetLBFactory()->getExternalLB( $wgBotPasswordsCluster )
79 return $lb->getConnectionRef( $db, [], $wgBotPasswordsDatabase );
80 }
81
89 public static function newFromUser( User $user, $appId, $flags = self::READ_NORMAL ) {
90 $centralId = CentralIdLookup::factory()->centralIdFromLocalUser(
92 );
93 return $centralId ? self::newFromCentralId( $centralId, $appId, $flags ) : null;
94 }
95
103 public static function newFromCentralId( $centralId, $appId, $flags = self::READ_NORMAL ) {
105
106 if ( !$wgEnableBotPasswords ) {
107 return null;
108 }
109
111 $db = self::getDB( $index );
112 $row = $db->selectRow(
113 'bot_passwords',
114 [ 'bp_user', 'bp_app_id', 'bp_token', 'bp_restrictions', 'bp_grants' ],
115 [ 'bp_user' => $centralId, 'bp_app_id' => $appId ],
116 __METHOD__,
118 );
119 return $row ? new self( $row, true, $flags ) : null;
120 }
121
134 public static function newUnsaved( array $data, $flags = self::READ_NORMAL ) {
135 $row = (object)[
136 'bp_user' => 0,
137 'bp_app_id' => isset( $data['appId'] ) ? trim( $data['appId'] ) : '',
138 'bp_token' => '**unsaved**',
139 'bp_restrictions' => isset( $data['restrictions'] )
140 ? $data['restrictions']
142 'bp_grants' => isset( $data['grants'] ) ? $data['grants'] : [],
143 ];
144
145 if (
146 $row->bp_app_id === '' || strlen( $row->bp_app_id ) > self::APPID_MAXLENGTH ||
147 !$row->bp_restrictions instanceof MWRestrictions ||
148 !is_array( $row->bp_grants )
149 ) {
150 return null;
151 }
152
153 $row->bp_restrictions = $row->bp_restrictions->toJson();
154 $row->bp_grants = FormatJson::encode( $row->bp_grants );
155
156 if ( isset( $data['user'] ) ) {
157 if ( !$data['user'] instanceof User ) {
158 return null;
159 }
160 $row->bp_user = CentralIdLookup::factory()->centralIdFromLocalUser(
162 );
163 } elseif ( isset( $data['username'] ) ) {
164 $row->bp_user = CentralIdLookup::factory()->centralIdFromName(
165 $data['username'], CentralIdLookup::AUDIENCE_RAW, $flags
166 );
167 } elseif ( isset( $data['centralId'] ) ) {
168 $row->bp_user = $data['centralId'];
169 }
170 if ( !$row->bp_user ) {
171 return null;
172 }
173
174 return new self( $row, false, $flags );
175 }
176
181 public function isSaved() {
182 return $this->isSaved;
183 }
184
189 public function getUserCentralId() {
190 return $this->centralId;
191 }
192
197 public function getAppId() {
198 return $this->appId;
199 }
200
205 public function getToken() {
206 return $this->token;
207 }
208
213 public function getRestrictions() {
214 return $this->restrictions;
215 }
216
221 public function getGrants() {
222 return $this->grants;
223 }
224
233
238 protected function getPassword() {
240 $db = self::getDB( $index );
241 $password = $db->selectField(
242 'bot_passwords',
243 'bp_password',
244 [ 'bp_user' => $this->centralId, 'bp_app_id' => $this->appId ],
245 __METHOD__,
247 );
248 if ( $password === false ) {
249 return PasswordFactory::newInvalidPassword();
250 }
251
252 $passwordFactory = new \PasswordFactory();
253 $passwordFactory->init( \RequestContext::getMain()->getConfig() );
254 try {
255 return $passwordFactory->newFromCiphertext( $password );
256 } catch ( PasswordError $ex ) {
257 return PasswordFactory::newInvalidPassword();
258 }
259 }
260
267 public function save( $operation, Password $password = null ) {
268 $conds = [
269 'bp_user' => $this->centralId,
270 'bp_app_id' => $this->appId,
271 ];
272 $fields = [
273 'bp_token' => MWCryptRand::generateHex( User::TOKEN_LENGTH ),
274 'bp_restrictions' => $this->restrictions->toJson(),
275 'bp_grants' => FormatJson::encode( $this->grants ),
276 ];
277
278 if ( $password !== null ) {
279 $fields['bp_password'] = $password->toString();
280 } elseif ( $operation === 'insert' ) {
281 $fields['bp_password'] = PasswordFactory::newInvalidPassword()->toString();
282 }
283
284 $dbw = self::getDB( DB_MASTER );
285 switch ( $operation ) {
286 case 'insert':
287 $dbw->insert( 'bot_passwords', $fields + $conds, __METHOD__, [ 'IGNORE' ] );
288 break;
289
290 case 'update':
291 $dbw->update( 'bot_passwords', $fields, $conds, __METHOD__ );
292 break;
293
294 default:
295 return false;
296 }
297 $ok = (bool)$dbw->affectedRows();
298 if ( $ok ) {
299 $this->token = $dbw->selectField( 'bot_passwords', 'bp_token', $conds, __METHOD__ );
300 $this->isSaved = true;
301 }
302 return $ok;
303 }
304
309 public function delete() {
310 $conds = [
311 'bp_user' => $this->centralId,
312 'bp_app_id' => $this->appId,
313 ];
314 $dbw = self::getDB( DB_MASTER );
315 $dbw->delete( 'bot_passwords', $conds, __METHOD__ );
316 $ok = (bool)$dbw->affectedRows();
317 if ( $ok ) {
318 $this->token = '**unsaved**';
319 $this->isSaved = false;
320 }
321 return $ok;
322 }
323
329 public static function invalidateAllPasswordsForUser( $username ) {
330 $centralId = CentralIdLookup::factory()->centralIdFromName(
331 $username, CentralIdLookup::AUDIENCE_RAW, CentralIdLookup::READ_LATEST
332 );
333 return $centralId && self::invalidateAllPasswordsForCentralId( $centralId );
334 }
335
341 public static function invalidateAllPasswordsForCentralId( $centralId ) {
343
344 if ( !$wgEnableBotPasswords ) {
345 return false;
346 }
347
348 $dbw = self::getDB( DB_MASTER );
349 $dbw->update(
350 'bot_passwords',
351 [ 'bp_password' => PasswordFactory::newInvalidPassword()->toString() ],
352 [ 'bp_user' => $centralId ],
353 __METHOD__
354 );
355 return (bool)$dbw->affectedRows();
356 }
357
363 public static function removeAllPasswordsForUser( $username ) {
364 $centralId = CentralIdLookup::factory()->centralIdFromName(
365 $username, CentralIdLookup::AUDIENCE_RAW, CentralIdLookup::READ_LATEST
366 );
367 return $centralId && self::removeAllPasswordsForCentralId( $centralId );
368 }
369
375 public static function removeAllPasswordsForCentralId( $centralId ) {
377
378 if ( !$wgEnableBotPasswords ) {
379 return false;
380 }
381
382 $dbw = self::getDB( DB_MASTER );
383 $dbw->delete(
384 'bot_passwords',
385 [ 'bp_user' => $centralId ],
386 __METHOD__
387 );
388 return (bool)$dbw->affectedRows();
389 }
390
396 public static function generatePassword( $config ) {
397 return PasswordFactory::generateRandomPasswordString(
398 max( 32, $config->get( 'MinimalPasswordLength' ) ) );
399 }
400
412 public static function canonicalizeLoginData( $username, $password ) {
414 // the strlen check helps minimize the password information obtainable from timing
415 if ( strlen( $password ) >= 32 && strpos( $username, $sep ) !== false ) {
416 // the separator is not valid in new usernames but might appear in legacy ones
417 if ( preg_match( '/^[0-9a-w]{32,}$/', $password ) ) {
418 return [ $username, $password, true ];
419 }
420 } elseif ( strlen( $password ) > 32 && strpos( $password, $sep ) !== false ) {
421 $segments = explode( $sep, $password );
422 $password = array_pop( $segments );
423 $appId = implode( $sep, $segments );
424 if ( preg_match( '/^[0-9a-w]{32,}$/', $password ) ) {
425 return [ $username . $sep . $appId, $password, true ];
426 }
427 }
428 return false;
429 }
430
438 public static function login( $username, $password, WebRequest $request ) {
440
441 if ( !$wgEnableBotPasswords ) {
442 return Status::newFatal( 'botpasswords-disabled' );
443 }
444
445 $manager = MediaWiki\Session\SessionManager::singleton();
446 $provider = $manager->getProvider( BotPasswordSessionProvider::class );
447 if ( !$provider ) {
448 return Status::newFatal( 'botpasswords-no-provider' );
449 }
450
451 // Split name into name+appId
452 $sep = self::getSeparator();
453 if ( strpos( $username, $sep ) === false ) {
454 return Status::newFatal( 'botpasswords-invalid-name', $sep );
455 }
456 list( $name, $appId ) = explode( $sep, $username, 2 );
457
458 // Find the named user
459 $user = User::newFromName( $name );
460 if ( !$user || $user->isAnon() ) {
461 return Status::newFatal( 'nosuchuser', $name );
462 }
463
464 // Throttle
465 $throttle = null;
466 if ( !empty( $wgPasswordAttemptThrottle ) ) {
468 'type' => 'botpassword',
469 'cache' => ObjectCache::getLocalClusterInstance(),
470 ] );
471 $result = $throttle->increase( $user->getName(), $request->getIP(), __METHOD__ );
472 if ( $result ) {
473 $msg = wfMessage( 'login-throttled' )->durationParams( $result['wait'] );
474 return Status::newFatal( $msg );
475 }
476 }
477
478 // Get the bot password
479 $bp = self::newFromUser( $user, $appId );
480 if ( !$bp ) {
481 return Status::newFatal( 'botpasswords-not-exist', $name, $appId );
482 }
483
484 // Check restrictions
485 $status = $bp->getRestrictions()->check( $request );
486 if ( !$status->isOK() ) {
487 return Status::newFatal( 'botpasswords-restriction-failed' );
488 }
489
490 // Check the password
491 if ( !$bp->getPassword()->equals( $password ) ) {
492 return Status::newFatal( 'wrongpassword' );
493 }
494
495 // Ok! Create the session.
496 if ( $throttle ) {
497 $throttle->clear( $user->getName(), $request->getIP() );
498 }
499 return Status::newGood( $provider->newSessionForRequest( $user, $bp, $request ) );
500 }
501}
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
$wgUserrightsInterwikiDelimiter
Character used as a delimiter when testing for interwiki userrights (In Special:UserRights,...
bool $wgEnableBotPasswords
Whether to enable bot passwords.
$wgPasswordAttemptThrottle
Limit password attempts to X attempts per Y seconds per IP per account.
string bool $wgBotPasswordsDatabase
Database name for the bot_passwords table.
string bool $wgBotPasswordsCluster
Cluster for the bot_passwords table If false, the normal cluster will be used.
wfGetLB( $wiki=false)
Get a load balancer object.
wfGetLBFactory()
Get the load balancer factory object.
Utility class for bot passwords.
static newFromUser(User $user, $appId, $flags=self::READ_NORMAL)
Load a BotPassword from the database.
__construct( $row, $isSaved, $flags=self::READ_NORMAL)
const APPID_MAXLENGTH
static invalidateAllPasswordsForUser( $username)
Invalidate all passwords for a user, by name.
getRestrictions()
Get the restrictions.
MWRestrictions $restrictions
static generatePassword( $config)
Returns a (raw, unhashed) random password string.
getPassword()
Get the password.
getUserCentralId()
Get the central user ID.
getGrants()
Get the grants.
string[] $grants
string $token
static getDB( $db)
Get a database connection for the bot passwords database.
getAppId()
Get the app ID.
static newFromCentralId( $centralId, $appId, $flags=self::READ_NORMAL)
Load a BotPassword from the database.
static login( $username, $password, WebRequest $request)
Try to log the user in.
static invalidateAllPasswordsForCentralId( $centralId)
Invalidate all passwords for a user, by central ID.
isSaved()
Indicate whether this is known to be saved.
string $appId
static removeAllPasswordsForUser( $username)
Remove all passwords for a user, by name.
static removeAllPasswordsForCentralId( $centralId)
Remove all passwords for a user, by central ID.
static newUnsaved(array $data, $flags=self::READ_NORMAL)
Create an unsaved BotPassword.
getToken()
Get the token.
static getSeparator()
Get the separator for combined user name + app ID.
save( $operation, Password $password=null)
Save the BotPassword to the database.
static canonicalizeLoginData( $username, $password)
There are two ways to login with a bot password: "username@appId", "password" and "username",...
static factory( $providerId=null)
Fetch a CentralIdLookup.
static getDBOptions( $bitfield)
Get an appropriate DB index, options, and fallback DB index for a query.
static generateHex( $chars, $forceStrong=false)
Generate a run of (ideally) cryptographically random data and return it in hexadecimal string format.
A class to check request restrictions expressed as a JSON object.
static newFromJson( $json)
Show an error when any operation involving passwords fails to run.
Represents a password hash for use in authentication.
Definition Password.php:66
static getMain()
Static methods.
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Definition User.php:48
The WebRequest class encapsulates getting at data passed in the URL or via a POSTed form stripping il...
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 etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
Definition deferred.txt:11
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 in any and then calling but I prefer the flexibility This should also do the output encoding The system allocates a global one in $wgOut Title Represents the title of an and does all the work of translating among various forms such as plain database etc For and for historical it also represents a few features of articles that don t involve their such as access rights See also title txt Article Encapsulates access to the page table of the database The object represents a an and maintains state such as flags
Definition design.txt:34
when a variable name is used in a it is silently declared as a new local masking the global
Definition design.txt:95
globals will be eliminated from MediaWiki replaced by an application object which would be passed to constructors Whether that would be an convenient solution remains to be but certainly PHP makes such object oriented programming models easier than they were in previous versions For the time being MediaWiki programmers will have to work in an environment with some global context At the time of globals were initialised on startup by MediaWiki of these were configuration which are documented in DefaultSettings php There is no comprehensive documentation for the remaining however some of the most important ones are listed below They are typically initialised either in index php or in Setup php For a description of the see design txt $wgTitle Title object created from the request URL $wgOut OutputPage object for HTTP response $wgUser User object for the user associated with the current request $wgLang Language object selected by user preferences $wgContLang Language object associated with the wiki being viewed $wgParser Parser object Parser extensions register their hooks here $wgRequest WebRequest object
Definition globals.txt:64
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set $status
Definition hooks.txt:1049
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
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message. Please note the header message cannot receive/use parameters. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item. Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page. Return false to stop further processing of the tag $reader:XMLReader object & $pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision. Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag. Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload. Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports. & $fullInterwikiPrefix:Interwiki prefix, may contain colons. & $pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable. Can be used to lazy-load the import sources list. & $importSources:The value of $wgImportSources. Modify as necessary. See the comment in DefaultSettings.php for the detail of how to structure this array. 'InfoAction':When building information to display on the action=info page. $context:IContextSource object & $pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect. & $title:Title object for the current page & $request:WebRequest & $ignoreRedirect:boolean to skip redirect check & $target:Title/string of redirect target & $article:Article object 'InternalParseBeforeLinks':during Parser 's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InternalParseBeforeSanitize':during Parser 's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings. Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not. Return true without providing an interwiki to continue interwiki search. $prefix:interwiki prefix we are looking for. & $iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InvalidateEmailComplete':Called after a user 's email has been invalidated successfully. $user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification. Callee may modify $url and $query, URL will be constructed as $url . $query & $url:URL to index.php & $query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) & $article:article(object) being checked 'IsTrustedProxy':Override the result of IP::isTrustedProxy() & $ip:IP being check & $result:Change this value to override the result of IP::isTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from & $allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of Sanitizer::validateEmail(), for instance to return false if the domain name doesn 't match your organization. $addr:The e-mail address entered by the user & $result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user & $result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we 're looking for a messages file for & $file:The messages file path, you can override this to change the location. 'LanguageGetMagic':DEPRECATED! Use $magicWords in a file listed in $wgExtensionMessagesFiles instead. Use this to define synonyms of magic words depending of the language & $magicExtensions:associative array of magic words synonyms $lang:language code(string) 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces. Do not use this hook to add namespaces. Use CanonicalNamespaces for that. & $namespaces:Array of namespaces indexed by their numbers 'LanguageGetSpecialPageAliases':DEPRECATED! Use $specialPageAliases in a file listed in $wgExtensionMessagesFiles instead. Use to define aliases of special pages names depending of the language & $specialPageAliases:associative array of magic words synonyms $lang:language code(string) 'LanguageGetTranslatedLanguageNames':Provide translated language names. & $names:array of language code=> language name $code:language of the preferred translations 'LanguageLinks':Manipulate a page 's language links. This is called in various places to allow extensions to define the effective language links for a page. $title:The page 's Title. & $links:Associative array mapping language codes to prefixed links of the form "language:title". & $linkFlags:Associative array mapping prefixed links to arrays of flags. Currently unused, but planned to provide support for marking individual language links in the UI, e.g. for featured articles. 'LanguageSelector':Hook to change the language selector available on a page. $out:The output page. $cssClassName:CSS class name of the language selector. 'LinkBegin':DEPRECATED! Use HtmlPageLinkRendererBegin instead. Used when generating internal and interwiki links in Linker::link(), before processing starts. Return false to skip default processing and return $ret. See documentation for Linker::link() for details on the expected meanings of parameters. $skin:the Skin object $target:the Title that the link is pointing to & $html:the contents that the< a > tag should have(raw HTML) $result
Definition hooks.txt:1937
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content as context as context $options
Definition hooks.txt:1096
either a unescaped string or a HtmlArmor object after in associative array form externallinks including delete and has completed for all link tables whether this was an auto creation default is conds Array Extra conditions for the No matching items in log is displayed if loglist is empty msgKey Array If you want a nice box with a set this to the key of the message First element is the message additional optional elements are parameters for the key that are processed with wfMessage() -> params() ->parseAsBlock() - offset Set to overwrite offset parameter in $wgRequest set to '' to unset offset - wrap String Wrap the message in html(usually something like "&lt;div ...>$1&lt;/div>"). - flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException':Called before an exception(or PHP error) is logged. This is meant for integration with external error aggregation services
it s the revision text itself In either if gzip is the revision text is gzipped $flags
Definition hooks.txt:2710
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return true
Definition hooks.txt:1950
error also a ContextSource you ll probably need to make sure the header is varied on $request
Definition hooks.txt:2685
this hook is for auditing only or null if authentication failed before getting that far $username
Definition hooks.txt:807
Allows to change the fields on the form that will be generated $name
Definition hooks.txt:304
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
Interface for database access objects.
const DB_MASTER
Definition defines.php:23