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