Completed
Branch master (9259dd)
by
unknown
27:26
created

WikiPage::doUpdateRestrictions()   F

Complexity

Conditions 36
Paths > 20000

Size

Total Lines 241
Code Lines 152

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 36
eloc 152
nc 52529
nop 6
dl 0
loc 241
rs 2
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * Base representation for a MediaWiki page.
4
 *
5
 * This program is free software; you can redistribute it and/or modify
6
 * it under the terms of the GNU General Public License as published by
7
 * the Free Software Foundation; either version 2 of the License, or
8
 * (at your option) any later version.
9
 *
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
 * GNU General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License along
16
 * with this program; if not, write to the Free Software Foundation, Inc.,
17
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18
 * http://www.gnu.org/copyleft/gpl.html
19
 *
20
 * @file
21
 */
22
23
/**
24
 * Class representing a MediaWiki article and history.
25
 *
26
 * Some fields are public only for backwards-compatibility. Use accessors.
27
 * In the past, this class was part of Article.php and everything was public.
28
 */
29
class WikiPage implements Page, IDBAccessObject {
30
	// Constants for $mDataLoadedFrom and related
31
32
	/**
33
	 * @var Title
34
	 */
35
	public $mTitle = null;
36
37
	/**@{{
38
	 * @protected
39
	 */
40
	public $mDataLoaded = false;         // !< Boolean
41
	public $mIsRedirect = false;         // !< Boolean
42
	public $mLatest = false;             // !< Integer (false means "not loaded")
43
	/**@}}*/
44
45
	/** @var stdClass Map of cache fields (text, parser output, ect) for a proposed/new edit */
46
	public $mPreparedEdit = false;
47
48
	/**
49
	 * @var int
50
	 */
51
	protected $mId = null;
52
53
	/**
54
	 * @var int One of the READ_* constants
55
	 */
56
	protected $mDataLoadedFrom = self::READ_NONE;
57
58
	/**
59
	 * @var Title
60
	 */
61
	protected $mRedirectTarget = null;
62
63
	/**
64
	 * @var Revision
65
	 */
66
	protected $mLastRevision = null;
67
68
	/**
69
	 * @var string Timestamp of the current revision or empty string if not loaded
70
	 */
71
	protected $mTimestamp = '';
72
73
	/**
74
	 * @var string
75
	 */
76
	protected $mTouched = '19700101000000';
77
78
	/**
79
	 * @var string
80
	 */
81
	protected $mLinksUpdated = '19700101000000';
82
83
	/**
84
	 * Constructor and clear the article
85
	 * @param Title $title Reference to a Title object.
86
	 */
87
	public function __construct( Title $title ) {
88
		$this->mTitle = $title;
89
	}
90
91
	/**
92
	 * Create a WikiPage object of the appropriate class for the given title.
93
	 *
94
	 * @param Title $title
95
	 *
96
	 * @throws MWException
97
	 * @return WikiPage|WikiCategoryPage|WikiFilePage
98
	 */
99
	public static function factory( Title $title ) {
100
		$ns = $title->getNamespace();
101
102
		if ( $ns == NS_MEDIA ) {
103
			throw new MWException( "NS_MEDIA is a virtual namespace; use NS_FILE." );
104
		} elseif ( $ns < 0 ) {
105
			throw new MWException( "Invalid or virtual namespace $ns given." );
106
		}
107
108
		switch ( $ns ) {
109
			case NS_FILE:
110
				$page = new WikiFilePage( $title );
111
				break;
112
			case NS_CATEGORY:
113
				$page = new WikiCategoryPage( $title );
114
				break;
115
			default:
116
				$page = new WikiPage( $title );
117
		}
118
119
		return $page;
120
	}
121
122
	/**
123
	 * Constructor from a page id
124
	 *
125
	 * @param int $id Article ID to load
126
	 * @param string|int $from One of the following values:
127
	 *        - "fromdb" or WikiPage::READ_NORMAL to select from a slave database
128
	 *        - "fromdbmaster" or WikiPage::READ_LATEST to select from the master database
129
	 *
130
	 * @return WikiPage|null
131
	 */
132
	public static function newFromID( $id, $from = 'fromdb' ) {
133
		// page id's are never 0 or negative, see bug 61166
134
		if ( $id < 1 ) {
135
			return null;
136
		}
137
138
		$from = self::convertSelectType( $from );
139
		$db = wfGetDB( $from === self::READ_LATEST ? DB_MASTER : DB_SLAVE );
140
		$row = $db->selectRow(
141
			'page', self::selectFields(), [ 'page_id' => $id ], __METHOD__ );
142
		if ( !$row ) {
143
			return null;
144
		}
145
		return self::newFromRow( $row, $from );
0 ignored issues
show
Bug introduced by
It seems like $row defined by $db->selectRow('page', s...d' => $id), __METHOD__) on line 140 can also be of type boolean; however, WikiPage::newFromRow() does only seem to accept object, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
Bug introduced by
It seems like $from defined by self::convertSelectType($from) on line 138 can also be of type object; however, WikiPage::newFromRow() does only seem to accept string|integer, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
146
	}
147
148
	/**
149
	 * Constructor from a database row
150
	 *
151
	 * @since 1.20
152
	 * @param object $row Database row containing at least fields returned by selectFields().
153
	 * @param string|int $from Source of $data:
154
	 *        - "fromdb" or WikiPage::READ_NORMAL: from a slave DB
155
	 *        - "fromdbmaster" or WikiPage::READ_LATEST: from the master DB
156
	 *        - "forupdate" or WikiPage::READ_LOCKING: from the master DB using SELECT FOR UPDATE
157
	 * @return WikiPage
158
	 */
159
	public static function newFromRow( $row, $from = 'fromdb' ) {
160
		$page = self::factory( Title::newFromRow( $row ) );
161
		$page->loadFromRow( $row, $from );
162
		return $page;
163
	}
164
165
	/**
166
	 * Convert 'fromdb', 'fromdbmaster' and 'forupdate' to READ_* constants.
167
	 *
168
	 * @param object|string|int $type
169
	 * @return mixed
170
	 */
171
	private static function convertSelectType( $type ) {
172
		switch ( $type ) {
173
		case 'fromdb':
174
			return self::READ_NORMAL;
175
		case 'fromdbmaster':
176
			return self::READ_LATEST;
177
		case 'forupdate':
178
			return self::READ_LOCKING;
179
		default:
180
			// It may already be an integer or whatever else
181
			return $type;
182
		}
183
	}
184
185
	/**
186
	 * @todo Move this UI stuff somewhere else
187
	 *
188
	 * @see ContentHandler::getActionOverrides
189
	 */
190
	public function getActionOverrides() {
191
		return $this->getContentHandler()->getActionOverrides();
192
	}
193
194
	/**
195
	 * Returns the ContentHandler instance to be used to deal with the content of this WikiPage.
196
	 *
197
	 * Shorthand for ContentHandler::getForModelID( $this->getContentModel() );
198
	 *
199
	 * @return ContentHandler
200
	 *
201
	 * @since 1.21
202
	 */
203
	public function getContentHandler() {
204
		return ContentHandler::getForModelID( $this->getContentModel() );
205
	}
206
207
	/**
208
	 * Get the title object of the article
209
	 * @return Title Title object of this page
210
	 */
211
	public function getTitle() {
212
		return $this->mTitle;
213
	}
214
215
	/**
216
	 * Clear the object
217
	 * @return void
218
	 */
219
	public function clear() {
220
		$this->mDataLoaded = false;
221
		$this->mDataLoadedFrom = self::READ_NONE;
222
223
		$this->clearCacheFields();
224
	}
225
226
	/**
227
	 * Clear the object cache fields
228
	 * @return void
229
	 */
230
	protected function clearCacheFields() {
231
		$this->mId = null;
232
		$this->mRedirectTarget = null; // Title object if set
233
		$this->mLastRevision = null; // Latest revision
234
		$this->mTouched = '19700101000000';
235
		$this->mLinksUpdated = '19700101000000';
236
		$this->mTimestamp = '';
237
		$this->mIsRedirect = false;
238
		$this->mLatest = false;
239
		// Bug 57026: do not clear mPreparedEdit since prepareTextForEdit() already checks
240
		// the requested rev ID and content against the cached one for equality. For most
241
		// content types, the output should not change during the lifetime of this cache.
242
		// Clearing it can cause extra parses on edit for no reason.
243
	}
244
245
	/**
246
	 * Clear the mPreparedEdit cache field, as may be needed by mutable content types
247
	 * @return void
248
	 * @since 1.23
249
	 */
250
	public function clearPreparedEdit() {
251
		$this->mPreparedEdit = false;
0 ignored issues
show
Documentation Bug introduced by
It seems like false of type false is incompatible with the declared type object<stdClass> of property $mPreparedEdit.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
252
	}
253
254
	/**
255
	 * Return the list of revision fields that should be selected to create
256
	 * a new page.
257
	 *
258
	 * @return array
259
	 */
260
	public static function selectFields() {
261
		global $wgContentHandlerUseDB, $wgPageLanguageUseDB;
262
263
		$fields = [
264
			'page_id',
265
			'page_namespace',
266
			'page_title',
267
			'page_restrictions',
268
			'page_is_redirect',
269
			'page_is_new',
270
			'page_random',
271
			'page_touched',
272
			'page_links_updated',
273
			'page_latest',
274
			'page_len',
275
		];
276
277
		if ( $wgContentHandlerUseDB ) {
278
			$fields[] = 'page_content_model';
279
		}
280
281
		if ( $wgPageLanguageUseDB ) {
282
			$fields[] = 'page_lang';
283
		}
284
285
		return $fields;
286
	}
287
288
	/**
289
	 * Fetch a page record with the given conditions
290
	 * @param IDatabase $dbr
291
	 * @param array $conditions
292
	 * @param array $options
293
	 * @return object|bool Database result resource, or false on failure
294
	 */
295
	protected function pageData( $dbr, $conditions, $options = [] ) {
296
		$fields = self::selectFields();
297
298
		Hooks::run( 'ArticlePageDataBefore', [ &$this, &$fields ] );
299
300
		$row = $dbr->selectRow( 'page', $fields, $conditions, __METHOD__, $options );
301
302
		Hooks::run( 'ArticlePageDataAfter', [ &$this, &$row ] );
303
304
		return $row;
305
	}
306
307
	/**
308
	 * Fetch a page record matching the Title object's namespace and title
309
	 * using a sanitized title string
310
	 *
311
	 * @param IDatabase $dbr
312
	 * @param Title $title
313
	 * @param array $options
314
	 * @return object|bool Database result resource, or false on failure
315
	 */
316
	public function pageDataFromTitle( $dbr, $title, $options = [] ) {
317
		return $this->pageData( $dbr, [
318
			'page_namespace' => $title->getNamespace(),
319
			'page_title' => $title->getDBkey() ], $options );
320
	}
321
322
	/**
323
	 * Fetch a page record matching the requested ID
324
	 *
325
	 * @param IDatabase $dbr
326
	 * @param int $id
327
	 * @param array $options
328
	 * @return object|bool Database result resource, or false on failure
329
	 */
330
	public function pageDataFromId( $dbr, $id, $options = [] ) {
331
		return $this->pageData( $dbr, [ 'page_id' => $id ], $options );
332
	}
333
334
	/**
335
	 * Load the object from a given source by title
336
	 *
337
	 * @param object|string|int $from One of the following:
338
	 *   - A DB query result object.
339
	 *   - "fromdb" or WikiPage::READ_NORMAL to get from a slave DB.
340
	 *   - "fromdbmaster" or WikiPage::READ_LATEST to get from the master DB.
341
	 *   - "forupdate"  or WikiPage::READ_LOCKING to get from the master DB
342
	 *     using SELECT FOR UPDATE.
343
	 *
344
	 * @return void
345
	 */
346
	public function loadPageData( $from = 'fromdb' ) {
347
		$from = self::convertSelectType( $from );
348
		if ( is_int( $from ) && $from <= $this->mDataLoadedFrom ) {
349
			// We already have the data from the correct location, no need to load it twice.
350
			return;
351
		}
352
353
		if ( is_int( $from ) ) {
354
			list( $index, $opts ) = DBAccessObjectUtils::getDBOptions( $from );
355
			$data = $this->pageDataFromTitle( wfGetDB( $index ), $this->mTitle, $opts );
356
357
			if ( !$data
358
				&& $index == DB_SLAVE
359
				&& wfGetLB()->getServerCount() > 1
0 ignored issues
show
Deprecated Code introduced by
The function wfGetLB() has been deprecated with message: since 1.27, use MediaWikiServices::getDBLoadBalancer() or MediaWikiServices::getDBLoadBalancerFactory() instead.

This function has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed from the class and what other function to use instead.

Loading history...
360
				&& wfGetLB()->hasOrMadeRecentMasterChanges()
0 ignored issues
show
Deprecated Code introduced by
The function wfGetLB() has been deprecated with message: since 1.27, use MediaWikiServices::getDBLoadBalancer() or MediaWikiServices::getDBLoadBalancerFactory() instead.

This function has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed from the class and what other function to use instead.

Loading history...
361
			) {
362
				$from = self::READ_LATEST;
363
				list( $index, $opts ) = DBAccessObjectUtils::getDBOptions( $from );
364
				$data = $this->pageDataFromTitle( wfGetDB( $index ), $this->mTitle, $opts );
365
			}
366
		} else {
367
			// No idea from where the caller got this data, assume slave database.
368
			$data = $from;
369
			$from = self::READ_NORMAL;
370
		}
371
372
		$this->loadFromRow( $data, $from );
0 ignored issues
show
Bug introduced by
It seems like $data defined by $from on line 368 can also be of type string; however, WikiPage::loadFromRow() does only seem to accept object|boolean, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
373
	}
374
375
	/**
376
	 * Load the object from a database row
377
	 *
378
	 * @since 1.20
379
	 * @param object|bool $data DB row containing fields returned by selectFields() or false
380
	 * @param string|int $from One of the following:
381
	 *        - "fromdb" or WikiPage::READ_NORMAL if the data comes from a slave DB
382
	 *        - "fromdbmaster" or WikiPage::READ_LATEST if the data comes from the master DB
383
	 *        - "forupdate"  or WikiPage::READ_LOCKING if the data comes from
384
	 *          the master DB using SELECT FOR UPDATE
385
	 */
386
	public function loadFromRow( $data, $from ) {
387
		$lc = LinkCache::singleton();
0 ignored issues
show
Deprecated Code introduced by
The method LinkCache::singleton() has been deprecated with message: since 1.28, use MediaWikiServices instead

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
388
		$lc->clearLink( $this->mTitle );
389
390
		if ( $data ) {
391
			$lc->addGoodLinkObjFromRow( $this->mTitle, $data );
392
393
			$this->mTitle->loadFromRow( $data );
0 ignored issues
show
Bug introduced by
It seems like $data defined by parameter $data on line 386 can also be of type object; however, Title::loadFromRow() does only seem to accept object<stdClass>|boolean, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
394
395
			// Old-fashioned restrictions
396
			$this->mTitle->loadRestrictions( $data->page_restrictions );
397
398
			$this->mId = intval( $data->page_id );
399
			$this->mTouched = wfTimestamp( TS_MW, $data->page_touched );
0 ignored issues
show
Documentation Bug introduced by
It seems like wfTimestamp(TS_MW, $data->page_touched) can also be of type false. However, the property $mTouched is declared as type string. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
400
			$this->mLinksUpdated = wfTimestampOrNull( TS_MW, $data->page_links_updated );
0 ignored issues
show
Documentation Bug introduced by
It seems like wfTimestampOrNull(TS_MW,...ta->page_links_updated) can also be of type false. However, the property $mLinksUpdated is declared as type string. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
401
			$this->mIsRedirect = intval( $data->page_is_redirect );
0 ignored issues
show
Documentation Bug introduced by
The property $mIsRedirect was declared of type boolean, but intval($data->page_is_redirect) is of type integer. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
402
			$this->mLatest = intval( $data->page_latest );
0 ignored issues
show
Documentation Bug introduced by
The property $mLatest was declared of type boolean, but intval($data->page_latest) is of type integer. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
403
			// Bug 37225: $latest may no longer match the cached latest Revision object.
404
			// Double-check the ID of any cached latest Revision object for consistency.
405
			if ( $this->mLastRevision && $this->mLastRevision->getId() != $this->mLatest ) {
406
				$this->mLastRevision = null;
407
				$this->mTimestamp = '';
408
			}
409
		} else {
410
			$lc->addBadLinkObj( $this->mTitle );
411
412
			$this->mTitle->loadFromRow( false );
413
414
			$this->clearCacheFields();
415
416
			$this->mId = 0;
417
		}
418
419
		$this->mDataLoaded = true;
420
		$this->mDataLoadedFrom = self::convertSelectType( $from );
0 ignored issues
show
Documentation Bug introduced by
It seems like self::convertSelectType($from) can also be of type object or string. However, the property $mDataLoadedFrom is declared as type integer. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
421
	}
422
423
	/**
424
	 * @return int Page ID
425
	 */
426
	public function getId() {
427
		if ( !$this->mDataLoaded ) {
428
			$this->loadPageData();
429
		}
430
		return $this->mId;
431
	}
432
433
	/**
434
	 * @return bool Whether or not the page exists in the database
435
	 */
436
	public function exists() {
437
		if ( !$this->mDataLoaded ) {
438
			$this->loadPageData();
439
		}
440
		return $this->mId > 0;
441
	}
442
443
	/**
444
	 * Check if this page is something we're going to be showing
445
	 * some sort of sensible content for. If we return false, page
446
	 * views (plain action=view) will return an HTTP 404 response,
447
	 * so spiders and robots can know they're following a bad link.
448
	 *
449
	 * @return bool
450
	 */
451
	public function hasViewableContent() {
452
		return $this->exists() || $this->mTitle->isAlwaysKnown();
453
	}
454
455
	/**
456
	 * Tests if the article content represents a redirect
457
	 *
458
	 * @return bool
459
	 */
460
	public function isRedirect() {
461
		if ( !$this->mDataLoaded ) {
462
			$this->loadPageData();
463
		}
464
465
		return (bool)$this->mIsRedirect;
466
	}
467
468
	/**
469
	 * Returns the page's content model id (see the CONTENT_MODEL_XXX constants).
470
	 *
471
	 * Will use the revisions actual content model if the page exists,
472
	 * and the page's default if the page doesn't exist yet.
473
	 *
474
	 * @return string
475
	 *
476
	 * @since 1.21
477
	 */
478
	public function getContentModel() {
479
		if ( $this->exists() ) {
480
			// look at the revision's actual content model
481
			$rev = $this->getRevision();
482
483
			if ( $rev !== null ) {
484
				return $rev->getContentModel();
485
			} else {
486
				$title = $this->mTitle->getPrefixedDBkey();
487
				wfWarn( "Page $title exists but has no (visible) revisions!" );
488
			}
489
		}
490
491
		// use the default model for this page
492
		return $this->mTitle->getContentModel();
493
	}
494
495
	/**
496
	 * Loads page_touched and returns a value indicating if it should be used
497
	 * @return bool True if not a redirect
498
	 */
499
	public function checkTouched() {
500
		if ( !$this->mDataLoaded ) {
501
			$this->loadPageData();
502
		}
503
		return !$this->mIsRedirect;
504
	}
505
506
	/**
507
	 * Get the page_touched field
508
	 * @return string Containing GMT timestamp
509
	 */
510
	public function getTouched() {
511
		if ( !$this->mDataLoaded ) {
512
			$this->loadPageData();
513
		}
514
		return $this->mTouched;
515
	}
516
517
	/**
518
	 * Get the page_links_updated field
519
	 * @return string|null Containing GMT timestamp
520
	 */
521
	public function getLinksTimestamp() {
522
		if ( !$this->mDataLoaded ) {
523
			$this->loadPageData();
524
		}
525
		return $this->mLinksUpdated;
526
	}
527
528
	/**
529
	 * Get the page_latest field
530
	 * @return int The rev_id of current revision
531
	 */
532
	public function getLatest() {
533
		if ( !$this->mDataLoaded ) {
534
			$this->loadPageData();
535
		}
536
		return (int)$this->mLatest;
537
	}
538
539
	/**
540
	 * Get the Revision object of the oldest revision
541
	 * @return Revision|null
542
	 */
543
	public function getOldestRevision() {
544
545
		// Try using the slave database first, then try the master
546
		$continue = 2;
547
		$db = wfGetDB( DB_SLAVE );
548
		$revSelectFields = Revision::selectFields();
549
550
		$row = null;
551
		while ( $continue ) {
552
			$row = $db->selectRow(
553
				[ 'page', 'revision' ],
554
				$revSelectFields,
555
				[
556
					'page_namespace' => $this->mTitle->getNamespace(),
557
					'page_title' => $this->mTitle->getDBkey(),
558
					'rev_page = page_id'
559
				],
560
				__METHOD__,
561
				[
562
					'ORDER BY' => 'rev_timestamp ASC'
563
				]
564
			);
565
566
			if ( $row ) {
567
				$continue = 0;
568
			} else {
569
				$db = wfGetDB( DB_MASTER );
570
				$continue--;
571
			}
572
		}
573
574
		return $row ? Revision::newFromRow( $row ) : null;
0 ignored issues
show
Bug introduced by
It seems like $row can also be of type boolean; however, Revision::newFromRow() does only seem to accept object, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
575
	}
576
577
	/**
578
	 * Loads everything except the text
579
	 * This isn't necessary for all uses, so it's only done if needed.
580
	 */
581
	protected function loadLastEdit() {
582
		if ( $this->mLastRevision !== null ) {
583
			return; // already loaded
584
		}
585
586
		$latest = $this->getLatest();
587
		if ( !$latest ) {
588
			return; // page doesn't exist or is missing page_latest info
589
		}
590
591
		if ( $this->mDataLoadedFrom == self::READ_LOCKING ) {
592
			// Bug 37225: if session S1 loads the page row FOR UPDATE, the result always
593
			// includes the latest changes committed. This is true even within REPEATABLE-READ
594
			// transactions, where S1 normally only sees changes committed before the first S1
595
			// SELECT. Thus we need S1 to also gets the revision row FOR UPDATE; otherwise, it
596
			// may not find it since a page row UPDATE and revision row INSERT by S2 may have
597
			// happened after the first S1 SELECT.
598
			// http://dev.mysql.com/doc/refman/5.0/en/set-transaction.html#isolevel_repeatable-read
599
			$flags = Revision::READ_LOCKING;
600
		} elseif ( $this->mDataLoadedFrom == self::READ_LATEST ) {
601
			// Bug T93976: if page_latest was loaded from the master, fetch the
602
			// revision from there as well, as it may not exist yet on a slave DB.
603
			// Also, this keeps the queries in the same REPEATABLE-READ snapshot.
604
			$flags = Revision::READ_LATEST;
605
		} else {
606
			$flags = 0;
607
		}
608
		$revision = Revision::newFromPageId( $this->getId(), $latest, $flags );
609
		if ( $revision ) { // sanity
610
			$this->setLastEdit( $revision );
611
		}
612
	}
613
614
	/**
615
	 * Set the latest revision
616
	 * @param Revision $revision
617
	 */
618
	protected function setLastEdit( Revision $revision ) {
619
		$this->mLastRevision = $revision;
620
		$this->mTimestamp = $revision->getTimestamp();
0 ignored issues
show
Documentation Bug introduced by
It seems like $revision->getTimestamp() can also be of type false. However, the property $mTimestamp is declared as type string. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
621
	}
622
623
	/**
624
	 * Get the latest revision
625
	 * @return Revision|null
626
	 */
627
	public function getRevision() {
628
		$this->loadLastEdit();
629
		if ( $this->mLastRevision ) {
630
			return $this->mLastRevision;
631
		}
632
		return null;
633
	}
634
635
	/**
636
	 * Get the content of the current revision. No side-effects...
637
	 *
638
	 * @param int $audience One of:
639
	 *   Revision::FOR_PUBLIC       to be displayed to all users
640
	 *   Revision::FOR_THIS_USER    to be displayed to $wgUser
641
	 *   Revision::RAW              get the text regardless of permissions
642
	 * @param User $user User object to check for, only if FOR_THIS_USER is passed
643
	 *   to the $audience parameter
644
	 * @return Content|null The content of the current revision
645
	 *
646
	 * @since 1.21
647
	 */
648 View Code Duplication
	public function getContent( $audience = Revision::FOR_PUBLIC, User $user = null ) {
649
		$this->loadLastEdit();
650
		if ( $this->mLastRevision ) {
651
			return $this->mLastRevision->getContent( $audience, $user );
652
		}
653
		return null;
654
	}
655
656
	/**
657
	 * Get the text of the current revision. No side-effects...
658
	 *
659
	 * @param int $audience One of:
660
	 *   Revision::FOR_PUBLIC       to be displayed to all users
661
	 *   Revision::FOR_THIS_USER    to be displayed to the given user
662
	 *   Revision::RAW              get the text regardless of permissions
663
	 * @param User $user User object to check for, only if FOR_THIS_USER is passed
664
	 *   to the $audience parameter
665
	 * @return string|bool The text of the current revision
666
	 * @deprecated since 1.21, getContent() should be used instead.
667
	 */
668
	public function getText( $audience = Revision::FOR_PUBLIC, User $user = null ) {
669
		ContentHandler::deprecated( __METHOD__, '1.21' );
670
671
		$this->loadLastEdit();
672
		if ( $this->mLastRevision ) {
673
			return $this->mLastRevision->getText( $audience, $user );
0 ignored issues
show
Deprecated Code introduced by
The method Revision::getText() has been deprecated with message: since 1.21, use getContent() instead

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
674
		}
675
		return false;
676
	}
677
678
	/**
679
	 * @return string MW timestamp of last article revision
680
	 */
681
	public function getTimestamp() {
682
		// Check if the field has been filled by WikiPage::setTimestamp()
683
		if ( !$this->mTimestamp ) {
684
			$this->loadLastEdit();
685
		}
686
687
		return wfTimestamp( TS_MW, $this->mTimestamp );
688
	}
689
690
	/**
691
	 * Set the page timestamp (use only to avoid DB queries)
692
	 * @param string $ts MW timestamp of last article revision
693
	 * @return void
694
	 */
695
	public function setTimestamp( $ts ) {
696
		$this->mTimestamp = wfTimestamp( TS_MW, $ts );
0 ignored issues
show
Documentation Bug introduced by
It seems like wfTimestamp(TS_MW, $ts) can also be of type false. However, the property $mTimestamp is declared as type string. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
697
	}
698
699
	/**
700
	 * @param int $audience One of:
701
	 *   Revision::FOR_PUBLIC       to be displayed to all users
702
	 *   Revision::FOR_THIS_USER    to be displayed to the given user
703
	 *   Revision::RAW              get the text regardless of permissions
704
	 * @param User $user User object to check for, only if FOR_THIS_USER is passed
705
	 *   to the $audience parameter
706
	 * @return int User ID for the user that made the last article revision
707
	 */
708 View Code Duplication
	public function getUser( $audience = Revision::FOR_PUBLIC, User $user = null ) {
709
		$this->loadLastEdit();
710
		if ( $this->mLastRevision ) {
711
			return $this->mLastRevision->getUser( $audience, $user );
712
		} else {
713
			return -1;
714
		}
715
	}
716
717
	/**
718
	 * Get the User object of the user who created the page
719
	 * @param int $audience One of:
720
	 *   Revision::FOR_PUBLIC       to be displayed to all users
721
	 *   Revision::FOR_THIS_USER    to be displayed to the given user
722
	 *   Revision::RAW              get the text regardless of permissions
723
	 * @param User $user User object to check for, only if FOR_THIS_USER is passed
724
	 *   to the $audience parameter
725
	 * @return User|null
726
	 */
727
	public function getCreator( $audience = Revision::FOR_PUBLIC, User $user = null ) {
728
		$revision = $this->getOldestRevision();
729
		if ( $revision ) {
730
			$userName = $revision->getUserText( $audience, $user );
731
			return User::newFromName( $userName, false );
0 ignored issues
show
Bug introduced by
It seems like $userName defined by $revision->getUserText($audience, $user) on line 730 can also be of type boolean; however, User::newFromName() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
732
		} else {
733
			return null;
734
		}
735
	}
736
737
	/**
738
	 * @param int $audience One of:
739
	 *   Revision::FOR_PUBLIC       to be displayed to all users
740
	 *   Revision::FOR_THIS_USER    to be displayed to the given user
741
	 *   Revision::RAW              get the text regardless of permissions
742
	 * @param User $user User object to check for, only if FOR_THIS_USER is passed
743
	 *   to the $audience parameter
744
	 * @return string Username of the user that made the last article revision
745
	 */
746 View Code Duplication
	public function getUserText( $audience = Revision::FOR_PUBLIC, User $user = null ) {
747
		$this->loadLastEdit();
748
		if ( $this->mLastRevision ) {
749
			return $this->mLastRevision->getUserText( $audience, $user );
750
		} else {
751
			return '';
752
		}
753
	}
754
755
	/**
756
	 * @param int $audience One of:
757
	 *   Revision::FOR_PUBLIC       to be displayed to all users
758
	 *   Revision::FOR_THIS_USER    to be displayed to the given user
759
	 *   Revision::RAW              get the text regardless of permissions
760
	 * @param User $user User object to check for, only if FOR_THIS_USER is passed
761
	 *   to the $audience parameter
762
	 * @return string Comment stored for the last article revision
763
	 */
764 View Code Duplication
	public function getComment( $audience = Revision::FOR_PUBLIC, User $user = null ) {
765
		$this->loadLastEdit();
766
		if ( $this->mLastRevision ) {
767
			return $this->mLastRevision->getComment( $audience, $user );
768
		} else {
769
			return '';
770
		}
771
	}
772
773
	/**
774
	 * Returns true if last revision was marked as "minor edit"
775
	 *
776
	 * @return bool Minor edit indicator for the last article revision.
777
	 */
778
	public function getMinorEdit() {
779
		$this->loadLastEdit();
780
		if ( $this->mLastRevision ) {
781
			return $this->mLastRevision->isMinor();
782
		} else {
783
			return false;
784
		}
785
	}
786
787
	/**
788
	 * Determine whether a page would be suitable for being counted as an
789
	 * article in the site_stats table based on the title & its content
790
	 *
791
	 * @param object|bool $editInfo (false): object returned by prepareTextForEdit(),
792
	 *   if false, the current database state will be used
793
	 * @return bool
794
	 */
795
	public function isCountable( $editInfo = false ) {
796
		global $wgArticleCountMethod;
797
798
		if ( !$this->mTitle->isContentPage() ) {
799
			return false;
800
		}
801
802
		if ( $editInfo ) {
803
			$content = $editInfo->pstContent;
804
		} else {
805
			$content = $this->getContent();
806
		}
807
808
		if ( !$content || $content->isRedirect() ) {
809
			return false;
810
		}
811
812
		$hasLinks = null;
813
814
		if ( $wgArticleCountMethod === 'link' ) {
815
			// nasty special case to avoid re-parsing to detect links
816
817
			if ( $editInfo ) {
818
				// ParserOutput::getLinks() is a 2D array of page links, so
819
				// to be really correct we would need to recurse in the array
820
				// but the main array should only have items in it if there are
821
				// links.
822
				$hasLinks = (bool)count( $editInfo->output->getLinks() );
823
			} else {
824
				$hasLinks = (bool)wfGetDB( DB_SLAVE )->selectField( 'pagelinks', 1,
825
					[ 'pl_from' => $this->getId() ], __METHOD__ );
826
			}
827
		}
828
829
		return $content->isCountable( $hasLinks );
830
	}
831
832
	/**
833
	 * If this page is a redirect, get its target
834
	 *
835
	 * The target will be fetched from the redirect table if possible.
836
	 * If this page doesn't have an entry there, call insertRedirect()
837
	 * @return Title|null Title object, or null if this page is not a redirect
838
	 */
839
	public function getRedirectTarget() {
840
		if ( !$this->mTitle->isRedirect() ) {
841
			return null;
842
		}
843
844
		if ( $this->mRedirectTarget !== null ) {
845
			return $this->mRedirectTarget;
846
		}
847
848
		// Query the redirect table
849
		$dbr = wfGetDB( DB_SLAVE );
850
		$row = $dbr->selectRow( 'redirect',
851
			[ 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ],
852
			[ 'rd_from' => $this->getId() ],
853
			__METHOD__
854
		);
855
856
		// rd_fragment and rd_interwiki were added later, populate them if empty
857
		if ( $row && !is_null( $row->rd_fragment ) && !is_null( $row->rd_interwiki ) ) {
858
			$this->mRedirectTarget = Title::makeTitle(
859
				$row->rd_namespace, $row->rd_title,
860
				$row->rd_fragment, $row->rd_interwiki
861
			);
862
			return $this->mRedirectTarget;
863
		}
864
865
		// This page doesn't have an entry in the redirect table
866
		$this->mRedirectTarget = $this->insertRedirect();
867
		return $this->mRedirectTarget;
868
	}
869
870
	/**
871
	 * Insert an entry for this page into the redirect table if the content is a redirect
872
	 *
873
	 * The database update will be deferred via DeferredUpdates
874
	 *
875
	 * Don't call this function directly unless you know what you're doing.
876
	 * @return Title|null Title object or null if not a redirect
877
	 */
878
	public function insertRedirect() {
879
		$content = $this->getContent();
880
		$retval = $content ? $content->getUltimateRedirectTarget() : null;
881
		if ( !$retval ) {
882
			return null;
883
		}
884
885
		// Update the DB post-send if the page has not cached since now
886
		$that = $this;
887
		$latest = $this->getLatest();
888
		DeferredUpdates::addCallableUpdate( function() use ( $that, $retval, $latest ) {
889
			$that->insertRedirectEntry( $retval, $latest );
890
		} );
891
892
		return $retval;
893
	}
894
895
	/**
896
	 * Insert or update the redirect table entry for this page to indicate it redirects to $rt
897
	 * @param Title $rt Redirect target
898
	 * @param int|null $oldLatest Prior page_latest for check and set
899
	 */
900
	public function insertRedirectEntry( Title $rt, $oldLatest = null ) {
901
		$dbw = wfGetDB( DB_MASTER );
902
		$dbw->startAtomic( __METHOD__ );
903
904
		if ( !$oldLatest || $oldLatest == $this->lockAndGetLatest() ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $oldLatest of type integer|null is loosely compared to false; this is ambiguous if the integer can be zero. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
905
			$dbw->replace( 'redirect',
906
				[ 'rd_from' ],
907
				[
908
					'rd_from' => $this->getId(),
909
					'rd_namespace' => $rt->getNamespace(),
910
					'rd_title' => $rt->getDBkey(),
911
					'rd_fragment' => $rt->getFragment(),
912
					'rd_interwiki' => $rt->getInterwiki(),
913
				],
914
				__METHOD__
915
			);
916
		}
917
918
		$dbw->endAtomic( __METHOD__ );
919
	}
920
921
	/**
922
	 * Get the Title object or URL this page redirects to
923
	 *
924
	 * @return bool|Title|string False, Title of in-wiki target, or string with URL
925
	 */
926
	public function followRedirect() {
927
		return $this->getRedirectURL( $this->getRedirectTarget() );
0 ignored issues
show
Bug introduced by
It seems like $this->getRedirectTarget() can be null; however, getRedirectURL() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
928
	}
929
930
	/**
931
	 * Get the Title object or URL to use for a redirect. We use Title
932
	 * objects for same-wiki, non-special redirects and URLs for everything
933
	 * else.
934
	 * @param Title $rt Redirect target
935
	 * @return bool|Title|string False, Title object of local target, or string with URL
936
	 */
937
	public function getRedirectURL( $rt ) {
938
		if ( !$rt ) {
939
			return false;
940
		}
941
942
		if ( $rt->isExternal() ) {
943
			if ( $rt->isLocal() ) {
944
				// Offsite wikis need an HTTP redirect.
945
				// This can be hard to reverse and may produce loops,
946
				// so they may be disabled in the site configuration.
947
				$source = $this->mTitle->getFullURL( 'redirect=no' );
948
				return $rt->getFullURL( [ 'rdfrom' => $source ] );
949
			} else {
950
				// External pages without "local" bit set are not valid
951
				// redirect targets
952
				return false;
953
			}
954
		}
955
956
		if ( $rt->isSpecialPage() ) {
957
			// Gotta handle redirects to special pages differently:
958
			// Fill the HTTP response "Location" header and ignore the rest of the page we're on.
959
			// Some pages are not valid targets.
960
			if ( $rt->isValidRedirectTarget() ) {
961
				return $rt->getFullURL();
962
			} else {
963
				return false;
964
			}
965
		}
966
967
		return $rt;
968
	}
969
970
	/**
971
	 * Get a list of users who have edited this article, not including the user who made
972
	 * the most recent revision, which you can get from $article->getUser() if you want it
973
	 * @return UserArrayFromResult
974
	 */
975
	public function getContributors() {
976
		// @todo FIXME: This is expensive; cache this info somewhere.
977
978
		$dbr = wfGetDB( DB_SLAVE );
979
980
		if ( $dbr->implicitGroupby() ) {
981
			$realNameField = 'user_real_name';
982
		} else {
983
			$realNameField = 'MIN(user_real_name) AS user_real_name';
984
		}
985
986
		$tables = [ 'revision', 'user' ];
987
988
		$fields = [
989
			'user_id' => 'rev_user',
990
			'user_name' => 'rev_user_text',
991
			$realNameField,
992
			'timestamp' => 'MAX(rev_timestamp)',
993
		];
994
995
		$conds = [ 'rev_page' => $this->getId() ];
996
997
		// The user who made the top revision gets credited as "this page was last edited by
998
		// John, based on contributions by Tom, Dick and Harry", so don't include them twice.
999
		$user = $this->getUser();
1000
		if ( $user ) {
1001
			$conds[] = "rev_user != $user";
1002
		} else {
1003
			$conds[] = "rev_user_text != {$dbr->addQuotes( $this->getUserText() )}";
0 ignored issues
show
Bug introduced by
It seems like $this->getUserText() targeting WikiPage::getUserText() can also be of type boolean; however, DatabaseBase::addQuotes() does only seem to accept string|object<Blob>, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
1004
		}
1005
1006
		// Username hidden?
1007
		$conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0";
1008
1009
		$jconds = [
1010
			'user' => [ 'LEFT JOIN', 'rev_user = user_id' ],
1011
		];
1012
1013
		$options = [
1014
			'GROUP BY' => [ 'rev_user', 'rev_user_text' ],
1015
			'ORDER BY' => 'timestamp DESC',
1016
		];
1017
1018
		$res = $dbr->select( $tables, $fields, $conds, __METHOD__, $options, $jconds );
1019
		return new UserArrayFromResult( $res );
0 ignored issues
show
Bug introduced by
It seems like $res defined by $dbr->select($tables, $f...D__, $options, $jconds) on line 1018 can also be of type boolean; however, UserArrayFromResult::__construct() does only seem to accept object<ResultWrapper>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
1020
	}
1021
1022
	/**
1023
	 * Should the parser cache be used?
1024
	 *
1025
	 * @param ParserOptions $parserOptions ParserOptions to check
1026
	 * @param int $oldId
1027
	 * @return bool
1028
	 */
1029
	public function shouldCheckParserCache( ParserOptions $parserOptions, $oldId ) {
1030
		return $parserOptions->getStubThreshold() == 0
1031
			&& $this->exists()
1032
			&& ( $oldId === null || $oldId === 0 || $oldId === $this->getLatest() )
1033
			&& $this->getContentHandler()->isParserCacheSupported();
1034
	}
1035
1036
	/**
1037
	 * Get a ParserOutput for the given ParserOptions and revision ID.
1038
	 *
1039
	 * The parser cache will be used if possible. Cache misses that result
1040
	 * in parser runs are debounced with PoolCounter.
1041
	 *
1042
	 * @since 1.19
1043
	 * @param ParserOptions $parserOptions ParserOptions to use for the parse operation
1044
	 * @param null|int $oldid Revision ID to get the text from, passing null or 0 will
1045
	 *   get the current revision (default value)
1046
	 *
1047
	 * @return ParserOutput|bool ParserOutput or false if the revision was not found
1048
	 */
1049
	public function getParserOutput( ParserOptions $parserOptions, $oldid = null ) {
1050
1051
		$useParserCache = $this->shouldCheckParserCache( $parserOptions, $oldid );
1052
		wfDebug( __METHOD__ .
1053
			': using parser cache: ' . ( $useParserCache ? 'yes' : 'no' ) . "\n" );
1054
		if ( $parserOptions->getStubThreshold() ) {
1055
			wfIncrStats( 'pcache.miss.stub' );
1056
		}
1057
1058
		if ( $useParserCache ) {
1059
			$parserOutput = ParserCache::singleton()->get( $this, $parserOptions );
1060
			if ( $parserOutput !== false ) {
1061
				return $parserOutput;
1062
			}
1063
		}
1064
1065
		if ( $oldid === null || $oldid === 0 ) {
1066
			$oldid = $this->getLatest();
1067
		}
1068
1069
		$pool = new PoolWorkArticleView( $this, $parserOptions, $oldid, $useParserCache );
1070
		$pool->execute();
1071
1072
		return $pool->getParserOutput();
1073
	}
1074
1075
	/**
1076
	 * Do standard deferred updates after page view (existing or missing page)
1077
	 * @param User $user The relevant user
1078
	 * @param int $oldid Revision id being viewed; if not given or 0, latest revision is assumed
1079
	 */
1080
	public function doViewUpdates( User $user, $oldid = 0 ) {
1081
		if ( wfReadOnly() ) {
1082
			return;
1083
		}
1084
1085
		Hooks::run( 'PageViewUpdates', [ $this, $user ] );
1086
		// Update newtalk / watchlist notification status
1087
		try {
1088
			$user->clearNotification( $this->mTitle, $oldid );
1089
		} catch ( DBError $e ) {
1090
			// Avoid outage if the master is not reachable
1091
			MWExceptionHandler::logException( $e );
1092
		}
1093
	}
1094
1095
	/**
1096
	 * Perform the actions of a page purging
1097
	 * @return bool
1098
	 */
1099
	public function doPurge() {
1100
		if ( !Hooks::run( 'ArticlePurge', [ &$this ] ) ) {
1101
			return false;
1102
		}
1103
1104
		$title = $this->mTitle;
1105
		wfGetDB( DB_MASTER )->onTransactionIdle( function() use ( $title ) {
1106
			// Invalidate the cache in auto-commit mode
1107
			$title->invalidateCache();
1108
		} );
1109
1110
		// Send purge after above page_touched update was committed
1111
		DeferredUpdates::addUpdate(
1112
			new CdnCacheUpdate( $title->getCdnUrls() ),
1113
			DeferredUpdates::PRESEND
1114
		);
1115
1116
		if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
1117
			// @todo move this logic to MessageCache
1118
			if ( $this->exists() ) {
1119
				// NOTE: use transclusion text for messages.
1120
				//       This is consistent with  MessageCache::getMsgFromNamespace()
1121
1122
				$content = $this->getContent();
1123
				$text = $content === null ? null : $content->getWikitextForTransclusion();
1124
1125
				if ( $text === null ) {
1126
					$text = false;
1127
				}
1128
			} else {
1129
				$text = false;
1130
			}
1131
1132
			MessageCache::singleton()->replace( $this->mTitle->getDBkey(), $text );
1133
		}
1134
1135
		return true;
1136
	}
1137
1138
	/**
1139
	 * Insert a new empty page record for this article.
1140
	 * This *must* be followed up by creating a revision
1141
	 * and running $this->updateRevisionOn( ... );
1142
	 * or else the record will be left in a funky state.
1143
	 * Best if all done inside a transaction.
1144
	 *
1145
	 * @param IDatabase $dbw
1146
	 * @param int|null $pageId Custom page ID that will be used for the insert statement
1147
	 *
1148
	 * @return bool|int The newly created page_id key; false if the title already existed
1149
	 */
1150
	public function insertOn( $dbw, $pageId = null ) {
1151
		$pageIdForInsert = $pageId ?: $dbw->nextSequenceValue( 'page_page_id_seq' );
1152
		$dbw->insert(
1153
			'page',
1154
			[
1155
				'page_id'           => $pageIdForInsert,
1156
				'page_namespace'    => $this->mTitle->getNamespace(),
1157
				'page_title'        => $this->mTitle->getDBkey(),
1158
				'page_restrictions' => '',
1159
				'page_is_redirect'  => 0, // Will set this shortly...
1160
				'page_is_new'       => 1,
1161
				'page_random'       => wfRandom(),
1162
				'page_touched'      => $dbw->timestamp(),
1163
				'page_latest'       => 0, // Fill this in shortly...
1164
				'page_len'          => 0, // Fill this in shortly...
1165
			],
1166
			__METHOD__,
1167
			'IGNORE'
1168
		);
1169
1170
		if ( $dbw->affectedRows() > 0 ) {
1171
			$newid = $pageId ?: $dbw->insertId();
1172
			$this->mId = $newid;
1173
			$this->mTitle->resetArticleID( $newid );
1174
1175
			return $newid;
1176
		} else {
1177
			return false; // nothing changed
1178
		}
1179
	}
1180
1181
	/**
1182
	 * Update the page record to point to a newly saved revision.
1183
	 *
1184
	 * @param IDatabase $dbw
1185
	 * @param Revision $revision For ID number, and text used to set
1186
	 *   length and redirect status fields
1187
	 * @param int $lastRevision If given, will not overwrite the page field
1188
	 *   when different from the currently set value.
1189
	 *   Giving 0 indicates the new page flag should be set on.
1190
	 * @param bool $lastRevIsRedirect If given, will optimize adding and
1191
	 *   removing rows in redirect table.
1192
	 * @return bool Success; false if the page row was missing or page_latest changed
1193
	 */
1194
	public function updateRevisionOn( $dbw, $revision, $lastRevision = null,
1195
		$lastRevIsRedirect = null
1196
	) {
1197
		global $wgContentHandlerUseDB;
1198
1199
		// Assertion to try to catch T92046
1200
		if ( (int)$revision->getId() === 0 ) {
1201
			throw new InvalidArgumentException(
1202
				__METHOD__ . ': Revision has ID ' . var_export( $revision->getId(), 1 )
1203
			);
1204
		}
1205
1206
		$content = $revision->getContent();
1207
		$len = $content ? $content->getSize() : 0;
1208
		$rt = $content ? $content->getUltimateRedirectTarget() : null;
1209
1210
		$conditions = [ 'page_id' => $this->getId() ];
1211
1212
		if ( !is_null( $lastRevision ) ) {
1213
			// An extra check against threads stepping on each other
1214
			$conditions['page_latest'] = $lastRevision;
1215
		}
1216
1217
		$row = [ /* SET */
1218
			'page_latest'      => $revision->getId(),
1219
			'page_touched'     => $dbw->timestamp( $revision->getTimestamp() ),
1220
			'page_is_new'      => ( $lastRevision === 0 ) ? 1 : 0,
1221
			'page_is_redirect' => $rt !== null ? 1 : 0,
1222
			'page_len'         => $len,
1223
		];
1224
1225
		if ( $wgContentHandlerUseDB ) {
1226
			$row['page_content_model'] = $revision->getContentModel();
1227
		}
1228
1229
		$dbw->update( 'page',
1230
			$row,
1231
			$conditions,
1232
			__METHOD__ );
1233
1234
		$result = $dbw->affectedRows() > 0;
1235
		if ( $result ) {
1236
			$this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
0 ignored issues
show
Bug introduced by
It seems like $rt defined by $content ? $content->get...RedirectTarget() : null on line 1208 can be null; however, WikiPage::updateRedirectOn() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
1237
			$this->setLastEdit( $revision );
1238
			$this->mLatest = $revision->getId();
0 ignored issues
show
Documentation Bug introduced by
It seems like $revision->getId() can also be of type integer. However, the property $mLatest is declared as type boolean. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
1239
			$this->mIsRedirect = (bool)$rt;
1240
			// Update the LinkCache.
1241
			LinkCache::singleton()->addGoodLinkObj(
0 ignored issues
show
Deprecated Code introduced by
The method LinkCache::singleton() has been deprecated with message: since 1.28, use MediaWikiServices instead

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
1242
				$this->getId(),
1243
				$this->mTitle,
1244
				$len,
1245
				$this->mIsRedirect,
1246
				$this->mLatest,
1247
				$revision->getContentModel()
1248
			);
1249
		}
1250
1251
		return $result;
1252
	}
1253
1254
	/**
1255
	 * Add row to the redirect table if this is a redirect, remove otherwise.
1256
	 *
1257
	 * @param IDatabase $dbw
1258
	 * @param Title $redirectTitle Title object pointing to the redirect target,
1259
	 *   or NULL if this is not a redirect
1260
	 * @param null|bool $lastRevIsRedirect If given, will optimize adding and
1261
	 *   removing rows in redirect table.
1262
	 * @return bool True on success, false on failure
1263
	 * @private
1264
	 */
1265
	public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1266
		// Always update redirects (target link might have changed)
1267
		// Update/Insert if we don't know if the last revision was a redirect or not
1268
		// Delete if changing from redirect to non-redirect
1269
		$isRedirect = !is_null( $redirectTitle );
1270
1271
		if ( !$isRedirect && $lastRevIsRedirect === false ) {
1272
			return true;
1273
		}
1274
1275
		if ( $isRedirect ) {
1276
			$this->insertRedirectEntry( $redirectTitle );
1277
		} else {
1278
			// This is not a redirect, remove row from redirect table
1279
			$where = [ 'rd_from' => $this->getId() ];
1280
			$dbw->delete( 'redirect', $where, __METHOD__ );
1281
		}
1282
1283
		if ( $this->getTitle()->getNamespace() == NS_FILE ) {
1284
			RepoGroup::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1285
		}
1286
1287
		return ( $dbw->affectedRows() != 0 );
1288
	}
1289
1290
	/**
1291
	 * If the given revision is newer than the currently set page_latest,
1292
	 * update the page record. Otherwise, do nothing.
1293
	 *
1294
	 * @deprecated since 1.24, use updateRevisionOn instead
1295
	 *
1296
	 * @param IDatabase $dbw
1297
	 * @param Revision $revision
1298
	 * @return bool
1299
	 */
1300
	public function updateIfNewerOn( $dbw, $revision ) {
1301
1302
		$row = $dbw->selectRow(
1303
			[ 'revision', 'page' ],
1304
			[ 'rev_id', 'rev_timestamp', 'page_is_redirect' ],
1305
			[
1306
				'page_id' => $this->getId(),
1307
				'page_latest=rev_id' ],
1308
			__METHOD__ );
1309
1310
		if ( $row ) {
1311
			if ( wfTimestamp( TS_MW, $row->rev_timestamp ) >= $revision->getTimestamp() ) {
1312
				return false;
1313
			}
1314
			$prev = $row->rev_id;
1315
			$lastRevIsRedirect = (bool)$row->page_is_redirect;
1316
		} else {
1317
			// No or missing previous revision; mark the page as new
1318
			$prev = 0;
1319
			$lastRevIsRedirect = null;
1320
		}
1321
1322
		$ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1323
1324
		return $ret;
1325
	}
1326
1327
	/**
1328
	 * Get the content that needs to be saved in order to undo all revisions
1329
	 * between $undo and $undoafter. Revisions must belong to the same page,
1330
	 * must exist and must not be deleted
1331
	 * @param Revision $undo
1332
	 * @param Revision $undoafter Must be an earlier revision than $undo
1333
	 * @return Content|bool Content on success, false on failure
1334
	 * @since 1.21
1335
	 * Before we had the Content object, this was done in getUndoText
1336
	 */
1337
	public function getUndoContent( Revision $undo, Revision $undoafter = null ) {
1338
		$handler = $undo->getContentHandler();
1339
		return $handler->getUndoContent( $this->getRevision(), $undo, $undoafter );
0 ignored issues
show
Bug introduced by
It seems like $this->getRevision() can be null; however, getUndoContent() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
Bug introduced by
It seems like $undoafter defined by parameter $undoafter on line 1337 can be null; however, ContentHandler::getUndoContent() does not accept null, maybe add an additional type check?

It seems like you allow that null is being passed for a parameter, however the function which is called does not seem to accept null.

We recommend to add an additional type check (or disallow null for the parameter):

function notNullable(stdClass $x) { }

// Unsafe
function withoutCheck(stdClass $x = null) {
    notNullable($x);
}

// Safe - Alternative 1: Adding Additional Type-Check
function withCheck(stdClass $x = null) {
    if ($x instanceof stdClass) {
        notNullable($x);
    }
}

// Safe - Alternative 2: Changing Parameter
function withNonNullableParam(stdClass $x) {
    notNullable($x);
}
Loading history...
1340
	}
1341
1342
	/**
1343
	 * Returns true if this page's content model supports sections.
1344
	 *
1345
	 * @return bool
1346
	 *
1347
	 * @todo The skin should check this and not offer section functionality if
1348
	 *   sections are not supported.
1349
	 * @todo The EditPage should check this and not offer section functionality
1350
	 *   if sections are not supported.
1351
	 */
1352
	public function supportsSections() {
1353
		return $this->getContentHandler()->supportsSections();
1354
	}
1355
1356
	/**
1357
	 * @param string|number|null|bool $sectionId Section identifier as a number or string
1358
	 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1359
	 * or 'new' for a new section.
1360
	 * @param Content $sectionContent New content of the section.
1361
	 * @param string $sectionTitle New section's subject, only if $section is "new".
1362
	 * @param string $edittime Revision timestamp or null to use the current revision.
1363
	 *
1364
	 * @throws MWException
1365
	 * @return Content|null New complete article content, or null if error.
1366
	 *
1367
	 * @since 1.21
1368
	 * @deprecated since 1.24, use replaceSectionAtRev instead
1369
	 */
1370
	public function replaceSectionContent(
1371
		$sectionId, Content $sectionContent, $sectionTitle = '', $edittime = null
1372
	) {
1373
1374
		$baseRevId = null;
1375
		if ( $edittime && $sectionId !== 'new' ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $edittime of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
1376
			$dbr = wfGetDB( DB_SLAVE );
1377
			$rev = Revision::loadFromTimestamp( $dbr, $this->mTitle, $edittime );
1378
			// Try the master if this thread may have just added it.
1379
			// This could be abstracted into a Revision method, but we don't want
1380
			// to encourage loading of revisions by timestamp.
1381
			if ( !$rev
1382
				&& wfGetLB()->getServerCount() > 1
0 ignored issues
show
Deprecated Code introduced by
The function wfGetLB() has been deprecated with message: since 1.27, use MediaWikiServices::getDBLoadBalancer() or MediaWikiServices::getDBLoadBalancerFactory() instead.

This function has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed from the class and what other function to use instead.

Loading history...
1383
				&& wfGetLB()->hasOrMadeRecentMasterChanges()
0 ignored issues
show
Deprecated Code introduced by
The function wfGetLB() has been deprecated with message: since 1.27, use MediaWikiServices::getDBLoadBalancer() or MediaWikiServices::getDBLoadBalancerFactory() instead.

This function has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed from the class and what other function to use instead.

Loading history...
1384
			) {
1385
				$dbw = wfGetDB( DB_MASTER );
1386
				$rev = Revision::loadFromTimestamp( $dbw, $this->mTitle, $edittime );
1387
			}
1388
			if ( $rev ) {
1389
				$baseRevId = $rev->getId();
1390
			}
1391
		}
1392
1393
		return $this->replaceSectionAtRev( $sectionId, $sectionContent, $sectionTitle, $baseRevId );
1394
	}
1395
1396
	/**
1397
	 * @param string|number|null|bool $sectionId Section identifier as a number or string
1398
	 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1399
	 * or 'new' for a new section.
1400
	 * @param Content $sectionContent New content of the section.
1401
	 * @param string $sectionTitle New section's subject, only if $section is "new".
1402
	 * @param int|null $baseRevId
1403
	 *
1404
	 * @throws MWException
1405
	 * @return Content|null New complete article content, or null if error.
1406
	 *
1407
	 * @since 1.24
1408
	 */
1409
	public function replaceSectionAtRev( $sectionId, Content $sectionContent,
1410
		$sectionTitle = '', $baseRevId = null
1411
	) {
1412
1413
		if ( strval( $sectionId ) === '' ) {
1414
			// Whole-page edit; let the whole text through
1415
			$newContent = $sectionContent;
1416
		} else {
1417
			if ( !$this->supportsSections() ) {
1418
				throw new MWException( "sections not supported for content model " .
1419
					$this->getContentHandler()->getModelID() );
1420
			}
1421
1422
			// Bug 30711: always use current version when adding a new section
1423
			if ( is_null( $baseRevId ) || $sectionId === 'new' ) {
1424
				$oldContent = $this->getContent();
1425
			} else {
1426
				$rev = Revision::newFromId( $baseRevId );
1427
				if ( !$rev ) {
1428
					wfDebug( __METHOD__ . " asked for bogus section (page: " .
1429
						$this->getId() . "; section: $sectionId)\n" );
1430
					return null;
1431
				}
1432
1433
				$oldContent = $rev->getContent();
1434
			}
1435
1436
			if ( !$oldContent ) {
1437
				wfDebug( __METHOD__ . ": no page text\n" );
1438
				return null;
1439
			}
1440
1441
			$newContent = $oldContent->replaceSection( $sectionId, $sectionContent, $sectionTitle );
1442
		}
1443
1444
		return $newContent;
1445
	}
1446
1447
	/**
1448
	 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1449
	 * @param int $flags
1450
	 * @return int Updated $flags
1451
	 */
1452
	public function checkFlags( $flags ) {
1453
		if ( !( $flags & EDIT_NEW ) && !( $flags & EDIT_UPDATE ) ) {
1454
			if ( $this->exists() ) {
1455
				$flags |= EDIT_UPDATE;
1456
			} else {
1457
				$flags |= EDIT_NEW;
1458
			}
1459
		}
1460
1461
		return $flags;
1462
	}
1463
1464
	/**
1465
	 * Change an existing article or create a new article. Updates RC and all necessary caches,
1466
	 * optionally via the deferred update array.
1467
	 *
1468
	 * @param string $text New text
1469
	 * @param string $summary Edit summary
1470
	 * @param int $flags Bitfield:
1471
	 *      EDIT_NEW
1472
	 *          Article is known or assumed to be non-existent, create a new one
1473
	 *      EDIT_UPDATE
1474
	 *          Article is known or assumed to be pre-existing, update it
1475
	 *      EDIT_MINOR
1476
	 *          Mark this edit minor, if the user is allowed to do so
1477
	 *      EDIT_SUPPRESS_RC
1478
	 *          Do not log the change in recentchanges
1479
	 *      EDIT_FORCE_BOT
1480
	 *          Mark the edit a "bot" edit regardless of user rights
1481
	 *      EDIT_AUTOSUMMARY
1482
	 *          Fill in blank summaries with generated text where possible
1483
	 *      EDIT_INTERNAL
1484
	 *          Signal that the page retrieve/save cycle happened entirely in this request.
1485
	 *
1486
	 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the
1487
	 * article will be detected. If EDIT_UPDATE is specified and the article
1488
	 * doesn't exist, the function will return an edit-gone-missing error. If
1489
	 * EDIT_NEW is specified and the article does exist, an edit-already-exists
1490
	 * error will be returned. These two conditions are also possible with
1491
	 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1492
	 *
1493
	 * @param bool|int $baseRevId The revision ID this edit was based off, if any.
1494
	 *   This is not the parent revision ID, rather the revision ID for older
1495
	 *   content used as the source for a rollback, for example.
1496
	 * @param User $user The user doing the edit
1497
	 *
1498
	 * @throws MWException
1499
	 * @return Status Possible errors:
1500
	 *   edit-hook-aborted: The ArticleSave hook aborted the edit but didn't
1501
	 *     set the fatal flag of $status
1502
	 *   edit-gone-missing: In update mode, but the article didn't exist.
1503
	 *   edit-conflict: In update mode, the article changed unexpectedly.
1504
	 *   edit-no-change: Warning that the text was the same as before.
1505
	 *   edit-already-exists: In creation mode, but the article already exists.
1506
	 *
1507
	 * Extensions may define additional errors.
1508
	 *
1509
	 * $return->value will contain an associative array with members as follows:
1510
	 *     new: Boolean indicating if the function attempted to create a new article.
1511
	 *     revision: The revision object for the inserted revision, or null.
1512
	 *
1513
	 * Compatibility note: this function previously returned a boolean value
1514
	 * indicating success/failure
1515
	 *
1516
	 * @deprecated since 1.21: use doEditContent() instead.
1517
	 */
1518
	public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
1519
		ContentHandler::deprecated( __METHOD__, '1.21' );
1520
1521
		$content = ContentHandler::makeContent( $text, $this->getTitle() );
1522
1523
		return $this->doEditContent( $content, $summary, $flags, $baseRevId, $user );
1524
	}
1525
1526
	/**
1527
	 * Change an existing article or create a new article. Updates RC and all necessary caches,
1528
	 * optionally via the deferred update array.
1529
	 *
1530
	 * @param Content $content New content
1531
	 * @param string $summary Edit summary
1532
	 * @param int $flags Bitfield:
1533
	 *      EDIT_NEW
1534
	 *          Article is known or assumed to be non-existent, create a new one
1535
	 *      EDIT_UPDATE
1536
	 *          Article is known or assumed to be pre-existing, update it
1537
	 *      EDIT_MINOR
1538
	 *          Mark this edit minor, if the user is allowed to do so
1539
	 *      EDIT_SUPPRESS_RC
1540
	 *          Do not log the change in recentchanges
1541
	 *      EDIT_FORCE_BOT
1542
	 *          Mark the edit a "bot" edit regardless of user rights
1543
	 *      EDIT_AUTOSUMMARY
1544
	 *          Fill in blank summaries with generated text where possible
1545
	 *      EDIT_INTERNAL
1546
	 *          Signal that the page retrieve/save cycle happened entirely in this request.
1547
	 *
1548
	 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the
1549
	 * article will be detected. If EDIT_UPDATE is specified and the article
1550
	 * doesn't exist, the function will return an edit-gone-missing error. If
1551
	 * EDIT_NEW is specified and the article does exist, an edit-already-exists
1552
	 * error will be returned. These two conditions are also possible with
1553
	 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1554
	 *
1555
	 * @param bool|int $baseRevId The revision ID this edit was based off, if any.
1556
	 *   This is not the parent revision ID, rather the revision ID for older
1557
	 *   content used as the source for a rollback, for example.
1558
	 * @param User $user The user doing the edit
1559
	 * @param string $serialFormat Format for storing the content in the
1560
	 *   database.
1561
	 * @param array|null $tags Change tags to apply to this edit
1562
	 * Callers are responsible for permission checks
1563
	 * (with ChangeTags::canAddTagsAccompanyingChange)
1564
	 *
1565
	 * @throws MWException
1566
	 * @return Status Possible errors:
1567
	 *     edit-hook-aborted: The ArticleSave hook aborted the edit but didn't
1568
	 *       set the fatal flag of $status.
1569
	 *     edit-gone-missing: In update mode, but the article didn't exist.
1570
	 *     edit-conflict: In update mode, the article changed unexpectedly.
1571
	 *     edit-no-change: Warning that the text was the same as before.
1572
	 *     edit-already-exists: In creation mode, but the article already exists.
1573
	 *
1574
	 *  Extensions may define additional errors.
1575
	 *
1576
	 *  $return->value will contain an associative array with members as follows:
1577
	 *     new: Boolean indicating if the function attempted to create a new article.
1578
	 *     revision: The revision object for the inserted revision, or null.
1579
	 *
1580
	 * @since 1.21
1581
	 * @throws MWException
1582
	 */
1583
	public function doEditContent(
1584
		Content $content, $summary, $flags = 0, $baseRevId = false,
1585
		User $user = null, $serialFormat = null, $tags = null
1586
	) {
1587
		global $wgUser, $wgUseAutomaticEditSummaries;
1588
1589
		// Low-level sanity check
1590
		if ( $this->mTitle->getText() === '' ) {
1591
			throw new MWException( 'Something is trying to edit an article with an empty title' );
1592
		}
1593
		// Make sure the given content type is allowed for this page
1594
		if ( !$content->getContentHandler()->canBeUsedOn( $this->mTitle ) ) {
1595
			return Status::newFatal( 'content-not-allowed-here',
1596
				ContentHandler::getLocalizedName( $content->getModel() ),
1597
				$this->mTitle->getPrefixedText()
1598
			);
1599
		}
1600
1601
		// Load the data from the master database if needed.
1602
		// The caller may already loaded it from the master or even loaded it using
1603
		// SELECT FOR UPDATE, so do not override that using clear().
1604
		$this->loadPageData( 'fromdbmaster' );
1605
1606
		$user = $user ?: $wgUser;
1607
		$flags = $this->checkFlags( $flags );
1608
1609
		// Trigger pre-save hook (using provided edit summary)
1610
		$hookStatus = Status::newGood( [] );
1611
		$hook_args = [ &$this, &$user, &$content, &$summary,
1612
							$flags & EDIT_MINOR, null, null, &$flags, &$hookStatus ];
1613
		// Check if the hook rejected the attempted save
1614
		if ( !Hooks::run( 'PageContentSave', $hook_args )
1615
			|| !ContentHandler::runLegacyHooks( 'ArticleSave', $hook_args )
1616
		) {
1617
			if ( $hookStatus->isOK() ) {
1618
				// Hook returned false but didn't call fatal(); use generic message
1619
				$hookStatus->fatal( 'edit-hook-aborted' );
1620
			}
1621
1622
			return $hookStatus;
1623
		}
1624
1625
		$old_revision = $this->getRevision(); // current revision
1626
		$old_content = $this->getContent( Revision::RAW ); // current revision's content
1627
1628
		// Provide autosummaries if one is not provided and autosummaries are enabled
1629
		if ( $wgUseAutomaticEditSummaries && ( $flags & EDIT_AUTOSUMMARY ) && $summary == '' ) {
1630
			$handler = $content->getContentHandler();
1631
			$summary = $handler->getAutosummary( $old_content, $content, $flags );
1632
		}
1633
1634
		// Avoid statsd noise and wasted cycles check the edit stash (T136678)
1635
		if ( ( $flags & EDIT_INTERNAL ) || ( $flags & EDIT_FORCE_BOT ) ) {
1636
			$useCache = false;
1637
		} else {
1638
			$useCache = true;
1639
		}
1640
1641
		// Get the pre-save transform content and final parser output
1642
		$editInfo = $this->prepareContentForEdit( $content, null, $user, $serialFormat, $useCache );
1643
		$pstContent = $editInfo->pstContent; // Content object
1644
		$meta = [
1645
			'bot' => ( $flags & EDIT_FORCE_BOT ),
1646
			'minor' => ( $flags & EDIT_MINOR ) && $user->isAllowed( 'minoredit' ),
1647
			'serialized' => $editInfo->pst,
1648
			'serialFormat' => $serialFormat,
1649
			'baseRevId' => $baseRevId,
1650
			'oldRevision' => $old_revision,
1651
			'oldContent' => $old_content,
1652
			'oldId' => $this->getLatest(),
1653
			'oldIsRedirect' => $this->isRedirect(),
1654
			'oldCountable' => $this->isCountable(),
1655
			'tags' => ( $tags !== null ) ? (array)$tags : []
1656
		];
1657
1658
		// Actually create the revision and create/update the page
1659
		if ( $flags & EDIT_UPDATE ) {
1660
			$status = $this->doModify( $pstContent, $flags, $user, $summary, $meta );
1661
		} else {
1662
			$status = $this->doCreate( $pstContent, $flags, $user, $summary, $meta );
1663
		}
1664
1665
		// Promote user to any groups they meet the criteria for
1666
		DeferredUpdates::addCallableUpdate( function () use ( $user ) {
1667
			$user->addAutopromoteOnceGroups( 'onEdit' );
1668
			$user->addAutopromoteOnceGroups( 'onView' ); // b/c
1669
		} );
1670
1671
		return $status;
1672
	}
1673
1674
	/**
1675
	 * @param Content $content Pre-save transform content
1676
	 * @param integer $flags
1677
	 * @param User $user
1678
	 * @param string $summary
1679
	 * @param array $meta
1680
	 * @return Status
1681
	 * @throws DBUnexpectedError
1682
	 * @throws Exception
1683
	 * @throws FatalError
1684
	 * @throws MWException
1685
	 */
1686
	private function doModify(
1687
		Content $content, $flags, User $user, $summary, array $meta
1688
	) {
1689
		global $wgUseRCPatrol;
1690
1691
		// Update article, but only if changed.
1692
		$status = Status::newGood( [ 'new' => false, 'revision' => null ] );
1693
1694
		// Convenience variables
1695
		$now = wfTimestampNow();
1696
		$oldid = $meta['oldId'];
1697
		/** @var $oldContent Content|null */
1698
		$oldContent = $meta['oldContent'];
1699
		$newsize = $content->getSize();
1700
1701
		if ( !$oldid ) {
1702
			// Article gone missing
1703
			$status->fatal( 'edit-gone-missing' );
1704
1705
			return $status;
1706
		} elseif ( !$oldContent ) {
1707
			// Sanity check for bug 37225
1708
			throw new MWException( "Could not find text for current revision {$oldid}." );
1709
		}
1710
1711
		// @TODO: pass content object?!
1712
		$revision = new Revision( [
1713
			'page'       => $this->getId(),
1714
			'title'      => $this->mTitle, // for determining the default content model
1715
			'comment'    => $summary,
1716
			'minor_edit' => $meta['minor'],
1717
			'text'       => $meta['serialized'],
1718
			'len'        => $newsize,
1719
			'parent_id'  => $oldid,
1720
			'user'       => $user->getId(),
1721
			'user_text'  => $user->getName(),
1722
			'timestamp'  => $now,
1723
			'content_model' => $content->getModel(),
1724
			'content_format' => $meta['serialFormat'],
1725
		] );
1726
1727
		$changed = !$content->equals( $oldContent );
1728
1729
		$dbw = wfGetDB( DB_MASTER );
1730
1731
		if ( $changed ) {
1732
			$prepStatus = $content->prepareSave( $this, $flags, $oldid, $user );
1733
			$status->merge( $prepStatus );
1734
			if ( !$status->isOK() ) {
1735
				return $status;
1736
			}
1737
1738
			$dbw->startAtomic( __METHOD__ );
1739
			// Get the latest page_latest value while locking it.
1740
			// Do a CAS style check to see if it's the same as when this method
1741
			// started. If it changed then bail out before touching the DB.
1742
			$latestNow = $this->lockAndGetLatest();
1743
			if ( $latestNow != $oldid ) {
1744
				$dbw->endAtomic( __METHOD__ );
1745
				// Page updated or deleted in the mean time
1746
				$status->fatal( 'edit-conflict' );
1747
1748
				return $status;
1749
			}
1750
1751
			// At this point we are now comitted to returning an OK
1752
			// status unless some DB query error or other exception comes up.
1753
			// This way callers don't have to call rollback() if $status is bad
1754
			// unless they actually try to catch exceptions (which is rare).
1755
1756
			// Save the revision text
1757
			$revisionId = $revision->insertOn( $dbw );
1758
			// Update page_latest and friends to reflect the new revision
1759
			if ( !$this->updateRevisionOn( $dbw, $revision, null, $meta['oldIsRedirect'] ) ) {
1760
				$dbw->rollback( __METHOD__ ); // sanity; this should never happen
1761
				throw new MWException( "Failed to update page row to use new revision." );
1762
			}
1763
1764
			Hooks::run( 'NewRevisionFromEditComplete',
1765
				[ $this, $revision, $meta['baseRevId'], $user ] );
1766
1767
			// Update recentchanges
1768
			if ( !( $flags & EDIT_SUPPRESS_RC ) ) {
1769
				// Mark as patrolled if the user can do so
1770
				$patrolled = $wgUseRCPatrol && !count(
1771
						$this->mTitle->getUserPermissionsErrors( 'autopatrol', $user ) );
1772
				// Add RC row to the DB
1773
				RecentChange::notifyEdit(
1774
					$now,
0 ignored issues
show
Security Bug introduced by
It seems like $now defined by wfTimestampNow() on line 1695 can also be of type false; however, RecentChange::notifyEdit() does only seem to accept string, did you maybe forget to handle an error condition?

This check looks for type mismatches where the missing type is false. This is usually indicative of an error condtion.

Consider the follow example

<?php

function getDate($date)
{
    if ($date !== null) {
        return new DateTime($date);
    }

    return false;
}

This function either returns a new DateTime object or false, if there was an error. This is a typical pattern in PHP programming to show that an error has occurred without raising an exception. The calling code should check for this returned false before passing on the value to another function or method that may not be able to handle a false.

Loading history...
1775
					$this->mTitle,
1776
					$revision->isMinor(),
1777
					$user,
1778
					$summary,
1779
					$oldid,
1780
					$this->getTimestamp(),
0 ignored issues
show
Security Bug introduced by
It seems like $this->getTimestamp() targeting WikiPage::getTimestamp() can also be of type false; however, RecentChange::notifyEdit() does only seem to accept string, did you maybe forget to handle an error condition?
Loading history...
1781
					$meta['bot'],
1782
					'',
1783
					$oldContent ? $oldContent->getSize() : 0,
1784
					$newsize,
1785
					$revisionId,
1786
					$patrolled,
1787
					$meta['tags']
1788
				);
1789
			}
1790
1791
			$user->incEditCount();
1792
1793
			$dbw->endAtomic( __METHOD__ );
1794
			$this->mTimestamp = $now;
0 ignored issues
show
Documentation Bug introduced by
It seems like $now can also be of type false. However, the property $mTimestamp is declared as type string. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
1795
		} else {
1796
			// Bug 32948: revision ID must be set to page {{REVISIONID}} and
1797
			// related variables correctly. Likewise for {{REVISIONUSER}} (T135261).
1798
			$revision->setId( $this->getLatest() );
1799
			$revision->setUserIdAndName(
1800
				$this->getUser( Revision::RAW ),
1801
				$this->getUserText( Revision::RAW )
0 ignored issues
show
Bug introduced by
It seems like $this->getUserText(\Revision::RAW) targeting WikiPage::getUserText() can also be of type boolean; however, Revision::setUserIdAndName() does only seem to accept string, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
1802
			);
1803
		}
1804
1805
		if ( $changed ) {
1806
			// Return the new revision to the caller
1807
			$status->value['revision'] = $revision;
1808
		} else {
1809
			$status->warning( 'edit-no-change' );
1810
			// Update page_touched as updateRevisionOn() was not called.
1811
			// Other cache updates are managed in onArticleEdit() via doEditUpdates().
1812
			$this->mTitle->invalidateCache( $now );
0 ignored issues
show
Security Bug introduced by
It seems like $now defined by wfTimestampNow() on line 1695 can also be of type false; however, Title::invalidateCache() does only seem to accept string|null, did you maybe forget to handle an error condition?

This check looks for type mismatches where the missing type is false. This is usually indicative of an error condtion.

Consider the follow example

<?php

function getDate($date)
{
    if ($date !== null) {
        return new DateTime($date);
    }

    return false;
}

This function either returns a new DateTime object or false, if there was an error. This is a typical pattern in PHP programming to show that an error has occurred without raising an exception. The calling code should check for this returned false before passing on the value to another function or method that may not be able to handle a false.

Loading history...
1813
		}
1814
1815
		// Do secondary updates once the main changes have been committed...
1816
		$that = $this;
1817
		$dbw->onTransactionIdle(
1818
			function () use (
1819
				$dbw, &$that, $revision, &$user, $content, $summary, &$flags,
1820
				$changed, $meta, &$status
1821
			) {
1822
				// Do per-page updates in a transaction
1823
				$dbw->setFlag( DBO_TRX );
1824
				// Update links tables, site stats, etc.
1825
				$that->doEditUpdates(
1826
					$revision,
1827
					$user,
1828
					[
1829
						'changed' => $changed,
1830
						'oldcountable' => $meta['oldCountable'],
1831
						'oldrevision' => $meta['oldRevision']
1832
					]
1833
				);
1834
				// Trigger post-save hook
1835
				$params = [ &$that, &$user, $content, $summary, $flags & EDIT_MINOR,
1836
					null, null, &$flags, $revision, &$status, $meta['baseRevId'] ];
1837
				ContentHandler::runLegacyHooks( 'ArticleSaveComplete', $params );
1838
				Hooks::run( 'PageContentSaveComplete', $params );
1839
			}
1840
		);
1841
1842
		return $status;
1843
	}
1844
1845
	/**
1846
	 * @param Content $content Pre-save transform content
1847
	 * @param integer $flags
1848
	 * @param User $user
1849
	 * @param string $summary
1850
	 * @param array $meta
1851
	 * @return Status
1852
	 * @throws DBUnexpectedError
1853
	 * @throws Exception
1854
	 * @throws FatalError
1855
	 * @throws MWException
1856
	 */
1857
	private function doCreate(
1858
		Content $content, $flags, User $user, $summary, array $meta
1859
	) {
1860
		global $wgUseRCPatrol, $wgUseNPPatrol;
1861
1862
		$status = Status::newGood( [ 'new' => true, 'revision' => null ] );
1863
1864
		$now = wfTimestampNow();
1865
		$newsize = $content->getSize();
1866
		$prepStatus = $content->prepareSave( $this, $flags, $meta['oldId'], $user );
1867
		$status->merge( $prepStatus );
1868
		if ( !$status->isOK() ) {
1869
			return $status;
1870
		}
1871
1872
		$dbw = wfGetDB( DB_MASTER );
1873
		$dbw->startAtomic( __METHOD__ );
1874
1875
		// Add the page record unless one already exists for the title
1876
		$newid = $this->insertOn( $dbw );
1877
		if ( $newid === false ) {
1878
			$dbw->endAtomic( __METHOD__ ); // nothing inserted
1879
			$status->fatal( 'edit-already-exists' );
1880
1881
			return $status; // nothing done
1882
		}
1883
1884
		// At this point we are now comitted to returning an OK
1885
		// status unless some DB query error or other exception comes up.
1886
		// This way callers don't have to call rollback() if $status is bad
1887
		// unless they actually try to catch exceptions (which is rare).
1888
1889
		// @TODO: pass content object?!
1890
		$revision = new Revision( [
1891
			'page'       => $newid,
1892
			'title'      => $this->mTitle, // for determining the default content model
1893
			'comment'    => $summary,
1894
			'minor_edit' => $meta['minor'],
1895
			'text'       => $meta['serialized'],
1896
			'len'        => $newsize,
1897
			'user'       => $user->getId(),
1898
			'user_text'  => $user->getName(),
1899
			'timestamp'  => $now,
1900
			'content_model' => $content->getModel(),
1901
			'content_format' => $meta['serialFormat'],
1902
		] );
1903
1904
		// Save the revision text...
1905
		$revisionId = $revision->insertOn( $dbw );
1906
		// Update the page record with revision data
1907
		if ( !$this->updateRevisionOn( $dbw, $revision, 0 ) ) {
1908
			$dbw->rollback( __METHOD__ ); // sanity; this should never happen
1909
			throw new MWException( "Failed to update page row to use new revision." );
1910
		}
1911
1912
		Hooks::run( 'NewRevisionFromEditComplete', [ $this, $revision, false, $user ] );
1913
1914
		// Update recentchanges
1915
		if ( !( $flags & EDIT_SUPPRESS_RC ) ) {
1916
			// Mark as patrolled if the user can do so
1917
			$patrolled = ( $wgUseRCPatrol || $wgUseNPPatrol ) &&
1918
				!count( $this->mTitle->getUserPermissionsErrors( 'autopatrol', $user ) );
1919
			// Add RC row to the DB
1920
			RecentChange::notifyNew(
1921
				$now,
0 ignored issues
show
Security Bug introduced by
It seems like $now defined by wfTimestampNow() on line 1864 can also be of type false; however, RecentChange::notifyNew() does only seem to accept string, did you maybe forget to handle an error condition?

This check looks for type mismatches where the missing type is false. This is usually indicative of an error condtion.

Consider the follow example

<?php

function getDate($date)
{
    if ($date !== null) {
        return new DateTime($date);
    }

    return false;
}

This function either returns a new DateTime object or false, if there was an error. This is a typical pattern in PHP programming to show that an error has occurred without raising an exception. The calling code should check for this returned false before passing on the value to another function or method that may not be able to handle a false.

Loading history...
1922
				$this->mTitle,
1923
				$revision->isMinor(),
1924
				$user,
1925
				$summary,
1926
				$meta['bot'],
1927
				'',
1928
				$newsize,
1929
				$revisionId,
1930
				$patrolled,
1931
				$meta['tags']
1932
			);
1933
		}
1934
1935
		$user->incEditCount();
1936
1937
		$dbw->endAtomic( __METHOD__ );
1938
		$this->mTimestamp = $now;
0 ignored issues
show
Documentation Bug introduced by
It seems like $now can also be of type false. However, the property $mTimestamp is declared as type string. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
1939
1940
		// Return the new revision to the caller
1941
		$status->value['revision'] = $revision;
1942
1943
		// Do secondary updates once the main changes have been committed...
1944
		$that = $this;
1945
		$dbw->onTransactionIdle(
1946
			function () use (
1947
				&$that, $dbw, $revision, &$user, $content, $summary, &$flags, $meta, &$status
1948
			) {
1949
				// Do per-page updates in a transaction
1950
				$dbw->setFlag( DBO_TRX );
1951
				// Update links, etc.
1952
				$that->doEditUpdates( $revision, $user, [ 'created' => true ] );
1953
				// Trigger post-create hook
1954
				$params = [ &$that, &$user, $content, $summary,
1955
					$flags & EDIT_MINOR, null, null, &$flags, $revision ];
1956
				ContentHandler::runLegacyHooks( 'ArticleInsertComplete', $params );
1957
				Hooks::run( 'PageContentInsertComplete', $params );
1958
				// Trigger post-save hook
1959
				$params = array_merge( $params, [ &$status, $meta['baseRevId'] ] );
1960
				ContentHandler::runLegacyHooks( 'ArticleSaveComplete', $params );
1961
				Hooks::run( 'PageContentSaveComplete', $params );
1962
1963
			}
1964
		);
1965
1966
		return $status;
1967
	}
1968
1969
	/**
1970
	 * Get parser options suitable for rendering the primary article wikitext
1971
	 *
1972
	 * @see ContentHandler::makeParserOptions
1973
	 *
1974
	 * @param IContextSource|User|string $context One of the following:
1975
	 *        - IContextSource: Use the User and the Language of the provided
1976
	 *          context
1977
	 *        - User: Use the provided User object and $wgLang for the language,
1978
	 *          so use an IContextSource object if possible.
1979
	 *        - 'canonical': Canonical options (anonymous user with default
1980
	 *          preferences and content language).
1981
	 * @return ParserOptions
1982
	 */
1983
	public function makeParserOptions( $context ) {
1984
		$options = $this->getContentHandler()->makeParserOptions( $context );
1985
1986
		if ( $this->getTitle()->isConversionTable() ) {
1987
			// @todo ConversionTable should become a separate content model, so
1988
			// we don't need special cases like this one.
1989
			$options->disableContentConversion();
1990
		}
1991
1992
		return $options;
1993
	}
1994
1995
	/**
1996
	 * Prepare text which is about to be saved.
1997
	 * Returns a stdClass with source, pst and output members
1998
	 *
1999
	 * @param string $text
2000
	 * @param int|null $revid
2001
	 * @param User|null $user
2002
	 * @deprecated since 1.21: use prepareContentForEdit instead.
2003
	 * @return object
2004
	 */
2005
	public function prepareTextForEdit( $text, $revid = null, User $user = null ) {
2006
		ContentHandler::deprecated( __METHOD__, '1.21' );
2007
		$content = ContentHandler::makeContent( $text, $this->getTitle() );
2008
		return $this->prepareContentForEdit( $content, $revid, $user );
2009
	}
2010
2011
	/**
2012
	 * Prepare content which is about to be saved.
2013
	 * Returns a stdClass with source, pst and output members
2014
	 *
2015
	 * @param Content $content
2016
	 * @param Revision|int|null $revision Revision object. For backwards compatibility, a
2017
	 *        revision ID is also accepted, but this is deprecated.
2018
	 * @param User|null $user
2019
	 * @param string|null $serialFormat
2020
	 * @param bool $useCache Check shared prepared edit cache
2021
	 *
2022
	 * @return object
2023
	 *
2024
	 * @since 1.21
2025
	 */
2026
	public function prepareContentForEdit(
2027
		Content $content, $revision = null, User $user = null,
2028
		$serialFormat = null, $useCache = true
2029
	) {
2030
		global $wgContLang, $wgUser, $wgAjaxEditStash;
2031
2032
		if ( is_object( $revision ) ) {
2033
			$revid = $revision->getId();
2034
		} else {
2035
			$revid = $revision;
2036
			// This code path is deprecated, and nothing is known to
2037
			// use it, so performance here shouldn't be a worry.
2038
			if ( $revid !== null ) {
2039
				$revision = Revision::newFromId( $revid, Revision::READ_LATEST );
2040
			} else {
2041
				$revision = null;
2042
			}
2043
		}
2044
2045
		$user = is_null( $user ) ? $wgUser : $user;
2046
		// XXX: check $user->getId() here???
2047
2048
		// Use a sane default for $serialFormat, see bug 57026
2049
		if ( $serialFormat === null ) {
2050
			$serialFormat = $content->getContentHandler()->getDefaultFormat();
2051
		}
2052
2053
		if ( $this->mPreparedEdit
2054
			&& $this->mPreparedEdit->newContent
2055
			&& $this->mPreparedEdit->newContent->equals( $content )
2056
			&& $this->mPreparedEdit->revid == $revid
2057
			&& $this->mPreparedEdit->format == $serialFormat
2058
			// XXX: also check $user here?
2059
		) {
2060
			// Already prepared
2061
			return $this->mPreparedEdit;
2062
		}
2063
2064
		// The edit may have already been prepared via api.php?action=stashedit
2065
		$cachedEdit = $useCache && $wgAjaxEditStash
2066
			? ApiStashEdit::checkCache( $this->getTitle(), $content, $user )
2067
			: false;
2068
2069
		$popts = ParserOptions::newFromUserAndLang( $user, $wgContLang );
2070
		Hooks::run( 'ArticlePrepareTextForEdit', [ $this, $popts ] );
2071
2072
		$edit = (object)[];
2073
		if ( $cachedEdit ) {
2074
			$edit->timestamp = $cachedEdit->timestamp;
2075
		} else {
2076
			$edit->timestamp = wfTimestampNow();
2077
		}
2078
		// @note: $cachedEdit is safely not used if the rev ID was referenced in the text
2079
		$edit->revid = $revid;
2080
2081
		if ( $cachedEdit ) {
2082
			$edit->pstContent = $cachedEdit->pstContent;
2083
		} else {
2084
			$edit->pstContent = $content
2085
				? $content->preSaveTransform( $this->mTitle, $user, $popts )
2086
				: null;
2087
		}
2088
2089
		$edit->format = $serialFormat;
2090
		$edit->popts = $this->makeParserOptions( 'canonical' );
2091
		if ( $cachedEdit ) {
2092
			$edit->output = $cachedEdit->output;
2093
		} else {
2094
			if ( $revision ) {
2095
				// We get here if vary-revision is set. This means that this page references
2096
				// itself (such as via self-transclusion). In this case, we need to make sure
2097
				// that any such self-references refer to the newly-saved revision, and not
2098
				// to the previous one, which could otherwise happen due to slave lag.
2099
				$oldCallback = $edit->popts->getCurrentRevisionCallback();
2100
				$edit->popts->setCurrentRevisionCallback(
2101
					function ( Title $title, $parser = false ) use ( $revision, &$oldCallback ) {
2102
						if ( $title->equals( $revision->getTitle() ) ) {
2103
							return $revision;
2104
						} else {
2105
							return call_user_func( $oldCallback, $title, $parser );
2106
						}
2107
					}
2108
				);
2109
			}
2110
			$edit->output = $edit->pstContent
2111
				? $edit->pstContent->getParserOutput( $this->mTitle, $revid, $edit->popts )
2112
				: null;
2113
		}
2114
2115
		$edit->newContent = $content;
2116
		$edit->oldContent = $this->getContent( Revision::RAW );
2117
2118
		// NOTE: B/C for hooks! don't use these fields!
2119
		$edit->newText = $edit->newContent
2120
			? ContentHandler::getContentText( $edit->newContent )
2121
			: '';
2122
		$edit->oldText = $edit->oldContent
2123
			? ContentHandler::getContentText( $edit->oldContent )
2124
			: '';
2125
		$edit->pst = $edit->pstContent ? $edit->pstContent->serialize( $serialFormat ) : '';
2126
2127
		if ( $edit->output ) {
2128
			$edit->output->setCacheTime( wfTimestampNow() );
2129
		}
2130
2131
		// Process cache the result
2132
		$this->mPreparedEdit = $edit;
2133
2134
		return $edit;
2135
	}
2136
2137
	/**
2138
	 * Do standard deferred updates after page edit.
2139
	 * Update links tables, site stats, search index and message cache.
2140
	 * Purges pages that include this page if the text was changed here.
2141
	 * Every 100th edit, prune the recent changes table.
2142
	 *
2143
	 * @param Revision $revision
2144
	 * @param User $user User object that did the revision
2145
	 * @param array $options Array of options, following indexes are used:
2146
	 * - changed: boolean, whether the revision changed the content (default true)
2147
	 * - created: boolean, whether the revision created the page (default false)
2148
	 * - moved: boolean, whether the page was moved (default false)
2149
	 * - restored: boolean, whether the page was undeleted (default false)
2150
	 * - oldrevision: Revision object for the pre-update revision (default null)
2151
	 * - oldcountable: boolean, null, or string 'no-change' (default null):
2152
	 *   - boolean: whether the page was counted as an article before that
2153
	 *     revision, only used in changed is true and created is false
2154
	 *   - null: if created is false, don't update the article count; if created
2155
	 *     is true, do update the article count
2156
	 *   - 'no-change': don't update the article count, ever
2157
	 */
2158
	public function doEditUpdates( Revision $revision, User $user, array $options = [] ) {
2159
		global $wgRCWatchCategoryMembership, $wgContLang;
2160
2161
		$options += [
2162
			'changed' => true,
2163
			'created' => false,
2164
			'moved' => false,
2165
			'restored' => false,
2166
			'oldrevision' => null,
2167
			'oldcountable' => null
2168
		];
2169
		$content = $revision->getContent();
2170
2171
		// See if the parser output before $revision was inserted is still valid
2172
		$editInfo = false;
2173
		if ( !$this->mPreparedEdit ) {
2174
			wfDebug( __METHOD__ . ": No prepared edit...\n" );
2175
		} elseif ( $this->mPreparedEdit->output->getFlag( 'vary-revision' ) ) {
2176
			wfDebug( __METHOD__ . ": Prepared edit has vary-revision...\n" );
2177
		} elseif ( $this->mPreparedEdit->output->getFlag( 'vary-user' ) && !$options['changed'] ) {
2178
			wfDebug( __METHOD__ . ": Prepared edit has vary-user and is null...\n" );
2179
		} else {
2180
			wfDebug( __METHOD__ . ": Using prepared edit...\n" );
2181
			$editInfo = $this->mPreparedEdit;
2182
		}
2183
2184
		if ( !$editInfo ) {
2185
			// Parse the text again if needed. Be careful not to do pre-save transform twice:
2186
			// $text is usually already pre-save transformed once. Avoid using the edit stash
2187
			// as any prepared content from there or in doEditContent() was already rejected.
2188
			$editInfo = $this->prepareContentForEdit( $content, $revision, $user, null, false );
0 ignored issues
show
Bug introduced by
It seems like $content defined by $revision->getContent() on line 2169 can be null; however, WikiPage::prepareContentForEdit() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
2189
		}
2190
2191
		// Save it to the parser cache.
2192
		// Make sure the cache time matches page_touched to avoid double parsing.
2193
		ParserCache::singleton()->save(
2194
			$editInfo->output, $this, $editInfo->popts,
2195
			$revision->getTimestamp(), $editInfo->revid
0 ignored issues
show
Security Bug introduced by
It seems like $revision->getTimestamp() targeting Revision::getTimestamp() can also be of type false; however, ParserCache::save() does only seem to accept string|null, did you maybe forget to handle an error condition?
Loading history...
2196
		);
2197
2198
		// Update the links tables and other secondary data
2199
		if ( $content ) {
2200
			$recursive = $options['changed']; // bug 50785
2201
			$updates = $content->getSecondaryDataUpdates(
2202
				$this->getTitle(), null, $recursive, $editInfo->output
2203
			);
2204
			foreach ( $updates as $update ) {
2205
				if ( $update instanceof LinksUpdate ) {
2206
					$update->setRevision( $revision );
2207
					$update->setTriggeringUser( $user );
2208
				}
2209
				DeferredUpdates::addUpdate( $update );
2210
			}
2211
			if ( $wgRCWatchCategoryMembership
2212
				&& $this->getContentHandler()->supportsCategories() === true
2213
				&& ( $options['changed'] || $options['created'] )
2214
				&& !$options['restored']
2215
			) {
2216
				// Note: jobs are pushed after deferred updates, so the job should be able to see
2217
				// the recent change entry (also done via deferred updates) and carry over any
2218
				// bot/deletion/IP flags, ect.
2219
				JobQueueGroup::singleton()->lazyPush( new CategoryMembershipChangeJob(
2220
					$this->getTitle(),
2221
					[
2222
						'pageId' => $this->getId(),
2223
						'revTimestamp' => $revision->getTimestamp()
2224
					]
2225
				) );
2226
			}
2227
		}
2228
2229
		Hooks::run( 'ArticleEditUpdates', [ &$this, &$editInfo, $options['changed'] ] );
2230
2231
		if ( Hooks::run( 'ArticleEditUpdatesDeleteFromRecentchanges', [ &$this ] ) ) {
2232
			// Flush old entries from the `recentchanges` table
2233
			if ( mt_rand( 0, 9 ) == 0 ) {
2234
				JobQueueGroup::singleton()->lazyPush( RecentChangesUpdateJob::newPurgeJob() );
2235
			}
2236
		}
2237
2238
		if ( !$this->exists() ) {
2239
			return;
2240
		}
2241
2242
		$id = $this->getId();
2243
		$title = $this->mTitle->getPrefixedDBkey();
2244
		$shortTitle = $this->mTitle->getDBkey();
2245
2246
		if ( $options['oldcountable'] === 'no-change' ||
2247
			( !$options['changed'] && !$options['moved'] )
2248
		) {
2249
			$good = 0;
2250
		} elseif ( $options['created'] ) {
2251
			$good = (int)$this->isCountable( $editInfo );
2252
		} elseif ( $options['oldcountable'] !== null ) {
2253
			$good = (int)$this->isCountable( $editInfo ) - (int)$options['oldcountable'];
2254
		} else {
2255
			$good = 0;
2256
		}
2257
		$edits = $options['changed'] ? 1 : 0;
2258
		$total = $options['created'] ? 1 : 0;
2259
2260
		DeferredUpdates::addUpdate( new SiteStatsUpdate( 0, $edits, $good, $total ) );
2261
		DeferredUpdates::addUpdate( new SearchUpdate( $id, $title, $content ) );
0 ignored issues
show
Bug introduced by
It seems like $content defined by $revision->getContent() on line 2169 can be null; however, SearchUpdate::__construct() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
2262
2263
		// If this is another user's talk page, update newtalk.
2264
		// Don't do this if $options['changed'] = false (null-edits) nor if
2265
		// it's a minor edit and the user doesn't want notifications for those.
2266
		if ( $options['changed']
2267
			&& $this->mTitle->getNamespace() == NS_USER_TALK
2268
			&& $shortTitle != $user->getTitleKey()
2269
			&& !( $revision->isMinor() && $user->isAllowed( 'nominornewtalk' ) )
2270
		) {
2271
			$recipient = User::newFromName( $shortTitle, false );
2272
			if ( !$recipient ) {
2273
				wfDebug( __METHOD__ . ": invalid username\n" );
2274
			} else {
2275
				// Allow extensions to prevent user notification
2276
				// when a new message is added to their talk page
2277
				if ( Hooks::run( 'ArticleEditUpdateNewTalk', [ &$this, $recipient ] ) ) {
2278
					if ( User::isIP( $shortTitle ) ) {
2279
						// An anonymous user
2280
						$recipient->setNewtalk( true, $revision );
2281
					} elseif ( $recipient->isLoggedIn() ) {
2282
						$recipient->setNewtalk( true, $revision );
2283
					} else {
2284
						wfDebug( __METHOD__ . ": don't need to notify a nonexistent user\n" );
2285
					}
2286
				}
2287
			}
2288
		}
2289
2290
		if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
2291
			// XXX: could skip pseudo-messages like js/css here, based on content model.
2292
			$msgtext = $content ? $content->getWikitextForTransclusion() : null;
2293
			if ( $msgtext === false || $msgtext === null ) {
2294
				$msgtext = '';
2295
			}
2296
2297
			MessageCache::singleton()->replace( $shortTitle, $msgtext );
2298
2299
			if ( $wgContLang->hasVariants() ) {
2300
				$wgContLang->updateConversionTable( $this->mTitle );
2301
			}
2302
		}
2303
2304
		if ( $options['created'] ) {
2305
			self::onArticleCreate( $this->mTitle );
2306
		} elseif ( $options['changed'] ) { // bug 50785
2307
			self::onArticleEdit( $this->mTitle, $revision );
2308
		}
2309
	}
2310
2311
	/**
2312
	 * Edit an article without doing all that other stuff
2313
	 * The article must already exist; link tables etc
2314
	 * are not updated, caches are not flushed.
2315
	 *
2316
	 * @param Content $content Content submitted
2317
	 * @param User $user The relevant user
2318
	 * @param string $comment Comment submitted
2319
	 * @param bool $minor Whereas it's a minor modification
2320
	 * @param string $serialFormat Format for storing the content in the database
2321
	 */
2322
	public function doQuickEditContent(
2323
		Content $content, User $user, $comment = '', $minor = false, $serialFormat = null
2324
	) {
2325
2326
		$serialized = $content->serialize( $serialFormat );
2327
2328
		$dbw = wfGetDB( DB_MASTER );
2329
		$revision = new Revision( [
2330
			'title'      => $this->getTitle(), // for determining the default content model
2331
			'page'       => $this->getId(),
2332
			'user_text'  => $user->getName(),
2333
			'user'       => $user->getId(),
2334
			'text'       => $serialized,
2335
			'length'     => $content->getSize(),
2336
			'comment'    => $comment,
2337
			'minor_edit' => $minor ? 1 : 0,
2338
		] ); // XXX: set the content object?
2339
		$revision->insertOn( $dbw );
2340
		$this->updateRevisionOn( $dbw, $revision );
2341
2342
		Hooks::run( 'NewRevisionFromEditComplete', [ $this, $revision, false, $user ] );
2343
2344
	}
2345
2346
	/**
2347
	 * Update the article's restriction field, and leave a log entry.
2348
	 * This works for protection both existing and non-existing pages.
2349
	 *
2350
	 * @param array $limit Set of restriction keys
2351
	 * @param array $expiry Per restriction type expiration
2352
	 * @param int &$cascade Set to false if cascading protection isn't allowed.
2353
	 * @param string $reason
2354
	 * @param User $user The user updating the restrictions
2355
	 * @param string|string[] $tags Change tags to add to the pages and protection log entries
2356
	 *   ($user should be able to add the specified tags before this is called)
2357
	 * @return Status Status object; if action is taken, $status->value is the log_id of the
2358
	 *   protection log entry.
2359
	 */
2360
	public function doUpdateRestrictions( array $limit, array $expiry,
2361
		&$cascade, $reason, User $user, $tags = null
2362
	) {
2363
		global $wgCascadingRestrictionLevels, $wgContLang;
2364
2365
		if ( wfReadOnly() ) {
2366
			return Status::newFatal( 'readonlytext', wfReadOnlyReason() );
2367
		}
2368
2369
		$this->loadPageData( 'fromdbmaster' );
2370
		$restrictionTypes = $this->mTitle->getRestrictionTypes();
2371
		$id = $this->getId();
2372
2373
		if ( !$cascade ) {
2374
			$cascade = false;
2375
		}
2376
2377
		// Take this opportunity to purge out expired restrictions
2378
		Title::purgeExpiredRestrictions();
2379
2380
		// @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
2381
		// we expect a single selection, but the schema allows otherwise.
2382
		$isProtected = false;
2383
		$protect = false;
2384
		$changed = false;
2385
2386
		$dbw = wfGetDB( DB_MASTER );
2387
2388
		foreach ( $restrictionTypes as $action ) {
2389
			if ( !isset( $expiry[$action] ) || $expiry[$action] === $dbw->getInfinity() ) {
2390
				$expiry[$action] = 'infinity';
2391
			}
2392
			if ( !isset( $limit[$action] ) ) {
2393
				$limit[$action] = '';
2394
			} elseif ( $limit[$action] != '' ) {
2395
				$protect = true;
2396
			}
2397
2398
			// Get current restrictions on $action
2399
			$current = implode( '', $this->mTitle->getRestrictions( $action ) );
2400
			if ( $current != '' ) {
2401
				$isProtected = true;
2402
			}
2403
2404
			if ( $limit[$action] != $current ) {
2405
				$changed = true;
2406
			} elseif ( $limit[$action] != '' ) {
2407
				// Only check expiry change if the action is actually being
2408
				// protected, since expiry does nothing on an not-protected
2409
				// action.
2410
				if ( $this->mTitle->getRestrictionExpiry( $action ) != $expiry[$action] ) {
2411
					$changed = true;
2412
				}
2413
			}
2414
		}
2415
2416
		if ( !$changed && $protect && $this->mTitle->areRestrictionsCascading() != $cascade ) {
2417
			$changed = true;
2418
		}
2419
2420
		// If nothing has changed, do nothing
2421
		if ( !$changed ) {
2422
			return Status::newGood();
2423
		}
2424
2425
		if ( !$protect ) { // No protection at all means unprotection
2426
			$revCommentMsg = 'unprotectedarticle';
2427
			$logAction = 'unprotect';
2428
		} elseif ( $isProtected ) {
2429
			$revCommentMsg = 'modifiedarticleprotection';
2430
			$logAction = 'modify';
2431
		} else {
2432
			$revCommentMsg = 'protectedarticle';
2433
			$logAction = 'protect';
2434
		}
2435
2436
		// Truncate for whole multibyte characters
2437
		$reason = $wgContLang->truncate( $reason, 255 );
2438
2439
		$logRelationsValues = [];
2440
		$logRelationsField = null;
2441
		$logParamsDetails = [];
2442
2443
		// Null revision (used for change tag insertion)
2444
		$nullRevision = null;
2445
2446
		if ( $id ) { // Protection of existing page
2447
			if ( !Hooks::run( 'ArticleProtect', [ &$this, &$user, $limit, $reason ] ) ) {
2448
				return Status::newGood();
2449
			}
2450
2451
			// Only certain restrictions can cascade...
2452
			$editrestriction = isset( $limit['edit'] )
2453
				? [ $limit['edit'] ]
2454
				: $this->mTitle->getRestrictions( 'edit' );
2455
			foreach ( array_keys( $editrestriction, 'sysop' ) as $key ) {
2456
				$editrestriction[$key] = 'editprotected'; // backwards compatibility
2457
			}
2458
			foreach ( array_keys( $editrestriction, 'autoconfirmed' ) as $key ) {
2459
				$editrestriction[$key] = 'editsemiprotected'; // backwards compatibility
2460
			}
2461
2462
			$cascadingRestrictionLevels = $wgCascadingRestrictionLevels;
2463
			foreach ( array_keys( $cascadingRestrictionLevels, 'sysop' ) as $key ) {
2464
				$cascadingRestrictionLevels[$key] = 'editprotected'; // backwards compatibility
2465
			}
2466
			foreach ( array_keys( $cascadingRestrictionLevels, 'autoconfirmed' ) as $key ) {
2467
				$cascadingRestrictionLevels[$key] = 'editsemiprotected'; // backwards compatibility
2468
			}
2469
2470
			// The schema allows multiple restrictions
2471
			if ( !array_intersect( $editrestriction, $cascadingRestrictionLevels ) ) {
2472
				$cascade = false;
2473
			}
2474
2475
			// insert null revision to identify the page protection change as edit summary
2476
			$latest = $this->getLatest();
2477
			$nullRevision = $this->insertProtectNullRevision(
2478
				$revCommentMsg,
2479
				$limit,
2480
				$expiry,
2481
				$cascade,
2482
				$reason,
2483
				$user
2484
			);
2485
2486
			if ( $nullRevision === null ) {
2487
				return Status::newFatal( 'no-null-revision', $this->mTitle->getPrefixedText() );
2488
			}
2489
2490
			$logRelationsField = 'pr_id';
2491
2492
			// Update restrictions table
2493
			foreach ( $limit as $action => $restrictions ) {
2494
				$dbw->delete(
2495
					'page_restrictions',
2496
					[
2497
						'pr_page' => $id,
2498
						'pr_type' => $action
2499
					],
2500
					__METHOD__
2501
				);
2502
				if ( $restrictions != '' ) {
2503
					$cascadeValue = ( $cascade && $action == 'edit' ) ? 1 : 0;
2504
					$dbw->insert(
2505
						'page_restrictions',
2506
						[
2507
							'pr_id' => $dbw->nextSequenceValue( 'page_restrictions_pr_id_seq' ),
2508
							'pr_page' => $id,
2509
							'pr_type' => $action,
2510
							'pr_level' => $restrictions,
2511
							'pr_cascade' => $cascadeValue,
2512
							'pr_expiry' => $dbw->encodeExpiry( $expiry[$action] )
2513
						],
2514
						__METHOD__
2515
					);
2516
					$logRelationsValues[] = $dbw->insertId();
2517
					$logParamsDetails[] = [
2518
						'type' => $action,
2519
						'level' => $restrictions,
2520
						'expiry' => $expiry[$action],
2521
						'cascade' => (bool)$cascadeValue,
2522
					];
2523
				}
2524
			}
2525
2526
			// Clear out legacy restriction fields
2527
			$dbw->update(
2528
				'page',
2529
				[ 'page_restrictions' => '' ],
2530
				[ 'page_id' => $id ],
2531
				__METHOD__
2532
			);
2533
2534
			Hooks::run( 'NewRevisionFromEditComplete',
2535
				[ $this, $nullRevision, $latest, $user ] );
2536
			Hooks::run( 'ArticleProtectComplete', [ &$this, &$user, $limit, $reason ] );
2537
		} else { // Protection of non-existing page (also known as "title protection")
2538
			// Cascade protection is meaningless in this case
2539
			$cascade = false;
2540
2541
			if ( $limit['create'] != '' ) {
2542
				$dbw->replace( 'protected_titles',
2543
					[ [ 'pt_namespace', 'pt_title' ] ],
2544
					[
2545
						'pt_namespace' => $this->mTitle->getNamespace(),
2546
						'pt_title' => $this->mTitle->getDBkey(),
2547
						'pt_create_perm' => $limit['create'],
2548
						'pt_timestamp' => $dbw->timestamp(),
2549
						'pt_expiry' => $dbw->encodeExpiry( $expiry['create'] ),
2550
						'pt_user' => $user->getId(),
2551
						'pt_reason' => $reason,
2552
					], __METHOD__
2553
				);
2554
				$logParamsDetails[] = [
2555
					'type' => 'create',
2556
					'level' => $limit['create'],
2557
					'expiry' => $expiry['create'],
2558
				];
2559
			} else {
2560
				$dbw->delete( 'protected_titles',
2561
					[
2562
						'pt_namespace' => $this->mTitle->getNamespace(),
2563
						'pt_title' => $this->mTitle->getDBkey()
2564
					], __METHOD__
2565
				);
2566
			}
2567
		}
2568
2569
		$this->mTitle->flushRestrictions();
2570
		InfoAction::invalidateCache( $this->mTitle );
2571
2572
		if ( $logAction == 'unprotect' ) {
2573
			$params = [];
2574
		} else {
2575
			$protectDescriptionLog = $this->protectDescriptionLog( $limit, $expiry );
2576
			$params = [
2577
				'4::description' => $protectDescriptionLog, // parameter for IRC
2578
				'5:bool:cascade' => $cascade,
2579
				'details' => $logParamsDetails, // parameter for localize and api
2580
			];
2581
		}
2582
2583
		// Update the protection log
2584
		$logEntry = new ManualLogEntry( 'protect', $logAction );
2585
		$logEntry->setTarget( $this->mTitle );
2586
		$logEntry->setComment( $reason );
2587
		$logEntry->setPerformer( $user );
2588
		$logEntry->setParameters( $params );
2589
		if ( !is_null( $nullRevision ) ) {
2590
			$logEntry->setAssociatedRevId( $nullRevision->getId() );
2591
		}
2592
		$logEntry->setTags( $tags );
0 ignored issues
show
Bug introduced by
It seems like $tags defined by parameter $tags on line 2361 can also be of type null; however, ManualLogEntry::setTags() does only seem to accept string|array<integer,string>, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
2593
		if ( $logRelationsField !== null && count( $logRelationsValues ) ) {
2594
			$logEntry->setRelations( [ $logRelationsField => $logRelationsValues ] );
2595
		}
2596
		$logId = $logEntry->insert();
2597
		$logEntry->publish( $logId );
2598
2599
		return Status::newGood( $logId );
2600
	}
2601
2602
	/**
2603
	 * Insert a new null revision for this page.
2604
	 *
2605
	 * @param string $revCommentMsg Comment message key for the revision
2606
	 * @param array $limit Set of restriction keys
2607
	 * @param array $expiry Per restriction type expiration
2608
	 * @param int $cascade Set to false if cascading protection isn't allowed.
2609
	 * @param string $reason
2610
	 * @param User|null $user
2611
	 * @return Revision|null Null on error
2612
	 */
2613
	public function insertProtectNullRevision( $revCommentMsg, array $limit,
2614
		array $expiry, $cascade, $reason, $user = null
2615
	) {
2616
		global $wgContLang;
2617
		$dbw = wfGetDB( DB_MASTER );
2618
2619
		// Prepare a null revision to be added to the history
2620
		$editComment = $wgContLang->ucfirst(
2621
			wfMessage(
2622
				$revCommentMsg,
2623
				$this->mTitle->getPrefixedText()
2624
			)->inContentLanguage()->text()
2625
		);
2626
		if ( $reason ) {
2627
			$editComment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
2628
		}
2629
		$protectDescription = $this->protectDescription( $limit, $expiry );
2630
		if ( $protectDescription ) {
2631
			$editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2632
			$editComment .= wfMessage( 'parentheses' )->params( $protectDescription )
2633
				->inContentLanguage()->text();
2634
		}
2635
		if ( $cascade ) {
2636
			$editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2637
			$editComment .= wfMessage( 'brackets' )->params(
2638
				wfMessage( 'protect-summary-cascade' )->inContentLanguage()->text()
2639
			)->inContentLanguage()->text();
2640
		}
2641
2642
		$nullRev = Revision::newNullRevision( $dbw, $this->getId(), $editComment, true, $user );
2643
		if ( $nullRev ) {
2644
			$nullRev->insertOn( $dbw );
2645
2646
			// Update page record and touch page
2647
			$oldLatest = $nullRev->getParentId();
2648
			$this->updateRevisionOn( $dbw, $nullRev, $oldLatest );
2649
		}
2650
2651
		return $nullRev;
2652
	}
2653
2654
	/**
2655
	 * @param string $expiry 14-char timestamp or "infinity", or false if the input was invalid
2656
	 * @return string
2657
	 */
2658
	protected function formatExpiry( $expiry ) {
2659
		global $wgContLang;
2660
2661
		if ( $expiry != 'infinity' ) {
2662
			return wfMessage(
2663
				'protect-expiring',
2664
				$wgContLang->timeanddate( $expiry, false, false ),
2665
				$wgContLang->date( $expiry, false, false ),
2666
				$wgContLang->time( $expiry, false, false )
2667
			)->inContentLanguage()->text();
2668
		} else {
2669
			return wfMessage( 'protect-expiry-indefinite' )
2670
				->inContentLanguage()->text();
2671
		}
2672
	}
2673
2674
	/**
2675
	 * Builds the description to serve as comment for the edit.
2676
	 *
2677
	 * @param array $limit Set of restriction keys
2678
	 * @param array $expiry Per restriction type expiration
2679
	 * @return string
2680
	 */
2681
	public function protectDescription( array $limit, array $expiry ) {
2682
		$protectDescription = '';
2683
2684
		foreach ( array_filter( $limit ) as $action => $restrictions ) {
2685
			# $action is one of $wgRestrictionTypes = array( 'create', 'edit', 'move', 'upload' ).
2686
			# All possible message keys are listed here for easier grepping:
2687
			# * restriction-create
2688
			# * restriction-edit
2689
			# * restriction-move
2690
			# * restriction-upload
2691
			$actionText = wfMessage( 'restriction-' . $action )->inContentLanguage()->text();
2692
			# $restrictions is one of $wgRestrictionLevels = array( '', 'autoconfirmed', 'sysop' ),
2693
			# with '' filtered out. All possible message keys are listed below:
2694
			# * protect-level-autoconfirmed
2695
			# * protect-level-sysop
2696
			$restrictionsText = wfMessage( 'protect-level-' . $restrictions )
2697
				->inContentLanguage()->text();
2698
2699
			$expiryText = $this->formatExpiry( $expiry[$action] );
2700
2701
			if ( $protectDescription !== '' ) {
2702
				$protectDescription .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2703
			}
2704
			$protectDescription .= wfMessage( 'protect-summary-desc' )
2705
				->params( $actionText, $restrictionsText, $expiryText )
2706
				->inContentLanguage()->text();
2707
		}
2708
2709
		return $protectDescription;
2710
	}
2711
2712
	/**
2713
	 * Builds the description to serve as comment for the log entry.
2714
	 *
2715
	 * Some bots may parse IRC lines, which are generated from log entries which contain plain
2716
	 * protect description text. Keep them in old format to avoid breaking compatibility.
2717
	 * TODO: Fix protection log to store structured description and format it on-the-fly.
2718
	 *
2719
	 * @param array $limit Set of restriction keys
2720
	 * @param array $expiry Per restriction type expiration
2721
	 * @return string
2722
	 */
2723
	public function protectDescriptionLog( array $limit, array $expiry ) {
2724
		global $wgContLang;
2725
2726
		$protectDescriptionLog = '';
2727
2728
		foreach ( array_filter( $limit ) as $action => $restrictions ) {
2729
			$expiryText = $this->formatExpiry( $expiry[$action] );
2730
			$protectDescriptionLog .= $wgContLang->getDirMark() .
2731
				"[$action=$restrictions] ($expiryText)";
2732
		}
2733
2734
		return trim( $protectDescriptionLog );
2735
	}
2736
2737
	/**
2738
	 * Take an array of page restrictions and flatten it to a string
2739
	 * suitable for insertion into the page_restrictions field.
2740
	 *
2741
	 * @param string[] $limit
2742
	 *
2743
	 * @throws MWException
2744
	 * @return string
2745
	 */
2746
	protected static function flattenRestrictions( $limit ) {
2747
		if ( !is_array( $limit ) ) {
2748
			throw new MWException( __METHOD__ . ' given non-array restriction set' );
2749
		}
2750
2751
		$bits = [];
2752
		ksort( $limit );
2753
2754
		foreach ( array_filter( $limit ) as $action => $restrictions ) {
2755
			$bits[] = "$action=$restrictions";
2756
		}
2757
2758
		return implode( ':', $bits );
2759
	}
2760
2761
	/**
2762
	 * Same as doDeleteArticleReal(), but returns a simple boolean. This is kept around for
2763
	 * backwards compatibility, if you care about error reporting you should use
2764
	 * doDeleteArticleReal() instead.
2765
	 *
2766
	 * Deletes the article with database consistency, writes logs, purges caches
2767
	 *
2768
	 * @param string $reason Delete reason for deletion log
2769
	 * @param bool $suppress Suppress all revisions and log the deletion in
2770
	 *        the suppression log instead of the deletion log
2771
	 * @param int $u1 Unused
2772
	 * @param bool $u2 Unused
2773
	 * @param array|string &$error Array of errors to append to
2774
	 * @param User $user The deleting user
2775
	 * @return bool True if successful
2776
	 */
2777
	public function doDeleteArticle(
2778
		$reason, $suppress = false, $u1 = null, $u2 = null, &$error = '', User $user = null
2779
	) {
2780
		$status = $this->doDeleteArticleReal( $reason, $suppress, $u1, $u2, $error, $user );
2781
		return $status->isGood();
2782
	}
2783
2784
	/**
2785
	 * Back-end article deletion
2786
	 * Deletes the article with database consistency, writes logs, purges caches
2787
	 *
2788
	 * @since 1.19
2789
	 *
2790
	 * @param string $reason Delete reason for deletion log
2791
	 * @param bool $suppress Suppress all revisions and log the deletion in
2792
	 *   the suppression log instead of the deletion log
2793
	 * @param int $u1 Unused
2794
	 * @param bool $u2 Unused
2795
	 * @param array|string &$error Array of errors to append to
2796
	 * @param User $user The deleting user
2797
	 * @return Status Status object; if successful, $status->value is the log_id of the
2798
	 *   deletion log entry. If the page couldn't be deleted because it wasn't
2799
	 *   found, $status is a non-fatal 'cannotdelete' error
2800
	 */
2801
	public function doDeleteArticleReal(
2802
		$reason, $suppress = false, $u1 = null, $u2 = null, &$error = '', User $user = null
2803
	) {
2804
		global $wgUser, $wgContentHandlerUseDB;
2805
2806
		wfDebug( __METHOD__ . "\n" );
2807
2808
		$status = Status::newGood();
2809
2810
		if ( $this->mTitle->getDBkey() === '' ) {
2811
			$status->error( 'cannotdelete',
2812
				wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2813
			return $status;
2814
		}
2815
2816
		$user = is_null( $user ) ? $wgUser : $user;
2817
		if ( !Hooks::run( 'ArticleDelete',
2818
			[ &$this, &$user, &$reason, &$error, &$status, $suppress ]
2819
		) ) {
2820
			if ( $status->isOK() ) {
2821
				// Hook aborted but didn't set a fatal status
2822
				$status->fatal( 'delete-hook-aborted' );
2823
			}
2824
			return $status;
2825
		}
2826
2827
		$dbw = wfGetDB( DB_MASTER );
2828
		$dbw->startAtomic( __METHOD__ );
2829
2830
		$this->loadPageData( self::READ_LATEST );
2831
		$id = $this->getId();
2832
		// T98706: lock the page from various other updates but avoid using
2833
		// WikiPage::READ_LOCKING as that will carry over the FOR UPDATE to
2834
		// the revisions queries (which also JOIN on user). Only lock the page
2835
		// row and CAS check on page_latest to see if the trx snapshot matches.
2836
		$lockedLatest = $this->lockAndGetLatest();
2837
		if ( $id == 0 || $this->getLatest() != $lockedLatest ) {
2838
			$dbw->endAtomic( __METHOD__ );
2839
			// Page not there or trx snapshot is stale
2840
			$status->error( 'cannotdelete',
2841
				wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2842
			return $status;
2843
		}
2844
2845
		// At this point we are now comitted to returning an OK
2846
		// status unless some DB query error or other exception comes up.
2847
		// This way callers don't have to call rollback() if $status is bad
2848
		// unless they actually try to catch exceptions (which is rare).
2849
2850
		// we need to remember the old content so we can use it to generate all deletion updates.
2851
		$content = $this->getContent( Revision::RAW );
2852
2853
		// Bitfields to further suppress the content
2854 View Code Duplication
		if ( $suppress ) {
2855
			$bitfield = 0;
2856
			// This should be 15...
2857
			$bitfield |= Revision::DELETED_TEXT;
2858
			$bitfield |= Revision::DELETED_COMMENT;
2859
			$bitfield |= Revision::DELETED_USER;
2860
			$bitfield |= Revision::DELETED_RESTRICTED;
2861
		} else {
2862
			$bitfield = 'rev_deleted';
2863
		}
2864
2865
		/**
2866
		 * For now, shunt the revision data into the archive table.
2867
		 * Text is *not* removed from the text table; bulk storage
2868
		 * is left intact to avoid breaking block-compression or
2869
		 * immutable storage schemes.
2870
		 *
2871
		 * For backwards compatibility, note that some older archive
2872
		 * table entries will have ar_text and ar_flags fields still.
2873
		 *
2874
		 * In the future, we may keep revisions and mark them with
2875
		 * the rev_deleted field, which is reserved for this purpose.
2876
		 */
2877
2878
		$row = [
2879
			'ar_namespace'  => 'page_namespace',
2880
			'ar_title'      => 'page_title',
2881
			'ar_comment'    => 'rev_comment',
2882
			'ar_user'       => 'rev_user',
2883
			'ar_user_text'  => 'rev_user_text',
2884
			'ar_timestamp'  => 'rev_timestamp',
2885
			'ar_minor_edit' => 'rev_minor_edit',
2886
			'ar_rev_id'     => 'rev_id',
2887
			'ar_parent_id'  => 'rev_parent_id',
2888
			'ar_text_id'    => 'rev_text_id',
2889
			'ar_text'       => '\'\'', // Be explicit to appease
2890
			'ar_flags'      => '\'\'', // MySQL's "strict mode"...
2891
			'ar_len'        => 'rev_len',
2892
			'ar_page_id'    => 'page_id',
2893
			'ar_deleted'    => $bitfield,
2894
			'ar_sha1'       => 'rev_sha1',
2895
		];
2896
2897
		if ( $wgContentHandlerUseDB ) {
2898
			$row['ar_content_model'] = 'rev_content_model';
2899
			$row['ar_content_format'] = 'rev_content_format';
2900
		}
2901
2902
		// Copy all the page revisions into the archive table
2903
		$dbw->insertSelect(
2904
			'archive',
2905
			[ 'page', 'revision' ],
2906
			$row,
2907
			[
2908
				'page_id' => $id,
2909
				'page_id = rev_page'
2910
			],
2911
			__METHOD__
2912
		);
2913
2914
		// Now that it's safely backed up, delete it
2915
		$dbw->delete( 'page', [ 'page_id' => $id ], __METHOD__ );
2916
2917
		if ( !$dbw->cascadingDeletes() ) {
2918
			$dbw->delete( 'revision', [ 'rev_page' => $id ], __METHOD__ );
2919
		}
2920
2921
		// Clone the title, so we have the information we need when we log
2922
		$logTitle = clone $this->mTitle;
2923
2924
		// Log the deletion, if the page was suppressed, put it in the suppression log instead
2925
		$logtype = $suppress ? 'suppress' : 'delete';
2926
2927
		$logEntry = new ManualLogEntry( $logtype, 'delete' );
2928
		$logEntry->setPerformer( $user );
2929
		$logEntry->setTarget( $logTitle );
2930
		$logEntry->setComment( $reason );
2931
		$logid = $logEntry->insert();
2932
2933
		$dbw->onTransactionPreCommitOrIdle( function () use ( $dbw, $logEntry, $logid ) {
2934
			// Bug 56776: avoid deadlocks (especially from FileDeleteForm)
2935
			$logEntry->publish( $logid );
2936
		} );
2937
2938
		$dbw->endAtomic( __METHOD__ );
2939
2940
		$this->doDeleteUpdates( $id, $content );
2941
2942
		Hooks::run( 'ArticleDeleteComplete',
2943
			[ &$this, &$user, $reason, $id, $content, $logEntry ] );
2944
		$status->value = $logid;
2945
2946
		// Show log excerpt on 404 pages rather than just a link
2947
		$cache = ObjectCache::getMainStashInstance();
2948
		$key = wfMemcKey( 'page-recent-delete', md5( $logTitle->getPrefixedText() ) );
2949
		$cache->set( $key, 1, $cache::TTL_DAY );
2950
2951
		return $status;
2952
	}
2953
2954
	/**
2955
	 * Lock the page row for this title+id and return page_latest (or 0)
2956
	 *
2957
	 * @return integer Returns 0 if no row was found with this title+id
2958
	 * @since 1.27
2959
	 */
2960
	public function lockAndGetLatest() {
2961
		return (int)wfGetDB( DB_MASTER )->selectField(
2962
			'page',
2963
			'page_latest',
2964
			[
2965
				'page_id' => $this->getId(),
2966
				// Typically page_id is enough, but some code might try to do
2967
				// updates assuming the title is the same, so verify that
2968
				'page_namespace' => $this->getTitle()->getNamespace(),
2969
				'page_title' => $this->getTitle()->getDBkey()
2970
			],
2971
			__METHOD__,
2972
			[ 'FOR UPDATE' ]
2973
		);
2974
	}
2975
2976
	/**
2977
	 * Do some database updates after deletion
2978
	 *
2979
	 * @param int $id The page_id value of the page being deleted
2980
	 * @param Content $content Optional page content to be used when determining
2981
	 *   the required updates. This may be needed because $this->getContent()
2982
	 *   may already return null when the page proper was deleted.
2983
	 */
2984
	public function doDeleteUpdates( $id, Content $content = null ) {
2985
		// Update site status
2986
		DeferredUpdates::addUpdate( new SiteStatsUpdate( 0, 1, - (int)$this->isCountable(), -1 ) );
2987
2988
		// Delete pagelinks, update secondary indexes, etc
2989
		$updates = $this->getDeletionUpdates( $content );
2990
		foreach ( $updates as $update ) {
2991
			DeferredUpdates::addUpdate( $update );
2992
		}
2993
2994
		// Reparse any pages transcluding this page
2995
		LinksUpdate::queueRecursiveJobsForTable( $this->mTitle, 'templatelinks' );
2996
2997
		// Reparse any pages including this image
2998
		if ( $this->mTitle->getNamespace() == NS_FILE ) {
2999
			LinksUpdate::queueRecursiveJobsForTable( $this->mTitle, 'imagelinks' );
3000
		}
3001
3002
		// Clear caches
3003
		WikiPage::onArticleDelete( $this->mTitle );
3004
3005
		// Reset this object and the Title object
3006
		$this->loadFromRow( false, self::READ_LATEST );
3007
3008
		// Search engine
3009
		DeferredUpdates::addUpdate( new SearchUpdate( $id, $this->mTitle ) );
3010
	}
3011
3012
	/**
3013
	 * Roll back the most recent consecutive set of edits to a page
3014
	 * from the same user; fails if there are no eligible edits to
3015
	 * roll back to, e.g. user is the sole contributor. This function
3016
	 * performs permissions checks on $user, then calls commitRollback()
3017
	 * to do the dirty work
3018
	 *
3019
	 * @todo Separate the business/permission stuff out from backend code
3020
	 * @todo Remove $token parameter. Already verified by RollbackAction and ApiRollback.
3021
	 *
3022
	 * @param string $fromP Name of the user whose edits to rollback.
3023
	 * @param string $summary Custom summary. Set to default summary if empty.
3024
	 * @param string $token Rollback token.
3025
	 * @param bool $bot If true, mark all reverted edits as bot.
3026
	 *
3027
	 * @param array $resultDetails Array contains result-specific array of additional values
3028
	 *    'alreadyrolled' : 'current' (rev)
3029
	 *    success        : 'summary' (str), 'current' (rev), 'target' (rev)
3030
	 *
3031
	 * @param User $user The user performing the rollback
3032
	 * @param array|null $tags Change tags to apply to the rollback
3033
	 * Callers are responsible for permission checks
3034
	 * (with ChangeTags::canAddTagsAccompanyingChange)
3035
	 *
3036
	 * @return array Array of errors, each error formatted as
3037
	 *   array(messagekey, param1, param2, ...).
3038
	 * On success, the array is empty.  This array can also be passed to
3039
	 * OutputPage::showPermissionsErrorPage().
3040
	 */
3041
	public function doRollback(
3042
		$fromP, $summary, $token, $bot, &$resultDetails, User $user, $tags = null
3043
	) {
3044
		$resultDetails = null;
3045
3046
		// Check permissions
3047
		$editErrors = $this->mTitle->getUserPermissionsErrors( 'edit', $user );
3048
		$rollbackErrors = $this->mTitle->getUserPermissionsErrors( 'rollback', $user );
3049
		$errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
3050
3051
		if ( !$user->matchEditToken( $token, 'rollback' ) ) {
3052
			$errors[] = [ 'sessionfailure' ];
3053
		}
3054
3055
		if ( $user->pingLimiter( 'rollback' ) || $user->pingLimiter() ) {
3056
			$errors[] = [ 'actionthrottledtext' ];
3057
		}
3058
3059
		// If there were errors, bail out now
3060
		if ( !empty( $errors ) ) {
3061
			return $errors;
3062
		}
3063
3064
		return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user, $tags );
3065
	}
3066
3067
	/**
3068
	 * Backend implementation of doRollback(), please refer there for parameter
3069
	 * and return value documentation
3070
	 *
3071
	 * NOTE: This function does NOT check ANY permissions, it just commits the
3072
	 * rollback to the DB. Therefore, you should only call this function direct-
3073
	 * ly if you want to use custom permissions checks. If you don't, use
3074
	 * doRollback() instead.
3075
	 * @param string $fromP Name of the user whose edits to rollback.
3076
	 * @param string $summary Custom summary. Set to default summary if empty.
3077
	 * @param bool $bot If true, mark all reverted edits as bot.
3078
	 *
3079
	 * @param array $resultDetails Contains result-specific array of additional values
3080
	 * @param User $guser The user performing the rollback
3081
	 * @param array|null $tags Change tags to apply to the rollback
3082
	 * Callers are responsible for permission checks
3083
	 * (with ChangeTags::canAddTagsAccompanyingChange)
3084
	 *
3085
	 * @return array
3086
	 */
3087
	public function commitRollback( $fromP, $summary, $bot,
3088
		&$resultDetails, User $guser, $tags = null
3089
	) {
3090
		global $wgUseRCPatrol, $wgContLang;
3091
3092
		$dbw = wfGetDB( DB_MASTER );
3093
3094
		if ( wfReadOnly() ) {
3095
			return [ [ 'readonlytext' ] ];
3096
		}
3097
3098
		// Get the last editor
3099
		$current = $this->getRevision();
3100
		if ( is_null( $current ) ) {
3101
			// Something wrong... no page?
3102
			return [ [ 'notanarticle' ] ];
3103
		}
3104
3105
		$from = str_replace( '_', ' ', $fromP );
3106
		// User name given should match up with the top revision.
3107
		// If the user was deleted then $from should be empty.
3108 View Code Duplication
		if ( $from != $current->getUserText() ) {
3109
			$resultDetails = [ 'current' => $current ];
3110
			return [ [ 'alreadyrolled',
3111
				htmlspecialchars( $this->mTitle->getPrefixedText() ),
3112
				htmlspecialchars( $fromP ),
3113
				htmlspecialchars( $current->getUserText() )
3114
			] ];
3115
		}
3116
3117
		// Get the last edit not by this person...
3118
		// Note: these may not be public values
3119
		$user = intval( $current->getUser( Revision::RAW ) );
3120
		$user_text = $dbw->addQuotes( $current->getUserText( Revision::RAW ) );
0 ignored issues
show
Bug introduced by
It seems like $current->getUserText(\Revision::RAW) targeting Revision::getUserText() can also be of type boolean; however, DatabaseBase::addQuotes() does only seem to accept string|object<Blob>, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
3121
		$s = $dbw->selectRow( 'revision',
3122
			[ 'rev_id', 'rev_timestamp', 'rev_deleted' ],
3123
			[ 'rev_page' => $current->getPage(),
3124
				"rev_user != {$user} OR rev_user_text != {$user_text}"
3125
			], __METHOD__,
3126
			[ 'USE INDEX' => 'page_timestamp',
3127
				'ORDER BY' => 'rev_timestamp DESC' ]
3128
			);
3129
		if ( $s === false ) {
3130
			// No one else ever edited this page
3131
			return [ [ 'cantrollback' ] ];
3132
		} elseif ( $s->rev_deleted & Revision::DELETED_TEXT
3133
			|| $s->rev_deleted & Revision::DELETED_USER
3134
		) {
3135
			// Only admins can see this text
3136
			return [ [ 'notvisiblerev' ] ];
3137
		}
3138
3139
		// Generate the edit summary if necessary
3140
		$target = Revision::newFromId( $s->rev_id, Revision::READ_LATEST );
3141
		if ( empty( $summary ) ) {
3142
			if ( $from == '' ) { // no public user name
3143
				$summary = wfMessage( 'revertpage-nouser' );
3144
			} else {
3145
				$summary = wfMessage( 'revertpage' );
3146
			}
3147
		}
3148
3149
		// Allow the custom summary to use the same args as the default message
3150
		$args = [
3151
			$target->getUserText(), $from, $s->rev_id,
3152
			$wgContLang->timeanddate( wfTimestamp( TS_MW, $s->rev_timestamp ) ),
3153
			$current->getId(), $wgContLang->timeanddate( $current->getTimestamp() )
3154
		];
3155
		if ( $summary instanceof Message ) {
3156
			$summary = $summary->params( $args )->inContentLanguage()->text();
3157
		} else {
3158
			$summary = wfMsgReplaceArgs( $summary, $args );
3159
		}
3160
3161
		// Trim spaces on user supplied text
3162
		$summary = trim( $summary );
3163
3164
		// Truncate for whole multibyte characters.
3165
		$summary = $wgContLang->truncate( $summary, 255 );
3166
3167
		// Save
3168
		$flags = EDIT_UPDATE | EDIT_INTERNAL;
3169
3170
		if ( $guser->isAllowed( 'minoredit' ) ) {
3171
			$flags |= EDIT_MINOR;
3172
		}
3173
3174
		if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
3175
			$flags |= EDIT_FORCE_BOT;
3176
		}
3177
3178
		// Actually store the edit
3179
		$status = $this->doEditContent(
3180
			$target->getContent(),
3181
			$summary,
3182
			$flags,
3183
			$target->getId(),
3184
			$guser,
3185
			null,
3186
			$tags
3187
		);
3188
3189
		// Set patrolling and bot flag on the edits, which gets rollbacked.
3190
		// This is done even on edit failure to have patrolling in that case (bug 62157).
3191
		$set = [];
3192
		if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
3193
			// Mark all reverted edits as bot
3194
			$set['rc_bot'] = 1;
3195
		}
3196
3197
		if ( $wgUseRCPatrol ) {
3198
			// Mark all reverted edits as patrolled
3199
			$set['rc_patrolled'] = 1;
3200
		}
3201
3202
		if ( count( $set ) ) {
3203
			$dbw->update( 'recentchanges', $set,
3204
				[ /* WHERE */
3205
					'rc_cur_id' => $current->getPage(),
3206
					'rc_user_text' => $current->getUserText(),
3207
					'rc_timestamp > ' . $dbw->addQuotes( $s->rev_timestamp ),
3208
				],
3209
				__METHOD__
3210
			);
3211
		}
3212
3213
		if ( !$status->isOK() ) {
3214
			return $status->getErrorsArray();
0 ignored issues
show
Deprecated Code introduced by
The method Status::getErrorsArray() has been deprecated with message: 1.25

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
3215
		}
3216
3217
		// raise error, when the edit is an edit without a new version
3218
		$statusRev = isset( $status->value['revision'] )
3219
			? $status->value['revision']
3220
			: null;
3221 View Code Duplication
		if ( !( $statusRev instanceof Revision ) ) {
3222
			$resultDetails = [ 'current' => $current ];
3223
			return [ [ 'alreadyrolled',
3224
					htmlspecialchars( $this->mTitle->getPrefixedText() ),
3225
					htmlspecialchars( $fromP ),
3226
					htmlspecialchars( $current->getUserText() )
3227
			] ];
3228
		}
3229
3230
		$revId = $statusRev->getId();
3231
3232
		Hooks::run( 'ArticleRollbackComplete', [ $this, $guser, $target, $current ] );
3233
3234
		$resultDetails = [
3235
			'summary' => $summary,
3236
			'current' => $current,
3237
			'target' => $target,
3238
			'newid' => $revId
3239
		];
3240
3241
		return [];
3242
	}
3243
3244
	/**
3245
	 * The onArticle*() functions are supposed to be a kind of hooks
3246
	 * which should be called whenever any of the specified actions
3247
	 * are done.
3248
	 *
3249
	 * This is a good place to put code to clear caches, for instance.
3250
	 *
3251
	 * This is called on page move and undelete, as well as edit
3252
	 *
3253
	 * @param Title $title
3254
	 */
3255
	public static function onArticleCreate( Title $title ) {
3256
		// Update existence markers on article/talk tabs...
3257
		$other = $title->getOtherPage();
3258
3259
		$other->purgeSquid();
3260
3261
		$title->touchLinks();
3262
		$title->purgeSquid();
3263
		$title->deleteTitleProtection();
3264
	}
3265
3266
	/**
3267
	 * Clears caches when article is deleted
3268
	 *
3269
	 * @param Title $title
3270
	 */
3271
	public static function onArticleDelete( Title $title ) {
3272
		global $wgContLang;
3273
3274
		// Update existence markers on article/talk tabs...
3275
		$other = $title->getOtherPage();
3276
3277
		$other->purgeSquid();
3278
3279
		$title->touchLinks();
3280
		$title->purgeSquid();
3281
3282
		// File cache
3283
		HTMLFileCache::clearFileCache( $title );
3284
		InfoAction::invalidateCache( $title );
3285
3286
		// Messages
3287
		if ( $title->getNamespace() == NS_MEDIAWIKI ) {
3288
			MessageCache::singleton()->replace( $title->getDBkey(), false );
3289
3290
			if ( $wgContLang->hasVariants() ) {
3291
				$wgContLang->updateConversionTable( $title );
3292
			}
3293
		}
3294
3295
		// Images
3296
		if ( $title->getNamespace() == NS_FILE ) {
3297
			DeferredUpdates::addUpdate( new HTMLCacheUpdate( $title, 'imagelinks' ) );
3298
		}
3299
3300
		// User talk pages
3301
		if ( $title->getNamespace() == NS_USER_TALK ) {
3302
			$user = User::newFromName( $title->getText(), false );
3303
			if ( $user ) {
3304
				$user->setNewtalk( false );
3305
			}
3306
		}
3307
3308
		// Image redirects
3309
		RepoGroup::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
3310
	}
3311
3312
	/**
3313
	 * Purge caches on page update etc
3314
	 *
3315
	 * @param Title $title
3316
	 * @param Revision|null $revision Revision that was just saved, may be null
3317
	 */
3318
	public static function onArticleEdit( Title $title, Revision $revision = null ) {
3319
		// Invalidate caches of articles which include this page
3320
		DeferredUpdates::addUpdate( new HTMLCacheUpdate( $title, 'templatelinks' ) );
3321
3322
		// Invalidate the caches of all pages which redirect here
3323
		DeferredUpdates::addUpdate( new HTMLCacheUpdate( $title, 'redirect' ) );
3324
3325
		// Purge CDN for this page only
3326
		$title->purgeSquid();
3327
		// Clear file cache for this page only
3328
		HTMLFileCache::clearFileCache( $title );
3329
3330
		$revid = $revision ? $revision->getId() : null;
3331
		DeferredUpdates::addCallableUpdate( function() use ( $title, $revid ) {
3332
			InfoAction::invalidateCache( $title, $revid );
3333
		} );
3334
	}
3335
3336
	/**#@-*/
3337
3338
	/**
3339
	 * Returns a list of categories this page is a member of.
3340
	 * Results will include hidden categories
3341
	 *
3342
	 * @return TitleArray
3343
	 */
3344
	public function getCategories() {
3345
		$id = $this->getId();
3346
		if ( $id == 0 ) {
3347
			return TitleArray::newFromResult( new FakeResultWrapper( [] ) );
3348
		}
3349
3350
		$dbr = wfGetDB( DB_SLAVE );
3351
		$res = $dbr->select( 'categorylinks',
3352
			[ 'cl_to AS page_title, ' . NS_CATEGORY . ' AS page_namespace' ],
3353
			// Have to do that since DatabaseBase::fieldNamesWithAlias treats numeric indexes
3354
			// as not being aliases, and NS_CATEGORY is numeric
3355
			[ 'cl_from' => $id ],
3356
			__METHOD__ );
3357
3358
		return TitleArray::newFromResult( $res );
0 ignored issues
show
Bug introduced by
It seems like $res defined by $dbr->select('categoryli...m' => $id), __METHOD__) on line 3351 can also be of type boolean; however, TitleArray::newFromResult() does only seem to accept object<ResultWrapper>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
3359
	}
3360
3361
	/**
3362
	 * Returns a list of hidden categories this page is a member of.
3363
	 * Uses the page_props and categorylinks tables.
3364
	 *
3365
	 * @return array Array of Title objects
3366
	 */
3367
	public function getHiddenCategories() {
3368
		$result = [];
3369
		$id = $this->getId();
3370
3371
		if ( $id == 0 ) {
3372
			return [];
3373
		}
3374
3375
		$dbr = wfGetDB( DB_SLAVE );
3376
		$res = $dbr->select( [ 'categorylinks', 'page_props', 'page' ],
3377
			[ 'cl_to' ],
3378
			[ 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3379
				'page_namespace' => NS_CATEGORY, 'page_title=cl_to' ],
3380
			__METHOD__ );
3381
3382
		if ( $res !== false ) {
3383
			foreach ( $res as $row ) {
0 ignored issues
show
Bug introduced by
The expression $res of type object<ResultWrapper>|boolean is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
3384
				$result[] = Title::makeTitle( NS_CATEGORY, $row->cl_to );
3385
			}
3386
		}
3387
3388
		return $result;
3389
	}
3390
3391
	/**
3392
	 * Return an applicable autosummary if one exists for the given edit.
3393
	 * @param string|null $oldtext The previous text of the page.
3394
	 * @param string|null $newtext The submitted text of the page.
3395
	 * @param int $flags Bitmask: a bitmask of flags submitted for the edit.
3396
	 * @return string An appropriate autosummary, or an empty string.
3397
	 *
3398
	 * @deprecated since 1.21, use ContentHandler::getAutosummary() instead
3399
	 */
3400
	public static function getAutosummary( $oldtext, $newtext, $flags ) {
3401
		// NOTE: stub for backwards-compatibility. assumes the given text is
3402
		// wikitext. will break horribly if it isn't.
3403
3404
		ContentHandler::deprecated( __METHOD__, '1.21' );
3405
3406
		$handler = ContentHandler::getForModelID( CONTENT_MODEL_WIKITEXT );
3407
		$oldContent = is_null( $oldtext ) ? null : $handler->unserializeContent( $oldtext );
3408
		$newContent = is_null( $newtext ) ? null : $handler->unserializeContent( $newtext );
3409
3410
		return $handler->getAutosummary( $oldContent, $newContent, $flags );
3411
	}
3412
3413
	/**
3414
	 * Auto-generates a deletion reason
3415
	 *
3416
	 * @param bool &$hasHistory Whether the page has a history
3417
	 * @return string|bool String containing deletion reason or empty string, or boolean false
3418
	 *    if no revision occurred
3419
	 */
3420
	public function getAutoDeleteReason( &$hasHistory ) {
3421
		return $this->getContentHandler()->getAutoDeleteReason( $this->getTitle(), $hasHistory );
3422
	}
3423
3424
	/**
3425
	 * Update all the appropriate counts in the category table, given that
3426
	 * we've added the categories $added and deleted the categories $deleted.
3427
	 *
3428
	 * @param array $added The names of categories that were added
3429
	 * @param array $deleted The names of categories that were deleted
3430
	 * @param integer $id Page ID (this should be the original deleted page ID)
3431
	 */
3432
	public function updateCategoryCounts( array $added, array $deleted, $id = 0 ) {
3433
		$id = $id ?: $this->getId();
3434
		$dbw = wfGetDB( DB_MASTER );
3435
		$method = __METHOD__;
3436
		// Do this at the end of the commit to reduce lock wait timeouts
3437
		$dbw->onTransactionPreCommitOrIdle(
3438
			function () use ( $dbw, $added, $deleted, $id, $method ) {
3439
				$ns = $this->getTitle()->getNamespace();
3440
3441
				$addFields = [ 'cat_pages = cat_pages + 1' ];
3442
				$removeFields = [ 'cat_pages = cat_pages - 1' ];
3443
				if ( $ns == NS_CATEGORY ) {
3444
					$addFields[] = 'cat_subcats = cat_subcats + 1';
3445
					$removeFields[] = 'cat_subcats = cat_subcats - 1';
3446
				} elseif ( $ns == NS_FILE ) {
3447
					$addFields[] = 'cat_files = cat_files + 1';
3448
					$removeFields[] = 'cat_files = cat_files - 1';
3449
				}
3450
3451
				if ( count( $added ) ) {
3452
					$existingAdded = $dbw->selectFieldValues(
3453
						'category',
3454
						'cat_title',
3455
						[ 'cat_title' => $added ],
3456
						$method
3457
					);
3458
3459
					// For category rows that already exist, do a plain
3460
					// UPDATE instead of INSERT...ON DUPLICATE KEY UPDATE
3461
					// to avoid creating gaps in the cat_id sequence.
3462
					if ( count( $existingAdded ) ) {
3463
						$dbw->update(
3464
							'category',
3465
							$addFields,
3466
							[ 'cat_title' => $existingAdded ],
3467
							$method
3468
						);
3469
					}
3470
3471
					$missingAdded = array_diff( $added, $existingAdded );
3472
					if ( count( $missingAdded ) ) {
3473
						$insertRows = [];
3474
						foreach ( $missingAdded as $cat ) {
3475
							$insertRows[] = [
3476
								'cat_title'   => $cat,
3477
								'cat_pages'   => 1,
3478
								'cat_subcats' => ( $ns == NS_CATEGORY ) ? 1 : 0,
3479
								'cat_files'   => ( $ns == NS_FILE ) ? 1 : 0,
3480
							];
3481
						}
3482
						$dbw->upsert(
3483
							'category',
3484
							$insertRows,
3485
							[ 'cat_title' ],
3486
							$addFields,
3487
							$method
3488
						);
3489
					}
3490
				}
3491
3492
				if ( count( $deleted ) ) {
3493
					$dbw->update(
3494
						'category',
3495
						$removeFields,
3496
						[ 'cat_title' => $deleted ],
3497
						$method
3498
					);
3499
				}
3500
3501
				foreach ( $added as $catName ) {
3502
					$cat = Category::newFromName( $catName );
3503
					Hooks::run( 'CategoryAfterPageAdded', [ $cat, $this ] );
3504
				}
3505
3506
				foreach ( $deleted as $catName ) {
3507
					$cat = Category::newFromName( $catName );
3508
					Hooks::run( 'CategoryAfterPageRemoved', [ $cat, $this, $id ] );
3509
				}
3510
			}
3511
		);
3512
	}
3513
3514
	/**
3515
	 * Opportunistically enqueue link update jobs given fresh parser output if useful
3516
	 *
3517
	 * @param ParserOutput $parserOutput Current version page output
3518
	 * @since 1.25
3519
	 */
3520
	public function triggerOpportunisticLinksUpdate( ParserOutput $parserOutput ) {
3521
		if ( wfReadOnly() ) {
3522
			return;
3523
		}
3524
3525
		if ( !Hooks::run( 'OpportunisticLinksUpdate',
3526
			[ $this, $this->mTitle, $parserOutput ]
3527
		) ) {
3528
			return;
3529
		}
3530
3531
		$config = RequestContext::getMain()->getConfig();
3532
3533
		$params = [
3534
			'isOpportunistic' => true,
3535
			'rootJobTimestamp' => $parserOutput->getCacheTime()
3536
		];
3537
3538
		if ( $this->mTitle->areRestrictionsCascading() ) {
3539
			// If the page is cascade protecting, the links should really be up-to-date
3540
			JobQueueGroup::singleton()->lazyPush(
3541
				RefreshLinksJob::newPrioritized( $this->mTitle, $params )
3542
			);
3543
		} elseif ( !$config->get( 'MiserMode' ) && $parserOutput->hasDynamicContent() ) {
3544
			// Assume the output contains "dynamic" time/random based magic words.
3545
			// Only update pages that expired due to dynamic content and NOT due to edits
3546
			// to referenced templates/files. When the cache expires due to dynamic content,
3547
			// page_touched is unchanged. We want to avoid triggering redundant jobs due to
3548
			// views of pages that were just purged via HTMLCacheUpdateJob. In that case, the
3549
			// template/file edit already triggered recursive RefreshLinksJob jobs.
3550
			if ( $this->getLinksTimestamp() > $this->getTouched() ) {
3551
				// If a page is uncacheable, do not keep spamming a job for it.
3552
				// Although it would be de-duplicated, it would still waste I/O.
3553
				$cache = ObjectCache::getLocalClusterInstance();
3554
				$key = $cache->makeKey( 'dynamic-linksupdate', 'last', $this->getId() );
3555
				$ttl = max( $parserOutput->getCacheExpiry(), 3600 );
3556
				if ( $cache->add( $key, time(), $ttl ) ) {
3557
					JobQueueGroup::singleton()->lazyPush(
3558
						RefreshLinksJob::newDynamic( $this->mTitle, $params )
3559
					);
3560
				}
3561
			}
3562
		}
3563
	}
3564
3565
	/**
3566
	 * Returns a list of updates to be performed when this page is deleted. The
3567
	 * updates should remove any information about this page from secondary data
3568
	 * stores such as links tables.
3569
	 *
3570
	 * @param Content|null $content Optional Content object for determining the
3571
	 *   necessary updates.
3572
	 * @return DataUpdate[]
3573
	 */
3574
	public function getDeletionUpdates( Content $content = null ) {
3575
		if ( !$content ) {
3576
			// load content object, which may be used to determine the necessary updates.
3577
			// XXX: the content may not be needed to determine the updates.
3578
			$content = $this->getContent( Revision::RAW );
3579
		}
3580
3581
		if ( !$content ) {
3582
			$updates = [];
3583
		} else {
3584
			$updates = $content->getDeletionUpdates( $this );
3585
		}
3586
3587
		Hooks::run( 'WikiPageDeletionUpdates', [ $this, $content, &$updates ] );
3588
		return $updates;
3589
	}
3590
}
3591