MediaWiki  1.27.3
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(
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(
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 
398  public static function login( $username, $password, WebRequest $request ) {
399  global $wgEnableBotPasswords;
400 
401  if ( !$wgEnableBotPasswords ) {
402  return Status::newFatal( 'botpasswords-disabled' );
403  }
404 
406  $provider = $manager->getProvider( BotPasswordSessionProvider::class );
407  if ( !$provider ) {
408  return Status::newFatal( 'botpasswords-no-provider' );
409  }
410 
411  // Split name into name+appId
412  $sep = self::getSeparator();
413  if ( strpos( $username, $sep ) === false ) {
414  return Status::newFatal( 'botpasswords-invalid-name', $sep );
415  }
416  list( $name, $appId ) = explode( $sep, $username, 2 );
417 
418  // Find the named user
420  if ( !$user || $user->isAnon() ) {
421  return Status::newFatal( 'nosuchuser', $name );
422  }
423 
424  // Get the bot password
425  $bp = self::newFromUser( $user, $appId );
426  if ( !$bp ) {
427  return Status::newFatal( 'botpasswords-not-exist', $name, $appId );
428  }
429 
430  // Check restrictions
431  $status = $bp->getRestrictions()->check( $request );
432  if ( !$status->isOK() ) {
433  return Status::newFatal( 'botpasswords-restriction-failed' );
434  }
435 
436  // Check the password
437  if ( !$bp->getPassword()->equals( $password ) ) {
438  return Status::newFatal( 'wrongpassword' );
439  }
440 
441  // Ok! Create the session.
442  return Status::newGood( $provider->newSessionForRequest( $user, $bp, $request ) );
443  }
444 }
static newFromName($name, $validate= 'valid')
Static factory method for creation from username.
Definition: User.php:568
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
getUserCentralId()
Get the central user ID.
const TOKEN_LENGTH
int Number of characters in user_token field.
Definition: User.php:51
static removeAllPasswordsForCentralId($centralId)
Remove all passwords for a user, by central ID.
const APPID_MAXLENGTH
Definition: BotPassword.php:29
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
static newFatal($message)
Factory function for fatal errors.
Definition: Status.php:89
string[] $grants
Definition: BotPassword.php:47
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.
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:1008
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 getDBOptions($bitfield)
Get an appropriate DB index and options 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:246
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:766
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:2422
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 generateHex($chars, $forceStrong=false)
Generate a run of (ideally) cryptographically random data and return it in hexadecimal string format...
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:1008
static newDefault()
const DB_MASTER
Definition: Defines.php:47
__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
static newGood($value=null)
Factory function for good results.
Definition: Status.php:101
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:314