Expand on r91123 Article refactoring:
[lhc/web/wiklou.git] / includes / WikiPage.php
1 <?php
2 /**
3 * Abstract class for type hinting (accepts WikiPage, Article, ImagePage, CategoryPage)
4 */
5 abstract class Page {}
6
7 /**
8 * Class representing a MediaWiki article and history.
9 *
10 * Some fields are public only for backwards-compatibility. Use accessors.
11 * In the past, this class was part of Article.php and everything was public.
12 *
13 * @internal documentation reviewed 15 Mar 2010
14 */
15 class WikiPage extends Page {
16 /**@{{
17 * @protected
18 * Fields are public for backwards-compatibility. Use accessors.
19 * In the past, this class was part of Article.php and everything was public.
20 */
21 public $mTitle = null; // !< Title object
22 public $mCounter = -1; // !< Not loaded
23 public $mDataLoaded = false; // !<
24 public $mIsRedirect = false; // !<
25 public $mLatest = false; // !<
26 public $mPreparedEdit = false; // !<
27 public $mRedirectTarget = null; // !< Title object
28 public $mLastRevision = null; // !< Revision object
29 public $mTimestamp = ''; // !<
30 public $mTouched = '19700101000000'; // !<
31 /**@}}*/
32
33 /**
34 * @protected
35 * @var ParserOptions: ParserOptions object for $wgUser articles
36 */
37 public $mParserOptions;
38
39 /**
40 * Constructor and clear the article
41 * @param $title Title Reference to a Title object.
42 */
43 public function __construct( Title $title ) {
44 $this->mTitle = $title;
45 }
46
47 /**
48 * Constructor from a page id
49 *
50 * Always override this for all subclasses (until we use PHP with LSB)
51 *
52 * @param $id Int article ID to load
53 */
54 public static function newFromID( $id ) {
55 $t = Title::newFromID( $id );
56 # @todo FIXME: Doesn't inherit right
57 return $t == null ? null : new self( $t );
58 # return $t == null ? null : new static( $t ); // PHP 5.3
59 }
60
61 /**
62 * If this page is a redirect, get its target
63 *
64 * The target will be fetched from the redirect table if possible.
65 * If this page doesn't have an entry there, call insertRedirect()
66 * @return Title|mixed object, or null if this page is not a redirect
67 */
68 public function getRedirectTarget() {
69 if ( !$this->mTitle->isRedirect() ) {
70 return null;
71 }
72
73 if ( $this->mRedirectTarget !== null ) {
74 return $this->mRedirectTarget;
75 }
76
77 # Query the redirect table
78 $dbr = wfGetDB( DB_SLAVE );
79 $row = $dbr->selectRow( 'redirect',
80 array( 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ),
81 array( 'rd_from' => $this->getID() ),
82 __METHOD__
83 );
84
85 // rd_fragment and rd_interwiki were added later, populate them if empty
86 if ( $row && !is_null( $row->rd_fragment ) && !is_null( $row->rd_interwiki ) ) {
87 return $this->mRedirectTarget = Title::makeTitle(
88 $row->rd_namespace, $row->rd_title,
89 $row->rd_fragment, $row->rd_interwiki );
90 }
91
92 # This page doesn't have an entry in the redirect table
93 return $this->mRedirectTarget = $this->insertRedirect();
94 }
95
96 /**
97 * Insert an entry for this page into the redirect table.
98 *
99 * Don't call this function directly unless you know what you're doing.
100 * @return Title object or null if not a redirect
101 */
102 public function insertRedirect() {
103 // recurse through to only get the final target
104 $retval = Title::newFromRedirectRecurse( $this->getRawText() );
105 if ( !$retval ) {
106 return null;
107 }
108 $this->insertRedirectEntry( $retval );
109 return $retval;
110 }
111
112 /**
113 * Insert or update the redirect table entry for this page to indicate
114 * it redirects to $rt .
115 * @param $rt Title redirect target
116 */
117 public function insertRedirectEntry( $rt ) {
118 $dbw = wfGetDB( DB_MASTER );
119 $dbw->replace( 'redirect', array( 'rd_from' ),
120 array(
121 'rd_from' => $this->getID(),
122 'rd_namespace' => $rt->getNamespace(),
123 'rd_title' => $rt->getDBkey(),
124 'rd_fragment' => $rt->getFragment(),
125 'rd_interwiki' => $rt->getInterwiki(),
126 ),
127 __METHOD__
128 );
129 }
130
131 /**
132 * Get the Title object or URL this page redirects to
133 *
134 * @return mixed false, Title of in-wiki target, or string with URL
135 */
136 public function followRedirect() {
137 return $this->getRedirectURL( $this->getRedirectTarget() );
138 }
139
140 /**
141 * Get the Title object or URL to use for a redirect. We use Title
142 * objects for same-wiki, non-special redirects and URLs for everything
143 * else.
144 * @param $rt Title Redirect target
145 * @return mixed false, Title object of local target, or string with URL
146 */
147 public function getRedirectURL( $rt ) {
148 if ( $rt ) {
149 if ( $rt->getInterwiki() != '' ) {
150 if ( $rt->isLocal() ) {
151 // Offsite wikis need an HTTP redirect.
152 //
153 // This can be hard to reverse and may produce loops,
154 // so they may be disabled in the site configuration.
155 $source = $this->mTitle->getFullURL( 'redirect=no' );
156 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
157 }
158 } else {
159 if ( $rt->getNamespace() == NS_SPECIAL ) {
160 // Gotta handle redirects to special pages differently:
161 // Fill the HTTP response "Location" header and ignore
162 // the rest of the page we're on.
163 //
164 // This can be hard to reverse, so they may be disabled.
165 if ( $rt->isSpecial( 'Userlogout' ) ) {
166 // rolleyes
167 } else {
168 return $rt->getFullURL();
169 }
170 }
171
172 return $rt;
173 }
174 }
175
176 // No or invalid redirect
177 return false;
178 }
179
180 /**
181 * Get the title object of the article
182 * @return Title object of this page
183 */
184 public function getTitle() {
185 return $this->mTitle;
186 }
187
188 /**
189 * Clear the object
190 */
191 public function clear() {
192 $this->mDataLoaded = false;
193
194 $this->mCounter = -1; # Not loaded
195 $this->mRedirectTarget = null; # Title object if set
196 $this->mLastRevision = null; # Latest revision
197 $this->mTimestamp = '';
198 $this->mTouched = '19700101000000';
199 $this->mIsRedirect = false;
200 $this->mLatest = false;
201 $this->mPreparedEdit = false;
202 }
203
204 /**
205 * Get the text that needs to be saved in order to undo all revisions
206 * between $undo and $undoafter. Revisions must belong to the same page,
207 * must exist and must not be deleted
208 * @param $undo Revision
209 * @param $undoafter Revision Must be an earlier revision than $undo
210 * @return mixed string on success, false on failure
211 */
212 public function getUndoText( Revision $undo, Revision $undoafter = null ) {
213 $cur_text = $this->getRawText();
214 if ( $cur_text === false ) {
215 return false; // no page
216 }
217 $undo_text = $undo->getText();
218 $undoafter_text = $undoafter->getText();
219
220 if ( $cur_text == $undo_text ) {
221 # No use doing a merge if it's just a straight revert.
222 return $undoafter_text;
223 }
224
225 $undone_text = '';
226
227 if ( !wfMerge( $undo_text, $undoafter_text, $cur_text, $undone_text ) ) {
228 return false;
229 }
230
231 return $undone_text;
232 }
233
234 /**
235 * Return the list of revision fields that should be selected to create
236 * a new page.
237 */
238 public static function selectFields() {
239 return array(
240 'page_id',
241 'page_namespace',
242 'page_title',
243 'page_restrictions',
244 'page_counter',
245 'page_is_redirect',
246 'page_is_new',
247 'page_random',
248 'page_touched',
249 'page_latest',
250 'page_len',
251 );
252 }
253
254 /**
255 * Fetch a page record with the given conditions
256 * @param $dbr DatabaseBase object
257 * @param $conditions Array
258 * @return mixed Database result resource, or false on failure
259 */
260 protected function pageData( $dbr, $conditions ) {
261 $fields = self::selectFields();
262
263 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
264
265 $row = $dbr->selectRow( 'page', $fields, $conditions, __METHOD__ );
266
267 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
268
269 return $row;
270 }
271
272 /**
273 * Fetch a page record matching the Title object's namespace and title
274 * using a sanitized title string
275 *
276 * @param $dbr DatabaseBase object
277 * @param $title Title object
278 * @return mixed Database result resource, or false on failure
279 */
280 protected function pageDataFromTitle( $dbr, $title ) {
281 return $this->pageData( $dbr, array(
282 'page_namespace' => $title->getNamespace(),
283 'page_title' => $title->getDBkey() ) );
284 }
285
286 /**
287 * Fetch a page record matching the requested ID
288 *
289 * @param $dbr DatabaseBase
290 * @param $id Integer
291 * @return mixed Database result resource, or false on failure
292 */
293 protected function pageDataFromId( $dbr, $id ) {
294 return $this->pageData( $dbr, array( 'page_id' => $id ) );
295 }
296
297 /**
298 * Set the general counter, title etc data loaded from
299 * some source.
300 *
301 * @param $data Object|String $res->fetchObject() object or the string "fromdb" to reload
302 */
303 public function loadPageData( $data = 'fromdb' ) {
304 if ( $data === 'fromdb' ) {
305 $dbr = wfGetDB( DB_SLAVE );
306 $data = $this->pageDataFromTitle( $dbr, $this->mTitle );
307 }
308
309 $lc = LinkCache::singleton();
310
311 if ( $data ) {
312 $lc->addGoodLinkObj( $data->page_id, $this->mTitle, $data->page_len, $data->page_is_redirect, $data->page_latest );
313
314 $this->mTitle->mArticleID = intval( $data->page_id );
315
316 # Old-fashioned restrictions
317 $this->mTitle->loadRestrictions( $data->page_restrictions );
318
319 $this->mCounter = intval( $data->page_counter );
320 $this->mTouched = wfTimestamp( TS_MW, $data->page_touched );
321 $this->mIsRedirect = intval( $data->page_is_redirect );
322 $this->mLatest = intval( $data->page_latest );
323 } else {
324 $lc->addBadLinkObj( $this->mTitle );
325 $this->mTitle->mArticleID = 0;
326 }
327
328 $this->mDataLoaded = true;
329 }
330
331 /**
332 * @return int Page ID
333 */
334 public function getID() {
335 return $this->mTitle->getArticleID();
336 }
337
338 /**
339 * @return bool Whether or not the page exists in the database
340 */
341 public function exists() {
342 return $this->getId() > 0;
343 }
344
345 /**
346 * Check if this page is something we're going to be showing
347 * some sort of sensible content for. If we return false, page
348 * views (plain action=view) will return an HTTP 404 response,
349 * so spiders and robots can know they're following a bad link.
350 *
351 * @return bool
352 */
353 public function hasViewableContent() {
354 return $this->exists() || $this->mTitle->isAlwaysKnown();
355 }
356
357 /**
358 * @return int The view count for the page
359 */
360 public function getCount() {
361 if ( -1 == $this->mCounter ) {
362 $id = $this->getID();
363
364 if ( $id == 0 ) {
365 $this->mCounter = 0;
366 } else {
367 $dbr = wfGetDB( DB_SLAVE );
368 $this->mCounter = $dbr->selectField( 'page',
369 'page_counter',
370 array( 'page_id' => $id ),
371 __METHOD__
372 );
373 }
374 }
375
376 return $this->mCounter;
377 }
378
379 /**
380 * Determine whether a page would be suitable for being counted as an
381 * article in the site_stats table based on the title & its content
382 *
383 * @param $editInfo Object or false: object returned by prepareTextForEdit(),
384 * if false, the current database state will be used
385 * @return Boolean
386 */
387 public function isCountable( $editInfo = false ) {
388 global $wgArticleCountMethod;
389
390 if ( !$this->mTitle->isContentPage() ) {
391 return false;
392 }
393
394 $text = $editInfo ? $editInfo->pst : false;
395
396 if ( $this->isRedirect( $text ) ) {
397 return false;
398 }
399
400 switch ( $wgArticleCountMethod ) {
401 case 'any':
402 return true;
403 case 'comma':
404 if ( $text === false ) {
405 $text = $this->getRawText();
406 }
407 return strpos( $text, ',' ) !== false;
408 case 'link':
409 if ( $editInfo ) {
410 // ParserOutput::getLinks() is a 2D array of page links, so
411 // to be really correct we would need to recurse in the array
412 // but the main array should only have items in it if there are
413 // links.
414 return (bool)count( $editInfo->output->getLinks() );
415 } else {
416 return (bool)wfGetDB( DB_SLAVE )->selectField( 'pagelinks', 1,
417 array( 'pl_from' => $this->getId() ), __METHOD__ );
418 }
419 }
420 }
421
422 /**
423 * Tests if the article text represents a redirect
424 *
425 * @param $text mixed string containing article contents, or boolean
426 * @return bool
427 */
428 public function isRedirect( $text = false ) {
429 if ( $text === false ) {
430 if ( !$this->mDataLoaded ) {
431 $this->loadPageData();
432 }
433
434 return (bool)$this->mIsRedirect;
435 } else {
436 return Title::newFromRedirect( $text ) !== null;
437 }
438 }
439
440 /**
441 * Loads everything except the text
442 * This isn't necessary for all uses, so it's only done if needed.
443 */
444 protected function loadLastEdit() {
445 if ( $this->mLastRevision !== null ) {
446 return; // already loaded
447 }
448
449 # New or non-existent articles have no user information
450 $id = $this->getID();
451 if ( 0 == $id ) {
452 return;
453 }
454
455 $revision = Revision::loadFromPageId( wfGetDB( DB_MASTER ), $id );
456 if ( $revision ) {
457 $this->setLastEdit( $revision );
458 }
459 }
460
461 /**
462 * Set the latest revision
463 */
464 protected function setLastEdit( Revision $revision ) {
465 $this->mLastRevision = $revision;
466 $this->mTimestamp = $revision->getTimestamp();
467 }
468
469 /**
470 * Get the latest revision
471 * @return Revision|false
472 */
473 public function getRevision() {
474 $this->loadLastEdit();
475 if ( $this->mLastRevision ) {
476 return $this->mLastRevision;
477 }
478 return false;
479 }
480
481 /**
482 * Get the text of the current revision. No side-effects...
483 *
484 * @param $audience Integer: one of:
485 * Revision::FOR_PUBLIC to be displayed to all users
486 * Revision::FOR_THIS_USER to be displayed to $wgUser
487 * Revision::RAW get the text regardless of permissions
488 * @return String|false The text of the current revision
489 */
490 public function getText( $audience = Revision::FOR_PUBLIC ) {
491 $this->loadLastEdit();
492 if ( $this->mLastRevision ) {
493 return $this->mLastRevision->getText( $audience );
494 }
495 return false;
496 }
497
498 /**
499 * Get the text of the current revision. No side-effects...
500 *
501 * @return String|false The text of the current revision
502 */
503 public function getRawText() {
504 $this->loadLastEdit();
505 if ( $this->mLastRevision ) {
506 return $this->mLastRevision->getRawText();
507 }
508 return false;
509 }
510
511 /**
512 * @return string MW timestamp of last article revision
513 */
514 public function getTimestamp() {
515 // Check if the field has been filled by ParserCache::get()
516 if ( !$this->mTimestamp ) {
517 $this->loadLastEdit();
518 }
519 return wfTimestamp( TS_MW, $this->mTimestamp );
520 }
521
522 /**
523 * Set the page timestamp (use only to avoid DB queries)
524 * @param $ts string MW timestamp of last article revision
525 * @return void
526 */
527 public function setTimestamp( $ts ) {
528 $this->mTimestamp = wfTimestamp( TS_MW, $ts );
529 }
530
531 /**
532 * @param $audience Integer: one of:
533 * Revision::FOR_PUBLIC to be displayed to all users
534 * Revision::FOR_THIS_USER to be displayed to $wgUser
535 * Revision::RAW get the text regardless of permissions
536 * @return int user ID for the user that made the last article revision
537 */
538 public function getUser( $audience = Revision::FOR_PUBLIC ) {
539 $this->loadLastEdit();
540 if ( $this->mLastRevision ) {
541 return $this->mLastRevision->getUser( $audience );
542 } else {
543 return -1;
544 }
545 }
546
547 /**
548 * @param $audience Integer: one of:
549 * Revision::FOR_PUBLIC to be displayed to all users
550 * Revision::FOR_THIS_USER to be displayed to $wgUser
551 * Revision::RAW get the text regardless of permissions
552 * @return string username of the user that made the last article revision
553 */
554 public function getUserText( $audience = Revision::FOR_PUBLIC ) {
555 $this->loadLastEdit();
556 if ( $this->mLastRevision ) {
557 return $this->mLastRevision->getUserText( $audience );
558 } else {
559 return '';
560 }
561 }
562
563 /**
564 * @param $audience Integer: one of:
565 * Revision::FOR_PUBLIC to be displayed to all users
566 * Revision::FOR_THIS_USER to be displayed to $wgUser
567 * Revision::RAW get the text regardless of permissions
568 * @return string Comment stored for the last article revision
569 */
570 public function getComment( $audience = Revision::FOR_PUBLIC ) {
571 $this->loadLastEdit();
572 if ( $this->mLastRevision ) {
573 return $this->mLastRevision->getComment( $audience );
574 } else {
575 return '';
576 }
577 }
578
579 /**
580 * Returns true if last revision was marked as "minor edit"
581 *
582 * @return boolean Minor edit indicator for the last article revision.
583 */
584 public function getMinorEdit() {
585 $this->loadLastEdit();
586 if ( $this->mLastRevision ) {
587 return $this->mLastRevision->isMinor();
588 } else {
589 return false;
590 }
591 }
592
593 /**
594 * Get a list of users who have edited this article, not including the user who made
595 * the most recent revision, which you can get from $article->getUser() if you want it
596 * @return UserArrayFromResult
597 */
598 public function getContributors() {
599 # @todo FIXME: This is expensive; cache this info somewhere.
600
601 $dbr = wfGetDB( DB_SLAVE );
602
603 if ( $dbr->implicitGroupby() ) {
604 $realNameField = 'user_real_name';
605 } else {
606 $realNameField = 'FIRST(user_real_name) AS user_real_name';
607 }
608
609 $tables = array( 'revision', 'user' );
610
611 $fields = array(
612 'rev_user as user_id',
613 'rev_user_text AS user_name',
614 $realNameField,
615 'MAX(rev_timestamp) AS timestamp',
616 );
617
618 $conds = array( 'rev_page' => $this->getId() );
619
620 // The user who made the top revision gets credited as "this page was last edited by
621 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
622 $user = $this->getUser();
623 if ( $user ) {
624 $conds[] = "rev_user != $user";
625 } else {
626 $conds[] = "rev_user_text != {$dbr->addQuotes( $this->getUserText() )}";
627 }
628
629 $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0"; // username hidden?
630
631 $jconds = array(
632 'user' => array( 'LEFT JOIN', 'rev_user = user_id' ),
633 );
634
635 $options = array(
636 'GROUP BY' => array( 'rev_user', 'rev_user_text' ),
637 'ORDER BY' => 'timestamp DESC',
638 );
639
640 $res = $dbr->select( $tables, $fields, $conds, __METHOD__, $options, $jconds );
641 return new UserArrayFromResult( $res );
642 }
643
644 /**
645 * Should the parser cache be used?
646 *
647 * @param $user User The relevant user
648 * @return boolean
649 */
650 public function isParserCacheUsed( User $user, $oldid ) {
651 global $wgEnableParserCache;
652
653 return $wgEnableParserCache
654 && $user->getStubThreshold() == 0
655 && $this->exists()
656 && empty( $oldid )
657 && !$this->mTitle->isCssOrJsPage()
658 && !$this->mTitle->isCssJsSubpage();
659 }
660
661 /**
662 * Perform the actions of a page purging
663 */
664 public function doPurge() {
665 global $wgUseSquid;
666
667 if( !wfRunHooks( 'ArticlePurge', array( &$this ) ) ){
668 return false;
669 }
670
671 // Invalidate the cache
672 $this->mTitle->invalidateCache();
673 $this->clear();
674
675 if ( $wgUseSquid ) {
676 // Commit the transaction before the purge is sent
677 $dbw = wfGetDB( DB_MASTER );
678 $dbw->commit();
679
680 // Send purge
681 $update = SquidUpdate::newSimplePurge( $this->mTitle );
682 $update->doUpdate();
683 }
684
685 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
686 if ( $this->getID() == 0 ) {
687 $text = false;
688 } else {
689 $text = $this->getRawText();
690 }
691
692 MessageCache::singleton()->replace( $this->mTitle->getDBkey(), $text );
693 }
694 }
695
696 /**
697 * Insert a new empty page record for this article.
698 * This *must* be followed up by creating a revision
699 * and running $this->updateRevisionOn( ... );
700 * or else the record will be left in a funky state.
701 * Best if all done inside a transaction.
702 *
703 * @param $dbw DatabaseBase
704 * @return int The newly created page_id key, or false if the title already existed
705 * @private
706 */
707 public function insertOn( $dbw ) {
708 wfProfileIn( __METHOD__ );
709
710 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
711 $dbw->insert( 'page', array(
712 'page_id' => $page_id,
713 'page_namespace' => $this->mTitle->getNamespace(),
714 'page_title' => $this->mTitle->getDBkey(),
715 'page_counter' => 0,
716 'page_restrictions' => '',
717 'page_is_redirect' => 0, # Will set this shortly...
718 'page_is_new' => 1,
719 'page_random' => wfRandom(),
720 'page_touched' => $dbw->timestamp(),
721 'page_latest' => 0, # Fill this in shortly...
722 'page_len' => 0, # Fill this in shortly...
723 ), __METHOD__, 'IGNORE' );
724
725 $affected = $dbw->affectedRows();
726
727 if ( $affected ) {
728 $newid = $dbw->insertId();
729 $this->mTitle->resetArticleID( $newid );
730 }
731 wfProfileOut( __METHOD__ );
732
733 return $affected ? $newid : false;
734 }
735
736 /**
737 * Update the page record to point to a newly saved revision.
738 *
739 * @param $dbw DatabaseBase: object
740 * @param $revision Revision: For ID number, and text used to set
741 length and redirect status fields
742 * @param $lastRevision Integer: if given, will not overwrite the page field
743 * when different from the currently set value.
744 * Giving 0 indicates the new page flag should be set
745 * on.
746 * @param $lastRevIsRedirect Boolean: if given, will optimize adding and
747 * removing rows in redirect table.
748 * @return bool true on success, false on failure
749 * @private
750 */
751 public function updateRevisionOn( $dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
752 wfProfileIn( __METHOD__ );
753
754 $text = $revision->getText();
755 $rt = Title::newFromRedirectRecurse( $text );
756
757 $conditions = array( 'page_id' => $this->getId() );
758
759 if ( !is_null( $lastRevision ) ) {
760 # An extra check against threads stepping on each other
761 $conditions['page_latest'] = $lastRevision;
762 }
763
764 $dbw->update( 'page',
765 array( /* SET */
766 'page_latest' => $revision->getId(),
767 'page_touched' => $dbw->timestamp(),
768 'page_is_new' => ( $lastRevision === 0 ) ? 1 : 0,
769 'page_is_redirect' => $rt !== null ? 1 : 0,
770 'page_len' => strlen( $text ),
771 ),
772 $conditions,
773 __METHOD__ );
774
775 $result = $dbw->affectedRows() != 0;
776 if ( $result ) {
777 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
778 }
779
780 wfProfileOut( __METHOD__ );
781 return $result;
782 }
783
784 /**
785 * Add row to the redirect table if this is a redirect, remove otherwise.
786 *
787 * @param $dbw DatabaseBase
788 * @param $redirectTitle Title object pointing to the redirect target,
789 * or NULL if this is not a redirect
790 * @param $lastRevIsRedirect If given, will optimize adding and
791 * removing rows in redirect table.
792 * @return bool true on success, false on failure
793 * @private
794 */
795 public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
796 // Always update redirects (target link might have changed)
797 // Update/Insert if we don't know if the last revision was a redirect or not
798 // Delete if changing from redirect to non-redirect
799 $isRedirect = !is_null( $redirectTitle );
800
801 if ( !$isRedirect && !is_null( $lastRevIsRedirect ) && $lastRevIsRedirect === $isRedirect ) {
802 return true;
803 }
804
805 wfProfileIn( __METHOD__ );
806 if ( $isRedirect ) {
807 $this->insertRedirectEntry( $redirectTitle );
808 } else {
809 // This is not a redirect, remove row from redirect table
810 $where = array( 'rd_from' => $this->getId() );
811 $dbw->delete( 'redirect', $where, __METHOD__ );
812 }
813
814 if ( $this->getTitle()->getNamespace() == NS_FILE ) {
815 RepoGroup::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
816 }
817 wfProfileOut( __METHOD__ );
818
819 return ( $dbw->affectedRows() != 0 );
820 }
821
822 /**
823 * If the given revision is newer than the currently set page_latest,
824 * update the page record. Otherwise, do nothing.
825 *
826 * @param $dbw Database object
827 * @param $revision Revision object
828 * @return mixed
829 */
830 public function updateIfNewerOn( $dbw, $revision ) {
831 wfProfileIn( __METHOD__ );
832
833 $row = $dbw->selectRow(
834 array( 'revision', 'page' ),
835 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
836 array(
837 'page_id' => $this->getId(),
838 'page_latest=rev_id' ),
839 __METHOD__ );
840
841 if ( $row ) {
842 if ( wfTimestamp( TS_MW, $row->rev_timestamp ) >= $revision->getTimestamp() ) {
843 wfProfileOut( __METHOD__ );
844 return false;
845 }
846 $prev = $row->rev_id;
847 $lastRevIsRedirect = (bool)$row->page_is_redirect;
848 } else {
849 # No or missing previous revision; mark the page as new
850 $prev = 0;
851 $lastRevIsRedirect = null;
852 }
853
854 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
855
856 wfProfileOut( __METHOD__ );
857 return $ret;
858 }
859
860 /**
861 * @param $section empty/null/false or a section number (0, 1, 2, T1, T2...)
862 * @param $text String: new text of the section
863 * @param $summary String: new section's subject, only if $section is 'new'
864 * @param $edittime String: revision timestamp or null to use the current revision
865 * @return string Complete article text, or null if error
866 */
867 public function replaceSection( $section, $text, $summary = '', $edittime = null ) {
868 wfProfileIn( __METHOD__ );
869
870 if ( strval( $section ) == '' ) {
871 // Whole-page edit; let the whole text through
872 } else {
873 if ( is_null( $edittime ) ) {
874 $rev = Revision::newFromTitle( $this->mTitle );
875 } else {
876 $dbw = wfGetDB( DB_MASTER );
877 $rev = Revision::loadFromTimestamp( $dbw, $this->mTitle, $edittime );
878 }
879
880 if ( !$rev ) {
881 wfDebug( "WikiPage::replaceSection asked for bogus section (page: " .
882 $this->getId() . "; section: $section; edittime: $edittime)\n" );
883 wfProfileOut( __METHOD__ );
884 return null;
885 }
886
887 $oldtext = $rev->getText();
888
889 if ( $section == 'new' ) {
890 # Inserting a new section
891 $subject = $summary ? wfMsgForContent( 'newsectionheaderdefaultlevel', $summary ) . "\n\n" : '';
892 $text = strlen( trim( $oldtext ) ) > 0
893 ? "{$oldtext}\n\n{$subject}{$text}"
894 : "{$subject}{$text}";
895 } else {
896 # Replacing an existing section; roll out the big guns
897 global $wgParser;
898
899 $text = $wgParser->replaceSection( $oldtext, $section, $text );
900 }
901 }
902
903 wfProfileOut( __METHOD__ );
904 return $text;
905 }
906
907 /**
908 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
909 * @param $flags Int
910 * @return Int updated $flags
911 */
912 function checkFlags( $flags ) {
913 if ( !( $flags & EDIT_NEW ) && !( $flags & EDIT_UPDATE ) ) {
914 if ( $this->mTitle->getArticleID() ) {
915 $flags |= EDIT_UPDATE;
916 } else {
917 $flags |= EDIT_NEW;
918 }
919 }
920
921 return $flags;
922 }
923
924 /**
925 * Change an existing article or create a new article. Updates RC and all necessary caches,
926 * optionally via the deferred update array.
927 *
928 * @param $text String: new text
929 * @param $summary String: edit summary
930 * @param $flags Integer bitfield:
931 * EDIT_NEW
932 * Article is known or assumed to be non-existent, create a new one
933 * EDIT_UPDATE
934 * Article is known or assumed to be pre-existing, update it
935 * EDIT_MINOR
936 * Mark this edit minor, if the user is allowed to do so
937 * EDIT_SUPPRESS_RC
938 * Do not log the change in recentchanges
939 * EDIT_FORCE_BOT
940 * Mark the edit a "bot" edit regardless of user rights
941 * EDIT_DEFER_UPDATES
942 * Defer some of the updates until the end of index.php
943 * EDIT_AUTOSUMMARY
944 * Fill in blank summaries with generated text where possible
945 *
946 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
947 * If EDIT_UPDATE is specified and the article doesn't exist, the function will an
948 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
949 * edit-already-exists error will be returned. These two conditions are also possible with
950 * auto-detection due to MediaWiki's performance-optimised locking strategy.
951 *
952 * @param $baseRevId the revision ID this edit was based off, if any
953 * @param $user User the user doing the edit
954 *
955 * @return Status object. Possible errors:
956 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
957 * edit-gone-missing: In update mode, but the article didn't exist
958 * edit-conflict: In update mode, the article changed unexpectedly
959 * edit-no-change: Warning that the text was the same as before
960 * edit-already-exists: In creation mode, but the article already exists
961 *
962 * Extensions may define additional errors.
963 *
964 * $return->value will contain an associative array with members as follows:
965 * new: Boolean indicating if the function attempted to create a new article
966 * revision: The revision object for the inserted revision, or null
967 *
968 * Compatibility note: this function previously returned a boolean value indicating success/failure
969 */
970 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
971 global $wgUser, $wgDBtransactions, $wgUseAutomaticEditSummaries;
972
973 # Low-level sanity check
974 if ( $this->mTitle->getText() === '' ) {
975 throw new MWException( 'Something is trying to edit an article with an empty title' );
976 }
977
978 wfProfileIn( __METHOD__ );
979
980 $user = is_null( $user ) ? $wgUser : $user;
981 $status = Status::newGood( array() );
982
983 # Load $this->mTitle->getArticleID() and $this->mLatest if it's not already
984 $this->loadPageData();
985
986 $flags = $this->checkFlags( $flags );
987
988 if ( !wfRunHooks( 'ArticleSave', array( &$this, &$user, &$text, &$summary,
989 $flags & EDIT_MINOR, null, null, &$flags, &$status ) ) )
990 {
991 wfDebug( __METHOD__ . ": ArticleSave hook aborted save!\n" );
992
993 if ( $status->isOK() ) {
994 $status->fatal( 'edit-hook-aborted' );
995 }
996
997 wfProfileOut( __METHOD__ );
998 return $status;
999 }
1000
1001 # Silently ignore EDIT_MINOR if not allowed
1002 $isminor = ( $flags & EDIT_MINOR ) && $user->isAllowed( 'minoredit' );
1003 $bot = $flags & EDIT_FORCE_BOT;
1004
1005 $oldtext = $this->getRawText(); // current revision
1006 $oldsize = strlen( $oldtext );
1007
1008 # Provide autosummaries if one is not provided and autosummaries are enabled.
1009 if ( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY && $summary == '' ) {
1010 $summary = $this->getAutosummary( $oldtext, $text, $flags );
1011 }
1012
1013 $editInfo = $this->prepareTextForEdit( $text, null, $user );
1014 $text = $editInfo->pst;
1015 $newsize = strlen( $text );
1016
1017 $dbw = wfGetDB( DB_MASTER );
1018 $now = wfTimestampNow();
1019 $this->mTimestamp = $now;
1020
1021 if ( $flags & EDIT_UPDATE ) {
1022 # Update article, but only if changed.
1023 $status->value['new'] = false;
1024
1025 # Make sure the revision is either completely inserted or not inserted at all
1026 if ( !$wgDBtransactions ) {
1027 $userAbort = ignore_user_abort( true );
1028 }
1029
1030 $changed = ( strcmp( $text, $oldtext ) != 0 );
1031
1032 if ( $changed ) {
1033 if ( !$this->mLatest ) {
1034 # Article gone missing
1035 wfDebug( __METHOD__ . ": EDIT_UPDATE specified but article doesn't exist\n" );
1036 $status->fatal( 'edit-gone-missing' );
1037
1038 wfProfileOut( __METHOD__ );
1039 return $status;
1040 }
1041
1042 $revision = new Revision( array(
1043 'page' => $this->getId(),
1044 'comment' => $summary,
1045 'minor_edit' => $isminor,
1046 'text' => $text,
1047 'parent_id' => $this->mLatest,
1048 'user' => $user->getId(),
1049 'user_text' => $user->getName(),
1050 'timestamp' => $now
1051 ) );
1052
1053 $dbw->begin();
1054 $revisionId = $revision->insertOn( $dbw );
1055
1056 # Update page
1057 #
1058 # Note that we use $this->mLatest instead of fetching a value from the master DB
1059 # during the course of this function. This makes sure that EditPage can detect
1060 # edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
1061 # before this function is called. A previous function used a separate query, this
1062 # creates a window where concurrent edits can cause an ignored edit conflict.
1063 $ok = $this->updateRevisionOn( $dbw, $revision, $this->mLatest );
1064
1065 if ( !$ok ) {
1066 /* Belated edit conflict! Run away!! */
1067 $status->fatal( 'edit-conflict' );
1068
1069 # Delete the invalid revision if the DB is not transactional
1070 if ( !$wgDBtransactions ) {
1071 $dbw->delete( 'revision', array( 'rev_id' => $revisionId ), __METHOD__ );
1072 }
1073
1074 $revisionId = 0;
1075 $dbw->rollback();
1076 } else {
1077 global $wgUseRCPatrol;
1078 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId, $user ) );
1079 # Update recentchanges
1080 if ( !( $flags & EDIT_SUPPRESS_RC ) ) {
1081 # Mark as patrolled if the user can do so
1082 $patrolled = $wgUseRCPatrol && !count(
1083 $this->mTitle->getUserPermissionsErrors( 'autopatrol', $user ) );
1084 # Add RC row to the DB
1085 $rc = RecentChange::notifyEdit( $now, $this->mTitle, $isminor, $user, $summary,
1086 $this->mLatest, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1087 $revisionId, $patrolled
1088 );
1089
1090 # Log auto-patrolled edits
1091 if ( $patrolled ) {
1092 PatrolLog::record( $rc, true );
1093 }
1094 }
1095 $user->incEditCount();
1096 $dbw->commit();
1097 }
1098 } else {
1099 $status->warning( 'edit-no-change' );
1100 $revision = null;
1101 // Keep the same revision ID, but do some updates on it
1102 $revisionId = $this->getLatest();
1103 // Update page_touched, this is usually implicit in the page update
1104 // Other cache updates are done in onArticleEdit()
1105 $this->mTitle->invalidateCache();
1106 }
1107
1108 if ( !$wgDBtransactions ) {
1109 ignore_user_abort( $userAbort );
1110 }
1111
1112 // Now that ignore_user_abort is restored, we can respond to fatal errors
1113 if ( !$status->isOK() ) {
1114 wfProfileOut( __METHOD__ );
1115 return $status;
1116 }
1117
1118 # Invalidate cache of this article and all pages using this article
1119 # as a template. Partly deferred.
1120 self::onArticleEdit( $this->mTitle );
1121 # Update links tables, site stats, etc.
1122 $this->doEditUpdates( $text, $user, $summary, $isminor, $revisionId, $changed );
1123 } else {
1124 # Create new article
1125 $status->value['new'] = true;
1126
1127 $dbw->begin();
1128
1129 # Add the page record; stake our claim on this title!
1130 # This will return false if the article already exists
1131 $newid = $this->insertOn( $dbw );
1132
1133 if ( $newid === false ) {
1134 $dbw->rollback();
1135 $status->fatal( 'edit-already-exists' );
1136
1137 wfProfileOut( __METHOD__ );
1138 return $status;
1139 }
1140
1141 # Save the revision text...
1142 $revision = new Revision( array(
1143 'page' => $newid,
1144 'comment' => $summary,
1145 'minor_edit' => $isminor,
1146 'text' => $text,
1147 'user' => $user->getId(),
1148 'user_text' => $user->getName(),
1149 'timestamp' => $now
1150 ) );
1151 $revisionId = $revision->insertOn( $dbw );
1152
1153 $this->mTitle->resetArticleID( $newid );
1154 # Update the LinkCache. Resetting the Title ArticleID means it will rely on having that already cached
1155 # @todo FIXME?
1156 LinkCache::singleton()->addGoodLinkObj( $newid, $this->mTitle, strlen( $text ), (bool)Title::newFromRedirect( $text ), $revisionId );
1157
1158 # Update the page record with revision data
1159 $this->updateRevisionOn( $dbw, $revision, 0 );
1160
1161 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1162
1163 # Update recentchanges
1164 if ( !( $flags & EDIT_SUPPRESS_RC ) ) {
1165 global $wgUseRCPatrol, $wgUseNPPatrol;
1166
1167 # Mark as patrolled if the user can do so
1168 $patrolled = ( $wgUseRCPatrol || $wgUseNPPatrol ) && !count(
1169 $this->mTitle->getUserPermissionsErrors( 'autopatrol', $user ) );
1170 # Add RC row to the DB
1171 $rc = RecentChange::notifyNew( $now, $this->mTitle, $isminor, $user, $summary, $bot,
1172 '', strlen( $text ), $revisionId, $patrolled );
1173
1174 # Log auto-patrolled edits
1175 if ( $patrolled ) {
1176 PatrolLog::record( $rc, true );
1177 }
1178 }
1179 $user->incEditCount();
1180 $dbw->commit();
1181
1182 # Update links, etc.
1183 $this->doEditUpdates( $text, $user, $summary, $isminor, $revisionId, true, true );
1184
1185 # Clear caches
1186 self::onArticleCreate( $this->mTitle );
1187
1188 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$user, $text, $summary,
1189 $flags & EDIT_MINOR, null, null, &$flags, $revision ) );
1190 }
1191
1192 # Do updates right now unless deferral was requested
1193 if ( !( $flags & EDIT_DEFER_UPDATES ) ) {
1194 wfDoUpdates();
1195 }
1196
1197 // Return the new revision (or null) to the caller
1198 $status->value['revision'] = $revision;
1199
1200 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $text, $summary,
1201 $flags & EDIT_MINOR, null, null, &$flags, $revision, &$status, $baseRevId ) );
1202
1203 # Promote user to any groups they meet the criteria for
1204 $user->addAutopromoteOnceGroups( 'onEdit' );
1205
1206 wfProfileOut( __METHOD__ );
1207 return $status;
1208 }
1209
1210 /**
1211 * Update the article's restriction field, and leave a log entry.
1212 *
1213 * @param $limit Array: set of restriction keys
1214 * @param $reason String
1215 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
1216 * @param $expiry Array: per restriction type expiration
1217 * @param $user User The user updating the restrictions
1218 * @return bool true on success
1219 */
1220 public function updateRestrictions(
1221 $limit = array(), $reason = '', &$cascade = 0, $expiry = array(), User $user = null
1222 ) {
1223 global $wgUser, $wgContLang;
1224 $user = is_null( $user ) ? $wgUser : $user;
1225
1226 $restrictionTypes = $this->mTitle->getRestrictionTypes();
1227
1228 $id = $this->mTitle->getArticleID();
1229
1230 if ( $id <= 0 ) {
1231 wfDebug( "updateRestrictions failed: article id $id <= 0\n" );
1232 return false;
1233 }
1234
1235 if ( wfReadOnly() ) {
1236 wfDebug( "updateRestrictions failed: read-only\n" );
1237 return false;
1238 }
1239
1240 if ( !$this->mTitle->userCan( 'protect' ) ) {
1241 wfDebug( "updateRestrictions failed: insufficient permissions\n" );
1242 return false;
1243 }
1244
1245 if ( !$cascade ) {
1246 $cascade = false;
1247 }
1248
1249 // Take this opportunity to purge out expired restrictions
1250 Title::purgeExpiredRestrictions();
1251
1252 # @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
1253 # we expect a single selection, but the schema allows otherwise.
1254 $current = array();
1255 $updated = self::flattenRestrictions( $limit );
1256 $changed = false;
1257
1258 foreach ( $restrictionTypes as $action ) {
1259 if ( isset( $expiry[$action] ) ) {
1260 # Get current restrictions on $action
1261 $aLimits = $this->mTitle->getRestrictions( $action );
1262 $current[$action] = implode( '', $aLimits );
1263 # Are any actual restrictions being dealt with here?
1264 $aRChanged = count( $aLimits ) || !empty( $limit[$action] );
1265
1266 # If something changed, we need to log it. Checking $aRChanged
1267 # assures that "unprotecting" a page that is not protected does
1268 # not log just because the expiry was "changed".
1269 if ( $aRChanged && $this->mTitle->mRestrictionsExpiry[$action] != $expiry[$action] ) {
1270 $changed = true;
1271 }
1272 }
1273 }
1274
1275 $current = self::flattenRestrictions( $current );
1276
1277 $changed = ( $changed || $current != $updated );
1278 $changed = $changed || ( $updated && $this->mTitle->areRestrictionsCascading() != $cascade );
1279 $protect = ( $updated != '' );
1280
1281 # If nothing's changed, do nothing
1282 if ( $changed ) {
1283 if ( wfRunHooks( 'ArticleProtect', array( &$this, &$user, $limit, $reason ) ) ) {
1284 $dbw = wfGetDB( DB_MASTER );
1285
1286 # Prepare a null revision to be added to the history
1287 $modified = $current != '' && $protect;
1288
1289 if ( $protect ) {
1290 $comment_type = $modified ? 'modifiedarticleprotection' : 'protectedarticle';
1291 } else {
1292 $comment_type = 'unprotectedarticle';
1293 }
1294
1295 $comment = $wgContLang->ucfirst( wfMsgForContent( $comment_type, $this->mTitle->getPrefixedText() ) );
1296
1297 # Only restrictions with the 'protect' right can cascade...
1298 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
1299 $editrestriction = isset( $limit['edit'] ) ? array( $limit['edit'] ) : $this->mTitle->getRestrictions( 'edit' );
1300
1301 # The schema allows multiple restrictions
1302 if ( !in_array( 'protect', $editrestriction ) && !in_array( 'sysop', $editrestriction ) ) {
1303 $cascade = false;
1304 }
1305
1306 $cascade_description = '';
1307
1308 if ( $cascade ) {
1309 $cascade_description = ' [' . wfMsgForContent( 'protect-summary-cascade' ) . ']';
1310 }
1311
1312 if ( $reason ) {
1313 $comment .= ": $reason";
1314 }
1315
1316 $editComment = $comment;
1317 $encodedExpiry = array();
1318 $protect_description = '';
1319 foreach ( $limit as $action => $restrictions ) {
1320 if ( !isset( $expiry[$action] ) )
1321 $expiry[$action] = $dbw->getInfinity();
1322
1323 $encodedExpiry[$action] = $dbw->encodeExpiry( $expiry[$action] );
1324 if ( $restrictions != '' ) {
1325 $protect_description .= "[$action=$restrictions] (";
1326 if ( $encodedExpiry[$action] != 'infinity' ) {
1327 $protect_description .= wfMsgForContent( 'protect-expiring',
1328 $wgContLang->timeanddate( $expiry[$action], false, false ) ,
1329 $wgContLang->date( $expiry[$action], false, false ) ,
1330 $wgContLang->time( $expiry[$action], false, false ) );
1331 } else {
1332 $protect_description .= wfMsgForContent( 'protect-expiry-indefinite' );
1333 }
1334
1335 $protect_description .= ') ';
1336 }
1337 }
1338 $protect_description = trim( $protect_description );
1339
1340 if ( $protect_description && $protect ) {
1341 $editComment .= " ($protect_description)";
1342 }
1343
1344 if ( $cascade ) {
1345 $editComment .= "$cascade_description";
1346 }
1347
1348 # Update restrictions table
1349 foreach ( $limit as $action => $restrictions ) {
1350 if ( $restrictions != '' ) {
1351 $dbw->replace( 'page_restrictions', array( array( 'pr_page', 'pr_type' ) ),
1352 array( 'pr_page' => $id,
1353 'pr_type' => $action,
1354 'pr_level' => $restrictions,
1355 'pr_cascade' => ( $cascade && $action == 'edit' ) ? 1 : 0,
1356 'pr_expiry' => $encodedExpiry[$action]
1357 ),
1358 __METHOD__
1359 );
1360 } else {
1361 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
1362 'pr_type' => $action ), __METHOD__ );
1363 }
1364 }
1365
1366 # Insert a null revision
1367 $nullRevision = Revision::newNullRevision( $dbw, $id, $editComment, true );
1368 $nullRevId = $nullRevision->insertOn( $dbw );
1369
1370 $latest = $this->getLatest();
1371 # Update page record
1372 $dbw->update( 'page',
1373 array( /* SET */
1374 'page_touched' => $dbw->timestamp(),
1375 'page_restrictions' => '',
1376 'page_latest' => $nullRevId
1377 ), array( /* WHERE */
1378 'page_id' => $id
1379 ), __METHOD__
1380 );
1381
1382 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $nullRevision, $latest, $user ) );
1383 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$user, $limit, $reason ) );
1384
1385 # Update the protection log
1386 $log = new LogPage( 'protect' );
1387 if ( $protect ) {
1388 $params = array( $protect_description, $cascade ? 'cascade' : '' );
1389 $log->addEntry( $modified ? 'modify' : 'protect', $this->mTitle, trim( $reason ), $params );
1390 } else {
1391 $log->addEntry( 'unprotect', $this->mTitle, $reason );
1392 }
1393 } # End hook
1394 } # End "changed" check
1395
1396 return true;
1397 }
1398
1399 /**
1400 * Take an array of page restrictions and flatten it to a string
1401 * suitable for insertion into the page_restrictions field.
1402 * @param $limit Array
1403 * @return String
1404 */
1405 protected static function flattenRestrictions( $limit ) {
1406 if ( !is_array( $limit ) ) {
1407 throw new MWException( 'WikiPage::flattenRestrictions given non-array restriction set' );
1408 }
1409
1410 $bits = array();
1411 ksort( $limit );
1412
1413 foreach ( $limit as $action => $restrictions ) {
1414 if ( $restrictions != '' ) {
1415 $bits[] = "$action=$restrictions";
1416 }
1417 }
1418
1419 return implode( ':', $bits );
1420 }
1421
1422 /**
1423 * @return bool whether or not the page surpasses $wgDeleteRevisionsLimit revisions
1424 */
1425 public function isBigDeletion() {
1426 global $wgDeleteRevisionsLimit;
1427
1428 if ( $wgDeleteRevisionsLimit ) {
1429 $revCount = $this->estimateRevisionCount();
1430
1431 return $revCount > $wgDeleteRevisionsLimit;
1432 }
1433
1434 return false;
1435 }
1436
1437 /**
1438 * @return int approximate revision count
1439 */
1440 public function estimateRevisionCount() {
1441 $dbr = wfGetDB( DB_SLAVE );
1442
1443 // For an exact count...
1444 // return $dbr->selectField( 'revision', 'COUNT(*)',
1445 // array( 'rev_page' => $this->getId() ), __METHOD__ );
1446 return $dbr->estimateRowCount( 'revision', '*',
1447 array( 'rev_page' => $this->getId() ), __METHOD__ );
1448 }
1449
1450 /**
1451 * Get the last N authors
1452 * @param $num Integer: number of revisions to get
1453 * @param $revLatest String: the latest rev_id, selected from the master (optional)
1454 * @return array Array of authors, duplicates not removed
1455 */
1456 public function getLastNAuthors( $num, $revLatest = 0 ) {
1457 wfProfileIn( __METHOD__ );
1458 // First try the slave
1459 // If that doesn't have the latest revision, try the master
1460 $continue = 2;
1461 $db = wfGetDB( DB_SLAVE );
1462
1463 do {
1464 $res = $db->select( array( 'page', 'revision' ),
1465 array( 'rev_id', 'rev_user_text' ),
1466 array(
1467 'page_namespace' => $this->mTitle->getNamespace(),
1468 'page_title' => $this->mTitle->getDBkey(),
1469 'rev_page = page_id'
1470 ), __METHOD__,
1471 array(
1472 'ORDER BY' => 'rev_timestamp DESC',
1473 'LIMIT' => $num
1474 )
1475 );
1476
1477 if ( !$res ) {
1478 wfProfileOut( __METHOD__ );
1479 return array();
1480 }
1481
1482 $row = $db->fetchObject( $res );
1483
1484 if ( $continue == 2 && $revLatest && $row->rev_id != $revLatest ) {
1485 $db = wfGetDB( DB_MASTER );
1486 $continue--;
1487 } else {
1488 $continue = 0;
1489 }
1490 } while ( $continue );
1491
1492 $authors = array( $row->rev_user_text );
1493
1494 foreach ( $res as $row ) {
1495 $authors[] = $row->rev_user_text;
1496 }
1497
1498 wfProfileOut( __METHOD__ );
1499 return $authors;
1500 }
1501
1502 /**
1503 * Back-end article deletion
1504 * Deletes the article with database consistency, writes logs, purges caches
1505 *
1506 * @param $reason string delete reason for deletion log
1507 * @param suppress bitfield
1508 * Revision::DELETED_TEXT
1509 * Revision::DELETED_COMMENT
1510 * Revision::DELETED_USER
1511 * Revision::DELETED_RESTRICTED
1512 * @param $id int article ID
1513 * @param $commit boolean defaults to true, triggers transaction end
1514 * @param &$errors Array of errors to append to
1515 * @param $user User The relevant user
1516 * @return boolean true if successful
1517 */
1518 public function doDeleteArticle(
1519 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User $user = null
1520 ) {
1521 global $wgDeferredUpdateList, $wgUseTrackbacks, $wgUser;
1522 $user = is_null( $user ) ? $wgUser : $user;
1523
1524 wfDebug( __METHOD__ . "\n" );
1525
1526 if ( ! wfRunHooks( 'ArticleDelete', array( &$this, &$user, &$reason, &$error ) ) ) {
1527 return false;
1528 }
1529 $dbw = wfGetDB( DB_MASTER );
1530 $t = $this->mTitle->getDBkey();
1531 $id = $id ? $id : $this->mTitle->getArticleID( Title::GAID_FOR_UPDATE );
1532
1533 if ( $t === '' || $id == 0 ) {
1534 return false;
1535 }
1536
1537 $u = new SiteStatsUpdate( 0, 1, - (int)$this->isCountable(), -1 );
1538 array_push( $wgDeferredUpdateList, $u );
1539
1540 // Bitfields to further suppress the content
1541 if ( $suppress ) {
1542 $bitfield = 0;
1543 // This should be 15...
1544 $bitfield |= Revision::DELETED_TEXT;
1545 $bitfield |= Revision::DELETED_COMMENT;
1546 $bitfield |= Revision::DELETED_USER;
1547 $bitfield |= Revision::DELETED_RESTRICTED;
1548 } else {
1549 $bitfield = 'rev_deleted';
1550 }
1551
1552 $dbw->begin();
1553 // For now, shunt the revision data into the archive table.
1554 // Text is *not* removed from the text table; bulk storage
1555 // is left intact to avoid breaking block-compression or
1556 // immutable storage schemes.
1557 //
1558 // For backwards compatibility, note that some older archive
1559 // table entries will have ar_text and ar_flags fields still.
1560 //
1561 // In the future, we may keep revisions and mark them with
1562 // the rev_deleted field, which is reserved for this purpose.
1563 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
1564 array(
1565 'ar_namespace' => 'page_namespace',
1566 'ar_title' => 'page_title',
1567 'ar_comment' => 'rev_comment',
1568 'ar_user' => 'rev_user',
1569 'ar_user_text' => 'rev_user_text',
1570 'ar_timestamp' => 'rev_timestamp',
1571 'ar_minor_edit' => 'rev_minor_edit',
1572 'ar_rev_id' => 'rev_id',
1573 'ar_text_id' => 'rev_text_id',
1574 'ar_text' => '\'\'', // Be explicit to appease
1575 'ar_flags' => '\'\'', // MySQL's "strict mode"...
1576 'ar_len' => 'rev_len',
1577 'ar_page_id' => 'page_id',
1578 'ar_deleted' => $bitfield
1579 ), array(
1580 'page_id' => $id,
1581 'page_id = rev_page'
1582 ), __METHOD__
1583 );
1584
1585 # Delete restrictions for it
1586 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__ );
1587
1588 # Now that it's safely backed up, delete it
1589 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__ );
1590 $ok = ( $dbw->affectedRows() > 0 ); // getArticleId() uses slave, could be laggy
1591
1592 if ( !$ok ) {
1593 $dbw->rollback();
1594 return false;
1595 }
1596
1597 # Fix category table counts
1598 $cats = array();
1599 $res = $dbw->select( 'categorylinks', 'cl_to', array( 'cl_from' => $id ), __METHOD__ );
1600
1601 foreach ( $res as $row ) {
1602 $cats [] = $row->cl_to;
1603 }
1604
1605 $this->updateCategoryCounts( array(), $cats );
1606
1607 # If using cascading deletes, we can skip some explicit deletes
1608 if ( !$dbw->cascadingDeletes() ) {
1609 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__ );
1610
1611 if ( $wgUseTrackbacks )
1612 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__ );
1613
1614 # Delete outgoing links
1615 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
1616 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
1617 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
1618 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
1619 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
1620 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
1621 $dbw->delete( 'iwlinks', array( 'iwl_from' => $id ) );
1622 $dbw->delete( 'redirect', array( 'rd_from' => $id ) );
1623 }
1624
1625 # If using cleanup triggers, we can skip some manual deletes
1626 if ( !$dbw->cleanupTriggers() ) {
1627 # Clean up recentchanges entries...
1628 $dbw->delete( 'recentchanges',
1629 array( 'rc_type != ' . RC_LOG,
1630 'rc_namespace' => $this->mTitle->getNamespace(),
1631 'rc_title' => $this->mTitle->getDBkey() ),
1632 __METHOD__ );
1633 $dbw->delete( 'recentchanges',
1634 array( 'rc_type != ' . RC_LOG, 'rc_cur_id' => $id ),
1635 __METHOD__ );
1636 }
1637
1638 # Clear caches
1639 self::onArticleDelete( $this->mTitle );
1640
1641 # Clear the cached article id so the interface doesn't act like we exist
1642 $this->mTitle->resetArticleID( 0 );
1643
1644 # Log the deletion, if the page was suppressed, log it at Oversight instead
1645 $logtype = $suppress ? 'suppress' : 'delete';
1646 $log = new LogPage( $logtype );
1647
1648 # Make sure logging got through
1649 $log->addEntry( 'delete', $this->mTitle, $reason, array() );
1650
1651 if ( $commit ) {
1652 $dbw->commit();
1653 }
1654
1655 wfRunHooks( 'ArticleDeleteComplete', array( &$this, &$user, $reason, $id ) );
1656 return true;
1657 }
1658
1659 /**
1660 * Roll back the most recent consecutive set of edits to a page
1661 * from the same user; fails if there are no eligible edits to
1662 * roll back to, e.g. user is the sole contributor. This function
1663 * performs permissions checks on $user, then calls commitRollback()
1664 * to do the dirty work
1665 *
1666 * @param $fromP String: Name of the user whose edits to rollback.
1667 * @param $summary String: Custom summary. Set to default summary if empty.
1668 * @param $token String: Rollback token.
1669 * @param $bot Boolean: If true, mark all reverted edits as bot.
1670 *
1671 * @param $resultDetails Array: contains result-specific array of additional values
1672 * 'alreadyrolled' : 'current' (rev)
1673 * success : 'summary' (str), 'current' (rev), 'target' (rev)
1674 *
1675 * @param $user User The user performing the rollback
1676 * @return array of errors, each error formatted as
1677 * array(messagekey, param1, param2, ...).
1678 * On success, the array is empty. This array can also be passed to
1679 * OutputPage::showPermissionsErrorPage().
1680 */
1681 public function doRollback(
1682 $fromP, $summary, $token, $bot, &$resultDetails, User $user = null
1683 ) {
1684 global $wgUser;
1685 $user = is_null( $user ) ? $wgUser : $user;
1686
1687 $resultDetails = null;
1688
1689 # Check permissions
1690 $editErrors = $this->mTitle->getUserPermissionsErrors( 'edit', $user );
1691 $rollbackErrors = $this->mTitle->getUserPermissionsErrors( 'rollback', $user );
1692 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
1693
1694 if ( !$user->matchEditToken( $token, array( $this->mTitle->getPrefixedText(), $fromP ) ) ) {
1695 $errors[] = array( 'sessionfailure' );
1696 }
1697
1698 if ( $user->pingLimiter( 'rollback' ) || $user->pingLimiter() ) {
1699 $errors[] = array( 'actionthrottledtext' );
1700 }
1701
1702 # If there were errors, bail out now
1703 if ( !empty( $errors ) ) {
1704 return $errors;
1705 }
1706
1707 return $this->commitRollback( $user, $fromP, $summary, $bot, $resultDetails );
1708 }
1709
1710 /**
1711 * Backend implementation of doRollback(), please refer there for parameter
1712 * and return value documentation
1713 *
1714 * NOTE: This function does NOT check ANY permissions, it just commits the
1715 * rollback to the DB Therefore, you should only call this function direct-
1716 * ly if you want to use custom permissions checks. If you don't, use
1717 * doRollback() instead.
1718 * @param $fromP String: Name of the user whose edits to rollback.
1719 * @param $summary String: Custom summary. Set to default summary if empty.
1720 * @param $bot Boolean: If true, mark all reverted edits as bot.
1721 *
1722 * @param $resultDetails Array: contains result-specific array of additional values
1723 * @param $guser User The user performing the rollback
1724 */
1725 public function commitRollback( $fromP, $summary, $bot, &$resultDetails, User $guser = null ) {
1726 global $wgUseRCPatrol, $wgUser, $wgContLang;
1727 $guser = is_null( $guser ) ? $wgUser : $guser;
1728
1729 $dbw = wfGetDB( DB_MASTER );
1730
1731 if ( wfReadOnly() ) {
1732 return array( array( 'readonlytext' ) );
1733 }
1734
1735 # Get the last editor
1736 $current = Revision::newFromTitle( $this->mTitle );
1737 if ( is_null( $current ) ) {
1738 # Something wrong... no page?
1739 return array( array( 'notanarticle' ) );
1740 }
1741
1742 $from = str_replace( '_', ' ', $fromP );
1743 # User name given should match up with the top revision.
1744 # If the user was deleted then $from should be empty.
1745 if ( $from != $current->getUserText() ) {
1746 $resultDetails = array( 'current' => $current );
1747 return array( array( 'alreadyrolled',
1748 htmlspecialchars( $this->mTitle->getPrefixedText() ),
1749 htmlspecialchars( $fromP ),
1750 htmlspecialchars( $current->getUserText() )
1751 ) );
1752 }
1753
1754 # Get the last edit not by this guy...
1755 # Note: these may not be public values
1756 $user = intval( $current->getRawUser() );
1757 $user_text = $dbw->addQuotes( $current->getRawUserText() );
1758 $s = $dbw->selectRow( 'revision',
1759 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
1760 array( 'rev_page' => $current->getPage(),
1761 "rev_user != {$user} OR rev_user_text != {$user_text}"
1762 ), __METHOD__,
1763 array( 'USE INDEX' => 'page_timestamp',
1764 'ORDER BY' => 'rev_timestamp DESC' )
1765 );
1766 if ( $s === false ) {
1767 # No one else ever edited this page
1768 return array( array( 'cantrollback' ) );
1769 } elseif ( $s->rev_deleted & Revision::DELETED_TEXT || $s->rev_deleted & Revision::DELETED_USER ) {
1770 # Only admins can see this text
1771 return array( array( 'notvisiblerev' ) );
1772 }
1773
1774 $set = array();
1775 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
1776 # Mark all reverted edits as bot
1777 $set['rc_bot'] = 1;
1778 }
1779
1780 if ( $wgUseRCPatrol ) {
1781 # Mark all reverted edits as patrolled
1782 $set['rc_patrolled'] = 1;
1783 }
1784
1785 if ( count( $set ) ) {
1786 $dbw->update( 'recentchanges', $set,
1787 array( /* WHERE */
1788 'rc_cur_id' => $current->getPage(),
1789 'rc_user_text' => $current->getUserText(),
1790 "rc_timestamp > '{$s->rev_timestamp}'",
1791 ), __METHOD__
1792 );
1793 }
1794
1795 # Generate the edit summary if necessary
1796 $target = Revision::newFromId( $s->rev_id );
1797 if ( empty( $summary ) ) {
1798 if ( $from == '' ) { // no public user name
1799 $summary = wfMsgForContent( 'revertpage-nouser' );
1800 } else {
1801 $summary = wfMsgForContent( 'revertpage' );
1802 }
1803 }
1804
1805 # Allow the custom summary to use the same args as the default message
1806 $args = array(
1807 $target->getUserText(), $from, $s->rev_id,
1808 $wgContLang->timeanddate( wfTimestamp( TS_MW, $s->rev_timestamp ) ),
1809 $current->getId(), $wgContLang->timeanddate( $current->getTimestamp() )
1810 );
1811 $summary = wfMsgReplaceArgs( $summary, $args );
1812
1813 # Save
1814 $flags = EDIT_UPDATE;
1815
1816 if ( $guser->isAllowed( 'minoredit' ) ) {
1817 $flags |= EDIT_MINOR;
1818 }
1819
1820 if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
1821 $flags |= EDIT_FORCE_BOT;
1822 }
1823
1824 # Actually store the edit
1825 $status = $this->doEdit( $target->getText(), $summary, $flags, $target->getId() );
1826 if ( !empty( $status->value['revision'] ) ) {
1827 $revId = $status->value['revision']->getId();
1828 } else {
1829 $revId = false;
1830 }
1831
1832 wfRunHooks( 'ArticleRollbackComplete', array( $this, $guser, $target, $current ) );
1833
1834 $resultDetails = array(
1835 'summary' => $summary,
1836 'current' => $current,
1837 'target' => $target,
1838 'newid' => $revId
1839 );
1840
1841 return array();
1842 }
1843
1844 /**
1845 * Do standard deferred updates after page view
1846 * @param $user User The relevant user
1847 */
1848 public function doViewUpdates( User $user ) {
1849 global $wgDeferredUpdateList, $wgDisableCounters;
1850 if ( wfReadOnly() ) {
1851 return;
1852 }
1853
1854 # Don't update page view counters on views from bot users (bug 14044)
1855 if ( !$wgDisableCounters && !$user->isAllowed( 'bot' ) && $this->getID() ) {
1856 $wgDeferredUpdateList[] = new ViewCountUpdate( $this->getID() );
1857 $wgDeferredUpdateList[] = new SiteStatsUpdate( 1, 0, 0 );
1858 }
1859
1860 # Update newtalk / watchlist notification status
1861 $user->clearNotification( $this->mTitle );
1862 }
1863
1864 /**
1865 * Prepare text which is about to be saved.
1866 * Returns a stdclass with source, pst and output members
1867 */
1868 public function prepareTextForEdit( $text, $revid = null, User $user = null ) {
1869 global $wgParser, $wgUser;
1870 $user = is_null( $user ) ? $wgUser : $user;
1871 // @TODO fixme: check $user->getId() here???
1872 if ( $this->mPreparedEdit
1873 && $this->mPreparedEdit->newText == $text
1874 && $this->mPreparedEdit->revid == $revid
1875 ) {
1876 // Already prepared
1877 return $this->mPreparedEdit;
1878 }
1879
1880 $popts = ParserOptions::newFromUser( $user );
1881 wfRunHooks( 'ArticlePrepareTextForEdit', array( $this, $popts ) );
1882
1883 $edit = (object)array();
1884 $edit->revid = $revid;
1885 $edit->newText = $text;
1886 $edit->pst = $this->preSaveTransform( $text, $user, $popts );
1887 $edit->popts = $this->getParserOptions( true );
1888 $edit->output = $wgParser->parse( $edit->pst, $this->mTitle, $edit->popts, true, true, $revid );
1889 $edit->oldText = $this->getRawText();
1890
1891 $this->mPreparedEdit = $edit;
1892
1893 return $edit;
1894 }
1895
1896 /**
1897 * Do standard deferred updates after page edit.
1898 * Update links tables, site stats, search index and message cache.
1899 * Purges pages that include this page if the text was changed here.
1900 * Every 100th edit, prune the recent changes table.
1901 *
1902 * @private
1903 * @param $text String: New text of the article
1904 * @param $user User object: User doing the edit
1905 * @param $summary String: Edit summary
1906 * @param $minoredit Boolean: Minor edit
1907 * @param $newid Integer: rev_id value of the new revision
1908 * @param $changed Boolean: Whether or not the content actually changed
1909 * @param $created Boolean: Whether the edit created the page
1910 */
1911 public function doEditUpdates(
1912 $text, $user, $summary, $minoredit, $newid, $changed = true, $created = false
1913 ) {
1914 global $wgDeferredUpdateList, $wgEnableParserCache;
1915
1916 wfProfileIn( __METHOD__ );
1917
1918 # Parse the text
1919 # Be careful not to double-PST: $text is usually already PST-ed once
1920 if ( !$this->mPreparedEdit || $this->mPreparedEdit->output->getFlag( 'vary-revision' ) ) {
1921 wfDebug( __METHOD__ . ": No prepared edit or vary-revision is set...\n" );
1922 $editInfo = $this->prepareTextForEdit( $text, $newid, $user );
1923 } else {
1924 wfDebug( __METHOD__ . ": No vary-revision, using prepared edit...\n" );
1925 $editInfo = $this->mPreparedEdit;
1926 }
1927
1928 # Save it to the parser cache
1929 if ( $wgEnableParserCache ) {
1930 $parserCache = ParserCache::singleton();
1931 $parserCache->save( $editInfo->output, $this, $editInfo->popts );
1932 }
1933
1934 # Update the links tables
1935 $u = new LinksUpdate( $this->mTitle, $editInfo->output );
1936 $u->doUpdate();
1937
1938 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $changed ) );
1939
1940 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
1941 if ( 0 == mt_rand( 0, 99 ) ) {
1942 // Flush old entries from the `recentchanges` table; we do this on
1943 // random requests so as to avoid an increase in writes for no good reason
1944 global $wgRCMaxAge;
1945
1946 $dbw = wfGetDB( DB_MASTER );
1947 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
1948 $dbw->delete(
1949 'recentchanges',
1950 array( "rc_timestamp < '$cutoff'" ),
1951 __METHOD__
1952 );
1953 }
1954 }
1955
1956 $id = $this->getID();
1957 $title = $this->mTitle->getPrefixedDBkey();
1958 $shortTitle = $this->mTitle->getDBkey();
1959
1960 if ( 0 == $id ) {
1961 wfProfileOut( __METHOD__ );
1962 return;
1963 }
1964
1965 if ( !$changed ) {
1966 $good = 0;
1967 $total = 0;
1968 } elseif ( $created ) {
1969 $good = (int)$this->isCountable( $editInfo );
1970 $total = 1;
1971 } else {
1972 $good = (int)$this->isCountable( $editInfo ) - (int)$this->isCountable();
1973 $total = 0;
1974 }
1975
1976 $wgDeferredUpdateList[] = new SiteStatsUpdate( 0, 1, $good, $total );
1977 $wgDeferredUpdateList[] = new SearchUpdate( $id, $title, $text );
1978
1979 # If this is another user's talk page, update newtalk
1980 # Don't do this if $changed = false otherwise some idiot can null-edit a
1981 # load of user talk pages and piss people off, nor if it's a minor edit
1982 # by a properly-flagged bot.
1983 if ( $this->mTitle->getNamespace() == NS_USER_TALK && $shortTitle != $user->getTitleKey() && $changed
1984 && !( $minoredit && $user->isAllowed( 'nominornewtalk' ) )
1985 ) {
1986 if ( wfRunHooks( 'ArticleEditUpdateNewTalk', array( &$this ) ) ) {
1987 $other = User::newFromName( $shortTitle, false );
1988 if ( !$other ) {
1989 wfDebug( __METHOD__ . ": invalid username\n" );
1990 } elseif ( User::isIP( $shortTitle ) ) {
1991 // An anonymous user
1992 $other->setNewtalk( true );
1993 } elseif ( $other->isLoggedIn() ) {
1994 $other->setNewtalk( true );
1995 } else {
1996 wfDebug( __METHOD__ . ": don't need to notify a nonexistent user\n" );
1997 }
1998 }
1999 }
2000
2001 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
2002 MessageCache::singleton()->replace( $shortTitle, $text );
2003 }
2004
2005 wfProfileOut( __METHOD__ );
2006 }
2007
2008 /**
2009 * Perform article updates on a special page creation.
2010 *
2011 * @param $rev Revision object
2012 *
2013 * @todo This is a shitty interface function. Kill it and replace the
2014 * other shitty functions like doEditUpdates and such so it's not needed
2015 * anymore.
2016 * @deprecated since 1.19, use doEditUpdates()
2017 */
2018 public function createUpdates( $rev ) {
2019 global $wgUser;
2020 $this->doEditUpdates( $rev->getText(), $wgUser, $rev->getComment(),
2021 $rev->isMinor(), $rev->getId(), true, true );
2022 }
2023
2024 /**
2025 * This function is called right before saving the wikitext,
2026 * so we can do things like signatures and links-in-context.
2027 *
2028 * @param $text String article contents
2029 * @param $user User object: user doing the edit
2030 * @param $popts ParserOptions object: parser options, default options for
2031 * the user loaded if null given
2032 * @return string article contents with altered wikitext markup (signatures
2033 * converted, {{subst:}}, templates, etc.)
2034 */
2035 public function preSaveTransform( $text, User $user = null, ParserOptions $popts = null ) {
2036 global $wgParser, $wgUser;
2037 $user = is_null( $user ) ? $wgUser : $user;
2038
2039 if ( $popts === null ) {
2040 $popts = ParserOptions::newFromUser( $user );
2041 }
2042
2043 return $wgParser->preSaveTransform( $text, $this->mTitle, $user, $popts );
2044 }
2045
2046 /**
2047 * Loads page_touched and returns a value indicating if it should be used
2048 * @return boolean true if not a redirect
2049 */
2050 public function checkTouched() {
2051 if ( !$this->mDataLoaded ) {
2052 $this->loadPageData();
2053 }
2054
2055 return !$this->mIsRedirect;
2056 }
2057
2058 /**
2059 * Get the page_touched field
2060 * @return string containing GMT timestamp
2061 */
2062 public function getTouched() {
2063 if ( !$this->mDataLoaded ) {
2064 $this->loadPageData();
2065 }
2066
2067 return $this->mTouched;
2068 }
2069
2070 /**
2071 * Get the page_latest field
2072 * @return integer rev_id of current revision
2073 */
2074 public function getLatest() {
2075 if ( !$this->mDataLoaded ) {
2076 $this->loadPageData();
2077 }
2078
2079 return (int)$this->mLatest;
2080 }
2081
2082 /**
2083 * Edit an article without doing all that other stuff
2084 * The article must already exist; link tables etc
2085 * are not updated, caches are not flushed.
2086 *
2087 * @param $text String: text submitted
2088 * @param $user User The relevant user
2089 * @param $comment String: comment submitted
2090 * @param $minor Boolean: whereas it's a minor modification
2091 */
2092 public function doQuickEdit( $text, User $user, $comment = '', $minor = 0 ) {
2093 wfProfileIn( __METHOD__ );
2094
2095 $dbw = wfGetDB( DB_MASTER );
2096 $revision = new Revision( array(
2097 'page' => $this->getId(),
2098 'text' => $text,
2099 'comment' => $comment,
2100 'minor_edit' => $minor ? 1 : 0,
2101 ) );
2102 $revision->insertOn( $dbw );
2103 $this->updateRevisionOn( $dbw, $revision );
2104
2105 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
2106
2107 wfProfileOut( __METHOD__ );
2108 }
2109
2110 /**
2111 * The onArticle*() functions are supposed to be a kind of hooks
2112 * which should be called whenever any of the specified actions
2113 * are done.
2114 *
2115 * This is a good place to put code to clear caches, for instance.
2116 *
2117 * This is called on page move and undelete, as well as edit
2118 *
2119 * @param $title Title object
2120 */
2121 public static function onArticleCreate( $title ) {
2122 # Update existence markers on article/talk tabs...
2123 if ( $title->isTalkPage() ) {
2124 $other = $title->getSubjectPage();
2125 } else {
2126 $other = $title->getTalkPage();
2127 }
2128
2129 $other->invalidateCache();
2130 $other->purgeSquid();
2131
2132 $title->touchLinks();
2133 $title->purgeSquid();
2134 $title->deleteTitleProtection();
2135 }
2136
2137 /**
2138 * Clears caches when article is deleted
2139 *
2140 * @param $title Title
2141 */
2142 public static function onArticleDelete( $title ) {
2143 # Update existence markers on article/talk tabs...
2144 if ( $title->isTalkPage() ) {
2145 $other = $title->getSubjectPage();
2146 } else {
2147 $other = $title->getTalkPage();
2148 }
2149
2150 $other->invalidateCache();
2151 $other->purgeSquid();
2152
2153 $title->touchLinks();
2154 $title->purgeSquid();
2155
2156 # File cache
2157 HTMLFileCache::clearFileCache( $title );
2158
2159 # Messages
2160 if ( $title->getNamespace() == NS_MEDIAWIKI ) {
2161 MessageCache::singleton()->replace( $title->getDBkey(), false );
2162 }
2163
2164 # Images
2165 if ( $title->getNamespace() == NS_FILE ) {
2166 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
2167 $update->doUpdate();
2168 }
2169
2170 # User talk pages
2171 if ( $title->getNamespace() == NS_USER_TALK ) {
2172 $user = User::newFromName( $title->getText(), false );
2173 $user->setNewtalk( false );
2174 }
2175
2176 # Image redirects
2177 RepoGroup::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
2178 }
2179
2180 /**
2181 * Purge caches on page update etc
2182 *
2183 * @param $title Title object
2184 * @todo: verify that $title is always a Title object (and never false or null), add Title hint to parameter $title
2185 */
2186 public static function onArticleEdit( $title ) {
2187 global $wgDeferredUpdateList;
2188
2189 // Invalidate caches of articles which include this page
2190 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'templatelinks' );
2191
2192 // Invalidate the caches of all pages which redirect here
2193 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'redirect' );
2194
2195 # Purge squid for this page only
2196 $title->purgeSquid();
2197
2198 # Clear file cache for this page only
2199 HTMLFileCache::clearFileCache( $title );
2200 }
2201
2202 /**#@-*/
2203
2204 /**
2205 * Return a list of templates used by this article.
2206 * Uses the templatelinks table
2207 *
2208 * @return Array of Title objects
2209 */
2210 public function getUsedTemplates() {
2211 $result = array();
2212 $id = $this->mTitle->getArticleID();
2213
2214 if ( $id == 0 ) {
2215 return array();
2216 }
2217
2218 $dbr = wfGetDB( DB_SLAVE );
2219 $res = $dbr->select( array( 'templatelinks' ),
2220 array( 'tl_namespace', 'tl_title' ),
2221 array( 'tl_from' => $id ),
2222 __METHOD__ );
2223
2224 if ( $res !== false ) {
2225 foreach ( $res as $row ) {
2226 $result[] = Title::makeTitle( $row->tl_namespace, $row->tl_title );
2227 }
2228 }
2229
2230 return $result;
2231 }
2232
2233 /**
2234 * Returns a list of hidden categories this page is a member of.
2235 * Uses the page_props and categorylinks tables.
2236 *
2237 * @return Array of Title objects
2238 */
2239 public function getHiddenCategories() {
2240 $result = array();
2241 $id = $this->mTitle->getArticleID();
2242
2243 if ( $id == 0 ) {
2244 return array();
2245 }
2246
2247 $dbr = wfGetDB( DB_SLAVE );
2248 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
2249 array( 'cl_to' ),
2250 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
2251 'page_namespace' => NS_CATEGORY, 'page_title=cl_to' ),
2252 __METHOD__ );
2253
2254 if ( $res !== false ) {
2255 foreach ( $res as $row ) {
2256 $result[] = Title::makeTitle( NS_CATEGORY, $row->cl_to );
2257 }
2258 }
2259
2260 return $result;
2261 }
2262
2263 /**
2264 * Return an applicable autosummary if one exists for the given edit.
2265 * @param $oldtext String: the previous text of the page.
2266 * @param $newtext String: The submitted text of the page.
2267 * @param $flags Int bitmask: a bitmask of flags submitted for the edit.
2268 * @return string An appropriate autosummary, or an empty string.
2269 */
2270 public static function getAutosummary( $oldtext, $newtext, $flags ) {
2271 global $wgContLang;
2272
2273 # Decide what kind of autosummary is needed.
2274
2275 # Redirect autosummaries
2276 $ot = Title::newFromRedirect( $oldtext );
2277 $rt = Title::newFromRedirect( $newtext );
2278
2279 if ( is_object( $rt ) && ( !is_object( $ot ) || !$rt->equals( $ot ) || $ot->getFragment() != $rt->getFragment() ) ) {
2280 return wfMsgForContent( 'autoredircomment', $rt->getFullText() );
2281 }
2282
2283 # New page autosummaries
2284 if ( $flags & EDIT_NEW && strlen( $newtext ) ) {
2285 # If they're making a new article, give its text, truncated, in the summary.
2286
2287 $truncatedtext = $wgContLang->truncate(
2288 str_replace( "\n", ' ', $newtext ),
2289 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new' ) ) ) );
2290
2291 return wfMsgForContent( 'autosumm-new', $truncatedtext );
2292 }
2293
2294 # Blanking autosummaries
2295 if ( $oldtext != '' && $newtext == '' ) {
2296 return wfMsgForContent( 'autosumm-blank' );
2297 } elseif ( strlen( $oldtext ) > 10 * strlen( $newtext ) && strlen( $newtext ) < 500 ) {
2298 # Removing more than 90% of the article
2299
2300 $truncatedtext = $wgContLang->truncate(
2301 $newtext,
2302 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) ) );
2303
2304 return wfMsgForContent( 'autosumm-replace', $truncatedtext );
2305 }
2306
2307 # If we reach this point, there's no applicable autosummary for our case, so our
2308 # autosummary is empty.
2309 return '';
2310 }
2311
2312 /**
2313 * Get parser options suitable for rendering the primary article wikitext
2314 * @param $canonical boolean Determines that the generated options must not depend on user preferences (see bug 14404)
2315 * @return mixed ParserOptions object or boolean false
2316 */
2317 public function getParserOptions( $canonical = false ) {
2318 global $wgUser, $wgLanguageCode;
2319
2320 if ( !$this->mParserOptions || $canonical ) {
2321 $user = !$canonical ? $wgUser : new User;
2322 $parserOptions = new ParserOptions( $user );
2323 $parserOptions->setTidy( true );
2324 $parserOptions->enableLimitReport();
2325
2326 if ( $canonical ) {
2327 $parserOptions->setUserLang( $wgLanguageCode ); # Must be set explicitely
2328 return $parserOptions;
2329 }
2330 $this->mParserOptions = $parserOptions;
2331 }
2332 // Clone to allow modifications of the return value without affecting cache
2333 return clone $this->mParserOptions;
2334 }
2335
2336 /**
2337 * Get parser options suitable for rendering the primary article wikitext
2338 * @param User $user
2339 * @return ParserOptions
2340 */
2341 public function makeParserOptions( User $user ) {
2342 $options = ParserOptions::newFromUser( $user );
2343 $options->enableLimitReport(); // show inclusion/loop reports
2344 $options->setTidy( true ); // fix bad HTML
2345 return $options;
2346 }
2347
2348 /**
2349 * Update all the appropriate counts in the category table, given that
2350 * we've added the categories $added and deleted the categories $deleted.
2351 *
2352 * @param $added array The names of categories that were added
2353 * @param $deleted array The names of categories that were deleted
2354 */
2355 public function updateCategoryCounts( $added, $deleted ) {
2356 $ns = $this->mTitle->getNamespace();
2357 $dbw = wfGetDB( DB_MASTER );
2358
2359 # First make sure the rows exist. If one of the "deleted" ones didn't
2360 # exist, we might legitimately not create it, but it's simpler to just
2361 # create it and then give it a negative value, since the value is bogus
2362 # anyway.
2363 #
2364 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
2365 $insertCats = array_merge( $added, $deleted );
2366 if ( !$insertCats ) {
2367 # Okay, nothing to do
2368 return;
2369 }
2370
2371 $insertRows = array();
2372
2373 foreach ( $insertCats as $cat ) {
2374 $insertRows[] = array(
2375 'cat_id' => $dbw->nextSequenceValue( 'category_cat_id_seq' ),
2376 'cat_title' => $cat
2377 );
2378 }
2379 $dbw->insert( 'category', $insertRows, __METHOD__, 'IGNORE' );
2380
2381 $addFields = array( 'cat_pages = cat_pages + 1' );
2382 $removeFields = array( 'cat_pages = cat_pages - 1' );
2383
2384 if ( $ns == NS_CATEGORY ) {
2385 $addFields[] = 'cat_subcats = cat_subcats + 1';
2386 $removeFields[] = 'cat_subcats = cat_subcats - 1';
2387 } elseif ( $ns == NS_FILE ) {
2388 $addFields[] = 'cat_files = cat_files + 1';
2389 $removeFields[] = 'cat_files = cat_files - 1';
2390 }
2391
2392 if ( $added ) {
2393 $dbw->update(
2394 'category',
2395 $addFields,
2396 array( 'cat_title' => $added ),
2397 __METHOD__
2398 );
2399 }
2400
2401 if ( $deleted ) {
2402 $dbw->update(
2403 'category',
2404 $removeFields,
2405 array( 'cat_title' => $deleted ),
2406 __METHOD__
2407 );
2408 }
2409 }
2410
2411 /**
2412 * Lightweight method to get the parser output for a page, checking the parser cache
2413 * and so on. Doesn't consider most of the stuff that WikiPage::view is forced to
2414 * consider, so it's not appropriate to use there.
2415 *
2416 * @since 1.16 (r52326) for LiquidThreads
2417 *
2418 * @param $oldid mixed integer Revision ID or null
2419 * @param $user User The relevant user
2420 * @return ParserOutput or false if the given revsion ID is not found
2421 */
2422 public function getParserOutput( $oldid = null, User $user = null ) {
2423 global $wgEnableParserCache, $wgUser;
2424 $user = is_null( $user ) ? $wgUser : $user;
2425
2426 // Should the parser cache be used?
2427 $useParserCache = $wgEnableParserCache &&
2428 $user->getStubThreshold() == 0 &&
2429 $this->exists() &&
2430 $oldid === null;
2431
2432 wfDebug( __METHOD__ . ': using parser cache: ' . ( $useParserCache ? 'yes' : 'no' ) . "\n" );
2433
2434 if ( $user->getStubThreshold() ) {
2435 wfIncrStats( 'pcache_miss_stub' );
2436 }
2437
2438 if ( $useParserCache ) {
2439 $parserOutput = ParserCache::singleton()->get( $this, $this->getParserOptions() );
2440 if ( $parserOutput !== false ) {
2441 return $parserOutput;
2442 }
2443 }
2444
2445 // Cache miss; parse and output it.
2446 if ( $oldid === null ) {
2447 $text = $this->getRawText();
2448 } else {
2449 $rev = Revision::newFromTitle( $this->getTitle(), $oldid );
2450 if ( $rev === null ) {
2451 return false;
2452 }
2453 $text = $rev->getText();
2454 }
2455
2456 return $this->getOutputFromWikitext( $text, $useParserCache );
2457 }
2458
2459 /*
2460 * @deprecated since 1.19
2461 */
2462 public function quickEdit( $text, $comment = '', $minor = 0 ) {
2463 global $wgUser;
2464 return $this->doQuickEdit( $text, $wgUser, $comment, $minor );
2465 }
2466
2467 /*
2468 * @deprecated since 1.19
2469 */
2470 public function editUpdates(
2471 $text, $summary, $minoredit, $timestamp_of_pagechange, $newid,
2472 $changed = true, User $user = null, $created = false
2473 ) {
2474 global $wgUser;
2475 return $this->doEditUpdates( $text, $wgUser, $summary, $minoredit, $newid, $changed, $created );
2476 }
2477
2478 /*
2479 * @deprecated since 1.19
2480 */
2481 public function viewUpdates() {
2482 global $wgUser;
2483 return $this->doViewUpdates( $wgUser );
2484 }
2485
2486 /*
2487 * @deprecated since 1.19
2488 */
2489 public function useParserCache( $oldid ) {
2490 global $wgUser;
2491 return $this->isParserCacheUsed( $wgUser, $oldid );
2492 }
2493 }