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