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