MediaWiki  master
ApiBlockTest.php
Go to the documentation of this file.
1 <?php
2 
6 
14 class ApiBlockTest extends ApiTestCase {
15  protected $mUser = null;
16 
17  protected function setUp() {
18  parent::setUp();
19  $this->tablesUsed = array_merge(
20  $this->tablesUsed,
21  [ 'ipblocks', 'change_tag', 'change_tag_def', 'logging' ]
22  );
23 
24  $this->mUser = $this->getMutableTestUser()->getUser();
25  $this->setMwGlobals( 'wgBlockCIDRLimit', [
26  'IPv4' => 16,
27  'IPv6' => 19,
28  ] );
29  }
30 
31  protected function getTokens() {
32  return $this->getTokenList( self::$users['sysop'] );
33  }
34 
40  private function doBlock( array $extraParams = [], User $blocker = null ) {
41  if ( $blocker === null ) {
42  $blocker = self::$users['sysop']->getUser();
43  }
44 
45  $tokens = $this->getTokens();
46 
47  $this->assertNotNull( $this->mUser, 'Sanity check' );
48 
49  $this->assertArrayHasKey( 'blocktoken', $tokens, 'Sanity check' );
50 
51  $params = [
52  'action' => 'block',
53  'user' => $this->mUser->getName(),
54  'reason' => 'Some reason',
55  'token' => $tokens['blocktoken'],
56  ];
57  if ( array_key_exists( 'userid', $extraParams ) ) {
58  // Make sure we don't have both user and userid
59  unset( $params['user'] );
60  }
61  $ret = $this->doApiRequest( array_merge( $params, $extraParams ), null,
62  false, $blocker );
63 
64  $block = DatabaseBlock::newFromTarget( $this->mUser->getName() );
65 
66  $this->assertTrue( !is_null( $block ), 'Block is valid' );
67 
68  $this->assertSame( $this->mUser->getName(), (string)$block->getTarget() );
69  $this->assertSame( 'Some reason', $block->getReason() );
70 
71  return $ret;
72  }
73 
77  public function testNormalBlock() {
78  $this->doBlock();
79  }
80 
84  public function testBlockById() {
85  $this->doBlock( [ 'userid' => $this->mUser->getId() ] );
86  }
87 
91  public function testBlockByBlockedUser() {
92  $this->setExpectedException( ApiUsageException::class,
93  'You cannot block or unblock other users because you are yourself blocked.' );
94 
95  $blocked = $this->getMutableTestUser( [ 'sysop' ] )->getUser();
96  $block = new DatabaseBlock( [
97  'address' => $blocked->getName(),
98  'by' => self::$users['sysop']->getUser()->getId(),
99  'reason' => 'Capriciousness',
100  'timestamp' => '19370101000000',
101  'expiry' => 'infinity',
102  ] );
103  $block->insert();
104 
105  $this->doBlock( [], $blocked );
106  }
107 
108  public function testBlockOfNonexistentUser() {
109  $this->setExpectedException( ApiUsageException::class,
110  'There is no user by the name "Nonexistent". Check your spelling.' );
111 
112  $this->doBlock( [ 'user' => 'Nonexistent' ] );
113  }
114 
115  public function testBlockOfNonexistentUserId() {
116  $id = 948206325;
117  $this->setExpectedException( ApiUsageException::class,
118  "There is no user with ID $id." );
119 
120  $this->assertFalse( User::whoIs( $id ), 'Sanity check' );
121 
122  $this->doBlock( [ 'userid' => $id ] );
123  }
124 
125  public function testBlockWithTag() {
126  ChangeTags::defineTag( 'custom tag' );
127 
128  $this->doBlock( [ 'tags' => 'custom tag' ] );
129 
130  $dbw = wfGetDB( DB_MASTER );
131  $this->assertSame( 1, (int)$dbw->selectField(
132  [ 'change_tag', 'logging', 'change_tag_def' ],
133  'COUNT(*)',
134  [ 'log_type' => 'block', 'ctd_name' => 'custom tag' ],
135  __METHOD__,
136  [],
137  [
138  'change_tag' => [ 'JOIN', 'ct_log_id = log_id' ],
139  'change_tag_def' => [ 'JOIN', 'ctd_id = ct_tag_id' ],
140  ]
141  ) );
142  }
143 
144  public function testBlockWithProhibitedTag() {
145  $this->setExpectedException( ApiUsageException::class,
146  'You do not have permission to apply change tags along with your changes.' );
147 
148  ChangeTags::defineTag( 'custom tag' );
149 
150  $this->setMwGlobals( 'wgRevokePermissions',
151  [ 'user' => [ 'applychangetags' => true ] ] );
152 
153  $this->doBlock( [ 'tags' => 'custom tag' ] );
154  }
155 
156  public function testBlockWithHide() {
157  global $wgGroupPermissions;
158  $newPermissions = $wgGroupPermissions['sysop'];
159  $newPermissions['hideuser'] = true;
160  $this->mergeMwGlobalArrayValue( 'wgGroupPermissions',
161  [ 'sysop' => $newPermissions ] );
162 
163  $res = $this->doBlock( [ 'hidename' => '' ] );
164 
165  $dbw = wfGetDB( DB_MASTER );
166  $this->assertSame( '1', $dbw->selectField(
167  'ipblocks',
168  'ipb_deleted',
169  [ 'ipb_id' => $res[0]['block']['id'] ],
170  __METHOD__
171  ) );
172  }
173 
174  public function testBlockWithProhibitedHide() {
175  $this->setExpectedException( ApiUsageException::class,
176  "You don't have permission to hide user names from the block log." );
177 
178  $this->doBlock( [ 'hidename' => '' ] );
179  }
180 
181  public function testBlockWithEmailBlock() {
182  $this->setMwGlobals( [
183  'wgEnableEmail' => true,
184  'wgEnableUserEmail' => true,
185  'wgSysopEmailBans' => true,
186  ] );
187 
188  $res = $this->doBlock( [ 'noemail' => '' ] );
189 
190  $dbw = wfGetDB( DB_MASTER );
191  $this->assertSame( '1', $dbw->selectField(
192  'ipblocks',
193  'ipb_block_email',
194  [ 'ipb_id' => $res[0]['block']['id'] ],
195  __METHOD__
196  ) );
197  }
198 
200  $this->setMwGlobals( [
201  'wgEnableEmail' => true,
202  'wgEnableUserEmail' => true,
203  'wgSysopEmailBans' => true,
204  ] );
205 
206  $this->setExpectedException( ApiUsageException::class,
207  "You don't have permission to block users from sending email through the wiki." );
208 
209  $this->setMwGlobals( 'wgRevokePermissions',
210  [ 'sysop' => [ 'blockemail' => true ] ] );
211 
212  $this->doBlock( [ 'noemail' => '' ] );
213  }
214 
215  public function testBlockWithExpiry() {
216  $res = $this->doBlock( [ 'expiry' => '1 day' ] );
217 
218  $dbw = wfGetDB( DB_MASTER );
219  $expiry = $dbw->selectField(
220  'ipblocks',
221  'ipb_expiry',
222  [ 'ipb_id' => $res[0]['block']['id'] ],
223  __METHOD__
224  );
225 
226  // Allow flakiness up to one second
227  $this->assertLessThanOrEqual( 1,
228  abs( wfTimestamp( TS_UNIX, $expiry ) - ( time() + 86400 ) ) );
229  }
230 
231  public function testBlockWithInvalidExpiry() {
232  $this->setExpectedException( ApiUsageException::class, "Expiry time invalid." );
233 
234  $this->doBlock( [ 'expiry' => '' ] );
235  }
236 
237  public function testBlockWithoutRestrictions() {
238  $this->setMwGlobals( [
239  'wgEnablePartialBlocks' => true,
240  ] );
241 
242  $this->doBlock();
243 
244  $block = DatabaseBlock::newFromTarget( $this->mUser->getName() );
245 
246  $this->assertTrue( $block->isSitewide() );
247  $this->assertCount( 0, $block->getRestrictions() );
248  }
249 
250  public function testBlockWithRestrictions() {
251  $this->setMwGlobals( [
252  'wgEnablePartialBlocks' => true,
253  ] );
254 
255  $title = 'Foo';
256  $page = $this->getExistingTestPage( $title );
257  $namespace = NS_TALK;
258 
259  $this->doBlock( [
260  'partial' => true,
261  'pagerestrictions' => $title,
262  'namespacerestrictions' => $namespace,
263  ] );
264 
265  $block = DatabaseBlock::newFromTarget( $this->mUser->getName() );
266 
267  $this->assertFalse( $block->isSitewide() );
268  $this->assertCount( 2, $block->getRestrictions() );
269  $this->assertInstanceOf( PageRestriction::class, $block->getRestrictions()[0] );
270  $this->assertEquals( $title, $block->getRestrictions()[0]->getTitle()->getText() );
271  $this->assertInstanceOf( NamespaceRestriction::class, $block->getRestrictions()[1] );
272  $this->assertEquals( $namespace, $block->getRestrictions()[1]->getValue() );
273  }
274 
279  public function testBlockingActionWithNoToken() {
280  $this->doApiRequest(
281  [
282  'action' => 'block',
283  'user' => $this->mUser->getName(),
284  'reason' => 'Some reason',
285  ],
286  null,
287  false,
288  self::$users['sysop']->getUser()
289  );
290  }
291 
296  public function testBlockWithLargeRange() {
297  $tokens = $this->getTokens();
298 
299  $this->doApiRequest(
300  [
301  'action' => 'block',
302  'user' => '127.0.0.1/64',
303  'reason' => 'Some reason',
304  'token' => $tokens['blocktoken'],
305  ],
306  null,
307  false,
308  self::$users['sysop']->getUser()
309  );
310  }
311 
318  $this->setMwGlobals( [
319  'wgEnablePartialBlocks' => true,
320  ] );
321 
322  $tokens = $this->getTokens();
323 
324  $this->doApiRequest(
325  [
326  'action' => 'block',
327  'user' => $this->mUser->getName(),
328  'reason' => 'Some reason',
329  'partial' => true,
330  'pagerestrictions' => 'One|Two|Three|Four|Five|Six|Seven|Eight|Nine|Ten|Eleven',
331  'token' => $tokens['blocktoken'],
332  ],
333  null,
334  false,
335  self::$users['sysop']->getUser()
336  );
337  }
338 
339  public function testRangeBlock() {
340  $this->mUser = User::newFromName( '128.0.0.0/16', false );
341  $this->doBlock();
342  }
343 
348  public function testVeryLargeRangeBlock() {
349  $this->mUser = User::newFromName( '128.0.0.0/1', false );
350  $this->doBlock();
351  }
352 }
static whoIs( $id)
Get the username corresponding to a given user ID.
Definition: User.php:903
testBlockingActionWithNoToken()
ApiUsageException The "token" parameter must be set.
testBlockWithoutRestrictions()
testBlockOfNonexistentUser()
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 & $ret
Definition: hooks.txt:1982
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
testBlockWithProhibitedHide()
This code would result in ircNotify being run twice when an article is and once for brion Hooks can return three possible true was required This is the default since MediaWiki *some string
Definition: hooks.txt:175
doApiRequest(array $params, array $session=null, $appendModule=false, User $user=null, $tokenType=null)
Does the API request and returns the result.
Definition: ApiTestCase.php:62
testBlockByBlockedUser()
A blocked user can&#39;t block.
A DatabaseBlock (unlike a SystemBlock) is stored in the database, may give rise to autoblocks and may...
mergeMwGlobalArrayValue( $name, $values)
Merges the given values into a MW global array variable.
testBlockWithProhibitedEmailBlock()
const DB_MASTER
Definition: defines.php:26
$wgGroupPermissions
Permission keys given to users in each group.
The User object encapsulates all of the user-specific settings (user_id, name, rights, email address, options, last login time).
Definition: User.php:51
insert( $dbw=null)
Insert a block into the block table.
testNormalBlock()
Block by username.
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
getTokenList(TestUser $user, $session=null)
doBlock(array $extraParams=[], User $blocker=null)
static getMutableTestUser( $groups=[])
Convenience method for getting a mutable test user.
$res
Definition: database.txt:21
testBlockWithProhibitedTag()
$params
testBlockingTooManyPageRestrictions()
ApiUsageException Too many values supplied for parameter "pagerestrictions".
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not null
Definition: hooks.txt:780
$tokens
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:925
setMwGlobals( $pairs, $value=null)
Sets a global, maintaining a stashed version of the previous global to be restored in tearDown...
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
static defineTag( $tag)
Set ctd_user_defined = 1 in change_tag_def without checking that the tag name is valid.
Definition: ChangeTags.php:881
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
testVeryLargeRangeBlock()
ApiUsageException Range blocks larger than /16 are not allowed.
testBlockById()
Block by user ID.
testBlockWithLargeRange()
ApiUsageException Invalid value "127.0.0.1/64" for user parameter "user".
const NS_TALK
Definition: Defines.php:61
API Database medium.
testBlockWithInvalidExpiry()
getExistingTestPage( $title=null)
Returns a WikiPage representing an existing page.
static newFromName( $name, $validate='valid')
Static factory method for creation from username.
Definition: User.php:594
testBlockOfNonexistentUserId()
testBlockWithRestrictions()