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