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