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