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->resetServices();
154 
155  $this->doBlock( [ 'tags' => 'custom tag' ] );
156  }
157 
158  public function testBlockWithHide() {
159  global $wgGroupPermissions;
160  $newPermissions = $wgGroupPermissions['sysop'];
161  $newPermissions['hideuser'] = true;
162  $this->mergeMwGlobalArrayValue( 'wgGroupPermissions',
163  [ 'sysop' => $newPermissions ] );
164 
165  $this->resetServices();
166  $res = $this->doBlock( [ 'hidename' => '' ] );
167 
168  $dbw = wfGetDB( DB_MASTER );
169  $this->assertSame( '1', $dbw->selectField(
170  'ipblocks',
171  'ipb_deleted',
172  [ 'ipb_id' => $res[0]['block']['id'] ],
173  __METHOD__
174  ) );
175  }
176 
177  public function testBlockWithProhibitedHide() {
178  $this->setExpectedException( ApiUsageException::class,
179  "You don't have permission to hide user names from the block log." );
180 
181  $this->doBlock( [ 'hidename' => '' ] );
182  }
183 
184  public function testBlockWithEmailBlock() {
185  $this->setMwGlobals( [
186  'wgEnableEmail' => true,
187  'wgEnableUserEmail' => true,
188  'wgSysopEmailBans' => true,
189  ] );
190 
191  $res = $this->doBlock( [ 'noemail' => '' ] );
192 
193  $dbw = wfGetDB( DB_MASTER );
194  $this->assertSame( '1', $dbw->selectField(
195  'ipblocks',
196  'ipb_block_email',
197  [ 'ipb_id' => $res[0]['block']['id'] ],
198  __METHOD__
199  ) );
200  }
201 
203  $this->setMwGlobals( [
204  'wgEnableEmail' => true,
205  'wgEnableUserEmail' => true,
206  'wgSysopEmailBans' => true,
207  ] );
208 
209  $this->setExpectedException( ApiUsageException::class,
210  "You don't have permission to block users from sending email through the wiki." );
211 
212  $this->setMwGlobals( 'wgRevokePermissions',
213  [ 'sysop' => [ 'blockemail' => true ] ] );
214 
215  $this->resetServices();
216 
217  $this->doBlock( [ 'noemail' => '' ] );
218  }
219 
220  public function testBlockWithExpiry() {
221  $res = $this->doBlock( [ 'expiry' => '1 day' ] );
222 
223  $dbw = wfGetDB( DB_MASTER );
224  $expiry = $dbw->selectField(
225  'ipblocks',
226  'ipb_expiry',
227  [ 'ipb_id' => $res[0]['block']['id'] ],
228  __METHOD__
229  );
230 
231  // Allow flakiness up to one second
232  $this->assertLessThanOrEqual( 1,
233  abs( wfTimestamp( TS_UNIX, $expiry ) - ( time() + 86400 ) ) );
234  }
235 
236  public function testBlockWithInvalidExpiry() {
237  $this->setExpectedException( ApiUsageException::class, "Expiry time invalid." );
238 
239  $this->doBlock( [ 'expiry' => '' ] );
240  }
241 
242  public function testBlockWithoutRestrictions() {
243  $this->setMwGlobals( [
244  'wgEnablePartialBlocks' => true,
245  ] );
246 
247  $this->doBlock();
248 
249  $block = DatabaseBlock::newFromTarget( $this->mUser->getName() );
250 
251  $this->assertTrue( $block->isSitewide() );
252  $this->assertCount( 0, $block->getRestrictions() );
253  }
254 
255  public function testBlockWithRestrictions() {
256  $this->setMwGlobals( [
257  'wgEnablePartialBlocks' => true,
258  ] );
259 
260  $title = 'Foo';
261  $page = $this->getExistingTestPage( $title );
262  $namespace = NS_TALK;
263 
264  $this->doBlock( [
265  'partial' => true,
266  'pagerestrictions' => $title,
267  'namespacerestrictions' => $namespace,
268  'allowusertalk' => true,
269  ] );
270 
271  $block = DatabaseBlock::newFromTarget( $this->mUser->getName() );
272 
273  $this->assertFalse( $block->isSitewide() );
274  $this->assertCount( 2, $block->getRestrictions() );
275  $this->assertInstanceOf( PageRestriction::class, $block->getRestrictions()[0] );
276  $this->assertEquals( $title, $block->getRestrictions()[0]->getTitle()->getText() );
277  $this->assertInstanceOf( NamespaceRestriction::class, $block->getRestrictions()[1] );
278  $this->assertEquals( $namespace, $block->getRestrictions()[1]->getValue() );
279  }
280 
285  public function testBlockingActionWithNoToken() {
286  $this->doApiRequest(
287  [
288  'action' => 'block',
289  'user' => $this->mUser->getName(),
290  'reason' => 'Some reason',
291  ],
292  null,
293  false,
294  self::$users['sysop']->getUser()
295  );
296  }
297 
302  public function testBlockWithLargeRange() {
303  $tokens = $this->getTokens();
304 
305  $this->doApiRequest(
306  [
307  'action' => 'block',
308  'user' => '127.0.0.1/64',
309  'reason' => 'Some reason',
310  'token' => $tokens['blocktoken'],
311  ],
312  null,
313  false,
314  self::$users['sysop']->getUser()
315  );
316  }
317 
324  $this->setMwGlobals( [
325  'wgEnablePartialBlocks' => true,
326  ] );
327 
328  $tokens = $this->getTokens();
329 
330  $this->doApiRequest(
331  [
332  'action' => 'block',
333  'user' => $this->mUser->getName(),
334  'reason' => 'Some reason',
335  'partial' => true,
336  'pagerestrictions' => 'One|Two|Three|Four|Five|Six|Seven|Eight|Nine|Ten|Eleven',
337  'token' => $tokens['blocktoken'],
338  ],
339  null,
340  false,
341  self::$users['sysop']->getUser()
342  );
343  }
344 
345  public function testRangeBlock() {
346  $this->mUser = User::newFromName( '128.0.0.0/16', false );
347  $this->doBlock();
348  }
349 
354  public function testVeryLargeRangeBlock() {
355  $this->mUser = User::newFromName( '128.0.0.0/1', false );
356  $this->doBlock();
357  }
358 }
insert(IDatabase $dbw=null)
Insert a block into the block table.
static whoIs( $id)
Get the username corresponding to a given user ID.
Definition: User.php:844
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:1972
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...
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
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)
$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:767
$tokens
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:912
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:921
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()
static newFromName( $name, $validate='valid')
Static factory method for creation from username.
Definition: User.php:535
testBlockOfNonexistentUserId()
testBlockWithRestrictions()