MediaWiki  1.28.1
BotPassword.php
Go to the documentation of this file.
1 <?php
22 
27 class 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 
44  private $restrictions;
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 ) {
74  global $wgBotPasswordsCluster, $wgBotPasswordsDatabase;
75 
76  $lb = $wgBotPasswordsCluster
77  ? wfGetLBFactory()->getExternalLB( $wgBotPasswordsCluster )
78  : wfGetLB( $wgBotPasswordsDatabase );
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 ) {
104  global $wgEnableBotPasswords;
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__,
117  $options
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(
161  $data['user'], CentralIdLookup::AUDIENCE_RAW, $flags
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 
229  public static function getSeparator() {
230  global $wgUserrightsInterwikiDelimiter;
231  return $wgUserrightsInterwikiDelimiter;
232  }
233 
238  protected function getPassword() {
239  list( $index, $options ) = DBAccessObjectUtils::getDBOptions( $this->flags );
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__,
246  $options
247  );
248  if ( $password === false ) {
250  }
251 
252  $passwordFactory = new \PasswordFactory();
253  $passwordFactory->init( \RequestContext::getMain()->getConfig() );
254  try {
255  return $passwordFactory->newFromCiphertext( $password );
256  } catch ( PasswordError $ex ) {
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 = [
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 ) {
342  global $wgEnableBotPasswords;
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 ) {
376  global $wgEnableBotPasswords;
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 ) {
398  max( 32, $config->get( 'MinimalPasswordLength' ) ) );
399  }
400 
412  public static function canonicalizeLoginData( $username, $password ) {
413  $sep = BotPassword::getSeparator();
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 ) {
439  global $wgEnableBotPasswords;
440 
441  if ( !$wgEnableBotPasswords ) {
442  return Status::newFatal( 'botpasswords-disabled' );
443  }
444 
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
460  if ( !$user || $user->isAnon() ) {
461  return Status::newFatal( 'nosuchuser', $name );
462  }
463 
464  // Get the bot password
465  $bp = self::newFromUser( $user, $appId );
466  if ( !$bp ) {
467  return Status::newFatal( 'botpasswords-not-exist', $name, $appId );
468  }
469 
470  // Check restrictions
471  $status = $bp->getRestrictions()->check( $request );
472  if ( !$status->isOK() ) {
473  return Status::newFatal( 'botpasswords-restriction-failed' );
474  }
475 
476  // Check the password
477  if ( !$bp->getPassword()->equals( $password ) ) {
478  return Status::newFatal( 'wrongpassword' );
479  }
480 
481  // Ok! Create the session.
482  return Status::newGood( $provider->newSessionForRequest( $user, $bp, $request ) );
483  }
484 }
static newFromName($name, $validate= 'valid')
Static factory method for creation from username.
Definition: User.php:525
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
static getSeparator()
Get the separator for combined user name + app ID.
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
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
static newFatal($message)
Factory function for fatal errors.
Definition: StatusValue.php:63
getUserCentralId()
Get the central user ID.
const TOKEN_LENGTH
int Number of characters in user_token field.
Definition: User.php:52
static removeAllPasswordsForCentralId($centralId)
Remove all passwords for a user, by central ID.
const APPID_MAXLENGTH
Definition: BotPassword.php:29
static generateRandomPasswordString($minLength=10)
Generate a random string suitable for a password.
static invalidateAllPasswordsForCentralId($centralId)
Invalidate all passwords for a user, by central ID.
getToken()
Get the token.
when a variable name is used in a it is silently declared as a new local masking the global
Definition: design.txt:93
string[] $grants
Definition: BotPassword.php:47
const DB_MASTER
Definition: defines.php:23
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:25
static newUnsaved(array $data, $flags=self::READ_NORMAL)
Create an unsaved BotPassword.
isSaved()
Indicate whether this is known to be saved.
static newFromCentralId($centralId, $appId, $flags=self::READ_NORMAL)
Load a BotPassword from the database.
static removeAllPasswordsForUser($username)
Remove all passwords for a user, by name.
getAppId()
Get the app ID.
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:1936
save($operation, Password $password=null)
Save the BotPassword to the database.
wfGetLB($wiki=false)
Get a load balancer object.
static getMain()
Static methods.
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:1046
static invalidateAllPasswordsForUser($username)
Invalidate all passwords for a user, by name.
string $token
Definition: BotPassword.php:41
static encode($value, $pretty=false, $escaping=0)
Returns the JSON representation of a value.
Definition: FormatJson.php:127
getPassword()
Get the password.
A class to check request restrictions expressed as a JSON object.
string $appId
Definition: BotPassword.php:38
static factory($providerId=null)
Fetch a CentralIdLookup.
static newGood($value=null)
Factory function for good results.
Definition: StatusValue.php:76
static getDBOptions($bitfield)
Get an appropriate DB index, options, and fallback DB index for a query.
static newFromJson($json)
static singleton()
Get the global SessionManager.
static newInvalidPassword()
Create an InvalidPassword.
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
static newFromUser(User $user, $appId, $flags=self::READ_NORMAL)
Load a BotPassword from the database.
Definition: BotPassword.php:89
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:802
wfGetLBFactory()
Get the load balancer factory object.
error also a ContextSource you ll probably need to make sure the header is varied on $request
Definition: hooks.txt:2573
Show an error when any operation involving passwords fails to run.
you have access to all of the normal MediaWiki so you can get a DB use the etc For full docs on the Maintenance class
Definition: maintenance.txt:52
static generatePassword($config)
Returns a (raw, unhashed) random password string.
static generateHex($chars, $forceStrong=false)
Generate a run of (ideally) cryptographically random data and return it in hexadecimal string format...
Definition: MWCryptRand.php:76
static canonicalizeLoginData($username, $password)
There are two ways to login with a bot password: "username@appId", "password" and "username"...
Interface for database access objects.
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:1046
static newDefault()
__construct($row, $isSaved, $flags=self::READ_NORMAL)
Definition: BotPassword.php:57
getGrants()
Get the grants.
static decode($value, $assoc=false)
Decodes a JSON string.
Definition: FormatJson.php:187
static login($username, $password, WebRequest $request)
Try to log the user in.
MWRestrictions $restrictions
Definition: BotPassword.php:44
getRestrictions()
Get the restrictions.
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
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:300