Merge "Drop outdated "documentation reviewed" tags"
[lhc/web/wiklou.git] / includes / page / WikiPage.php
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 * Abstract class for type hinting (accepts WikiPage, Article, ImagePage, CategoryPage)
25 */
26 interface Page {
27 }
28
29 /**
30 * Class representing a MediaWiki article and history.
31 *
32 * Some fields are public only for backwards-compatibility. Use accessors.
33 * In the past, this class was part of Article.php and everything was public.
34 */
35 class WikiPage implements Page, IDBAccessObject {
36 // Constants for $mDataLoadedFrom and related
37
38 /**
39 * @var Title
40 */
41 public $mTitle = null;
42
43 /**@{{
44 * @protected
45 */
46 public $mDataLoaded = false; // !< Boolean
47 public $mIsRedirect = false; // !< Boolean
48 public $mLatest = false; // !< Integer (false means "not loaded")
49 /**@}}*/
50
51 /** @var stdClass Map of cache fields (text, parser output, ect) for a proposed/new edit */
52 public $mPreparedEdit = false;
53
54 /**
55 * @var int
56 */
57 protected $mId = null;
58
59 /**
60 * @var int One of the READ_* constants
61 */
62 protected $mDataLoadedFrom = self::READ_NONE;
63
64 /**
65 * @var Title
66 */
67 protected $mRedirectTarget = null;
68
69 /**
70 * @var Revision
71 */
72 protected $mLastRevision = null;
73
74 /**
75 * @var string Timestamp of the current revision or empty string if not loaded
76 */
77 protected $mTimestamp = '';
78
79 /**
80 * @var string
81 */
82 protected $mTouched = '19700101000000';
83
84 /**
85 * @var string
86 */
87 protected $mLinksUpdated = '19700101000000';
88
89 /**
90 * Constructor and clear the article
91 * @param Title $title Reference to a Title object.
92 */
93 public function __construct( Title $title ) {
94 $this->mTitle = $title;
95 }
96
97 /**
98 * Create a WikiPage object of the appropriate class for the given title.
99 *
100 * @param Title $title
101 *
102 * @throws MWException
103 * @return WikiPage Object of the appropriate type
104 */
105 public static function factory( Title $title ) {
106 $ns = $title->getNamespace();
107
108 if ( $ns == NS_MEDIA ) {
109 throw new MWException( "NS_MEDIA is a virtual namespace; use NS_FILE." );
110 } elseif ( $ns < 0 ) {
111 throw new MWException( "Invalid or virtual namespace $ns given." );
112 }
113
114 switch ( $ns ) {
115 case NS_FILE:
116 $page = new WikiFilePage( $title );
117 break;
118 case NS_CATEGORY:
119 $page = new WikiCategoryPage( $title );
120 break;
121 default:
122 $page = new WikiPage( $title );
123 }
124
125 return $page;
126 }
127
128 /**
129 * Constructor from a page id
130 *
131 * @param int $id Article ID to load
132 * @param string|int $from One of the following values:
133 * - "fromdb" or WikiPage::READ_NORMAL to select from a slave database
134 * - "fromdbmaster" or WikiPage::READ_LATEST to select from the master database
135 *
136 * @return WikiPage|null
137 */
138 public static function newFromID( $id, $from = 'fromdb' ) {
139 // page id's are never 0 or negative, see bug 61166
140 if ( $id < 1 ) {
141 return null;
142 }
143
144 $from = self::convertSelectType( $from );
145 $db = wfGetDB( $from === self::READ_LATEST ? DB_MASTER : DB_SLAVE );
146 $row = $db->selectRow( 'page', self::selectFields(), array( 'page_id' => $id ), __METHOD__ );
147 if ( !$row ) {
148 return null;
149 }
150 return self::newFromRow( $row, $from );
151 }
152
153 /**
154 * Constructor from a database row
155 *
156 * @since 1.20
157 * @param object $row Database row containing at least fields returned by selectFields().
158 * @param string|int $from Source of $data:
159 * - "fromdb" or WikiPage::READ_NORMAL: from a slave DB
160 * - "fromdbmaster" or WikiPage::READ_LATEST: from the master DB
161 * - "forupdate" or WikiPage::READ_LOCKING: from the master DB using SELECT FOR UPDATE
162 * @return WikiPage
163 */
164 public static function newFromRow( $row, $from = 'fromdb' ) {
165 $page = self::factory( Title::newFromRow( $row ) );
166 $page->loadFromRow( $row, $from );
167 return $page;
168 }
169
170 /**
171 * Convert 'fromdb', 'fromdbmaster' and 'forupdate' to READ_* constants.
172 *
173 * @param object|string|int $type
174 * @return mixed
175 */
176 private static function convertSelectType( $type ) {
177 switch ( $type ) {
178 case 'fromdb':
179 return self::READ_NORMAL;
180 case 'fromdbmaster':
181 return self::READ_LATEST;
182 case 'forupdate':
183 return self::READ_LOCKING;
184 default:
185 // It may already be an integer or whatever else
186 return $type;
187 }
188 }
189
190 /**
191 * Returns overrides for action handlers.
192 * Classes listed here will be used instead of the default one when
193 * (and only when) $wgActions[$action] === true. This allows subclasses
194 * to override the default behavior.
195 *
196 * @todo Move this UI stuff somewhere else
197 *
198 * @return array
199 */
200 public function getActionOverrides() {
201 $content_handler = $this->getContentHandler();
202 return $content_handler->getActionOverrides();
203 }
204
205 /**
206 * Returns the ContentHandler instance to be used to deal with the content of this WikiPage.
207 *
208 * Shorthand for ContentHandler::getForModelID( $this->getContentModel() );
209 *
210 * @return ContentHandler
211 *
212 * @since 1.21
213 */
214 public function getContentHandler() {
215 return ContentHandler::getForModelID( $this->getContentModel() );
216 }
217
218 /**
219 * Get the title object of the article
220 * @return Title Title object of this page
221 */
222 public function getTitle() {
223 return $this->mTitle;
224 }
225
226 /**
227 * Clear the object
228 * @return void
229 */
230 public function clear() {
231 $this->mDataLoaded = false;
232 $this->mDataLoadedFrom = self::READ_NONE;
233
234 $this->clearCacheFields();
235 }
236
237 /**
238 * Clear the object cache fields
239 * @return void
240 */
241 protected function clearCacheFields() {
242 $this->mId = null;
243 $this->mRedirectTarget = null; // Title object if set
244 $this->mLastRevision = null; // Latest revision
245 $this->mTouched = '19700101000000';
246 $this->mLinksUpdated = '19700101000000';
247 $this->mTimestamp = '';
248 $this->mIsRedirect = false;
249 $this->mLatest = false;
250 // Bug 57026: do not clear mPreparedEdit since prepareTextForEdit() already checks
251 // the requested rev ID and content against the cached one for equality. For most
252 // content types, the output should not change during the lifetime of this cache.
253 // Clearing it can cause extra parses on edit for no reason.
254 }
255
256 /**
257 * Clear the mPreparedEdit cache field, as may be needed by mutable content types
258 * @return void
259 * @since 1.23
260 */
261 public function clearPreparedEdit() {
262 $this->mPreparedEdit = false;
263 }
264
265 /**
266 * Return the list of revision fields that should be selected to create
267 * a new page.
268 *
269 * @return array
270 */
271 public static function selectFields() {
272 global $wgContentHandlerUseDB, $wgPageLanguageUseDB;
273
274 $fields = array(
275 'page_id',
276 'page_namespace',
277 'page_title',
278 'page_restrictions',
279 'page_is_redirect',
280 'page_is_new',
281 'page_random',
282 'page_touched',
283 'page_links_updated',
284 'page_latest',
285 'page_len',
286 );
287
288 if ( $wgContentHandlerUseDB ) {
289 $fields[] = 'page_content_model';
290 }
291
292 if ( $wgPageLanguageUseDB ) {
293 $fields[] = 'page_lang';
294 }
295
296 return $fields;
297 }
298
299 /**
300 * Fetch a page record with the given conditions
301 * @param DatabaseBase $dbr
302 * @param array $conditions
303 * @param array $options
304 * @return object|bool Database result resource, or false on failure
305 */
306 protected function pageData( $dbr, $conditions, $options = array() ) {
307 $fields = self::selectFields();
308
309 Hooks::run( 'ArticlePageDataBefore', array( &$this, &$fields ) );
310
311 $row = $dbr->selectRow( 'page', $fields, $conditions, __METHOD__, $options );
312
313 Hooks::run( 'ArticlePageDataAfter', array( &$this, &$row ) );
314
315 return $row;
316 }
317
318 /**
319 * Fetch a page record matching the Title object's namespace and title
320 * using a sanitized title string
321 *
322 * @param DatabaseBase $dbr
323 * @param Title $title
324 * @param array $options
325 * @return object|bool Database result resource, or false on failure
326 */
327 public function pageDataFromTitle( $dbr, $title, $options = array() ) {
328 return $this->pageData( $dbr, array(
329 'page_namespace' => $title->getNamespace(),
330 'page_title' => $title->getDBkey() ), $options );
331 }
332
333 /**
334 * Fetch a page record matching the requested ID
335 *
336 * @param DatabaseBase $dbr
337 * @param int $id
338 * @param array $options
339 * @return object|bool Database result resource, or false on failure
340 */
341 public function pageDataFromId( $dbr, $id, $options = array() ) {
342 return $this->pageData( $dbr, array( 'page_id' => $id ), $options );
343 }
344
345 /**
346 * Load the object from a given source by title
347 *
348 * @param object|string|int $from One of the following:
349 * - A DB query result object.
350 * - "fromdb" or WikiPage::READ_NORMAL to get from a slave DB.
351 * - "fromdbmaster" or WikiPage::READ_LATEST to get from the master DB.
352 * - "forupdate" or WikiPage::READ_LOCKING to get from the master DB
353 * using SELECT FOR UPDATE.
354 *
355 * @return void
356 */
357 public function loadPageData( $from = 'fromdb' ) {
358 $from = self::convertSelectType( $from );
359 if ( is_int( $from ) && $from <= $this->mDataLoadedFrom ) {
360 // We already have the data from the correct location, no need to load it twice.
361 return;
362 }
363
364 if ( $from === self::READ_LOCKING ) {
365 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER ), $this->mTitle, array( 'FOR UPDATE' ) );
366 } elseif ( $from === self::READ_LATEST ) {
367 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER ), $this->mTitle );
368 } elseif ( $from === self::READ_NORMAL ) {
369 $data = $this->pageDataFromTitle( wfGetDB( DB_SLAVE ), $this->mTitle );
370 // Use a "last rev inserted" timestamp key to diminish the issue of slave lag.
371 // Note that DB also stores the master position in the session and checks it.
372 $touched = $this->getCachedLastEditTime();
373 if ( $touched ) { // key set
374 if ( !$data || $touched > wfTimestamp( TS_MW, $data->page_touched ) ) {
375 $from = self::READ_LATEST;
376 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER ), $this->mTitle );
377 }
378 }
379 } else {
380 // No idea from where the caller got this data, assume slave database.
381 $data = $from;
382 $from = self::READ_NORMAL;
383 }
384
385 $this->loadFromRow( $data, $from );
386 }
387
388 /**
389 * Load the object from a database row
390 *
391 * @since 1.20
392 * @param object $data Database row containing at least fields returned by selectFields()
393 * @param string|int $from One of the following:
394 * - "fromdb" or WikiPage::READ_NORMAL if the data comes from a slave DB
395 * - "fromdbmaster" or WikiPage::READ_LATEST if the data comes from the master DB
396 * - "forupdate" or WikiPage::READ_LOCKING if the data comes from
397 * the master DB using SELECT FOR UPDATE
398 */
399 public function loadFromRow( $data, $from ) {
400 $lc = LinkCache::singleton();
401 $lc->clearLink( $this->mTitle );
402
403 if ( $data ) {
404 $lc->addGoodLinkObjFromRow( $this->mTitle, $data );
405
406 $this->mTitle->loadFromRow( $data );
407
408 // Old-fashioned restrictions
409 $this->mTitle->loadRestrictions( $data->page_restrictions );
410
411 $this->mId = intval( $data->page_id );
412 $this->mTouched = wfTimestamp( TS_MW, $data->page_touched );
413 $this->mLinksUpdated = wfTimestampOrNull( TS_MW, $data->page_links_updated );
414 $this->mIsRedirect = intval( $data->page_is_redirect );
415 $this->mLatest = intval( $data->page_latest );
416 // Bug 37225: $latest may no longer match the cached latest Revision object.
417 // Double-check the ID of any cached latest Revision object for consistency.
418 if ( $this->mLastRevision && $this->mLastRevision->getId() != $this->mLatest ) {
419 $this->mLastRevision = null;
420 $this->mTimestamp = '';
421 }
422 } else {
423 $lc->addBadLinkObj( $this->mTitle );
424
425 $this->mTitle->loadFromRow( false );
426
427 $this->clearCacheFields();
428
429 $this->mId = 0;
430 }
431
432 $this->mDataLoaded = true;
433 $this->mDataLoadedFrom = self::convertSelectType( $from );
434 }
435
436 /**
437 * @return int Page ID
438 */
439 public function getId() {
440 if ( !$this->mDataLoaded ) {
441 $this->loadPageData();
442 }
443 return $this->mId;
444 }
445
446 /**
447 * @return bool Whether or not the page exists in the database
448 */
449 public function exists() {
450 if ( !$this->mDataLoaded ) {
451 $this->loadPageData();
452 }
453 return $this->mId > 0;
454 }
455
456 /**
457 * Check if this page is something we're going to be showing
458 * some sort of sensible content for. If we return false, page
459 * views (plain action=view) will return an HTTP 404 response,
460 * so spiders and robots can know they're following a bad link.
461 *
462 * @return bool
463 */
464 public function hasViewableContent() {
465 return $this->exists() || $this->mTitle->isAlwaysKnown();
466 }
467
468 /**
469 * Tests if the article content represents a redirect
470 *
471 * @return bool
472 */
473 public function isRedirect() {
474 $content = $this->getContent();
475 if ( !$content ) {
476 return false;
477 }
478
479 return $content->isRedirect();
480 }
481
482 /**
483 * Returns the page's content model id (see the CONTENT_MODEL_XXX constants).
484 *
485 * Will use the revisions actual content model if the page exists,
486 * and the page's default if the page doesn't exist yet.
487 *
488 * @return string
489 *
490 * @since 1.21
491 */
492 public function getContentModel() {
493 if ( $this->exists() ) {
494 // look at the revision's actual content model
495 $rev = $this->getRevision();
496
497 if ( $rev !== null ) {
498 return $rev->getContentModel();
499 } else {
500 $title = $this->mTitle->getPrefixedDBkey();
501 wfWarn( "Page $title exists but has no (visible) revisions!" );
502 }
503 }
504
505 // use the default model for this page
506 return $this->mTitle->getContentModel();
507 }
508
509 /**
510 * Loads page_touched and returns a value indicating if it should be used
511 * @return bool True if not a redirect
512 */
513 public function checkTouched() {
514 if ( !$this->mDataLoaded ) {
515 $this->loadPageData();
516 }
517 return !$this->mIsRedirect;
518 }
519
520 /**
521 * Get the page_touched field
522 * @return string Containing GMT timestamp
523 */
524 public function getTouched() {
525 if ( !$this->mDataLoaded ) {
526 $this->loadPageData();
527 }
528 return $this->mTouched;
529 }
530
531 /**
532 * Get the page_links_updated field
533 * @return string|null Containing GMT timestamp
534 */
535 public function getLinksTimestamp() {
536 if ( !$this->mDataLoaded ) {
537 $this->loadPageData();
538 }
539 return $this->mLinksUpdated;
540 }
541
542 /**
543 * Get the page_latest field
544 * @return int The rev_id of current revision
545 */
546 public function getLatest() {
547 if ( !$this->mDataLoaded ) {
548 $this->loadPageData();
549 }
550 return (int)$this->mLatest;
551 }
552
553 /**
554 * Get the Revision object of the oldest revision
555 * @return Revision|null
556 */
557 public function getOldestRevision() {
558
559 // Try using the slave database first, then try the master
560 $continue = 2;
561 $db = wfGetDB( DB_SLAVE );
562 $revSelectFields = Revision::selectFields();
563
564 $row = null;
565 while ( $continue ) {
566 $row = $db->selectRow(
567 array( 'page', 'revision' ),
568 $revSelectFields,
569 array(
570 'page_namespace' => $this->mTitle->getNamespace(),
571 'page_title' => $this->mTitle->getDBkey(),
572 'rev_page = page_id'
573 ),
574 __METHOD__,
575 array(
576 'ORDER BY' => 'rev_timestamp ASC'
577 )
578 );
579
580 if ( $row ) {
581 $continue = 0;
582 } else {
583 $db = wfGetDB( DB_MASTER );
584 $continue--;
585 }
586 }
587
588 return $row ? Revision::newFromRow( $row ) : null;
589 }
590
591 /**
592 * Loads everything except the text
593 * This isn't necessary for all uses, so it's only done if needed.
594 */
595 protected function loadLastEdit() {
596 if ( $this->mLastRevision !== null ) {
597 return; // already loaded
598 }
599
600 $latest = $this->getLatest();
601 if ( !$latest ) {
602 return; // page doesn't exist or is missing page_latest info
603 }
604
605 // Bug 37225: if session S1 loads the page row FOR UPDATE, the result always includes the
606 // latest changes committed. This is true even within REPEATABLE-READ transactions, where
607 // S1 normally only sees changes committed before the first S1 SELECT. Thus we need S1 to
608 // also gets the revision row FOR UPDATE; otherwise, it may not find it since a page row
609 // UPDATE and revision row INSERT by S2 may have happened after the first S1 SELECT.
610 // http://dev.mysql.com/doc/refman/5.0/en/set-transaction.html#isolevel_repeatable-read.
611 $flags = ( $this->mDataLoadedFrom == self::READ_LOCKING ) ? Revision::READ_LOCKING : 0;
612 $revision = Revision::newFromPageId( $this->getId(), $latest, $flags );
613 if ( $revision ) { // sanity
614 $this->setLastEdit( $revision );
615 }
616 }
617
618 /**
619 * Set the latest revision
620 * @param Revision $revision
621 */
622 protected function setLastEdit( Revision $revision ) {
623 $this->mLastRevision = $revision;
624 $this->mTimestamp = $revision->getTimestamp();
625 }
626
627 /**
628 * Get the latest revision
629 * @return Revision|null
630 */
631 public function getRevision() {
632 $this->loadLastEdit();
633 if ( $this->mLastRevision ) {
634 return $this->mLastRevision;
635 }
636 return null;
637 }
638
639 /**
640 * Get the content of the current revision. No side-effects...
641 *
642 * @param int $audience One of:
643 * Revision::FOR_PUBLIC to be displayed to all users
644 * Revision::FOR_THIS_USER to be displayed to $wgUser
645 * Revision::RAW get the text regardless of permissions
646 * @param User $user User object to check for, only if FOR_THIS_USER is passed
647 * to the $audience parameter
648 * @return Content|null The content of the current revision
649 *
650 * @since 1.21
651 */
652 public function getContent( $audience = Revision::FOR_PUBLIC, User $user = null ) {
653 $this->loadLastEdit();
654 if ( $this->mLastRevision ) {
655 return $this->mLastRevision->getContent( $audience, $user );
656 }
657 return null;
658 }
659
660 /**
661 * Get the text of the current revision. No side-effects...
662 *
663 * @param int $audience One of:
664 * Revision::FOR_PUBLIC to be displayed to all users
665 * Revision::FOR_THIS_USER to be displayed to the given user
666 * Revision::RAW get the text regardless of permissions
667 * @param User $user User object to check for, only if FOR_THIS_USER is passed
668 * to the $audience parameter
669 * @return string|bool The text of the current revision
670 * @deprecated since 1.21, getContent() should be used instead.
671 */
672 public function getText( $audience = Revision::FOR_PUBLIC, User $user = null ) {
673 ContentHandler::deprecated( __METHOD__, '1.21' );
674
675 $this->loadLastEdit();
676 if ( $this->mLastRevision ) {
677 return $this->mLastRevision->getText( $audience, $user );
678 }
679 return false;
680 }
681
682 /**
683 * Get the text of the current revision. No side-effects...
684 *
685 * @return string|bool The text of the current revision. False on failure
686 * @deprecated since 1.21, getContent() should be used instead.
687 */
688 public function getRawText() {
689 ContentHandler::deprecated( __METHOD__, '1.21' );
690
691 return $this->getText( Revision::RAW );
692 }
693
694 /**
695 * @return string MW timestamp of last article revision
696 */
697 public function getTimestamp() {
698 // Check if the field has been filled by WikiPage::setTimestamp()
699 if ( !$this->mTimestamp ) {
700 $this->loadLastEdit();
701 }
702
703 return wfTimestamp( TS_MW, $this->mTimestamp );
704 }
705
706 /**
707 * Set the page timestamp (use only to avoid DB queries)
708 * @param string $ts MW timestamp of last article revision
709 * @return void
710 */
711 public function setTimestamp( $ts ) {
712 $this->mTimestamp = wfTimestamp( TS_MW, $ts );
713 }
714
715 /**
716 * @param int $audience One of:
717 * Revision::FOR_PUBLIC to be displayed to all users
718 * Revision::FOR_THIS_USER to be displayed to the given user
719 * Revision::RAW get the text regardless of permissions
720 * @param User $user User object to check for, only if FOR_THIS_USER is passed
721 * to the $audience parameter
722 * @return int User ID for the user that made the last article revision
723 */
724 public function getUser( $audience = Revision::FOR_PUBLIC, User $user = null ) {
725 $this->loadLastEdit();
726 if ( $this->mLastRevision ) {
727 return $this->mLastRevision->getUser( $audience, $user );
728 } else {
729 return -1;
730 }
731 }
732
733 /**
734 * Get the User object of the user who created the page
735 * @param int $audience One of:
736 * Revision::FOR_PUBLIC to be displayed to all users
737 * Revision::FOR_THIS_USER to be displayed to the given user
738 * Revision::RAW get the text regardless of permissions
739 * @param User $user User object to check for, only if FOR_THIS_USER is passed
740 * to the $audience parameter
741 * @return User|null
742 */
743 public function getCreator( $audience = Revision::FOR_PUBLIC, User $user = null ) {
744 $revision = $this->getOldestRevision();
745 if ( $revision ) {
746 $userName = $revision->getUserText( $audience, $user );
747 return User::newFromName( $userName, false );
748 } else {
749 return null;
750 }
751 }
752
753 /**
754 * @param int $audience One of:
755 * Revision::FOR_PUBLIC to be displayed to all users
756 * Revision::FOR_THIS_USER to be displayed to the given user
757 * Revision::RAW get the text regardless of permissions
758 * @param User $user User object to check for, only if FOR_THIS_USER is passed
759 * to the $audience parameter
760 * @return string Username of the user that made the last article revision
761 */
762 public function getUserText( $audience = Revision::FOR_PUBLIC, User $user = null ) {
763 $this->loadLastEdit();
764 if ( $this->mLastRevision ) {
765 return $this->mLastRevision->getUserText( $audience, $user );
766 } else {
767 return '';
768 }
769 }
770
771 /**
772 * @param int $audience One of:
773 * Revision::FOR_PUBLIC to be displayed to all users
774 * Revision::FOR_THIS_USER to be displayed to the given user
775 * Revision::RAW get the text regardless of permissions
776 * @param User $user User object to check for, only if FOR_THIS_USER is passed
777 * to the $audience parameter
778 * @return string Comment stored for the last article revision
779 */
780 public function getComment( $audience = Revision::FOR_PUBLIC, User $user = null ) {
781 $this->loadLastEdit();
782 if ( $this->mLastRevision ) {
783 return $this->mLastRevision->getComment( $audience, $user );
784 } else {
785 return '';
786 }
787 }
788
789 /**
790 * Returns true if last revision was marked as "minor edit"
791 *
792 * @return bool Minor edit indicator for the last article revision.
793 */
794 public function getMinorEdit() {
795 $this->loadLastEdit();
796 if ( $this->mLastRevision ) {
797 return $this->mLastRevision->isMinor();
798 } else {
799 return false;
800 }
801 }
802
803 /**
804 * Get the cached timestamp for the last time the page changed.
805 * This is only used to help handle slave lag by comparing to page_touched.
806 * @return string MW timestamp
807 */
808 protected function getCachedLastEditTime() {
809 global $wgMemc;
810 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle->getPrefixedDBkey() ) );
811 return $wgMemc->get( $key );
812 }
813
814 /**
815 * Set the cached timestamp for the last time the page changed.
816 * This is only used to help handle slave lag by comparing to page_touched.
817 * @param string $timestamp
818 * @return void
819 */
820 public function setCachedLastEditTime( $timestamp ) {
821 global $wgMemc;
822 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle->getPrefixedDBkey() ) );
823 $wgMemc->set( $key, wfTimestamp( TS_MW, $timestamp ), 60 * 15 );
824 }
825
826 /**
827 * Determine whether a page would be suitable for being counted as an
828 * article in the site_stats table based on the title & its content
829 *
830 * @param object|bool $editInfo (false): object returned by prepareTextForEdit(),
831 * if false, the current database state will be used
832 * @return bool
833 */
834 public function isCountable( $editInfo = false ) {
835 global $wgArticleCountMethod;
836
837 if ( !$this->mTitle->isContentPage() ) {
838 return false;
839 }
840
841 if ( $editInfo ) {
842 $content = $editInfo->pstContent;
843 } else {
844 $content = $this->getContent();
845 }
846
847 if ( !$content || $content->isRedirect() ) {
848 return false;
849 }
850
851 $hasLinks = null;
852
853 if ( $wgArticleCountMethod === 'link' ) {
854 // nasty special case to avoid re-parsing to detect links
855
856 if ( $editInfo ) {
857 // ParserOutput::getLinks() is a 2D array of page links, so
858 // to be really correct we would need to recurse in the array
859 // but the main array should only have items in it if there are
860 // links.
861 $hasLinks = (bool)count( $editInfo->output->getLinks() );
862 } else {
863 $hasLinks = (bool)wfGetDB( DB_SLAVE )->selectField( 'pagelinks', 1,
864 array( 'pl_from' => $this->getId() ), __METHOD__ );
865 }
866 }
867
868 return $content->isCountable( $hasLinks );
869 }
870
871 /**
872 * If this page is a redirect, get its target
873 *
874 * The target will be fetched from the redirect table if possible.
875 * If this page doesn't have an entry there, call insertRedirect()
876 * @return Title|null Title object, or null if this page is not a redirect
877 */
878 public function getRedirectTarget() {
879 if ( !$this->mTitle->isRedirect() ) {
880 return null;
881 }
882
883 if ( $this->mRedirectTarget !== null ) {
884 return $this->mRedirectTarget;
885 }
886
887 // Query the redirect table
888 $dbr = wfGetDB( DB_SLAVE );
889 $row = $dbr->selectRow( 'redirect',
890 array( 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ),
891 array( 'rd_from' => $this->getId() ),
892 __METHOD__
893 );
894
895 // rd_fragment and rd_interwiki were added later, populate them if empty
896 if ( $row && !is_null( $row->rd_fragment ) && !is_null( $row->rd_interwiki ) ) {
897 $this->mRedirectTarget = Title::makeTitle(
898 $row->rd_namespace, $row->rd_title,
899 $row->rd_fragment, $row->rd_interwiki );
900 return $this->mRedirectTarget;
901 }
902
903 // This page doesn't have an entry in the redirect table
904 $this->mRedirectTarget = $this->insertRedirect();
905 return $this->mRedirectTarget;
906 }
907
908 /**
909 * Insert an entry for this page into the redirect table.
910 *
911 * Don't call this function directly unless you know what you're doing.
912 * @return Title|null Title object or null if not a redirect
913 */
914 public function insertRedirect() {
915 // recurse through to only get the final target
916 $content = $this->getContent();
917 $retval = $content ? $content->getUltimateRedirectTarget() : null;
918 if ( !$retval ) {
919 return null;
920 }
921 $this->insertRedirectEntry( $retval );
922 return $retval;
923 }
924
925 /**
926 * Insert or update the redirect table entry for this page to indicate
927 * it redirects to $rt .
928 * @param Title $rt Redirect target
929 */
930 public function insertRedirectEntry( $rt ) {
931 $dbw = wfGetDB( DB_MASTER );
932 $dbw->replace( 'redirect', array( 'rd_from' ),
933 array(
934 'rd_from' => $this->getId(),
935 'rd_namespace' => $rt->getNamespace(),
936 'rd_title' => $rt->getDBkey(),
937 'rd_fragment' => $rt->getFragment(),
938 'rd_interwiki' => $rt->getInterwiki(),
939 ),
940 __METHOD__
941 );
942 }
943
944 /**
945 * Get the Title object or URL this page redirects to
946 *
947 * @return bool|Title|string False, Title of in-wiki target, or string with URL
948 */
949 public function followRedirect() {
950 return $this->getRedirectURL( $this->getRedirectTarget() );
951 }
952
953 /**
954 * Get the Title object or URL to use for a redirect. We use Title
955 * objects for same-wiki, non-special redirects and URLs for everything
956 * else.
957 * @param Title $rt Redirect target
958 * @return bool|Title|string False, Title object of local target, or string with URL
959 */
960 public function getRedirectURL( $rt ) {
961 if ( !$rt ) {
962 return false;
963 }
964
965 if ( $rt->isExternal() ) {
966 if ( $rt->isLocal() ) {
967 // Offsite wikis need an HTTP redirect.
968 //
969 // This can be hard to reverse and may produce loops,
970 // so they may be disabled in the site configuration.
971 $source = $this->mTitle->getFullURL( 'redirect=no' );
972 return $rt->getFullURL( array( 'rdfrom' => $source ) );
973 } else {
974 // External pages without "local" bit set are not valid
975 // redirect targets
976 return false;
977 }
978 }
979
980 if ( $rt->isSpecialPage() ) {
981 // Gotta handle redirects to special pages differently:
982 // Fill the HTTP response "Location" header and ignore
983 // the rest of the page we're on.
984 //
985 // Some pages are not valid targets
986 if ( $rt->isValidRedirectTarget() ) {
987 return $rt->getFullURL();
988 } else {
989 return false;
990 }
991 }
992
993 return $rt;
994 }
995
996 /**
997 * Get a list of users who have edited this article, not including the user who made
998 * the most recent revision, which you can get from $article->getUser() if you want it
999 * @return UserArrayFromResult
1000 */
1001 public function getContributors() {
1002 // @todo FIXME: This is expensive; cache this info somewhere.
1003
1004 $dbr = wfGetDB( DB_SLAVE );
1005
1006 if ( $dbr->implicitGroupby() ) {
1007 $realNameField = 'user_real_name';
1008 } else {
1009 $realNameField = 'MIN(user_real_name) AS user_real_name';
1010 }
1011
1012 $tables = array( 'revision', 'user' );
1013
1014 $fields = array(
1015 'user_id' => 'rev_user',
1016 'user_name' => 'rev_user_text',
1017 $realNameField,
1018 'timestamp' => 'MAX(rev_timestamp)',
1019 );
1020
1021 $conds = array( 'rev_page' => $this->getId() );
1022
1023 // The user who made the top revision gets credited as "this page was last edited by
1024 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
1025 $user = $this->getUser();
1026 if ( $user ) {
1027 $conds[] = "rev_user != $user";
1028 } else {
1029 $conds[] = "rev_user_text != {$dbr->addQuotes( $this->getUserText() )}";
1030 }
1031
1032 $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0"; // username hidden?
1033
1034 $jconds = array(
1035 'user' => array( 'LEFT JOIN', 'rev_user = user_id' ),
1036 );
1037
1038 $options = array(
1039 'GROUP BY' => array( 'rev_user', 'rev_user_text' ),
1040 'ORDER BY' => 'timestamp DESC',
1041 );
1042
1043 $res = $dbr->select( $tables, $fields, $conds, __METHOD__, $options, $jconds );
1044 return new UserArrayFromResult( $res );
1045 }
1046
1047 /**
1048 * Get the last N authors
1049 * @param int $num Number of revisions to get
1050 * @param int|string $revLatest The latest rev_id, selected from the master (optional)
1051 * @return array Array of authors, duplicates not removed
1052 */
1053 public function getLastNAuthors( $num, $revLatest = 0 ) {
1054 // First try the slave
1055 // If that doesn't have the latest revision, try the master
1056 $continue = 2;
1057 $db = wfGetDB( DB_SLAVE );
1058
1059 do {
1060 $res = $db->select( array( 'page', 'revision' ),
1061 array( 'rev_id', 'rev_user_text' ),
1062 array(
1063 'page_namespace' => $this->mTitle->getNamespace(),
1064 'page_title' => $this->mTitle->getDBkey(),
1065 'rev_page = page_id'
1066 ), __METHOD__,
1067 array(
1068 'ORDER BY' => 'rev_timestamp DESC',
1069 'LIMIT' => $num
1070 )
1071 );
1072
1073 if ( !$res ) {
1074 return array();
1075 }
1076
1077 $row = $db->fetchObject( $res );
1078
1079 if ( $continue == 2 && $revLatest && $row->rev_id != $revLatest ) {
1080 $db = wfGetDB( DB_MASTER );
1081 $continue--;
1082 } else {
1083 $continue = 0;
1084 }
1085 } while ( $continue );
1086
1087 $authors = array( $row->rev_user_text );
1088
1089 foreach ( $res as $row ) {
1090 $authors[] = $row->rev_user_text;
1091 }
1092
1093 return $authors;
1094 }
1095
1096 /**
1097 * Should the parser cache be used?
1098 *
1099 * @param ParserOptions $parserOptions ParserOptions to check
1100 * @param int $oldid
1101 * @return bool
1102 */
1103 public function isParserCacheUsed( ParserOptions $parserOptions, $oldid ) {
1104 global $wgEnableParserCache;
1105
1106 return $wgEnableParserCache
1107 && $parserOptions->getStubThreshold() == 0
1108 && $this->exists()
1109 && ( $oldid === null || $oldid === 0 || $oldid === $this->getLatest() )
1110 && $this->getContentHandler()->isParserCacheSupported();
1111 }
1112
1113 /**
1114 * Get a ParserOutput for the given ParserOptions and revision ID.
1115 * The parser cache will be used if possible.
1116 *
1117 * @since 1.19
1118 * @param ParserOptions $parserOptions ParserOptions to use for the parse operation
1119 * @param null|int $oldid Revision ID to get the text from, passing null or 0 will
1120 * get the current revision (default value)
1121 *
1122 * @return ParserOutput|bool ParserOutput or false if the revision was not found
1123 */
1124 public function getParserOutput( ParserOptions $parserOptions, $oldid = null ) {
1125
1126 $useParserCache = $this->isParserCacheUsed( $parserOptions, $oldid );
1127 wfDebug( __METHOD__ . ': using parser cache: ' . ( $useParserCache ? 'yes' : 'no' ) . "\n" );
1128 if ( $parserOptions->getStubThreshold() ) {
1129 wfIncrStats( 'pcache_miss_stub' );
1130 }
1131
1132 if ( $useParserCache ) {
1133 $parserOutput = ParserCache::singleton()->get( $this, $parserOptions );
1134 if ( $parserOutput !== false ) {
1135 return $parserOutput;
1136 }
1137 }
1138
1139 if ( $oldid === null || $oldid === 0 ) {
1140 $oldid = $this->getLatest();
1141 }
1142
1143 $pool = new PoolWorkArticleView( $this, $parserOptions, $oldid, $useParserCache );
1144 $pool->execute();
1145
1146 return $pool->getParserOutput();
1147 }
1148
1149 /**
1150 * Do standard deferred updates after page view (existing or missing page)
1151 * @param User $user The relevant user
1152 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
1153 */
1154 public function doViewUpdates( User $user, $oldid = 0 ) {
1155 if ( wfReadOnly() ) {
1156 return;
1157 }
1158
1159 // Update newtalk / watchlist notification status
1160 $user->clearNotification( $this->mTitle, $oldid );
1161 }
1162
1163 /**
1164 * Perform the actions of a page purging
1165 * @return bool
1166 */
1167 public function doPurge() {
1168 global $wgUseSquid;
1169
1170 if ( !Hooks::run( 'ArticlePurge', array( &$this ) ) ) {
1171 return false;
1172 }
1173
1174 // Invalidate the cache
1175 $this->mTitle->invalidateCache();
1176
1177 if ( $wgUseSquid ) {
1178 // Commit the transaction before the purge is sent
1179 $dbw = wfGetDB( DB_MASTER );
1180 $dbw->commit( __METHOD__ );
1181
1182 // Send purge
1183 $update = SquidUpdate::newSimplePurge( $this->mTitle );
1184 $update->doUpdate();
1185 }
1186
1187 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
1188 // @todo move this logic to MessageCache
1189
1190 if ( $this->exists() ) {
1191 // NOTE: use transclusion text for messages.
1192 // This is consistent with MessageCache::getMsgFromNamespace()
1193
1194 $content = $this->getContent();
1195 $text = $content === null ? null : $content->getWikitextForTransclusion();
1196
1197 if ( $text === null ) {
1198 $text = false;
1199 }
1200 } else {
1201 $text = false;
1202 }
1203
1204 MessageCache::singleton()->replace( $this->mTitle->getDBkey(), $text );
1205 }
1206 return true;
1207 }
1208
1209 /**
1210 * Insert a new empty page record for this article.
1211 * This *must* be followed up by creating a revision
1212 * and running $this->updateRevisionOn( ... );
1213 * or else the record will be left in a funky state.
1214 * Best if all done inside a transaction.
1215 *
1216 * @param DatabaseBase $dbw
1217 * @return int The newly created page_id key, or false if the title already existed
1218 */
1219 public function insertOn( $dbw ) {
1220
1221 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1222 $dbw->insert( 'page', array(
1223 'page_id' => $page_id,
1224 'page_namespace' => $this->mTitle->getNamespace(),
1225 'page_title' => $this->mTitle->getDBkey(),
1226 'page_restrictions' => '',
1227 'page_is_redirect' => 0, // Will set this shortly...
1228 'page_is_new' => 1,
1229 'page_random' => wfRandom(),
1230 'page_touched' => $dbw->timestamp(),
1231 'page_latest' => 0, // Fill this in shortly...
1232 'page_len' => 0, // Fill this in shortly...
1233 ), __METHOD__, 'IGNORE' );
1234
1235 $affected = $dbw->affectedRows();
1236
1237 if ( $affected ) {
1238 $newid = $dbw->insertId();
1239 $this->mId = $newid;
1240 $this->mTitle->resetArticleID( $newid );
1241 }
1242
1243 return $affected ? $newid : false;
1244 }
1245
1246 /**
1247 * Update the page record to point to a newly saved revision.
1248 *
1249 * @param DatabaseBase $dbw
1250 * @param Revision $revision For ID number, and text used to set
1251 * length and redirect status fields
1252 * @param int $lastRevision If given, will not overwrite the page field
1253 * when different from the currently set value.
1254 * Giving 0 indicates the new page flag should be set on.
1255 * @param bool $lastRevIsRedirect If given, will optimize adding and
1256 * removing rows in redirect table.
1257 * @return bool True on success, false on failure
1258 */
1259 public function updateRevisionOn( $dbw, $revision, $lastRevision = null,
1260 $lastRevIsRedirect = null
1261 ) {
1262 global $wgContentHandlerUseDB;
1263
1264 $content = $revision->getContent();
1265 $len = $content ? $content->getSize() : 0;
1266 $rt = $content ? $content->getUltimateRedirectTarget() : null;
1267
1268 $conditions = array( 'page_id' => $this->getId() );
1269
1270 if ( !is_null( $lastRevision ) ) {
1271 // An extra check against threads stepping on each other
1272 $conditions['page_latest'] = $lastRevision;
1273 }
1274
1275 $now = wfTimestampNow();
1276 $row = array( /* SET */
1277 'page_latest' => $revision->getId(),
1278 'page_touched' => $dbw->timestamp( $now ),
1279 'page_is_new' => ( $lastRevision === 0 ) ? 1 : 0,
1280 'page_is_redirect' => $rt !== null ? 1 : 0,
1281 'page_len' => $len,
1282 );
1283
1284 if ( $wgContentHandlerUseDB ) {
1285 $row['page_content_model'] = $revision->getContentModel();
1286 }
1287
1288 $dbw->update( 'page',
1289 $row,
1290 $conditions,
1291 __METHOD__ );
1292
1293 $result = $dbw->affectedRows() > 0;
1294 if ( $result ) {
1295 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1296 $this->setLastEdit( $revision );
1297 $this->setCachedLastEditTime( $now );
1298 $this->mLatest = $revision->getId();
1299 $this->mIsRedirect = (bool)$rt;
1300 // Update the LinkCache.
1301 LinkCache::singleton()->addGoodLinkObj( $this->getId(), $this->mTitle, $len, $this->mIsRedirect,
1302 $this->mLatest, $revision->getContentModel() );
1303 }
1304
1305 return $result;
1306 }
1307
1308 /**
1309 * Add row to the redirect table if this is a redirect, remove otherwise.
1310 *
1311 * @param DatabaseBase $dbw
1312 * @param Title $redirectTitle Title object pointing to the redirect target,
1313 * or NULL if this is not a redirect
1314 * @param null|bool $lastRevIsRedirect If given, will optimize adding and
1315 * removing rows in redirect table.
1316 * @return bool True on success, false on failure
1317 * @private
1318 */
1319 public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1320 // Always update redirects (target link might have changed)
1321 // Update/Insert if we don't know if the last revision was a redirect or not
1322 // Delete if changing from redirect to non-redirect
1323 $isRedirect = !is_null( $redirectTitle );
1324
1325 if ( !$isRedirect && $lastRevIsRedirect === false ) {
1326 return true;
1327 }
1328
1329 if ( $isRedirect ) {
1330 $this->insertRedirectEntry( $redirectTitle );
1331 } else {
1332 // This is not a redirect, remove row from redirect table
1333 $where = array( 'rd_from' => $this->getId() );
1334 $dbw->delete( 'redirect', $where, __METHOD__ );
1335 }
1336
1337 if ( $this->getTitle()->getNamespace() == NS_FILE ) {
1338 RepoGroup::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1339 }
1340
1341 return ( $dbw->affectedRows() != 0 );
1342 }
1343
1344 /**
1345 * If the given revision is newer than the currently set page_latest,
1346 * update the page record. Otherwise, do nothing.
1347 *
1348 * @deprecated since 1.24, use updateRevisionOn instead
1349 *
1350 * @param DatabaseBase $dbw
1351 * @param Revision $revision
1352 * @return bool
1353 */
1354 public function updateIfNewerOn( $dbw, $revision ) {
1355
1356 $row = $dbw->selectRow(
1357 array( 'revision', 'page' ),
1358 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1359 array(
1360 'page_id' => $this->getId(),
1361 'page_latest=rev_id' ),
1362 __METHOD__ );
1363
1364 if ( $row ) {
1365 if ( wfTimestamp( TS_MW, $row->rev_timestamp ) >= $revision->getTimestamp() ) {
1366 return false;
1367 }
1368 $prev = $row->rev_id;
1369 $lastRevIsRedirect = (bool)$row->page_is_redirect;
1370 } else {
1371 // No or missing previous revision; mark the page as new
1372 $prev = 0;
1373 $lastRevIsRedirect = null;
1374 }
1375
1376 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1377
1378 return $ret;
1379 }
1380
1381 /**
1382 * Get the content that needs to be saved in order to undo all revisions
1383 * between $undo and $undoafter. Revisions must belong to the same page,
1384 * must exist and must not be deleted
1385 * @param Revision $undo
1386 * @param Revision $undoafter Must be an earlier revision than $undo
1387 * @return mixed String on success, false on failure
1388 * @since 1.21
1389 * Before we had the Content object, this was done in getUndoText
1390 */
1391 public function getUndoContent( Revision $undo, Revision $undoafter = null ) {
1392 $handler = $undo->getContentHandler();
1393 return $handler->getUndoContent( $this->getRevision(), $undo, $undoafter );
1394 }
1395
1396 /**
1397 * Get the text that needs to be saved in order to undo all revisions
1398 * between $undo and $undoafter. Revisions must belong to the same page,
1399 * must exist and must not be deleted
1400 * @param Revision $undo
1401 * @param Revision $undoafter Must be an earlier revision than $undo
1402 * @return string|bool String on success, false on failure
1403 * @deprecated since 1.21: use ContentHandler::getUndoContent() instead.
1404 */
1405 public function getUndoText( Revision $undo, Revision $undoafter = null ) {
1406 ContentHandler::deprecated( __METHOD__, '1.21' );
1407
1408 $this->loadLastEdit();
1409
1410 if ( $this->mLastRevision ) {
1411 if ( is_null( $undoafter ) ) {
1412 $undoafter = $undo->getPrevious();
1413 }
1414
1415 $handler = $this->getContentHandler();
1416 $undone = $handler->getUndoContent( $this->mLastRevision, $undo, $undoafter );
1417
1418 if ( !$undone ) {
1419 return false;
1420 } else {
1421 return ContentHandler::getContentText( $undone );
1422 }
1423 }
1424
1425 return false;
1426 }
1427
1428 /**
1429 * @param string|number|null|bool $sectionId Section identifier as a number or string
1430 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1431 * or 'new' for a new section.
1432 * @param string $text New text of the section.
1433 * @param string $sectionTitle New section's subject, only if $section is "new".
1434 * @param string $edittime Revision timestamp or null to use the current revision.
1435 *
1436 * @throws MWException
1437 * @return string New complete article text, or null if error.
1438 *
1439 * @deprecated since 1.21, use replaceSectionAtRev() instead
1440 */
1441 public function replaceSection( $sectionId, $text, $sectionTitle = '',
1442 $edittime = null
1443 ) {
1444 ContentHandler::deprecated( __METHOD__, '1.21' );
1445
1446 //NOTE: keep condition in sync with condition in replaceSectionContent!
1447 if ( strval( $sectionId ) === '' ) {
1448 // Whole-page edit; let the whole text through
1449 return $text;
1450 }
1451
1452 if ( !$this->supportsSections() ) {
1453 throw new MWException( "sections not supported for content model " .
1454 $this->getContentHandler()->getModelID() );
1455 }
1456
1457 // could even make section title, but that's not required.
1458 $sectionContent = ContentHandler::makeContent( $text, $this->getTitle() );
1459
1460 $newContent = $this->replaceSectionContent( $sectionId, $sectionContent, $sectionTitle,
1461 $edittime );
1462
1463 return ContentHandler::getContentText( $newContent );
1464 }
1465
1466 /**
1467 * Returns true if this page's content model supports sections.
1468 *
1469 * @return bool
1470 *
1471 * @todo The skin should check this and not offer section functionality if
1472 * sections are not supported.
1473 * @todo The EditPage should check this and not offer section functionality
1474 * if sections are not supported.
1475 */
1476 public function supportsSections() {
1477 return $this->getContentHandler()->supportsSections();
1478 }
1479
1480 /**
1481 * @param string|number|null|bool $sectionId Section identifier as a number or string
1482 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1483 * or 'new' for a new section.
1484 * @param Content $sectionContent New content of the section.
1485 * @param string $sectionTitle New section's subject, only if $section is "new".
1486 * @param string $edittime Revision timestamp or null to use the current revision.
1487 *
1488 * @throws MWException
1489 * @return Content New complete article content, or null if error.
1490 *
1491 * @since 1.21
1492 * @deprecated since 1.24, use replaceSectionAtRev instead
1493 */
1494 public function replaceSectionContent( $sectionId, Content $sectionContent, $sectionTitle = '',
1495 $edittime = null ) {
1496
1497 $baseRevId = null;
1498 if ( $edittime && $sectionId !== 'new' ) {
1499 $dbw = wfGetDB( DB_MASTER );
1500 $rev = Revision::loadFromTimestamp( $dbw, $this->mTitle, $edittime );
1501 if ( $rev ) {
1502 $baseRevId = $rev->getId();
1503 }
1504 }
1505
1506 return $this->replaceSectionAtRev( $sectionId, $sectionContent, $sectionTitle, $baseRevId );
1507 }
1508
1509 /**
1510 * @param string|number|null|bool $sectionId Section identifier as a number or string
1511 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1512 * or 'new' for a new section.
1513 * @param Content $sectionContent New content of the section.
1514 * @param string $sectionTitle New section's subject, only if $section is "new".
1515 * @param int|null $baseRevId
1516 *
1517 * @throws MWException
1518 * @return Content New complete article content, or null if error.
1519 *
1520 * @since 1.24
1521 */
1522 public function replaceSectionAtRev( $sectionId, Content $sectionContent,
1523 $sectionTitle = '', $baseRevId = null
1524 ) {
1525
1526 if ( strval( $sectionId ) === '' ) {
1527 // Whole-page edit; let the whole text through
1528 $newContent = $sectionContent;
1529 } else {
1530 if ( !$this->supportsSections() ) {
1531 throw new MWException( "sections not supported for content model " .
1532 $this->getContentHandler()->getModelID() );
1533 }
1534
1535 // Bug 30711: always use current version when adding a new section
1536 if ( is_null( $baseRevId ) || $sectionId === 'new' ) {
1537 $oldContent = $this->getContent();
1538 } else {
1539 // TODO: try DB_SLAVE first
1540 $dbw = wfGetDB( DB_MASTER );
1541 $rev = Revision::loadFromId( $dbw, $baseRevId );
1542
1543 if ( !$rev ) {
1544 wfDebug( __METHOD__ . " asked for bogus section (page: " .
1545 $this->getId() . "; section: $sectionId)\n" );
1546 return null;
1547 }
1548
1549 $oldContent = $rev->getContent();
1550 }
1551
1552 if ( !$oldContent ) {
1553 wfDebug( __METHOD__ . ": no page text\n" );
1554 return null;
1555 }
1556
1557 $newContent = $oldContent->replaceSection( $sectionId, $sectionContent, $sectionTitle );
1558 }
1559
1560 return $newContent;
1561 }
1562
1563 /**
1564 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1565 * @param int $flags
1566 * @return int Updated $flags
1567 */
1568 public function checkFlags( $flags ) {
1569 if ( !( $flags & EDIT_NEW ) && !( $flags & EDIT_UPDATE ) ) {
1570 if ( $this->exists() ) {
1571 $flags |= EDIT_UPDATE;
1572 } else {
1573 $flags |= EDIT_NEW;
1574 }
1575 }
1576
1577 return $flags;
1578 }
1579
1580 /**
1581 * Change an existing article or create a new article. Updates RC and all necessary caches,
1582 * optionally via the deferred update array.
1583 *
1584 * @param string $text New text
1585 * @param string $summary Edit summary
1586 * @param int $flags Bitfield:
1587 * EDIT_NEW
1588 * Article is known or assumed to be non-existent, create a new one
1589 * EDIT_UPDATE
1590 * Article is known or assumed to be pre-existing, update it
1591 * EDIT_MINOR
1592 * Mark this edit minor, if the user is allowed to do so
1593 * EDIT_SUPPRESS_RC
1594 * Do not log the change in recentchanges
1595 * EDIT_FORCE_BOT
1596 * Mark the edit a "bot" edit regardless of user rights
1597 * EDIT_DEFER_UPDATES
1598 * Defer some of the updates until the end of index.php
1599 * EDIT_AUTOSUMMARY
1600 * Fill in blank summaries with generated text where possible
1601 *
1602 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the
1603 * article will be detected. If EDIT_UPDATE is specified and the article
1604 * doesn't exist, the function will return an edit-gone-missing error. If
1605 * EDIT_NEW is specified and the article does exist, an edit-already-exists
1606 * error will be returned. These two conditions are also possible with
1607 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1608 *
1609 * @param bool|int $baseRevId The revision ID this edit was based off, if any.
1610 * This is not the parent revision ID, rather the revision ID for older
1611 * content used as the source for a rollback, for example.
1612 * @param User $user The user doing the edit
1613 *
1614 * @throws MWException
1615 * @return Status Possible errors:
1616 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't
1617 * set the fatal flag of $status
1618 * edit-gone-missing: In update mode, but the article didn't exist.
1619 * edit-conflict: In update mode, the article changed unexpectedly.
1620 * edit-no-change: Warning that the text was the same as before.
1621 * edit-already-exists: In creation mode, but the article already exists.
1622 *
1623 * Extensions may define additional errors.
1624 *
1625 * $return->value will contain an associative array with members as follows:
1626 * new: Boolean indicating if the function attempted to create a new article.
1627 * revision: The revision object for the inserted revision, or null.
1628 *
1629 * Compatibility note: this function previously returned a boolean value
1630 * indicating success/failure
1631 *
1632 * @deprecated since 1.21: use doEditContent() instead.
1633 */
1634 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
1635 ContentHandler::deprecated( __METHOD__, '1.21' );
1636
1637 $content = ContentHandler::makeContent( $text, $this->getTitle() );
1638
1639 return $this->doEditContent( $content, $summary, $flags, $baseRevId, $user );
1640 }
1641
1642 /**
1643 * Change an existing article or create a new article. Updates RC and all necessary caches,
1644 * optionally via the deferred update array.
1645 *
1646 * @param Content $content New content
1647 * @param string $summary Edit summary
1648 * @param int $flags Bitfield:
1649 * EDIT_NEW
1650 * Article is known or assumed to be non-existent, create a new one
1651 * EDIT_UPDATE
1652 * Article is known or assumed to be pre-existing, update it
1653 * EDIT_MINOR
1654 * Mark this edit minor, if the user is allowed to do so
1655 * EDIT_SUPPRESS_RC
1656 * Do not log the change in recentchanges
1657 * EDIT_FORCE_BOT
1658 * Mark the edit a "bot" edit regardless of user rights
1659 * EDIT_DEFER_UPDATES
1660 * Defer some of the updates until the end of index.php
1661 * EDIT_AUTOSUMMARY
1662 * Fill in blank summaries with generated text where possible
1663 *
1664 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the
1665 * article will be detected. If EDIT_UPDATE is specified and the article
1666 * doesn't exist, the function will return an edit-gone-missing error. If
1667 * EDIT_NEW is specified and the article does exist, an edit-already-exists
1668 * error will be returned. These two conditions are also possible with
1669 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1670 *
1671 * @param bool|int $baseRevId The revision ID this edit was based off, if any.
1672 * This is not the parent revision ID, rather the revision ID for older
1673 * content used as the source for a rollback, for example.
1674 * @param User $user The user doing the edit
1675 * @param string $serialFormat Format for storing the content in the
1676 * database.
1677 *
1678 * @throws MWException
1679 * @return Status Possible errors:
1680 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't
1681 * set the fatal flag of $status.
1682 * edit-gone-missing: In update mode, but the article didn't exist.
1683 * edit-conflict: In update mode, the article changed unexpectedly.
1684 * edit-no-change: Warning that the text was the same as before.
1685 * edit-already-exists: In creation mode, but the article already exists.
1686 *
1687 * Extensions may define additional errors.
1688 *
1689 * $return->value will contain an associative array with members as follows:
1690 * new: Boolean indicating if the function attempted to create a new article.
1691 * revision: The revision object for the inserted revision, or null.
1692 *
1693 * @since 1.21
1694 */
1695 public function doEditContent( Content $content, $summary, $flags = 0, $baseRevId = false,
1696 User $user = null, $serialFormat = null
1697 ) {
1698 global $wgUser, $wgUseAutomaticEditSummaries, $wgUseRCPatrol, $wgUseNPPatrol;
1699
1700 // Low-level sanity check
1701 if ( $this->mTitle->getText() === '' ) {
1702 throw new MWException( 'Something is trying to edit an article with an empty title' );
1703 }
1704
1705 if ( !$content->getContentHandler()->canBeUsedOn( $this->getTitle() ) ) {
1706 return Status::newFatal( 'content-not-allowed-here',
1707 ContentHandler::getLocalizedName( $content->getModel() ),
1708 $this->getTitle()->getPrefixedText() );
1709 }
1710
1711 $user = is_null( $user ) ? $wgUser : $user;
1712 $status = Status::newGood( array() );
1713
1714 // Load the data from the master database if needed.
1715 // The caller may already loaded it from the master or even loaded it using
1716 // SELECT FOR UPDATE, so do not override that using clear().
1717 $this->loadPageData( 'fromdbmaster' );
1718
1719 $flags = $this->checkFlags( $flags );
1720
1721 // handle hook
1722 $hook_args = array( &$this, &$user, &$content, &$summary,
1723 $flags & EDIT_MINOR, null, null, &$flags, &$status );
1724
1725 if ( !Hooks::run( 'PageContentSave', $hook_args )
1726 || !ContentHandler::runLegacyHooks( 'ArticleSave', $hook_args ) ) {
1727
1728 wfDebug( __METHOD__ . ": ArticleSave or ArticleSaveContent hook aborted save!\n" );
1729
1730 if ( $status->isOK() ) {
1731 $status->fatal( 'edit-hook-aborted' );
1732 }
1733
1734 return $status;
1735 }
1736
1737 // Silently ignore EDIT_MINOR if not allowed
1738 $isminor = ( $flags & EDIT_MINOR ) && $user->isAllowed( 'minoredit' );
1739 $bot = $flags & EDIT_FORCE_BOT;
1740
1741 $old_content = $this->getContent( Revision::RAW ); // current revision's content
1742
1743 $oldsize = $old_content ? $old_content->getSize() : 0;
1744 $oldid = $this->getLatest();
1745 $oldIsRedirect = $this->isRedirect();
1746 $oldcountable = $this->isCountable();
1747
1748 $handler = $content->getContentHandler();
1749
1750 // Provide autosummaries if one is not provided and autosummaries are enabled.
1751 if ( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY && $summary == '' ) {
1752 if ( !$old_content ) {
1753 $old_content = null;
1754 }
1755 $summary = $handler->getAutosummary( $old_content, $content, $flags );
1756 }
1757
1758 $editInfo = $this->prepareContentForEdit( $content, null, $user, $serialFormat );
1759 $serialized = $editInfo->pst;
1760
1761 /**
1762 * @var Content $content
1763 */
1764 $content = $editInfo->pstContent;
1765 $newsize = $content->getSize();
1766
1767 $dbw = wfGetDB( DB_MASTER );
1768 $now = wfTimestampNow();
1769 $this->mTimestamp = $now;
1770
1771 if ( $flags & EDIT_UPDATE ) {
1772 // Update article, but only if changed.
1773 $status->value['new'] = false;
1774
1775 if ( !$oldid ) {
1776 // Article gone missing
1777 wfDebug( __METHOD__ . ": EDIT_UPDATE specified but article doesn't exist\n" );
1778 $status->fatal( 'edit-gone-missing' );
1779
1780 return $status;
1781 } elseif ( !$old_content ) {
1782 // Sanity check for bug 37225
1783 throw new MWException( "Could not find text for current revision {$oldid}." );
1784 }
1785
1786 $revision = new Revision( array(
1787 'page' => $this->getId(),
1788 'title' => $this->getTitle(), // for determining the default content model
1789 'comment' => $summary,
1790 'minor_edit' => $isminor,
1791 'text' => $serialized,
1792 'len' => $newsize,
1793 'parent_id' => $oldid,
1794 'user' => $user->getId(),
1795 'user_text' => $user->getName(),
1796 'timestamp' => $now,
1797 'content_model' => $content->getModel(),
1798 'content_format' => $serialFormat,
1799 ) ); // XXX: pass content object?!
1800
1801 $changed = !$content->equals( $old_content );
1802
1803 if ( $changed ) {
1804 $dbw->begin( __METHOD__ );
1805 try {
1806
1807 $prepStatus = $content->prepareSave( $this, $flags, $oldid, $user );
1808 $status->merge( $prepStatus );
1809
1810 if ( !$status->isOK() ) {
1811 $dbw->rollback( __METHOD__ );
1812
1813 return $status;
1814 }
1815 $revisionId = $revision->insertOn( $dbw );
1816
1817 // Update page
1818 //
1819 // We check for conflicts by comparing $oldid with the current latest revision ID.
1820 $ok = $this->updateRevisionOn( $dbw, $revision, $oldid, $oldIsRedirect );
1821
1822 if ( !$ok ) {
1823 // Belated edit conflict! Run away!!
1824 $status->fatal( 'edit-conflict' );
1825
1826 $dbw->rollback( __METHOD__ );
1827
1828 return $status;
1829 }
1830
1831 Hooks::run( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId, $user ) );
1832 // Update recentchanges
1833 if ( !( $flags & EDIT_SUPPRESS_RC ) ) {
1834 // Mark as patrolled if the user can do so
1835 $patrolled = $wgUseRCPatrol && !count(
1836 $this->mTitle->getUserPermissionsErrors( 'autopatrol', $user ) );
1837 // Add RC row to the DB
1838 $rc = RecentChange::notifyEdit( $now, $this->mTitle, $isminor, $user, $summary,
1839 $oldid, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1840 $revisionId, $patrolled
1841 );
1842
1843 // Log auto-patrolled edits
1844 if ( $patrolled ) {
1845 PatrolLog::record( $rc, true, $user );
1846 }
1847 }
1848 $user->incEditCount();
1849 } catch ( Exception $e ) {
1850 $dbw->rollback( __METHOD__ );
1851 // Question: Would it perhaps be better if this method turned all
1852 // exceptions into $status's?
1853 throw $e;
1854 }
1855 $dbw->commit( __METHOD__ );
1856 } else {
1857 // Bug 32948: revision ID must be set to page {{REVISIONID}} and
1858 // related variables correctly
1859 $revision->setId( $this->getLatest() );
1860 }
1861
1862 // Update links tables, site stats, etc.
1863 $this->doEditUpdates(
1864 $revision,
1865 $user,
1866 array(
1867 'changed' => $changed,
1868 'oldcountable' => $oldcountable
1869 )
1870 );
1871
1872 if ( !$changed ) {
1873 $status->warning( 'edit-no-change' );
1874 $revision = null;
1875 // Update page_touched, this is usually implicit in the page update
1876 // Other cache updates are done in onArticleEdit()
1877 $this->mTitle->invalidateCache();
1878 }
1879 } else {
1880 // Create new article
1881 $status->value['new'] = true;
1882
1883 $dbw->begin( __METHOD__ );
1884 try {
1885
1886 $prepStatus = $content->prepareSave( $this, $flags, $oldid, $user );
1887 $status->merge( $prepStatus );
1888
1889 if ( !$status->isOK() ) {
1890 $dbw->rollback( __METHOD__ );
1891
1892 return $status;
1893 }
1894
1895 $status->merge( $prepStatus );
1896
1897 // Add the page record; stake our claim on this title!
1898 // This will return false if the article already exists
1899 $newid = $this->insertOn( $dbw );
1900
1901 if ( $newid === false ) {
1902 $dbw->rollback( __METHOD__ );
1903 $status->fatal( 'edit-already-exists' );
1904
1905 return $status;
1906 }
1907
1908 // Save the revision text...
1909 $revision = new Revision( array(
1910 'page' => $newid,
1911 'title' => $this->getTitle(), // for determining the default content model
1912 'comment' => $summary,
1913 'minor_edit' => $isminor,
1914 'text' => $serialized,
1915 'len' => $newsize,
1916 'user' => $user->getId(),
1917 'user_text' => $user->getName(),
1918 'timestamp' => $now,
1919 'content_model' => $content->getModel(),
1920 'content_format' => $serialFormat,
1921 ) );
1922 $revisionId = $revision->insertOn( $dbw );
1923
1924 // Bug 37225: use accessor to get the text as Revision may trim it
1925 $content = $revision->getContent(); // sanity; get normalized version
1926
1927 if ( $content ) {
1928 $newsize = $content->getSize();
1929 }
1930
1931 // Update the page record with revision data
1932 $this->updateRevisionOn( $dbw, $revision, 0 );
1933
1934 Hooks::run( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1935
1936 // Update recentchanges
1937 if ( !( $flags & EDIT_SUPPRESS_RC ) ) {
1938 // Mark as patrolled if the user can do so
1939 $patrolled = ( $wgUseRCPatrol || $wgUseNPPatrol ) && !count(
1940 $this->mTitle->getUserPermissionsErrors( 'autopatrol', $user ) );
1941 // Add RC row to the DB
1942 $rc = RecentChange::notifyNew( $now, $this->mTitle, $isminor, $user, $summary, $bot,
1943 '', $newsize, $revisionId, $patrolled );
1944
1945 // Log auto-patrolled edits
1946 if ( $patrolled ) {
1947 PatrolLog::record( $rc, true, $user );
1948 }
1949 }
1950 $user->incEditCount();
1951
1952 } catch ( Exception $e ) {
1953 $dbw->rollback( __METHOD__ );
1954 throw $e;
1955 }
1956 $dbw->commit( __METHOD__ );
1957
1958 // Update links, etc.
1959 $this->doEditUpdates( $revision, $user, array( 'created' => true ) );
1960
1961 $hook_args = array( &$this, &$user, $content, $summary,
1962 $flags & EDIT_MINOR, null, null, &$flags, $revision );
1963
1964 ContentHandler::runLegacyHooks( 'ArticleInsertComplete', $hook_args );
1965 Hooks::run( 'PageContentInsertComplete', $hook_args );
1966 }
1967
1968 // Do updates right now unless deferral was requested
1969 if ( !( $flags & EDIT_DEFER_UPDATES ) ) {
1970 DeferredUpdates::doUpdates();
1971 }
1972
1973 // Return the new revision (or null) to the caller
1974 $status->value['revision'] = $revision;
1975
1976 $hook_args = array( &$this, &$user, $content, $summary,
1977 $flags & EDIT_MINOR, null, null, &$flags, $revision, &$status, $baseRevId );
1978
1979 ContentHandler::runLegacyHooks( 'ArticleSaveComplete', $hook_args );
1980 Hooks::run( 'PageContentSaveComplete', $hook_args );
1981
1982 // Promote user to any groups they meet the criteria for
1983 $dbw->onTransactionIdle( function () use ( $user ) {
1984 $user->addAutopromoteOnceGroups( 'onEdit' );
1985 } );
1986
1987 return $status;
1988 }
1989
1990 /**
1991 * Get parser options suitable for rendering the primary article wikitext
1992 *
1993 * @see ContentHandler::makeParserOptions
1994 *
1995 * @param IContextSource|User|string $context One of the following:
1996 * - IContextSource: Use the User and the Language of the provided
1997 * context
1998 * - User: Use the provided User object and $wgLang for the language,
1999 * so use an IContextSource object if possible.
2000 * - 'canonical': Canonical options (anonymous user with default
2001 * preferences and content language).
2002 * @return ParserOptions
2003 */
2004 public function makeParserOptions( $context ) {
2005 $options = $this->getContentHandler()->makeParserOptions( $context );
2006
2007 if ( $this->getTitle()->isConversionTable() ) {
2008 // @todo ConversionTable should become a separate content model, so
2009 // we don't need special cases like this one.
2010 $options->disableContentConversion();
2011 }
2012
2013 return $options;
2014 }
2015
2016 /**
2017 * Prepare text which is about to be saved.
2018 * Returns a stdClass with source, pst and output members
2019 *
2020 * @deprecated since 1.21: use prepareContentForEdit instead.
2021 * @return object
2022 */
2023 public function prepareTextForEdit( $text, $revid = null, User $user = null ) {
2024 ContentHandler::deprecated( __METHOD__, '1.21' );
2025 $content = ContentHandler::makeContent( $text, $this->getTitle() );
2026 return $this->prepareContentForEdit( $content, $revid, $user );
2027 }
2028
2029 /**
2030 * Prepare content which is about to be saved.
2031 * Returns a stdClass with source, pst and output members
2032 *
2033 * @param Content $content
2034 * @param Revision|int|null $revision Revision object. For backwards compatibility, a
2035 * revision ID is also accepted, but this is deprecated.
2036 * @param User|null $user
2037 * @param string|null $serialFormat
2038 * @param bool $useCache Check shared prepared edit cache
2039 *
2040 * @return object
2041 *
2042 * @since 1.21
2043 */
2044 public function prepareContentForEdit(
2045 Content $content, $revision = null, User $user = null, $serialFormat = null, $useCache = true
2046 ) {
2047 global $wgContLang, $wgUser, $wgAjaxEditStash;
2048
2049 if ( is_object( $revision ) ) {
2050 $revid = $revision->getId();
2051 } else {
2052 $revid = $revision;
2053 // This code path is deprecated, and nothing is known to
2054 // use it, so performance here shouldn't be a worry.
2055 if ( $revid !== null ) {
2056 $revision = Revision::newFromId( $revid, Revision::READ_LATEST );
2057 } else {
2058 $revision = null;
2059 }
2060 }
2061
2062 $user = is_null( $user ) ? $wgUser : $user;
2063 //XXX: check $user->getId() here???
2064
2065 // Use a sane default for $serialFormat, see bug 57026
2066 if ( $serialFormat === null ) {
2067 $serialFormat = $content->getContentHandler()->getDefaultFormat();
2068 }
2069
2070 if ( $this->mPreparedEdit
2071 && $this->mPreparedEdit->newContent
2072 && $this->mPreparedEdit->newContent->equals( $content )
2073 && $this->mPreparedEdit->revid == $revid
2074 && $this->mPreparedEdit->format == $serialFormat
2075 // XXX: also check $user here?
2076 ) {
2077 // Already prepared
2078 return $this->mPreparedEdit;
2079 }
2080
2081 // The edit may have already been prepared via api.php?action=stashedit
2082 $cachedEdit = $useCache && $wgAjaxEditStash
2083 ? ApiStashEdit::checkCache( $this->getTitle(), $content, $user )
2084 : false;
2085
2086 $popts = ParserOptions::newFromUserAndLang( $user, $wgContLang );
2087 Hooks::run( 'ArticlePrepareTextForEdit', array( $this, $popts ) );
2088
2089 $edit = (object)array();
2090 if ( $cachedEdit ) {
2091 $edit->timestamp = $cachedEdit->timestamp;
2092 } else {
2093 $edit->timestamp = wfTimestampNow();
2094 }
2095 // @note: $cachedEdit is not used if the rev ID was referenced in the text
2096 $edit->revid = $revid;
2097
2098 if ( $cachedEdit ) {
2099 $edit->pstContent = $cachedEdit->pstContent;
2100 } else {
2101 $edit->pstContent = $content
2102 ? $content->preSaveTransform( $this->mTitle, $user, $popts )
2103 : null;
2104 }
2105
2106 $edit->format = $serialFormat;
2107 $edit->popts = $this->makeParserOptions( 'canonical' );
2108 if ( $cachedEdit ) {
2109 $edit->output = $cachedEdit->output;
2110 } else {
2111 if ( $revision ) {
2112 // We get here if vary-revision is set. This means that this page references
2113 // itself (such as via self-transclusion). In this case, we need to make sure
2114 // that any such self-references refer to the newly-saved revision, and not
2115 // to the previous one, which could otherwise happen due to slave lag.
2116 $oldCallback = $edit->popts->setCurrentRevisionCallback(
2117 function ( $title, $parser = false ) use ( $revision, &$oldCallback ) {
2118 if ( $title->equals( $revision->getTitle() ) ) {
2119 return $revision;
2120 } else {
2121 return call_user_func(
2122 $oldCallback,
2123 $title,
2124 $parser
2125 );
2126 }
2127 }
2128 );
2129 }
2130 $edit->output = $edit->pstContent
2131 ? $edit->pstContent->getParserOutput( $this->mTitle, $revid, $edit->popts )
2132 : null;
2133 }
2134
2135 $edit->newContent = $content;
2136 $edit->oldContent = $this->getContent( Revision::RAW );
2137
2138 // NOTE: B/C for hooks! don't use these fields!
2139 $edit->newText = $edit->newContent ? ContentHandler::getContentText( $edit->newContent ) : '';
2140 $edit->oldText = $edit->oldContent ? ContentHandler::getContentText( $edit->oldContent ) : '';
2141 $edit->pst = $edit->pstContent ? $edit->pstContent->serialize( $serialFormat ) : '';
2142
2143 $this->mPreparedEdit = $edit;
2144 return $edit;
2145 }
2146
2147 /**
2148 * Do standard deferred updates after page edit.
2149 * Update links tables, site stats, search index and message cache.
2150 * Purges pages that include this page if the text was changed here.
2151 * Every 100th edit, prune the recent changes table.
2152 *
2153 * @param Revision $revision
2154 * @param User $user User object that did the revision
2155 * @param array $options Array of options, following indexes are used:
2156 * - changed: boolean, whether the revision changed the content (default true)
2157 * - created: boolean, whether the revision created the page (default false)
2158 * - moved: boolean, whether the page was moved (default false)
2159 * - oldcountable: boolean, null, or string 'no-change' (default null):
2160 * - boolean: whether the page was counted as an article before that
2161 * revision, only used in changed is true and created is false
2162 * - null: if created is false, don't update the article count; if created
2163 * is true, do update the article count
2164 * - 'no-change': don't update the article count, ever
2165 */
2166 public function doEditUpdates( Revision $revision, User $user, array $options = array() ) {
2167 global $wgEnableParserCache;
2168
2169 $options += array(
2170 'changed' => true,
2171 'created' => false,
2172 'moved' => false,
2173 'oldcountable' => null
2174 );
2175 $content = $revision->getContent();
2176
2177 // Parse the text
2178 // Be careful not to do pre-save transform twice: $text is usually
2179 // already pre-save transformed once.
2180 if ( !$this->mPreparedEdit || $this->mPreparedEdit->output->getFlag( 'vary-revision' ) ) {
2181 wfDebug( __METHOD__ . ": No prepared edit or vary-revision is set...\n" );
2182 $editInfo = $this->prepareContentForEdit( $content, $revision, $user );
2183 } else {
2184 wfDebug( __METHOD__ . ": No vary-revision, using prepared edit...\n" );
2185 $editInfo = $this->mPreparedEdit;
2186 }
2187
2188 // Save it to the parser cache
2189 if ( $wgEnableParserCache ) {
2190 $parserCache = ParserCache::singleton();
2191 $parserCache->save(
2192 $editInfo->output, $this, $editInfo->popts, $editInfo->timestamp, $editInfo->revid
2193 );
2194 }
2195
2196 // Update the links tables and other secondary data
2197 if ( $content ) {
2198 $recursive = $options['changed']; // bug 50785
2199 $updates = $content->getSecondaryDataUpdates(
2200 $this->getTitle(), null, $recursive, $editInfo->output );
2201 DataUpdate::runUpdates( $updates );
2202 }
2203
2204 Hooks::run( 'ArticleEditUpdates', array( &$this, &$editInfo, $options['changed'] ) );
2205
2206 if ( Hooks::run( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2207 // Flush old entries from the `recentchanges` table
2208 JobQueueGroup::singleton()->push( RecentChangesUpdateJob::newPurgeJob() );
2209 }
2210
2211 if ( !$this->exists() ) {
2212 return;
2213 }
2214
2215 $id = $this->getId();
2216 $title = $this->mTitle->getPrefixedDBkey();
2217 $shortTitle = $this->mTitle->getDBkey();
2218
2219 if ( $options['oldcountable'] === 'no-change' ||
2220 ( !$options['changed'] && !$options['moved'] )
2221 ) {
2222 $good = 0;
2223 } elseif ( $options['created'] ) {
2224 $good = (int)$this->isCountable( $editInfo );
2225 } elseif ( $options['oldcountable'] !== null ) {
2226 $good = (int)$this->isCountable( $editInfo ) - (int)$options['oldcountable'];
2227 } else {
2228 $good = 0;
2229 }
2230 $edits = $options['changed'] ? 1 : 0;
2231 $total = $options['created'] ? 1 : 0;
2232
2233 DeferredUpdates::addUpdate( new SiteStatsUpdate( 0, $edits, $good, $total ) );
2234 DeferredUpdates::addUpdate( new SearchUpdate( $id, $title, $content ) );
2235
2236 // If this is another user's talk page, update newtalk.
2237 // Don't do this if $options['changed'] = false (null-edits) nor if
2238 // it's a minor edit and the user doesn't want notifications for those.
2239 if ( $options['changed']
2240 && $this->mTitle->getNamespace() == NS_USER_TALK
2241 && $shortTitle != $user->getTitleKey()
2242 && !( $revision->isMinor() && $user->isAllowed( 'nominornewtalk' ) )
2243 ) {
2244 $recipient = User::newFromName( $shortTitle, false );
2245 if ( !$recipient ) {
2246 wfDebug( __METHOD__ . ": invalid username\n" );
2247 } else {
2248 // Allow extensions to prevent user notification when a new message is added to their talk page
2249 if ( Hooks::run( 'ArticleEditUpdateNewTalk', array( &$this, $recipient ) ) ) {
2250 if ( User::isIP( $shortTitle ) ) {
2251 // An anonymous user
2252 $recipient->setNewtalk( true, $revision );
2253 } elseif ( $recipient->isLoggedIn() ) {
2254 $recipient->setNewtalk( true, $revision );
2255 } else {
2256 wfDebug( __METHOD__ . ": don't need to notify a nonexistent user\n" );
2257 }
2258 }
2259 }
2260 }
2261
2262 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
2263 // XXX: could skip pseudo-messages like js/css here, based on content model.
2264 $msgtext = $content ? $content->getWikitextForTransclusion() : null;
2265 if ( $msgtext === false || $msgtext === null ) {
2266 $msgtext = '';
2267 }
2268
2269 MessageCache::singleton()->replace( $shortTitle, $msgtext );
2270 }
2271
2272 if ( $options['created'] ) {
2273 self::onArticleCreate( $this->mTitle );
2274 } elseif ( $options['changed'] ) { // bug 50785
2275 self::onArticleEdit( $this->mTitle );
2276 }
2277
2278 }
2279
2280 /**
2281 * Edit an article without doing all that other stuff
2282 * The article must already exist; link tables etc
2283 * are not updated, caches are not flushed.
2284 *
2285 * @param string $text Text submitted
2286 * @param User $user The relevant user
2287 * @param string $comment Comment submitted
2288 * @param bool $minor Whereas it's a minor modification
2289 *
2290 * @deprecated since 1.21, use doEditContent() instead.
2291 */
2292 public function doQuickEdit( $text, User $user, $comment = '', $minor = 0 ) {
2293 ContentHandler::deprecated( __METHOD__, "1.21" );
2294
2295 $content = ContentHandler::makeContent( $text, $this->getTitle() );
2296 $this->doQuickEditContent( $content, $user, $comment, $minor );
2297 }
2298
2299 /**
2300 * Edit an article without doing all that other stuff
2301 * The article must already exist; link tables etc
2302 * are not updated, caches are not flushed.
2303 *
2304 * @param Content $content Content submitted
2305 * @param User $user The relevant user
2306 * @param string $comment Comment submitted
2307 * @param bool $minor Whereas it's a minor modification
2308 * @param string $serialFormat Format for storing the content in the database
2309 */
2310 public function doQuickEditContent( Content $content, User $user, $comment = '', $minor = false,
2311 $serialFormat = null
2312 ) {
2313
2314 $serialized = $content->serialize( $serialFormat );
2315
2316 $dbw = wfGetDB( DB_MASTER );
2317 $revision = new Revision( array(
2318 'title' => $this->getTitle(), // for determining the default content model
2319 'page' => $this->getId(),
2320 'user_text' => $user->getName(),
2321 'user' => $user->getId(),
2322 'text' => $serialized,
2323 'length' => $content->getSize(),
2324 'comment' => $comment,
2325 'minor_edit' => $minor ? 1 : 0,
2326 ) ); // XXX: set the content object?
2327 $revision->insertOn( $dbw );
2328 $this->updateRevisionOn( $dbw, $revision );
2329
2330 Hooks::run( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
2331
2332 }
2333
2334 /**
2335 * Update the article's restriction field, and leave a log entry.
2336 * This works for protection both existing and non-existing pages.
2337 *
2338 * @param array $limit Set of restriction keys
2339 * @param array $expiry Per restriction type expiration
2340 * @param int &$cascade Set to false if cascading protection isn't allowed.
2341 * @param string $reason
2342 * @param User $user The user updating the restrictions
2343 * @return Status
2344 */
2345 public function doUpdateRestrictions( array $limit, array $expiry,
2346 &$cascade, $reason, User $user
2347 ) {
2348 global $wgCascadingRestrictionLevels, $wgContLang;
2349
2350 if ( wfReadOnly() ) {
2351 return Status::newFatal( 'readonlytext', wfReadOnlyReason() );
2352 }
2353
2354 $this->loadPageData( 'fromdbmaster' );
2355 $restrictionTypes = $this->mTitle->getRestrictionTypes();
2356 $id = $this->getId();
2357
2358 if ( !$cascade ) {
2359 $cascade = false;
2360 }
2361
2362 // Take this opportunity to purge out expired restrictions
2363 Title::purgeExpiredRestrictions();
2364
2365 // @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
2366 // we expect a single selection, but the schema allows otherwise.
2367 $isProtected = false;
2368 $protect = false;
2369 $changed = false;
2370
2371 $dbw = wfGetDB( DB_MASTER );
2372
2373 foreach ( $restrictionTypes as $action ) {
2374 if ( !isset( $expiry[$action] ) ) {
2375 $expiry[$action] = $dbw->getInfinity();
2376 }
2377 if ( !isset( $limit[$action] ) ) {
2378 $limit[$action] = '';
2379 } elseif ( $limit[$action] != '' ) {
2380 $protect = true;
2381 }
2382
2383 // Get current restrictions on $action
2384 $current = implode( '', $this->mTitle->getRestrictions( $action ) );
2385 if ( $current != '' ) {
2386 $isProtected = true;
2387 }
2388
2389 if ( $limit[$action] != $current ) {
2390 $changed = true;
2391 } elseif ( $limit[$action] != '' ) {
2392 // Only check expiry change if the action is actually being
2393 // protected, since expiry does nothing on an not-protected
2394 // action.
2395 if ( $this->mTitle->getRestrictionExpiry( $action ) != $expiry[$action] ) {
2396 $changed = true;
2397 }
2398 }
2399 }
2400
2401 if ( !$changed && $protect && $this->mTitle->areRestrictionsCascading() != $cascade ) {
2402 $changed = true;
2403 }
2404
2405 // If nothing has changed, do nothing
2406 if ( !$changed ) {
2407 return Status::newGood();
2408 }
2409
2410 if ( !$protect ) { // No protection at all means unprotection
2411 $revCommentMsg = 'unprotectedarticle';
2412 $logAction = 'unprotect';
2413 } elseif ( $isProtected ) {
2414 $revCommentMsg = 'modifiedarticleprotection';
2415 $logAction = 'modify';
2416 } else {
2417 $revCommentMsg = 'protectedarticle';
2418 $logAction = 'protect';
2419 }
2420
2421 // Truncate for whole multibyte characters
2422 $reason = $wgContLang->truncate( $reason, 255 );
2423
2424 $logRelationsValues = array();
2425 $logRelationsField = null;
2426
2427 if ( $id ) { // Protection of existing page
2428 if ( !Hooks::run( 'ArticleProtect', array( &$this, &$user, $limit, $reason ) ) ) {
2429 return Status::newGood();
2430 }
2431
2432 // Only certain restrictions can cascade...
2433 $editrestriction = isset( $limit['edit'] )
2434 ? array( $limit['edit'] )
2435 : $this->mTitle->getRestrictions( 'edit' );
2436 foreach ( array_keys( $editrestriction, 'sysop' ) as $key ) {
2437 $editrestriction[$key] = 'editprotected'; // backwards compatibility
2438 }
2439 foreach ( array_keys( $editrestriction, 'autoconfirmed' ) as $key ) {
2440 $editrestriction[$key] = 'editsemiprotected'; // backwards compatibility
2441 }
2442
2443 $cascadingRestrictionLevels = $wgCascadingRestrictionLevels;
2444 foreach ( array_keys( $cascadingRestrictionLevels, 'sysop' ) as $key ) {
2445 $cascadingRestrictionLevels[$key] = 'editprotected'; // backwards compatibility
2446 }
2447 foreach ( array_keys( $cascadingRestrictionLevels, 'autoconfirmed' ) as $key ) {
2448 $cascadingRestrictionLevels[$key] = 'editsemiprotected'; // backwards compatibility
2449 }
2450
2451 // The schema allows multiple restrictions
2452 if ( !array_intersect( $editrestriction, $cascadingRestrictionLevels ) ) {
2453 $cascade = false;
2454 }
2455
2456 // insert null revision to identify the page protection change as edit summary
2457 $latest = $this->getLatest();
2458 $nullRevision = $this->insertProtectNullRevision(
2459 $revCommentMsg,
2460 $limit,
2461 $expiry,
2462 $cascade,
2463 $reason,
2464 $user
2465 );
2466
2467 if ( $nullRevision === null ) {
2468 return Status::newFatal( 'no-null-revision', $this->mTitle->getPrefixedText() );
2469 }
2470
2471 $logRelationsField = 'pr_id';
2472
2473 // Update restrictions table
2474 foreach ( $limit as $action => $restrictions ) {
2475 $dbw->delete(
2476 'page_restrictions',
2477 array(
2478 'pr_page' => $id,
2479 'pr_type' => $action
2480 ),
2481 __METHOD__
2482 );
2483 if ( $restrictions != '' ) {
2484 $dbw->insert(
2485 'page_restrictions',
2486 array(
2487 'pr_id' => $dbw->nextSequenceValue( 'page_restrictions_pr_id_seq' ),
2488 'pr_page' => $id,
2489 'pr_type' => $action,
2490 'pr_level' => $restrictions,
2491 'pr_cascade' => ( $cascade && $action == 'edit' ) ? 1 : 0,
2492 'pr_expiry' => $dbw->encodeExpiry( $expiry[$action] )
2493 ),
2494 __METHOD__
2495 );
2496 $logRelationsValues[] = $dbw->insertId();
2497 }
2498 }
2499
2500 // Clear out legacy restriction fields
2501 $dbw->update(
2502 'page',
2503 array( 'page_restrictions' => '' ),
2504 array( 'page_id' => $id ),
2505 __METHOD__
2506 );
2507
2508 Hooks::run( 'NewRevisionFromEditComplete', array( $this, $nullRevision, $latest, $user ) );
2509 Hooks::run( 'ArticleProtectComplete', array( &$this, &$user, $limit, $reason ) );
2510 } else { // Protection of non-existing page (also known as "title protection")
2511 // Cascade protection is meaningless in this case
2512 $cascade = false;
2513
2514 if ( $limit['create'] != '' ) {
2515 $dbw->replace( 'protected_titles',
2516 array( array( 'pt_namespace', 'pt_title' ) ),
2517 array(
2518 'pt_namespace' => $this->mTitle->getNamespace(),
2519 'pt_title' => $this->mTitle->getDBkey(),
2520 'pt_create_perm' => $limit['create'],
2521 'pt_timestamp' => $dbw->timestamp(),
2522 'pt_expiry' => $dbw->encodeExpiry( $expiry['create'] ),
2523 'pt_user' => $user->getId(),
2524 'pt_reason' => $reason,
2525 ), __METHOD__
2526 );
2527 } else {
2528 $dbw->delete( 'protected_titles',
2529 array(
2530 'pt_namespace' => $this->mTitle->getNamespace(),
2531 'pt_title' => $this->mTitle->getDBkey()
2532 ), __METHOD__
2533 );
2534 }
2535 }
2536
2537 $this->mTitle->flushRestrictions();
2538 InfoAction::invalidateCache( $this->mTitle );
2539
2540 if ( $logAction == 'unprotect' ) {
2541 $params = array();
2542 } else {
2543 $protectDescriptionLog = $this->protectDescriptionLog( $limit, $expiry );
2544 $params = array( $protectDescriptionLog, $cascade ? 'cascade' : '' );
2545 }
2546
2547 // Update the protection log
2548 $log = new LogPage( 'protect' );
2549 $logId = $log->addEntry( $logAction, $this->mTitle, $reason, $params, $user );
2550 if ( $logRelationsField !== null && count( $logRelationsValues ) ) {
2551 $log->addRelations( $logRelationsField, $logRelationsValues, $logId );
2552 }
2553
2554 return Status::newGood();
2555 }
2556
2557 /**
2558 * Insert a new null revision for this page.
2559 *
2560 * @param string $revCommentMsg Comment message key for the revision
2561 * @param array $limit Set of restriction keys
2562 * @param array $expiry Per restriction type expiration
2563 * @param int $cascade Set to false if cascading protection isn't allowed.
2564 * @param string $reason
2565 * @param User|null $user
2566 * @return Revision|null Null on error
2567 */
2568 public function insertProtectNullRevision( $revCommentMsg, array $limit,
2569 array $expiry, $cascade, $reason, $user = null
2570 ) {
2571 global $wgContLang;
2572 $dbw = wfGetDB( DB_MASTER );
2573
2574 // Prepare a null revision to be added to the history
2575 $editComment = $wgContLang->ucfirst(
2576 wfMessage(
2577 $revCommentMsg,
2578 $this->mTitle->getPrefixedText()
2579 )->inContentLanguage()->text()
2580 );
2581 if ( $reason ) {
2582 $editComment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
2583 }
2584 $protectDescription = $this->protectDescription( $limit, $expiry );
2585 if ( $protectDescription ) {
2586 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2587 $editComment .= wfMessage( 'parentheses' )->params( $protectDescription )
2588 ->inContentLanguage()->text();
2589 }
2590 if ( $cascade ) {
2591 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2592 $editComment .= wfMessage( 'brackets' )->params(
2593 wfMessage( 'protect-summary-cascade' )->inContentLanguage()->text()
2594 )->inContentLanguage()->text();
2595 }
2596
2597 $nullRev = Revision::newNullRevision( $dbw, $this->getId(), $editComment, true, $user );
2598 if ( $nullRev ) {
2599 $nullRev->insertOn( $dbw );
2600
2601 // Update page record and touch page
2602 $oldLatest = $nullRev->getParentId();
2603 $this->updateRevisionOn( $dbw, $nullRev, $oldLatest );
2604 }
2605
2606 return $nullRev;
2607 }
2608
2609 /**
2610 * @param string $expiry 14-char timestamp or "infinity", or false if the input was invalid
2611 * @return string
2612 */
2613 protected function formatExpiry( $expiry ) {
2614 global $wgContLang;
2615 $dbr = wfGetDB( DB_SLAVE );
2616
2617 $encodedExpiry = $dbr->encodeExpiry( $expiry );
2618 if ( $encodedExpiry != 'infinity' ) {
2619 return wfMessage(
2620 'protect-expiring',
2621 $wgContLang->timeanddate( $expiry, false, false ),
2622 $wgContLang->date( $expiry, false, false ),
2623 $wgContLang->time( $expiry, false, false )
2624 )->inContentLanguage()->text();
2625 } else {
2626 return wfMessage( 'protect-expiry-indefinite' )
2627 ->inContentLanguage()->text();
2628 }
2629 }
2630
2631 /**
2632 * Builds the description to serve as comment for the edit.
2633 *
2634 * @param array $limit Set of restriction keys
2635 * @param array $expiry Per restriction type expiration
2636 * @return string
2637 */
2638 public function protectDescription( array $limit, array $expiry ) {
2639 $protectDescription = '';
2640
2641 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2642 # $action is one of $wgRestrictionTypes = array( 'create', 'edit', 'move', 'upload' ).
2643 # All possible message keys are listed here for easier grepping:
2644 # * restriction-create
2645 # * restriction-edit
2646 # * restriction-move
2647 # * restriction-upload
2648 $actionText = wfMessage( 'restriction-' . $action )->inContentLanguage()->text();
2649 # $restrictions is one of $wgRestrictionLevels = array( '', 'autoconfirmed', 'sysop' ),
2650 # with '' filtered out. All possible message keys are listed below:
2651 # * protect-level-autoconfirmed
2652 # * protect-level-sysop
2653 $restrictionsText = wfMessage( 'protect-level-' . $restrictions )->inContentLanguage()->text();
2654
2655 $expiryText = $this->formatExpiry( $expiry[$action] );
2656
2657 if ( $protectDescription !== '' ) {
2658 $protectDescription .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2659 }
2660 $protectDescription .= wfMessage( 'protect-summary-desc' )
2661 ->params( $actionText, $restrictionsText, $expiryText )
2662 ->inContentLanguage()->text();
2663 }
2664
2665 return $protectDescription;
2666 }
2667
2668 /**
2669 * Builds the description to serve as comment for the log entry.
2670 *
2671 * Some bots may parse IRC lines, which are generated from log entries which contain plain
2672 * protect description text. Keep them in old format to avoid breaking compatibility.
2673 * TODO: Fix protection log to store structured description and format it on-the-fly.
2674 *
2675 * @param array $limit Set of restriction keys
2676 * @param array $expiry Per restriction type expiration
2677 * @return string
2678 */
2679 public function protectDescriptionLog( array $limit, array $expiry ) {
2680 global $wgContLang;
2681
2682 $protectDescriptionLog = '';
2683
2684 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2685 $expiryText = $this->formatExpiry( $expiry[$action] );
2686 $protectDescriptionLog .= $wgContLang->getDirMark() . "[$action=$restrictions] ($expiryText)";
2687 }
2688
2689 return trim( $protectDescriptionLog );
2690 }
2691
2692 /**
2693 * Take an array of page restrictions and flatten it to a string
2694 * suitable for insertion into the page_restrictions field.
2695 *
2696 * @param string[] $limit
2697 *
2698 * @throws MWException
2699 * @return string
2700 */
2701 protected static function flattenRestrictions( $limit ) {
2702 if ( !is_array( $limit ) ) {
2703 throw new MWException( 'WikiPage::flattenRestrictions given non-array restriction set' );
2704 }
2705
2706 $bits = array();
2707 ksort( $limit );
2708
2709 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2710 $bits[] = "$action=$restrictions";
2711 }
2712
2713 return implode( ':', $bits );
2714 }
2715
2716 /**
2717 * Same as doDeleteArticleReal(), but returns a simple boolean. This is kept around for
2718 * backwards compatibility, if you care about error reporting you should use
2719 * doDeleteArticleReal() instead.
2720 *
2721 * Deletes the article with database consistency, writes logs, purges caches
2722 *
2723 * @param string $reason Delete reason for deletion log
2724 * @param bool $suppress Suppress all revisions and log the deletion in
2725 * the suppression log instead of the deletion log
2726 * @param int $id Article ID
2727 * @param bool $commit Defaults to true, triggers transaction end
2728 * @param array &$error Array of errors to append to
2729 * @param User $user The deleting user
2730 * @return bool True if successful
2731 */
2732 public function doDeleteArticle(
2733 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User $user = null
2734 ) {
2735 $status = $this->doDeleteArticleReal( $reason, $suppress, $id, $commit, $error, $user );
2736 return $status->isGood();
2737 }
2738
2739 /**
2740 * Back-end article deletion
2741 * Deletes the article with database consistency, writes logs, purges caches
2742 *
2743 * @since 1.19
2744 *
2745 * @param string $reason Delete reason for deletion log
2746 * @param bool $suppress Suppress all revisions and log the deletion in
2747 * the suppression log instead of the deletion log
2748 * @param int $id Article ID
2749 * @param bool $commit Defaults to true, triggers transaction end
2750 * @param array &$error Array of errors to append to
2751 * @param User $user The deleting user
2752 * @return Status Status object; if successful, $status->value is the log_id of the
2753 * deletion log entry. If the page couldn't be deleted because it wasn't
2754 * found, $status is a non-fatal 'cannotdelete' error
2755 */
2756 public function doDeleteArticleReal(
2757 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User $user = null
2758 ) {
2759 global $wgUser, $wgContentHandlerUseDB;
2760
2761 wfDebug( __METHOD__ . "\n" );
2762
2763 $status = Status::newGood();
2764
2765 if ( $this->mTitle->getDBkey() === '' ) {
2766 $status->error( 'cannotdelete', wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2767 return $status;
2768 }
2769
2770 $user = is_null( $user ) ? $wgUser : $user;
2771 if ( !Hooks::run( 'ArticleDelete', array( &$this, &$user, &$reason, &$error, &$status ) ) ) {
2772 if ( $status->isOK() ) {
2773 // Hook aborted but didn't set a fatal status
2774 $status->fatal( 'delete-hook-aborted' );
2775 }
2776 return $status;
2777 }
2778
2779 $dbw = wfGetDB( DB_MASTER );
2780 $dbw->begin( __METHOD__ );
2781
2782 if ( $id == 0 ) {
2783 $this->loadPageData( 'forupdate' );
2784 $id = $this->getID();
2785 if ( $id == 0 ) {
2786 $dbw->rollback( __METHOD__ );
2787 $status->error( 'cannotdelete', wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2788 return $status;
2789 }
2790 }
2791
2792 // we need to remember the old content so we can use it to generate all deletion updates.
2793 $content = $this->getContent( Revision::RAW );
2794
2795 // Bitfields to further suppress the content
2796 if ( $suppress ) {
2797 $bitfield = 0;
2798 // This should be 15...
2799 $bitfield |= Revision::DELETED_TEXT;
2800 $bitfield |= Revision::DELETED_COMMENT;
2801 $bitfield |= Revision::DELETED_USER;
2802 $bitfield |= Revision::DELETED_RESTRICTED;
2803 } else {
2804 $bitfield = 'rev_deleted';
2805 }
2806
2807 // For now, shunt the revision data into the archive table.
2808 // Text is *not* removed from the text table; bulk storage
2809 // is left intact to avoid breaking block-compression or
2810 // immutable storage schemes.
2811 //
2812 // For backwards compatibility, note that some older archive
2813 // table entries will have ar_text and ar_flags fields still.
2814 //
2815 // In the future, we may keep revisions and mark them with
2816 // the rev_deleted field, which is reserved for this purpose.
2817
2818 $row = array(
2819 'ar_namespace' => 'page_namespace',
2820 'ar_title' => 'page_title',
2821 'ar_comment' => 'rev_comment',
2822 'ar_user' => 'rev_user',
2823 'ar_user_text' => 'rev_user_text',
2824 'ar_timestamp' => 'rev_timestamp',
2825 'ar_minor_edit' => 'rev_minor_edit',
2826 'ar_rev_id' => 'rev_id',
2827 'ar_parent_id' => 'rev_parent_id',
2828 'ar_text_id' => 'rev_text_id',
2829 'ar_text' => '\'\'', // Be explicit to appease
2830 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2831 'ar_len' => 'rev_len',
2832 'ar_page_id' => 'page_id',
2833 'ar_deleted' => $bitfield,
2834 'ar_sha1' => 'rev_sha1',
2835 );
2836
2837 if ( $wgContentHandlerUseDB ) {
2838 $row['ar_content_model'] = 'rev_content_model';
2839 $row['ar_content_format'] = 'rev_content_format';
2840 }
2841
2842 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2843 $row,
2844 array(
2845 'page_id' => $id,
2846 'page_id = rev_page'
2847 ), __METHOD__
2848 );
2849
2850 // Now that it's safely backed up, delete it
2851 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__ );
2852 $ok = ( $dbw->affectedRows() > 0 ); // $id could be laggy
2853
2854 if ( !$ok ) {
2855 $dbw->rollback( __METHOD__ );
2856 $status->error( 'cannotdelete', wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2857 return $status;
2858 }
2859
2860 if ( !$dbw->cascadingDeletes() ) {
2861 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__ );
2862 }
2863
2864 // Clone the title, so we have the information we need when we log
2865 $logTitle = clone $this->mTitle;
2866
2867 // Log the deletion, if the page was suppressed, log it at Oversight instead
2868 $logtype = $suppress ? 'suppress' : 'delete';
2869
2870 $logEntry = new ManualLogEntry( $logtype, 'delete' );
2871 $logEntry->setPerformer( $user );
2872 $logEntry->setTarget( $logTitle );
2873 $logEntry->setComment( $reason );
2874 $logid = $logEntry->insert();
2875
2876 $dbw->onTransactionPreCommitOrIdle( function () use ( $dbw, $logEntry, $logid ) {
2877 // Bug 56776: avoid deadlocks (especially from FileDeleteForm)
2878 $logEntry->publish( $logid );
2879 } );
2880
2881 if ( $commit ) {
2882 $dbw->commit( __METHOD__ );
2883 }
2884
2885 $this->doDeleteUpdates( $id, $content );
2886
2887 Hooks::run( 'ArticleDeleteComplete', array( &$this, &$user, $reason, $id, $content, $logEntry ) );
2888 $status->value = $logid;
2889 return $status;
2890 }
2891
2892 /**
2893 * Do some database updates after deletion
2894 *
2895 * @param int $id The page_id value of the page being deleted
2896 * @param Content $content Optional page content to be used when determining
2897 * the required updates. This may be needed because $this->getContent()
2898 * may already return null when the page proper was deleted.
2899 */
2900 public function doDeleteUpdates( $id, Content $content = null ) {
2901 // update site status
2902 DeferredUpdates::addUpdate( new SiteStatsUpdate( 0, 1, - (int)$this->isCountable(), -1 ) );
2903
2904 // remove secondary indexes, etc
2905 $updates = $this->getDeletionUpdates( $content );
2906 DataUpdate::runUpdates( $updates );
2907
2908 // Reparse any pages transcluding this page
2909 LinksUpdate::queueRecursiveJobsForTable( $this->mTitle, 'templatelinks' );
2910
2911 // Reparse any pages including this image
2912 if ( $this->mTitle->getNamespace() == NS_FILE ) {
2913 LinksUpdate::queueRecursiveJobsForTable( $this->mTitle, 'imagelinks' );
2914 }
2915
2916 // Clear caches
2917 WikiPage::onArticleDelete( $this->mTitle );
2918
2919 // Reset this object and the Title object
2920 $this->loadFromRow( false, self::READ_LATEST );
2921
2922 // Search engine
2923 DeferredUpdates::addUpdate( new SearchUpdate( $id, $this->mTitle ) );
2924 }
2925
2926 /**
2927 * Roll back the most recent consecutive set of edits to a page
2928 * from the same user; fails if there are no eligible edits to
2929 * roll back to, e.g. user is the sole contributor. This function
2930 * performs permissions checks on $user, then calls commitRollback()
2931 * to do the dirty work
2932 *
2933 * @todo Separate the business/permission stuff out from backend code
2934 *
2935 * @param string $fromP Name of the user whose edits to rollback.
2936 * @param string $summary Custom summary. Set to default summary if empty.
2937 * @param string $token Rollback token.
2938 * @param bool $bot If true, mark all reverted edits as bot.
2939 *
2940 * @param array $resultDetails Array contains result-specific array of additional values
2941 * 'alreadyrolled' : 'current' (rev)
2942 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2943 *
2944 * @param User $user The user performing the rollback
2945 * @return array Array of errors, each error formatted as
2946 * array(messagekey, param1, param2, ...).
2947 * On success, the array is empty. This array can also be passed to
2948 * OutputPage::showPermissionsErrorPage().
2949 */
2950 public function doRollback(
2951 $fromP, $summary, $token, $bot, &$resultDetails, User $user
2952 ) {
2953 $resultDetails = null;
2954
2955 // Check permissions
2956 $editErrors = $this->mTitle->getUserPermissionsErrors( 'edit', $user );
2957 $rollbackErrors = $this->mTitle->getUserPermissionsErrors( 'rollback', $user );
2958 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
2959
2960 if ( !$user->matchEditToken( $token, array( $this->mTitle->getPrefixedText(), $fromP ) ) ) {
2961 $errors[] = array( 'sessionfailure' );
2962 }
2963
2964 if ( $user->pingLimiter( 'rollback' ) || $user->pingLimiter() ) {
2965 $errors[] = array( 'actionthrottledtext' );
2966 }
2967
2968 // If there were errors, bail out now
2969 if ( !empty( $errors ) ) {
2970 return $errors;
2971 }
2972
2973 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user );
2974 }
2975
2976 /**
2977 * Backend implementation of doRollback(), please refer there for parameter
2978 * and return value documentation
2979 *
2980 * NOTE: This function does NOT check ANY permissions, it just commits the
2981 * rollback to the DB. Therefore, you should only call this function direct-
2982 * ly if you want to use custom permissions checks. If you don't, use
2983 * doRollback() instead.
2984 * @param string $fromP Name of the user whose edits to rollback.
2985 * @param string $summary Custom summary. Set to default summary if empty.
2986 * @param bool $bot If true, mark all reverted edits as bot.
2987 *
2988 * @param array $resultDetails Contains result-specific array of additional values
2989 * @param User $guser The user performing the rollback
2990 * @return array
2991 */
2992 public function commitRollback( $fromP, $summary, $bot, &$resultDetails, User $guser ) {
2993 global $wgUseRCPatrol, $wgContLang;
2994
2995 $dbw = wfGetDB( DB_MASTER );
2996
2997 if ( wfReadOnly() ) {
2998 return array( array( 'readonlytext' ) );
2999 }
3000
3001 // Get the last editor
3002 $current = $this->getRevision();
3003 if ( is_null( $current ) ) {
3004 // Something wrong... no page?
3005 return array( array( 'notanarticle' ) );
3006 }
3007
3008 $from = str_replace( '_', ' ', $fromP );
3009 // User name given should match up with the top revision.
3010 // If the user was deleted then $from should be empty.
3011 if ( $from != $current->getUserText() ) {
3012 $resultDetails = array( 'current' => $current );
3013 return array( array( 'alreadyrolled',
3014 htmlspecialchars( $this->mTitle->getPrefixedText() ),
3015 htmlspecialchars( $fromP ),
3016 htmlspecialchars( $current->getUserText() )
3017 ) );
3018 }
3019
3020 // Get the last edit not by this guy...
3021 // Note: these may not be public values
3022 $user = intval( $current->getUser( Revision::RAW ) );
3023 $user_text = $dbw->addQuotes( $current->getUserText( Revision::RAW ) );
3024 $s = $dbw->selectRow( 'revision',
3025 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
3026 array( 'rev_page' => $current->getPage(),
3027 "rev_user != {$user} OR rev_user_text != {$user_text}"
3028 ), __METHOD__,
3029 array( 'USE INDEX' => 'page_timestamp',
3030 'ORDER BY' => 'rev_timestamp DESC' )
3031 );
3032 if ( $s === false ) {
3033 // No one else ever edited this page
3034 return array( array( 'cantrollback' ) );
3035 } elseif ( $s->rev_deleted & Revision::DELETED_TEXT
3036 || $s->rev_deleted & Revision::DELETED_USER
3037 ) {
3038 // Only admins can see this text
3039 return array( array( 'notvisiblerev' ) );
3040 }
3041
3042 // Set patrolling and bot flag on the edits, which gets rollbacked.
3043 // This is done before the rollback edit to have patrolling also on failure (bug 62157).
3044 $set = array();
3045 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
3046 // Mark all reverted edits as bot
3047 $set['rc_bot'] = 1;
3048 }
3049
3050 if ( $wgUseRCPatrol ) {
3051 // Mark all reverted edits as patrolled
3052 $set['rc_patrolled'] = 1;
3053 }
3054
3055 if ( count( $set ) ) {
3056 $dbw->update( 'recentchanges', $set,
3057 array( /* WHERE */
3058 'rc_cur_id' => $current->getPage(),
3059 'rc_user_text' => $current->getUserText(),
3060 'rc_timestamp > ' . $dbw->addQuotes( $s->rev_timestamp ),
3061 ), __METHOD__
3062 );
3063 }
3064
3065 // Generate the edit summary if necessary
3066 $target = Revision::newFromId( $s->rev_id, Revision::READ_LATEST );
3067 if ( empty( $summary ) ) {
3068 if ( $from == '' ) { // no public user name
3069 $summary = wfMessage( 'revertpage-nouser' );
3070 } else {
3071 $summary = wfMessage( 'revertpage' );
3072 }
3073 }
3074
3075 // Allow the custom summary to use the same args as the default message
3076 $args = array(
3077 $target->getUserText(), $from, $s->rev_id,
3078 $wgContLang->timeanddate( wfTimestamp( TS_MW, $s->rev_timestamp ) ),
3079 $current->getId(), $wgContLang->timeanddate( $current->getTimestamp() )
3080 );
3081 if ( $summary instanceof Message ) {
3082 $summary = $summary->params( $args )->inContentLanguage()->text();
3083 } else {
3084 $summary = wfMsgReplaceArgs( $summary, $args );
3085 }
3086
3087 // Trim spaces on user supplied text
3088 $summary = trim( $summary );
3089
3090 // Truncate for whole multibyte characters.
3091 $summary = $wgContLang->truncate( $summary, 255 );
3092
3093 // Save
3094 $flags = EDIT_UPDATE;
3095
3096 if ( $guser->isAllowed( 'minoredit' ) ) {
3097 $flags |= EDIT_MINOR;
3098 }
3099
3100 if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
3101 $flags |= EDIT_FORCE_BOT;
3102 }
3103
3104 // Actually store the edit
3105 $status = $this->doEditContent(
3106 $target->getContent(),
3107 $summary,
3108 $flags,
3109 $target->getId(),
3110 $guser
3111 );
3112
3113 if ( !$status->isOK() ) {
3114 return $status->getErrorsArray();
3115 }
3116
3117 // raise error, when the edit is an edit without a new version
3118 if ( empty( $status->value['revision'] ) ) {
3119 $resultDetails = array( 'current' => $current );
3120 return array( array( 'alreadyrolled',
3121 htmlspecialchars( $this->mTitle->getPrefixedText() ),
3122 htmlspecialchars( $fromP ),
3123 htmlspecialchars( $current->getUserText() )
3124 ) );
3125 }
3126
3127 $revId = $status->value['revision']->getId();
3128
3129 Hooks::run( 'ArticleRollbackComplete', array( $this, $guser, $target, $current ) );
3130
3131 $resultDetails = array(
3132 'summary' => $summary,
3133 'current' => $current,
3134 'target' => $target,
3135 'newid' => $revId
3136 );
3137
3138 return array();
3139 }
3140
3141 /**
3142 * The onArticle*() functions are supposed to be a kind of hooks
3143 * which should be called whenever any of the specified actions
3144 * are done.
3145 *
3146 * This is a good place to put code to clear caches, for instance.
3147 *
3148 * This is called on page move and undelete, as well as edit
3149 *
3150 * @param Title $title
3151 */
3152 public static function onArticleCreate( Title $title ) {
3153 // Update existence markers on article/talk tabs...
3154 $other = $title->getOtherPage();
3155
3156 $other->invalidateCache();
3157 $other->purgeSquid();
3158
3159 $title->touchLinks();
3160 $title->purgeSquid();
3161 $title->deleteTitleProtection();
3162 }
3163
3164 /**
3165 * Clears caches when article is deleted
3166 *
3167 * @param Title $title
3168 */
3169 public static function onArticleDelete( Title $title ) {
3170 // Update existence markers on article/talk tabs...
3171 $other = $title->getOtherPage();
3172
3173 $other->invalidateCache();
3174 $other->purgeSquid();
3175
3176 $title->touchLinks();
3177 $title->purgeSquid();
3178
3179 // File cache
3180 HTMLFileCache::clearFileCache( $title );
3181 InfoAction::invalidateCache( $title );
3182
3183 // Messages
3184 if ( $title->getNamespace() == NS_MEDIAWIKI ) {
3185 MessageCache::singleton()->replace( $title->getDBkey(), false );
3186 }
3187
3188 // Images
3189 if ( $title->getNamespace() == NS_FILE ) {
3190 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
3191 $update->doUpdate();
3192 }
3193
3194 // User talk pages
3195 if ( $title->getNamespace() == NS_USER_TALK ) {
3196 $user = User::newFromName( $title->getText(), false );
3197 if ( $user ) {
3198 $user->setNewtalk( false );
3199 }
3200 }
3201
3202 // Image redirects
3203 RepoGroup::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
3204 }
3205
3206 /**
3207 * Purge caches on page update etc
3208 *
3209 * @param Title $title
3210 */
3211 public static function onArticleEdit( Title $title ) {
3212 // Invalidate caches of articles which include this page
3213 DeferredUpdates::addHTMLCacheUpdate( $title, 'templatelinks' );
3214
3215 // Invalidate the caches of all pages which redirect here
3216 DeferredUpdates::addHTMLCacheUpdate( $title, 'redirect' );
3217
3218 // Purge squid for this page only
3219 $title->purgeSquid();
3220
3221 // Clear file cache for this page only
3222 HTMLFileCache::clearFileCache( $title );
3223 InfoAction::invalidateCache( $title );
3224 }
3225
3226 /**#@-*/
3227
3228 /**
3229 * Returns a list of categories this page is a member of.
3230 * Results will include hidden categories
3231 *
3232 * @return TitleArray
3233 */
3234 public function getCategories() {
3235 $id = $this->getId();
3236 if ( $id == 0 ) {
3237 return TitleArray::newFromResult( new FakeResultWrapper( array() ) );
3238 }
3239
3240 $dbr = wfGetDB( DB_SLAVE );
3241 $res = $dbr->select( 'categorylinks',
3242 array( 'cl_to AS page_title, ' . NS_CATEGORY . ' AS page_namespace' ),
3243 // Have to do that since DatabaseBase::fieldNamesWithAlias treats numeric indexes
3244 // as not being aliases, and NS_CATEGORY is numeric
3245 array( 'cl_from' => $id ),
3246 __METHOD__ );
3247
3248 return TitleArray::newFromResult( $res );
3249 }
3250
3251 /**
3252 * Returns a list of hidden categories this page is a member of.
3253 * Uses the page_props and categorylinks tables.
3254 *
3255 * @return array Array of Title objects
3256 */
3257 public function getHiddenCategories() {
3258 $result = array();
3259 $id = $this->getId();
3260
3261 if ( $id == 0 ) {
3262 return array();
3263 }
3264
3265 $dbr = wfGetDB( DB_SLAVE );
3266 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
3267 array( 'cl_to' ),
3268 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3269 'page_namespace' => NS_CATEGORY, 'page_title=cl_to' ),
3270 __METHOD__ );
3271
3272 if ( $res !== false ) {
3273 foreach ( $res as $row ) {
3274 $result[] = Title::makeTitle( NS_CATEGORY, $row->cl_to );
3275 }
3276 }
3277
3278 return $result;
3279 }
3280
3281 /**
3282 * Return an applicable autosummary if one exists for the given edit.
3283 * @param string|null $oldtext The previous text of the page.
3284 * @param string|null $newtext The submitted text of the page.
3285 * @param int $flags Bitmask: a bitmask of flags submitted for the edit.
3286 * @return string An appropriate autosummary, or an empty string.
3287 *
3288 * @deprecated since 1.21, use ContentHandler::getAutosummary() instead
3289 */
3290 public static function getAutosummary( $oldtext, $newtext, $flags ) {
3291 // NOTE: stub for backwards-compatibility. assumes the given text is
3292 // wikitext. will break horribly if it isn't.
3293
3294 ContentHandler::deprecated( __METHOD__, '1.21' );
3295
3296 $handler = ContentHandler::getForModelID( CONTENT_MODEL_WIKITEXT );
3297 $oldContent = is_null( $oldtext ) ? null : $handler->unserializeContent( $oldtext );
3298 $newContent = is_null( $newtext ) ? null : $handler->unserializeContent( $newtext );
3299
3300 return $handler->getAutosummary( $oldContent, $newContent, $flags );
3301 }
3302
3303 /**
3304 * Auto-generates a deletion reason
3305 *
3306 * @param bool &$hasHistory Whether the page has a history
3307 * @return string|bool String containing deletion reason or empty string, or boolean false
3308 * if no revision occurred
3309 */
3310 public function getAutoDeleteReason( &$hasHistory ) {
3311 return $this->getContentHandler()->getAutoDeleteReason( $this->getTitle(), $hasHistory );
3312 }
3313
3314 /**
3315 * Update all the appropriate counts in the category table, given that
3316 * we've added the categories $added and deleted the categories $deleted.
3317 *
3318 * @param array $added The names of categories that were added
3319 * @param array $deleted The names of categories that were deleted
3320 */
3321 public function updateCategoryCounts( array $added, array $deleted ) {
3322 $that = $this;
3323 $method = __METHOD__;
3324 $dbw = wfGetDB( DB_MASTER );
3325
3326 // Do this at the end of the commit to reduce lock wait timeouts
3327 $dbw->onTransactionPreCommitOrIdle(
3328 function () use ( $dbw, $that, $method, $added, $deleted ) {
3329 $ns = $that->getTitle()->getNamespace();
3330
3331 $addFields = array( 'cat_pages = cat_pages + 1' );
3332 $removeFields = array( 'cat_pages = cat_pages - 1' );
3333 if ( $ns == NS_CATEGORY ) {
3334 $addFields[] = 'cat_subcats = cat_subcats + 1';
3335 $removeFields[] = 'cat_subcats = cat_subcats - 1';
3336 } elseif ( $ns == NS_FILE ) {
3337 $addFields[] = 'cat_files = cat_files + 1';
3338 $removeFields[] = 'cat_files = cat_files - 1';
3339 }
3340
3341 if ( count( $added ) ) {
3342 $insertRows = array();
3343 foreach ( $added as $cat ) {
3344 $insertRows[] = array(
3345 'cat_title' => $cat,
3346 'cat_pages' => 1,
3347 'cat_subcats' => ( $ns == NS_CATEGORY ) ? 1 : 0,
3348 'cat_files' => ( $ns == NS_FILE ) ? 1 : 0,
3349 );
3350 }
3351 $dbw->upsert(
3352 'category',
3353 $insertRows,
3354 array( 'cat_title' ),
3355 $addFields,
3356 $method
3357 );
3358 }
3359
3360 if ( count( $deleted ) ) {
3361 $dbw->update(
3362 'category',
3363 $removeFields,
3364 array( 'cat_title' => $deleted ),
3365 $method
3366 );
3367 }
3368
3369 foreach ( $added as $catName ) {
3370 $cat = Category::newFromName( $catName );
3371 Hooks::run( 'CategoryAfterPageAdded', array( $cat, $that ) );
3372 }
3373
3374 foreach ( $deleted as $catName ) {
3375 $cat = Category::newFromName( $catName );
3376 Hooks::run( 'CategoryAfterPageRemoved', array( $cat, $that ) );
3377 }
3378 }
3379 );
3380 }
3381
3382 /**
3383 * Opportunistically enqueue link update jobs given fresh parser output if useful
3384 *
3385 * @param ParserOutput $parserOutput Current version page output
3386 * @return bool Whether a job was pushed
3387 * @since 1.25
3388 */
3389 public function triggerOpportunisticLinksUpdate( ParserOutput $parserOutput ) {
3390 if ( wfReadOnly() ) {
3391 return false;
3392 }
3393
3394 if ( $this->mTitle->areRestrictionsCascading() ) {
3395 // If the page is cascade protecting, the links should really be up-to-date
3396 $params = array( 'prioritize' => true );
3397 } elseif ( $parserOutput->hasDynamicContent() ) {
3398 // Assume the output contains time/random based magic words
3399 $params = array();
3400 } else {
3401 // If the inclusions are deterministic, the edit-triggered link jobs are enough
3402 return false;
3403 }
3404
3405 // Check if the last link refresh was before page_touched
3406 if ( $this->getLinksTimestamp() < $this->getTouched() ) {
3407 JobQueueGroup::singleton()->push( EnqueueJob::newFromLocalJobs(
3408 new JobSpecification( 'refreshLinks', $params, array(), $this->mTitle )
3409 ) );
3410 return true;
3411 }
3412
3413 return false;
3414 }
3415
3416 /**
3417 * Return a list of templates used by this article.
3418 * Uses the templatelinks table
3419 *
3420 * @deprecated since 1.19; use Title::getTemplateLinksFrom()
3421 * @return array Array of Title objects
3422 */
3423 public function getUsedTemplates() {
3424 return $this->mTitle->getTemplateLinksFrom();
3425 }
3426
3427 /**
3428 * This function is called right before saving the wikitext,
3429 * so we can do things like signatures and links-in-context.
3430 *
3431 * @deprecated since 1.19; use Parser::preSaveTransform() instead
3432 * @param string $text Article contents
3433 * @param User $user User doing the edit
3434 * @param ParserOptions $popts Parser options, default options for
3435 * the user loaded if null given
3436 * @return string Article contents with altered wikitext markup (signatures
3437 * converted, {{subst:}}, templates, etc.)
3438 */
3439 public function preSaveTransform( $text, User $user = null, ParserOptions $popts = null ) {
3440 global $wgParser, $wgUser;
3441
3442 wfDeprecated( __METHOD__, '1.19' );
3443
3444 $user = is_null( $user ) ? $wgUser : $user;
3445
3446 if ( $popts === null ) {
3447 $popts = ParserOptions::newFromUser( $user );
3448 }
3449
3450 return $wgParser->preSaveTransform( $text, $this->mTitle, $user, $popts );
3451 }
3452
3453 /**
3454 * Update the article's restriction field, and leave a log entry.
3455 *
3456 * @deprecated since 1.19
3457 * @param array $limit Set of restriction keys
3458 * @param string $reason
3459 * @param int &$cascade Set to false if cascading protection isn't allowed.
3460 * @param array $expiry Per restriction type expiration
3461 * @param User $user The user updating the restrictions
3462 * @return bool True on success
3463 */
3464 public function updateRestrictions(
3465 $limit = array(), $reason = '', &$cascade = 0, $expiry = array(), User $user = null
3466 ) {
3467 global $wgUser;
3468
3469 $user = is_null( $user ) ? $wgUser : $user;
3470
3471 return $this->doUpdateRestrictions( $limit, $expiry, $cascade, $reason, $user )->isOK();
3472 }
3473
3474 /**
3475 * Returns a list of updates to be performed when this page is deleted. The
3476 * updates should remove any information about this page from secondary data
3477 * stores such as links tables.
3478 *
3479 * @param Content|null $content Optional Content object for determining the
3480 * necessary updates.
3481 * @return array An array of DataUpdates objects
3482 */
3483 public function getDeletionUpdates( Content $content = null ) {
3484 if ( !$content ) {
3485 // load content object, which may be used to determine the necessary updates
3486 // XXX: the content may not be needed to determine the updates, then this would be overhead.
3487 $content = $this->getContent( Revision::RAW );
3488 }
3489
3490 if ( !$content ) {
3491 $updates = array();
3492 } else {
3493 $updates = $content->getDeletionUpdates( $this );
3494 }
3495
3496 Hooks::run( 'WikiPageDeletionUpdates', array( $this, $content, &$updates ) );
3497 return $updates;
3498 }
3499 }