* Put the LinkCache update in WikiPage::updateRevisionOn() so that we are sure that...
[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 }
759
760 /**
761 * Insert a new empty page record for this article.
762 * This *must* be followed up by creating a revision
763 * and running $this->updateRevisionOn( ... );
764 * or else the record will be left in a funky state.
765 * Best if all done inside a transaction.
766 *
767 * @param $dbw DatabaseBase
768 * @return int The newly created page_id key, or false if the title already existed
769 */
770 public function insertOn( $dbw ) {
771 wfProfileIn( __METHOD__ );
772
773 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
774 $dbw->insert( 'page', array(
775 'page_id' => $page_id,
776 'page_namespace' => $this->mTitle->getNamespace(),
777 'page_title' => $this->mTitle->getDBkey(),
778 'page_counter' => 0,
779 'page_restrictions' => '',
780 'page_is_redirect' => 0, # Will set this shortly...
781 'page_is_new' => 1,
782 'page_random' => wfRandom(),
783 'page_touched' => $dbw->timestamp(),
784 'page_latest' => 0, # Fill this in shortly...
785 'page_len' => 0, # Fill this in shortly...
786 ), __METHOD__, 'IGNORE' );
787
788 $affected = $dbw->affectedRows();
789
790 if ( $affected ) {
791 $newid = $dbw->insertId();
792 $this->mTitle->resetArticleID( $newid );
793 }
794 wfProfileOut( __METHOD__ );
795
796 return $affected ? $newid : false;
797 }
798
799 /**
800 * Update the page record to point to a newly saved revision.
801 *
802 * @param $dbw DatabaseBase: object
803 * @param $revision Revision: For ID number, and text used to set
804 * length and redirect status fields
805 * @param $lastRevision Integer: if given, will not overwrite the page field
806 * when different from the currently set value.
807 * Giving 0 indicates the new page flag should be set
808 * on.
809 * @param $lastRevIsRedirect Boolean: if given, will optimize adding and
810 * removing rows in redirect table.
811 * @return bool true on success, false on failure
812 * @private
813 */
814 public function updateRevisionOn( $dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
815 wfProfileIn( __METHOD__ );
816
817 $text = $revision->getText();
818 $len = strlen( $text );
819 $rt = Title::newFromRedirectRecurse( $text );
820
821 $conditions = array( 'page_id' => $this->getId() );
822
823 if ( !is_null( $lastRevision ) ) {
824 # An extra check against threads stepping on each other
825 $conditions['page_latest'] = $lastRevision;
826 }
827
828 $now = wfTimestampNow();
829 $dbw->update( 'page',
830 array( /* SET */
831 'page_latest' => $revision->getId(),
832 'page_touched' => $dbw->timestamp( $now ),
833 'page_is_new' => ( $lastRevision === 0 ) ? 1 : 0,
834 'page_is_redirect' => $rt !== null ? 1 : 0,
835 'page_len' => $len,
836 ),
837 $conditions,
838 __METHOD__ );
839
840 $result = $dbw->affectedRows() != 0;
841 if ( $result ) {
842 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
843 $this->setLastEdit( $revision );
844 $this->setCachedLastEditTime( $now );
845 $this->mLatest = $revision->getId();
846 $this->mIsRedirect = (bool)$rt;
847 # Update the LinkCache.
848 LinkCache::singleton()->addGoodLinkObj( $this->getId(), $this->mTitle, $len, $this->mIsRedirect, $this->mLatest );
849 }
850
851 wfProfileOut( __METHOD__ );
852 return $result;
853 }
854
855 /**
856 * Get the cached timestamp for the last time the page changed.
857 * This is only used to help handle slave lag by comparing to page_touched.
858 * @return string MW timestamp
859 */
860 protected function getCachedLastEditTime() {
861 global $wgMemc;
862 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle->getPrefixedDBkey() ) );
863 return $wgMemc->get( $key );
864 }
865
866 /**
867 * Set the cached timestamp for the last time the page changed.
868 * This is only used to help handle slave lag by comparing to page_touched.
869 * @param $timestamp string
870 * @return void
871 */
872 public function setCachedLastEditTime( $timestamp ) {
873 global $wgMemc;
874 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle->getPrefixedDBkey() ) );
875 $wgMemc->set( $key, wfTimestamp( TS_MW, $timestamp ), 60*15 );
876 }
877
878 /**
879 * Add row to the redirect table if this is a redirect, remove otherwise.
880 *
881 * @param $dbw DatabaseBase
882 * @param $redirectTitle Title object pointing to the redirect target,
883 * or NULL if this is not a redirect
884 * @param $lastRevIsRedirect If given, will optimize adding and
885 * removing rows in redirect table.
886 * @return bool true on success, false on failure
887 * @private
888 */
889 public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
890 // Always update redirects (target link might have changed)
891 // Update/Insert if we don't know if the last revision was a redirect or not
892 // Delete if changing from redirect to non-redirect
893 $isRedirect = !is_null( $redirectTitle );
894
895 if ( !$isRedirect && !is_null( $lastRevIsRedirect ) && $lastRevIsRedirect === $isRedirect ) {
896 return true;
897 }
898
899 wfProfileIn( __METHOD__ );
900 if ( $isRedirect ) {
901 $this->insertRedirectEntry( $redirectTitle );
902 } else {
903 // This is not a redirect, remove row from redirect table
904 $where = array( 'rd_from' => $this->getId() );
905 $dbw->delete( 'redirect', $where, __METHOD__ );
906 }
907
908 if ( $this->getTitle()->getNamespace() == NS_FILE ) {
909 RepoGroup::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
910 }
911 wfProfileOut( __METHOD__ );
912
913 return ( $dbw->affectedRows() != 0 );
914 }
915
916 /**
917 * If the given revision is newer than the currently set page_latest,
918 * update the page record. Otherwise, do nothing.
919 *
920 * @param $dbw Database object
921 * @param $revision Revision object
922 * @return mixed
923 */
924 public function updateIfNewerOn( $dbw, $revision ) {
925 wfProfileIn( __METHOD__ );
926
927 $row = $dbw->selectRow(
928 array( 'revision', 'page' ),
929 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
930 array(
931 'page_id' => $this->getId(),
932 'page_latest=rev_id' ),
933 __METHOD__ );
934
935 if ( $row ) {
936 if ( wfTimestamp( TS_MW, $row->rev_timestamp ) >= $revision->getTimestamp() ) {
937 wfProfileOut( __METHOD__ );
938 return false;
939 }
940 $prev = $row->rev_id;
941 $lastRevIsRedirect = (bool)$row->page_is_redirect;
942 } else {
943 # No or missing previous revision; mark the page as new
944 $prev = 0;
945 $lastRevIsRedirect = null;
946 }
947
948 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
949
950 wfProfileOut( __METHOD__ );
951 return $ret;
952 }
953
954 /**
955 * @param $section empty/null/false or a section number (0, 1, 2, T1, T2...)
956 * @param $text String: new text of the section
957 * @param $summary String: new section's subject, only if $section is 'new'
958 * @param $edittime String: revision timestamp or null to use the current revision
959 * @return string Complete article text, or null if error
960 */
961 public function replaceSection( $section, $text, $summary = '', $edittime = null ) {
962 wfProfileIn( __METHOD__ );
963
964 if ( strval( $section ) == '' ) {
965 // Whole-page edit; let the whole text through
966 } else {
967 if ( is_null( $edittime ) ) {
968 $rev = Revision::newFromTitle( $this->mTitle );
969 } else {
970 $dbw = wfGetDB( DB_MASTER );
971 $rev = Revision::loadFromTimestamp( $dbw, $this->mTitle, $edittime );
972 }
973
974 if ( !$rev ) {
975 wfDebug( "WikiPage::replaceSection asked for bogus section (page: " .
976 $this->getId() . "; section: $section; edittime: $edittime)\n" );
977 wfProfileOut( __METHOD__ );
978 return null;
979 }
980
981 $oldtext = $rev->getText();
982
983 if ( $section == 'new' ) {
984 # Inserting a new section
985 $subject = $summary ? wfMsgForContent( 'newsectionheaderdefaultlevel', $summary ) . "\n\n" : '';
986 if ( wfRunHooks( 'PlaceNewSection', array( $this, $oldtext, $subject, &$text ) ) ) {
987 $text = strlen( trim( $oldtext ) ) > 0
988 ? "{$oldtext}\n\n{$subject}{$text}"
989 : "{$subject}{$text}";
990 }
991 } else {
992 # Replacing an existing section; roll out the big guns
993 global $wgParser;
994
995 $text = $wgParser->replaceSection( $oldtext, $section, $text );
996 }
997 }
998
999 wfProfileOut( __METHOD__ );
1000 return $text;
1001 }
1002
1003 /**
1004 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1005 * @param $flags Int
1006 * @return Int updated $flags
1007 */
1008 function checkFlags( $flags ) {
1009 if ( !( $flags & EDIT_NEW ) && !( $flags & EDIT_UPDATE ) ) {
1010 if ( $this->mTitle->getArticleID() ) {
1011 $flags |= EDIT_UPDATE;
1012 } else {
1013 $flags |= EDIT_NEW;
1014 }
1015 }
1016
1017 return $flags;
1018 }
1019
1020 /**
1021 * Change an existing article or create a new article. Updates RC and all necessary caches,
1022 * optionally via the deferred update array.
1023 *
1024 * @param $text String: new text
1025 * @param $summary String: edit summary
1026 * @param $flags Integer bitfield:
1027 * EDIT_NEW
1028 * Article is known or assumed to be non-existent, create a new one
1029 * EDIT_UPDATE
1030 * Article is known or assumed to be pre-existing, update it
1031 * EDIT_MINOR
1032 * Mark this edit minor, if the user is allowed to do so
1033 * EDIT_SUPPRESS_RC
1034 * Do not log the change in recentchanges
1035 * EDIT_FORCE_BOT
1036 * Mark the edit a "bot" edit regardless of user rights
1037 * EDIT_DEFER_UPDATES
1038 * Defer some of the updates until the end of index.php
1039 * EDIT_AUTOSUMMARY
1040 * Fill in blank summaries with generated text where possible
1041 *
1042 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1043 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return an
1044 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1045 * edit-already-exists error will be returned. These two conditions are also possible with
1046 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1047 *
1048 * @param $baseRevId the revision ID this edit was based off, if any
1049 * @param $user User the user doing the edit
1050 *
1051 * @return Status object. Possible errors:
1052 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1053 * edit-gone-missing: In update mode, but the article didn't exist
1054 * edit-conflict: In update mode, the article changed unexpectedly
1055 * edit-no-change: Warning that the text was the same as before
1056 * edit-already-exists: In creation mode, but the article already exists
1057 *
1058 * Extensions may define additional errors.
1059 *
1060 * $return->value will contain an associative array with members as follows:
1061 * new: Boolean indicating if the function attempted to create a new article
1062 * revision: The revision object for the inserted revision, or null
1063 *
1064 * Compatibility note: this function previously returned a boolean value indicating success/failure
1065 */
1066 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
1067 global $wgUser, $wgDBtransactions, $wgUseAutomaticEditSummaries;
1068
1069 # Low-level sanity check
1070 if ( $this->mTitle->getText() === '' ) {
1071 throw new MWException( 'Something is trying to edit an article with an empty title' );
1072 }
1073
1074 wfProfileIn( __METHOD__ );
1075
1076 $user = is_null( $user ) ? $wgUser : $user;
1077 $status = Status::newGood( array() );
1078
1079 # Load $this->mTitle->getArticleID() and $this->mLatest if it's not already
1080 $this->loadPageData( 'fromdbmaster' );
1081
1082 $flags = $this->checkFlags( $flags );
1083
1084 if ( !wfRunHooks( 'ArticleSave', array( &$this, &$user, &$text, &$summary,
1085 $flags & EDIT_MINOR, null, null, &$flags, &$status ) ) )
1086 {
1087 wfDebug( __METHOD__ . ": ArticleSave hook aborted save!\n" );
1088
1089 if ( $status->isOK() ) {
1090 $status->fatal( 'edit-hook-aborted' );
1091 }
1092
1093 wfProfileOut( __METHOD__ );
1094 return $status;
1095 }
1096
1097 # Silently ignore EDIT_MINOR if not allowed
1098 $isminor = ( $flags & EDIT_MINOR ) && $user->isAllowed( 'minoredit' );
1099 $bot = $flags & EDIT_FORCE_BOT;
1100
1101 $oldtext = $this->getRawText(); // current revision
1102 $oldsize = strlen( $oldtext );
1103 $oldid = $this->getLatest();
1104 $oldIsRedirect = $this->isRedirect();
1105 $oldcountable = $this->isCountable();
1106
1107 # Provide autosummaries if one is not provided and autosummaries are enabled.
1108 if ( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY && $summary == '' ) {
1109 $summary = self::getAutosummary( $oldtext, $text, $flags );
1110 }
1111
1112 $editInfo = $this->prepareTextForEdit( $text, null, $user );
1113 $text = $editInfo->pst;
1114 $newsize = strlen( $text );
1115
1116 $dbw = wfGetDB( DB_MASTER );
1117 $now = wfTimestampNow();
1118 $this->mTimestamp = $now;
1119
1120 if ( $flags & EDIT_UPDATE ) {
1121 # Update article, but only if changed.
1122 $status->value['new'] = false;
1123
1124 # Make sure the revision is either completely inserted or not inserted at all
1125 if ( !$wgDBtransactions ) {
1126 $userAbort = ignore_user_abort( true );
1127 }
1128
1129 $revision = new Revision( array(
1130 'page' => $this->getId(),
1131 'comment' => $summary,
1132 'minor_edit' => $isminor,
1133 'text' => $text,
1134 'parent_id' => $oldid,
1135 'user' => $user->getId(),
1136 'user_text' => $user->getName(),
1137 'timestamp' => $now
1138 ) );
1139
1140 $changed = ( strcmp( $text, $oldtext ) != 0 );
1141
1142 if ( $changed ) {
1143 if ( !$this->mLatest ) {
1144 # Article gone missing
1145 wfDebug( __METHOD__ . ": EDIT_UPDATE specified but article doesn't exist\n" );
1146 $status->fatal( 'edit-gone-missing' );
1147
1148 wfProfileOut( __METHOD__ );
1149 return $status;
1150 }
1151
1152 $dbw->begin();
1153 $revisionId = $revision->insertOn( $dbw );
1154
1155 # Update page
1156 #
1157 # Note that we use $this->mLatest instead of fetching a value from the master DB
1158 # during the course of this function. This makes sure that EditPage can detect
1159 # edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
1160 # before this function is called. A previous function used a separate query, this
1161 # creates a window where concurrent edits can cause an ignored edit conflict.
1162 $ok = $this->updateRevisionOn( $dbw, $revision, $oldid, $oldIsRedirect );
1163
1164 if ( !$ok ) {
1165 /* Belated edit conflict! Run away!! */
1166 $status->fatal( 'edit-conflict' );
1167
1168 # Delete the invalid revision if the DB is not transactional
1169 if ( !$wgDBtransactions ) {
1170 $dbw->delete( 'revision', array( 'rev_id' => $revisionId ), __METHOD__ );
1171 }
1172
1173 $revisionId = 0;
1174 $dbw->rollback();
1175 } else {
1176 global $wgUseRCPatrol;
1177 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId, $user ) );
1178 # Update recentchanges
1179 if ( !( $flags & EDIT_SUPPRESS_RC ) ) {
1180 # Mark as patrolled if the user can do so
1181 $patrolled = $wgUseRCPatrol && !count(
1182 $this->mTitle->getUserPermissionsErrors( 'autopatrol', $user ) );
1183 # Add RC row to the DB
1184 $rc = RecentChange::notifyEdit( $now, $this->mTitle, $isminor, $user, $summary,
1185 $oldid, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1186 $revisionId, $patrolled
1187 );
1188
1189 # Log auto-patrolled edits
1190 if ( $patrolled ) {
1191 PatrolLog::record( $rc, true );
1192 }
1193 }
1194 $user->incEditCount();
1195 $dbw->commit();
1196 }
1197 }
1198
1199 if ( !$wgDBtransactions ) {
1200 ignore_user_abort( $userAbort );
1201 }
1202
1203 // Now that ignore_user_abort is restored, we can respond to fatal errors
1204 if ( !$status->isOK() ) {
1205 wfProfileOut( __METHOD__ );
1206 return $status;
1207 }
1208
1209 # Update links tables, site stats, etc.
1210 $this->doEditUpdates( $revision, $user, array( 'changed' => $changed,
1211 'oldcountable' => $oldcountable ) );
1212
1213 if ( !$changed ) {
1214 $status->warning( 'edit-no-change' );
1215 $revision = null;
1216 // Keep the same revision ID, but do some updates on it
1217 $revisionId = $this->getLatest();
1218 // Update page_touched, this is usually implicit in the page update
1219 // Other cache updates are done in onArticleEdit()
1220 $this->mTitle->invalidateCache();
1221 }
1222 } else {
1223 # Create new article
1224 $status->value['new'] = true;
1225
1226 $dbw->begin();
1227
1228 # Add the page record; stake our claim on this title!
1229 # This will return false if the article already exists
1230 $newid = $this->insertOn( $dbw );
1231
1232 if ( $newid === false ) {
1233 $dbw->rollback();
1234 $status->fatal( 'edit-already-exists' );
1235
1236 wfProfileOut( __METHOD__ );
1237 return $status;
1238 }
1239
1240 # Save the revision text...
1241 $revision = new Revision( array(
1242 'page' => $newid,
1243 'comment' => $summary,
1244 'minor_edit' => $isminor,
1245 'text' => $text,
1246 'user' => $user->getId(),
1247 'user_text' => $user->getName(),
1248 'timestamp' => $now
1249 ) );
1250 $revisionId = $revision->insertOn( $dbw );
1251
1252 # Update the page record with revision data
1253 $this->updateRevisionOn( $dbw, $revision, 0 );
1254
1255 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1256
1257 # Update recentchanges
1258 if ( !( $flags & EDIT_SUPPRESS_RC ) ) {
1259 global $wgUseRCPatrol, $wgUseNPPatrol;
1260
1261 # Mark as patrolled if the user can do so
1262 $patrolled = ( $wgUseRCPatrol || $wgUseNPPatrol ) && !count(
1263 $this->mTitle->getUserPermissionsErrors( 'autopatrol', $user ) );
1264 # Add RC row to the DB
1265 $rc = RecentChange::notifyNew( $now, $this->mTitle, $isminor, $user, $summary, $bot,
1266 '', strlen( $text ), $revisionId, $patrolled );
1267
1268 # Log auto-patrolled edits
1269 if ( $patrolled ) {
1270 PatrolLog::record( $rc, true );
1271 }
1272 }
1273 $user->incEditCount();
1274 $dbw->commit();
1275
1276 # Update links, etc.
1277 $this->doEditUpdates( $revision, $user, array( 'created' => true ) );
1278
1279 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$user, $text, $summary,
1280 $flags & EDIT_MINOR, null, null, &$flags, $revision ) );
1281 }
1282
1283 # Do updates right now unless deferral was requested
1284 if ( !( $flags & EDIT_DEFER_UPDATES ) ) {
1285 DeferredUpdates::doUpdates();
1286 }
1287
1288 // Return the new revision (or null) to the caller
1289 $status->value['revision'] = $revision;
1290
1291 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $text, $summary,
1292 $flags & EDIT_MINOR, null, null, &$flags, $revision, &$status, $baseRevId ) );
1293
1294 # Promote user to any groups they meet the criteria for
1295 $user->addAutopromoteOnceGroups( 'onEdit' );
1296
1297 wfProfileOut( __METHOD__ );
1298 return $status;
1299 }
1300
1301 /**
1302 * Update the article's restriction field, and leave a log entry.
1303 *
1304 * @todo: seperate the business/permission stuff out from backend code
1305 *
1306 * @param $limit Array: set of restriction keys
1307 * @param $reason String
1308 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
1309 * @param $expiry Array: per restriction type expiration
1310 * @param $user User The user updating the restrictions
1311 * @return bool true on success
1312 */
1313 public function updateRestrictions(
1314 $limit = array(), $reason = '', &$cascade = 0, $expiry = array(), User $user = null
1315 ) {
1316 global $wgUser, $wgContLang;
1317 $user = is_null( $user ) ? $wgUser : $user;
1318
1319 $restrictionTypes = $this->mTitle->getRestrictionTypes();
1320
1321 $id = $this->mTitle->getArticleID();
1322
1323 if ( $id <= 0 ) {
1324 wfDebug( "updateRestrictions failed: article id $id <= 0\n" );
1325 return false;
1326 }
1327
1328 if ( wfReadOnly() ) {
1329 wfDebug( "updateRestrictions failed: read-only\n" );
1330 return false;
1331 }
1332
1333 if ( count( $this->mTitle->getUserPermissionsErrors( 'protect', $user ) ) ) {
1334 wfDebug( "updateRestrictions failed: insufficient permissions\n" );
1335 return false;
1336 }
1337
1338 if ( !$cascade ) {
1339 $cascade = false;
1340 }
1341
1342 // Take this opportunity to purge out expired restrictions
1343 Title::purgeExpiredRestrictions();
1344
1345 # @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
1346 # we expect a single selection, but the schema allows otherwise.
1347 $current = array();
1348 $updated = self::flattenRestrictions( $limit );
1349 $changed = false;
1350
1351 foreach ( $restrictionTypes as $action ) {
1352 if ( isset( $expiry[$action] ) ) {
1353 # Get current restrictions on $action
1354 $aLimits = $this->mTitle->getRestrictions( $action );
1355 $current[$action] = implode( '', $aLimits );
1356 # Are any actual restrictions being dealt with here?
1357 $aRChanged = count( $aLimits ) || !empty( $limit[$action] );
1358
1359 # If something changed, we need to log it. Checking $aRChanged
1360 # assures that "unprotecting" a page that is not protected does
1361 # not log just because the expiry was "changed".
1362 if ( $aRChanged &&
1363 $this->mTitle->getRestrictionExpiry( $action ) != $expiry[$action] )
1364 {
1365 $changed = true;
1366 }
1367 }
1368 }
1369
1370 $current = self::flattenRestrictions( $current );
1371
1372 $changed = ( $changed || $current != $updated );
1373 $changed = $changed || ( $updated && $this->mTitle->areRestrictionsCascading() != $cascade );
1374 $protect = ( $updated != '' );
1375
1376 # If nothing's changed, do nothing
1377 if ( $changed ) {
1378 if ( wfRunHooks( 'ArticleProtect', array( &$this, &$user, $limit, $reason ) ) ) {
1379 $dbw = wfGetDB( DB_MASTER );
1380
1381 # Prepare a null revision to be added to the history
1382 $modified = $current != '' && $protect;
1383
1384 if ( $protect ) {
1385 $comment_type = $modified ? 'modifiedarticleprotection' : 'protectedarticle';
1386 } else {
1387 $comment_type = 'unprotectedarticle';
1388 }
1389
1390 $comment = $wgContLang->ucfirst( wfMsgForContent( $comment_type, $this->mTitle->getPrefixedText() ) );
1391
1392 # Only restrictions with the 'protect' right can cascade...
1393 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
1394 $editrestriction = isset( $limit['edit'] ) ? array( $limit['edit'] ) : $this->mTitle->getRestrictions( 'edit' );
1395
1396 # The schema allows multiple restrictions
1397 if ( !in_array( 'protect', $editrestriction ) && !in_array( 'sysop', $editrestriction ) ) {
1398 $cascade = false;
1399 }
1400
1401 $cascade_description = '';
1402
1403 if ( $cascade ) {
1404 $cascade_description = ' [' . wfMsgForContent( 'protect-summary-cascade' ) . ']';
1405 }
1406
1407 if ( $reason ) {
1408 $comment .= ": $reason";
1409 }
1410
1411 $editComment = $comment;
1412 $encodedExpiry = array();
1413 $protect_description = '';
1414 foreach ( $limit as $action => $restrictions ) {
1415 if ( !isset( $expiry[$action] ) )
1416 $expiry[$action] = $dbw->getInfinity();
1417
1418 $encodedExpiry[$action] = $dbw->encodeExpiry( $expiry[$action] );
1419 if ( $restrictions != '' ) {
1420 $protect_description .= $wgContLang->getDirMark() . "[$action=$restrictions] (";
1421 if ( $encodedExpiry[$action] != 'infinity' ) {
1422 $protect_description .= wfMsgForContent( 'protect-expiring',
1423 $wgContLang->timeanddate( $expiry[$action], false, false ) ,
1424 $wgContLang->date( $expiry[$action], false, false ) ,
1425 $wgContLang->time( $expiry[$action], false, false ) );
1426 } else {
1427 $protect_description .= wfMsgForContent( 'protect-expiry-indefinite' );
1428 }
1429
1430 $protect_description .= ') ';
1431 }
1432 }
1433 $protect_description = trim( $protect_description );
1434
1435 if ( $protect_description && $protect ) {
1436 $editComment .= " ($protect_description)";
1437 }
1438
1439 if ( $cascade ) {
1440 $editComment .= "$cascade_description";
1441 }
1442
1443 # Update restrictions table
1444 foreach ( $limit as $action => $restrictions ) {
1445 if ( $restrictions != '' ) {
1446 $dbw->replace( 'page_restrictions', array( array( 'pr_page', 'pr_type' ) ),
1447 array( 'pr_page' => $id,
1448 'pr_type' => $action,
1449 'pr_level' => $restrictions,
1450 'pr_cascade' => ( $cascade && $action == 'edit' ) ? 1 : 0,
1451 'pr_expiry' => $encodedExpiry[$action]
1452 ),
1453 __METHOD__
1454 );
1455 } else {
1456 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
1457 'pr_type' => $action ), __METHOD__ );
1458 }
1459 }
1460
1461 # Insert a null revision
1462 $nullRevision = Revision::newNullRevision( $dbw, $id, $editComment, true );
1463 $nullRevId = $nullRevision->insertOn( $dbw );
1464
1465 $latest = $this->getLatest();
1466 # Update page record
1467 $dbw->update( 'page',
1468 array( /* SET */
1469 'page_touched' => $dbw->timestamp(),
1470 'page_restrictions' => '',
1471 'page_latest' => $nullRevId
1472 ), array( /* WHERE */
1473 'page_id' => $id
1474 ), __METHOD__
1475 );
1476
1477 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $nullRevision, $latest, $user ) );
1478 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$user, $limit, $reason ) );
1479
1480 # Update the protection log
1481 $log = new LogPage( 'protect' );
1482 if ( $protect ) {
1483 $params = array( $protect_description, $cascade ? 'cascade' : '' );
1484 $log->addEntry( $modified ? 'modify' : 'protect', $this->mTitle, trim( $reason ), $params );
1485 } else {
1486 $log->addEntry( 'unprotect', $this->mTitle, $reason );
1487 }
1488 } # End hook
1489 } # End "changed" check
1490
1491 return true;
1492 }
1493
1494 /**
1495 * Take an array of page restrictions and flatten it to a string
1496 * suitable for insertion into the page_restrictions field.
1497 * @param $limit Array
1498 * @return String
1499 */
1500 protected static function flattenRestrictions( $limit ) {
1501 if ( !is_array( $limit ) ) {
1502 throw new MWException( 'WikiPage::flattenRestrictions given non-array restriction set' );
1503 }
1504
1505 $bits = array();
1506 ksort( $limit );
1507
1508 foreach ( $limit as $action => $restrictions ) {
1509 if ( $restrictions != '' ) {
1510 $bits[] = "$action=$restrictions";
1511 }
1512 }
1513
1514 return implode( ':', $bits );
1515 }
1516
1517 /**
1518 * @return bool whether or not the page surpasses $wgDeleteRevisionsLimit revisions
1519 */
1520 public function isBigDeletion() {
1521 global $wgDeleteRevisionsLimit;
1522
1523 if ( $wgDeleteRevisionsLimit ) {
1524 $revCount = $this->estimateRevisionCount();
1525
1526 return $revCount > $wgDeleteRevisionsLimit;
1527 }
1528
1529 return false;
1530 }
1531
1532 /**
1533 * @return int approximate revision count
1534 */
1535 public function estimateRevisionCount() {
1536 $dbr = wfGetDB( DB_SLAVE );
1537 return $dbr->estimateRowCount( 'revision', '*',
1538 array( 'rev_page' => $this->getId() ), __METHOD__ );
1539 }
1540
1541 /**
1542 * Get the last N authors
1543 * @param $num Integer: number of revisions to get
1544 * @param $revLatest String: the latest rev_id, selected from the master (optional)
1545 * @return array Array of authors, duplicates not removed
1546 */
1547 public function getLastNAuthors( $num, $revLatest = 0 ) {
1548 wfProfileIn( __METHOD__ );
1549 // First try the slave
1550 // If that doesn't have the latest revision, try the master
1551 $continue = 2;
1552 $db = wfGetDB( DB_SLAVE );
1553
1554 do {
1555 $res = $db->select( array( 'page', 'revision' ),
1556 array( 'rev_id', 'rev_user_text' ),
1557 array(
1558 'page_namespace' => $this->mTitle->getNamespace(),
1559 'page_title' => $this->mTitle->getDBkey(),
1560 'rev_page = page_id'
1561 ), __METHOD__,
1562 array(
1563 'ORDER BY' => 'rev_timestamp DESC',
1564 'LIMIT' => $num
1565 )
1566 );
1567
1568 if ( !$res ) {
1569 wfProfileOut( __METHOD__ );
1570 return array();
1571 }
1572
1573 $row = $db->fetchObject( $res );
1574
1575 if ( $continue == 2 && $revLatest && $row->rev_id != $revLatest ) {
1576 $db = wfGetDB( DB_MASTER );
1577 $continue--;
1578 } else {
1579 $continue = 0;
1580 }
1581 } while ( $continue );
1582
1583 $authors = array( $row->rev_user_text );
1584
1585 foreach ( $res as $row ) {
1586 $authors[] = $row->rev_user_text;
1587 }
1588
1589 wfProfileOut( __METHOD__ );
1590 return $authors;
1591 }
1592
1593 /**
1594 * Back-end article deletion
1595 * Deletes the article with database consistency, writes logs, purges caches
1596 *
1597 * @param $reason string delete reason for deletion log
1598 * @param $suppress bitfield
1599 * Revision::DELETED_TEXT
1600 * Revision::DELETED_COMMENT
1601 * Revision::DELETED_USER
1602 * Revision::DELETED_RESTRICTED
1603 * @param $id int article ID
1604 * @param $commit boolean defaults to true, triggers transaction end
1605 * @param &$errors Array of errors to append to
1606 * @param $user User The relevant user
1607 * @return boolean true if successful
1608 */
1609 public function doDeleteArticle(
1610 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User $user = null
1611 ) {
1612 global $wgUseTrackbacks, $wgUser;
1613 $user = is_null( $user ) ? $wgUser : $user;
1614
1615 wfDebug( __METHOD__ . "\n" );
1616
1617 if ( ! wfRunHooks( 'ArticleDelete', array( &$this, &$user, &$reason, &$error ) ) ) {
1618 return false;
1619 }
1620 $dbw = wfGetDB( DB_MASTER );
1621 $t = $this->mTitle->getDBkey();
1622 $id = $id ? $id : $this->mTitle->getArticleID( Title::GAID_FOR_UPDATE );
1623
1624 if ( $t === '' || $id == 0 ) {
1625 return false;
1626 }
1627
1628 DeferredUpdates::addUpdate(
1629 new SiteStatsUpdate( 0, 1, - (int)$this->isCountable(), -1 )
1630 );
1631
1632 // Bitfields to further suppress the content
1633 if ( $suppress ) {
1634 $bitfield = 0;
1635 // This should be 15...
1636 $bitfield |= Revision::DELETED_TEXT;
1637 $bitfield |= Revision::DELETED_COMMENT;
1638 $bitfield |= Revision::DELETED_USER;
1639 $bitfield |= Revision::DELETED_RESTRICTED;
1640 } else {
1641 $bitfield = 'rev_deleted';
1642 }
1643
1644 $dbw->begin();
1645 // For now, shunt the revision data into the archive table.
1646 // Text is *not* removed from the text table; bulk storage
1647 // is left intact to avoid breaking block-compression or
1648 // immutable storage schemes.
1649 //
1650 // For backwards compatibility, note that some older archive
1651 // table entries will have ar_text and ar_flags fields still.
1652 //
1653 // In the future, we may keep revisions and mark them with
1654 // the rev_deleted field, which is reserved for this purpose.
1655 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
1656 array(
1657 'ar_namespace' => 'page_namespace',
1658 'ar_title' => 'page_title',
1659 'ar_comment' => 'rev_comment',
1660 'ar_user' => 'rev_user',
1661 'ar_user_text' => 'rev_user_text',
1662 'ar_timestamp' => 'rev_timestamp',
1663 'ar_minor_edit' => 'rev_minor_edit',
1664 'ar_rev_id' => 'rev_id',
1665 'ar_parent_id' => 'rev_parent_id',
1666 'ar_text_id' => 'rev_text_id',
1667 'ar_text' => '\'\'', // Be explicit to appease
1668 'ar_flags' => '\'\'', // MySQL's "strict mode"...
1669 'ar_len' => 'rev_len',
1670 'ar_page_id' => 'page_id',
1671 'ar_deleted' => $bitfield,
1672 'ar_sha1' => 'rev_sha1'
1673 ), array(
1674 'page_id' => $id,
1675 'page_id = rev_page'
1676 ), __METHOD__
1677 );
1678
1679 # Delete restrictions for it
1680 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__ );
1681
1682 # Now that it's safely backed up, delete it
1683 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__ );
1684 $ok = ( $dbw->affectedRows() > 0 ); // getArticleId() uses slave, could be laggy
1685
1686 if ( !$ok ) {
1687 $dbw->rollback();
1688 return false;
1689 }
1690
1691 # Fix category table counts
1692 $cats = array();
1693 $res = $dbw->select( 'categorylinks', 'cl_to', array( 'cl_from' => $id ), __METHOD__ );
1694
1695 foreach ( $res as $row ) {
1696 $cats [] = $row->cl_to;
1697 }
1698
1699 $this->updateCategoryCounts( array(), $cats );
1700
1701 # If using cascading deletes, we can skip some explicit deletes
1702 if ( !$dbw->cascadingDeletes() ) {
1703 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__ );
1704
1705 if ( $wgUseTrackbacks ) {
1706 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__ );
1707 }
1708
1709 # Delete outgoing links
1710 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ), __METHOD__ );
1711 $dbw->delete( 'imagelinks', array( 'il_from' => $id ), __METHOD__ );
1712 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ), __METHOD__ );
1713 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ), __METHOD__ );
1714 $dbw->delete( 'externallinks', array( 'el_from' => $id ), __METHOD__ );
1715 $dbw->delete( 'langlinks', array( 'll_from' => $id ), __METHOD__ );
1716 $dbw->delete( 'iwlinks', array( 'iwl_from' => $id ), __METHOD__ );
1717 $dbw->delete( 'redirect', array( 'rd_from' => $id ), __METHOD__ );
1718 $dbw->delete( 'page_props', array( 'pp_page' => $id ), __METHOD__ );
1719 }
1720
1721 # If using cleanup triggers, we can skip some manual deletes
1722 if ( !$dbw->cleanupTriggers() ) {
1723 # Clean up recentchanges entries...
1724 $dbw->delete( 'recentchanges',
1725 array( 'rc_type != ' . RC_LOG,
1726 'rc_namespace' => $this->mTitle->getNamespace(),
1727 'rc_title' => $this->mTitle->getDBkey() ),
1728 __METHOD__ );
1729 $dbw->delete( 'recentchanges',
1730 array( 'rc_type != ' . RC_LOG, 'rc_cur_id' => $id ),
1731 __METHOD__ );
1732 }
1733
1734 # Clear caches
1735 self::onArticleDelete( $this->mTitle );
1736
1737 # Clear the cached article id so the interface doesn't act like we exist
1738 $this->mTitle->resetArticleID( 0 );
1739
1740 # Log the deletion, if the page was suppressed, log it at Oversight instead
1741 $logtype = $suppress ? 'suppress' : 'delete';
1742
1743 $logEntry = new ManualLogEntry( $logtype, 'delete' );
1744 $logEntry->setPerformer( $user );
1745 $logEntry->setTarget( $this->mTitle );
1746 $logEntry->setComment( $reason );
1747 $logid = $logEntry->insert();
1748 $logEntry->publish( $logid );
1749
1750 if ( $commit ) {
1751 $dbw->commit();
1752 }
1753
1754 wfRunHooks( 'ArticleDeleteComplete', array( &$this, &$user, $reason, $id ) );
1755 return true;
1756 }
1757
1758 /**
1759 * Roll back the most recent consecutive set of edits to a page
1760 * from the same user; fails if there are no eligible edits to
1761 * roll back to, e.g. user is the sole contributor. This function
1762 * performs permissions checks on $user, then calls commitRollback()
1763 * to do the dirty work
1764 *
1765 * @todo: seperate the business/permission stuff out from backend code
1766 *
1767 * @param $fromP String: Name of the user whose edits to rollback.
1768 * @param $summary String: Custom summary. Set to default summary if empty.
1769 * @param $token String: Rollback token.
1770 * @param $bot Boolean: If true, mark all reverted edits as bot.
1771 *
1772 * @param $resultDetails Array: contains result-specific array of additional values
1773 * 'alreadyrolled' : 'current' (rev)
1774 * success : 'summary' (str), 'current' (rev), 'target' (rev)
1775 *
1776 * @param $user User The user performing the rollback
1777 * @return array of errors, each error formatted as
1778 * array(messagekey, param1, param2, ...).
1779 * On success, the array is empty. This array can also be passed to
1780 * OutputPage::showPermissionsErrorPage().
1781 */
1782 public function doRollback(
1783 $fromP, $summary, $token, $bot, &$resultDetails, User $user
1784 ) {
1785 $resultDetails = null;
1786
1787 # Check permissions
1788 $editErrors = $this->mTitle->getUserPermissionsErrors( 'edit', $user );
1789 $rollbackErrors = $this->mTitle->getUserPermissionsErrors( 'rollback', $user );
1790 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
1791
1792 if ( !$user->matchEditToken( $token, array( $this->mTitle->getPrefixedText(), $fromP ) ) ) {
1793 $errors[] = array( 'sessionfailure' );
1794 }
1795
1796 if ( $user->pingLimiter( 'rollback' ) || $user->pingLimiter() ) {
1797 $errors[] = array( 'actionthrottledtext' );
1798 }
1799
1800 # If there were errors, bail out now
1801 if ( !empty( $errors ) ) {
1802 return $errors;
1803 }
1804
1805 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user );
1806 }
1807
1808 /**
1809 * Backend implementation of doRollback(), please refer there for parameter
1810 * and return value documentation
1811 *
1812 * NOTE: This function does NOT check ANY permissions, it just commits the
1813 * rollback to the DB. Therefore, you should only call this function direct-
1814 * ly if you want to use custom permissions checks. If you don't, use
1815 * doRollback() instead.
1816 * @param $fromP String: Name of the user whose edits to rollback.
1817 * @param $summary String: Custom summary. Set to default summary if empty.
1818 * @param $bot Boolean: If true, mark all reverted edits as bot.
1819 *
1820 * @param $resultDetails Array: contains result-specific array of additional values
1821 * @param $guser User The user performing the rollback
1822 */
1823 public function commitRollback( $fromP, $summary, $bot, &$resultDetails, User $guser ) {
1824 global $wgUseRCPatrol, $wgContLang;
1825
1826 $dbw = wfGetDB( DB_MASTER );
1827
1828 if ( wfReadOnly() ) {
1829 return array( array( 'readonlytext' ) );
1830 }
1831
1832 # Get the last editor
1833 $current = Revision::newFromTitle( $this->mTitle );
1834 if ( is_null( $current ) ) {
1835 # Something wrong... no page?
1836 return array( array( 'notanarticle' ) );
1837 }
1838
1839 $from = str_replace( '_', ' ', $fromP );
1840 # User name given should match up with the top revision.
1841 # If the user was deleted then $from should be empty.
1842 if ( $from != $current->getUserText() ) {
1843 $resultDetails = array( 'current' => $current );
1844 return array( array( 'alreadyrolled',
1845 htmlspecialchars( $this->mTitle->getPrefixedText() ),
1846 htmlspecialchars( $fromP ),
1847 htmlspecialchars( $current->getUserText() )
1848 ) );
1849 }
1850
1851 # Get the last edit not by this guy...
1852 # Note: these may not be public values
1853 $user = intval( $current->getRawUser() );
1854 $user_text = $dbw->addQuotes( $current->getRawUserText() );
1855 $s = $dbw->selectRow( 'revision',
1856 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
1857 array( 'rev_page' => $current->getPage(),
1858 "rev_user != {$user} OR rev_user_text != {$user_text}"
1859 ), __METHOD__,
1860 array( 'USE INDEX' => 'page_timestamp',
1861 'ORDER BY' => 'rev_timestamp DESC' )
1862 );
1863 if ( $s === false ) {
1864 # No one else ever edited this page
1865 return array( array( 'cantrollback' ) );
1866 } elseif ( $s->rev_deleted & Revision::DELETED_TEXT || $s->rev_deleted & Revision::DELETED_USER ) {
1867 # Only admins can see this text
1868 return array( array( 'notvisiblerev' ) );
1869 }
1870
1871 $set = array();
1872 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
1873 # Mark all reverted edits as bot
1874 $set['rc_bot'] = 1;
1875 }
1876
1877 if ( $wgUseRCPatrol ) {
1878 # Mark all reverted edits as patrolled
1879 $set['rc_patrolled'] = 1;
1880 }
1881
1882 if ( count( $set ) ) {
1883 $dbw->update( 'recentchanges', $set,
1884 array( /* WHERE */
1885 'rc_cur_id' => $current->getPage(),
1886 'rc_user_text' => $current->getUserText(),
1887 "rc_timestamp > '{$s->rev_timestamp}'",
1888 ), __METHOD__
1889 );
1890 }
1891
1892 # Generate the edit summary if necessary
1893 $target = Revision::newFromId( $s->rev_id );
1894 if ( empty( $summary ) ) {
1895 if ( $from == '' ) { // no public user name
1896 $summary = wfMsgForContent( 'revertpage-nouser' );
1897 } else {
1898 $summary = wfMsgForContent( 'revertpage' );
1899 }
1900 }
1901
1902 # Allow the custom summary to use the same args as the default message
1903 $args = array(
1904 $target->getUserText(), $from, $s->rev_id,
1905 $wgContLang->timeanddate( wfTimestamp( TS_MW, $s->rev_timestamp ) ),
1906 $current->getId(), $wgContLang->timeanddate( $current->getTimestamp() )
1907 );
1908 $summary = wfMsgReplaceArgs( $summary, $args );
1909
1910 # Save
1911 $flags = EDIT_UPDATE;
1912
1913 if ( $guser->isAllowed( 'minoredit' ) ) {
1914 $flags |= EDIT_MINOR;
1915 }
1916
1917 if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
1918 $flags |= EDIT_FORCE_BOT;
1919 }
1920
1921 # Actually store the edit
1922 $status = $this->doEdit( $target->getText(), $summary, $flags, $target->getId() );
1923 if ( !empty( $status->value['revision'] ) ) {
1924 $revId = $status->value['revision']->getId();
1925 } else {
1926 $revId = false;
1927 }
1928
1929 wfRunHooks( 'ArticleRollbackComplete', array( $this, $guser, $target, $current ) );
1930
1931 $resultDetails = array(
1932 'summary' => $summary,
1933 'current' => $current,
1934 'target' => $target,
1935 'newid' => $revId
1936 );
1937
1938 return array();
1939 }
1940
1941 /**
1942 * Do standard deferred updates after page view
1943 * @param $user User The relevant user
1944 */
1945 public function doViewUpdates( User $user ) {
1946 global $wgDisableCounters;
1947 if ( wfReadOnly() ) {
1948 return;
1949 }
1950
1951 # Don't update page view counters on views from bot users (bug 14044)
1952 if ( !$wgDisableCounters && !$user->isAllowed( 'bot' ) && $this->getId() ) {
1953 DeferredUpdates::addUpdate( new ViewCountUpdate( $this->getId() ) );
1954 DeferredUpdates::addUpdate( new SiteStatsUpdate( 1, 0, 0 ) );
1955 }
1956
1957 # Update newtalk / watchlist notification status
1958 $user->clearNotification( $this->mTitle );
1959 }
1960
1961 /**
1962 * Prepare text which is about to be saved.
1963 * Returns a stdclass with source, pst and output members
1964 */
1965 public function prepareTextForEdit( $text, $revid = null, User $user = null ) {
1966 global $wgParser, $wgContLang, $wgUser;
1967 $user = is_null( $user ) ? $wgUser : $user;
1968 // @TODO fixme: check $user->getId() here???
1969 if ( $this->mPreparedEdit
1970 && $this->mPreparedEdit->newText == $text
1971 && $this->mPreparedEdit->revid == $revid
1972 ) {
1973 // Already prepared
1974 return $this->mPreparedEdit;
1975 }
1976
1977 $popts = ParserOptions::newFromUserAndLang( $user, $wgContLang );
1978 wfRunHooks( 'ArticlePrepareTextForEdit', array( $this, $popts ) );
1979
1980 $edit = (object)array();
1981 $edit->revid = $revid;
1982 $edit->newText = $text;
1983 $edit->pst = $wgParser->preSaveTransform( $text, $this->mTitle, $user, $popts );
1984 $edit->popts = $this->makeParserOptions( 'canonical' );
1985 $edit->output = $wgParser->parse( $edit->pst, $this->mTitle, $edit->popts, true, true, $revid );
1986 $edit->oldText = $this->getRawText();
1987
1988 $this->mPreparedEdit = $edit;
1989
1990 return $edit;
1991 }
1992
1993 /**
1994 * Do standard deferred updates after page edit.
1995 * Update links tables, site stats, search index and message cache.
1996 * Purges pages that include this page if the text was changed here.
1997 * Every 100th edit, prune the recent changes table.
1998 *
1999 * @private
2000 * @param $revision Revision object
2001 * @param $user User object that did the revision
2002 * @param $options Array of options, following indexes are used:
2003 * - changed: boolean, whether the revision changed the content (default true)
2004 * - created: boolean, whether the revision created the page (default false)
2005 * - oldcountable: boolean or null (default null):
2006 * - boolean: whether the page was counted as an article before that
2007 * revision, only used in changed is true and created is false
2008 * - null: don't change the article count
2009 */
2010 public function doEditUpdates( Revision $revision, User $user, array $options = array() ) {
2011 global $wgEnableParserCache;
2012
2013 wfProfileIn( __METHOD__ );
2014
2015 $options += array( 'changed' => true, 'created' => false, 'oldcountable' => null );
2016 $text = $revision->getText();
2017
2018 # Parse the text
2019 # Be careful not to double-PST: $text is usually already PST-ed once
2020 if ( !$this->mPreparedEdit || $this->mPreparedEdit->output->getFlag( 'vary-revision' ) ) {
2021 wfDebug( __METHOD__ . ": No prepared edit or vary-revision is set...\n" );
2022 $editInfo = $this->prepareTextForEdit( $text, $revision->getId(), $user );
2023 } else {
2024 wfDebug( __METHOD__ . ": No vary-revision, using prepared edit...\n" );
2025 $editInfo = $this->mPreparedEdit;
2026 }
2027
2028 # Save it to the parser cache
2029 if ( $wgEnableParserCache ) {
2030 $parserCache = ParserCache::singleton();
2031 $parserCache->save( $editInfo->output, $this, $editInfo->popts );
2032 }
2033
2034 # Update the links tables
2035 $u = new LinksUpdate( $this->mTitle, $editInfo->output );
2036 $u->doUpdate();
2037
2038 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $options['changed'] ) );
2039
2040 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2041 if ( 0 == mt_rand( 0, 99 ) ) {
2042 // Flush old entries from the `recentchanges` table; we do this on
2043 // random requests so as to avoid an increase in writes for no good reason
2044 global $wgRCMaxAge;
2045
2046 $dbw = wfGetDB( DB_MASTER );
2047 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2048 $dbw->delete(
2049 'recentchanges',
2050 array( "rc_timestamp < '$cutoff'" ),
2051 __METHOD__
2052 );
2053 }
2054 }
2055
2056 $id = $this->getId();
2057 $title = $this->mTitle->getPrefixedDBkey();
2058 $shortTitle = $this->mTitle->getDBkey();
2059
2060 if ( 0 == $id ) {
2061 wfProfileOut( __METHOD__ );
2062 return;
2063 }
2064
2065 if ( !$options['changed'] ) {
2066 $good = 0;
2067 $total = 0;
2068 } elseif ( $options['created'] ) {
2069 $good = (int)$this->isCountable( $editInfo );
2070 $total = 1;
2071 } elseif ( $options['oldcountable'] !== null ) {
2072 $good = (int)$this->isCountable( $editInfo ) - (int)$options['oldcountable'];
2073 $total = 0;
2074 } else {
2075 $good = 0;
2076 $total = 0;
2077 }
2078
2079 DeferredUpdates::addUpdate( new SiteStatsUpdate( 0, 1, $good, $total ) );
2080 DeferredUpdates::addUpdate( new SearchUpdate( $id, $title, $text ) );
2081
2082 # If this is another user's talk page, update newtalk.
2083 # Don't do this if $options['changed'] = false (null-edits) nor if
2084 # it's a minor edit and the user doesn't want notifications for those.
2085 if ( $options['changed']
2086 && $this->mTitle->getNamespace() == NS_USER_TALK
2087 && $shortTitle != $user->getTitleKey()
2088 && !( $revision->isMinor() && $user->isAllowed( 'nominornewtalk' ) )
2089 ) {
2090 if ( wfRunHooks( 'ArticleEditUpdateNewTalk', array( &$this ) ) ) {
2091 $other = User::newFromName( $shortTitle, false );
2092 if ( !$other ) {
2093 wfDebug( __METHOD__ . ": invalid username\n" );
2094 } elseif ( User::isIP( $shortTitle ) ) {
2095 // An anonymous user
2096 $other->setNewtalk( true );
2097 } elseif ( $other->isLoggedIn() ) {
2098 $other->setNewtalk( true );
2099 } else {
2100 wfDebug( __METHOD__ . ": don't need to notify a nonexistent user\n" );
2101 }
2102 }
2103 }
2104
2105 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
2106 MessageCache::singleton()->replace( $shortTitle, $text );
2107 }
2108
2109 if( $options['created'] ) {
2110 self::onArticleCreate( $this->mTitle );
2111 } else {
2112 self::onArticleEdit( $this->mTitle );
2113 }
2114
2115 wfProfileOut( __METHOD__ );
2116 }
2117
2118 /**
2119 * Perform article updates on a special page creation.
2120 *
2121 * @param $rev Revision object
2122 *
2123 * @todo This is a shitty interface function. Kill it and replace the
2124 * other shitty functions like doEditUpdates and such so it's not needed
2125 * anymore.
2126 * @deprecated since 1.18, use doEditUpdates()
2127 */
2128 public function createUpdates( $rev ) {
2129 global $wgUser;
2130 $this->doEditUpdates( $rev, $wgUser, array( 'created' => true ) );
2131 }
2132
2133 /**
2134 * This function is called right before saving the wikitext,
2135 * so we can do things like signatures and links-in-context.
2136 *
2137 * @deprecated in 1.19; use Parser::preSaveTransform() instead
2138 * @param $text String article contents
2139 * @param $user User object: user doing the edit
2140 * @param $popts ParserOptions object: parser options, default options for
2141 * the user loaded if null given
2142 * @return string article contents with altered wikitext markup (signatures
2143 * converted, {{subst:}}, templates, etc.)
2144 */
2145 public function preSaveTransform( $text, User $user = null, ParserOptions $popts = null ) {
2146 global $wgParser, $wgUser;
2147
2148 wfDeprecated( __METHOD__ );
2149
2150 $user = is_null( $user ) ? $wgUser : $user;
2151
2152 if ( $popts === null ) {
2153 $popts = ParserOptions::newFromUser( $user );
2154 }
2155
2156 return $wgParser->preSaveTransform( $text, $this->mTitle, $user, $popts );
2157 }
2158
2159 /**
2160 * Loads page_touched and returns a value indicating if it should be used
2161 * @return boolean true if not a redirect
2162 */
2163 public function checkTouched() {
2164 if ( !$this->mDataLoaded ) {
2165 $this->loadPageData();
2166 }
2167 return !$this->mIsRedirect;
2168 }
2169
2170 /**
2171 * Get the page_touched field
2172 * @return string containing GMT timestamp
2173 */
2174 public function getTouched() {
2175 if ( !$this->mDataLoaded ) {
2176 $this->loadPageData();
2177 }
2178 return $this->mTouched;
2179 }
2180
2181 /**
2182 * Get the page_latest field
2183 * @return integer rev_id of current revision
2184 */
2185 public function getLatest() {
2186 if ( !$this->mDataLoaded ) {
2187 $this->loadPageData();
2188 }
2189 return (int)$this->mLatest;
2190 }
2191
2192 /**
2193 * Edit an article without doing all that other stuff
2194 * The article must already exist; link tables etc
2195 * are not updated, caches are not flushed.
2196 *
2197 * @param $text String: text submitted
2198 * @param $user User The relevant user
2199 * @param $comment String: comment submitted
2200 * @param $minor Boolean: whereas it's a minor modification
2201 */
2202 public function doQuickEdit( $text, User $user, $comment = '', $minor = 0 ) {
2203 wfProfileIn( __METHOD__ );
2204
2205 $dbw = wfGetDB( DB_MASTER );
2206 $revision = new Revision( array(
2207 'page' => $this->getId(),
2208 'text' => $text,
2209 'comment' => $comment,
2210 'minor_edit' => $minor ? 1 : 0,
2211 ) );
2212 $revision->insertOn( $dbw );
2213 $this->updateRevisionOn( $dbw, $revision );
2214
2215 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
2216
2217 wfProfileOut( __METHOD__ );
2218 }
2219
2220 /**
2221 * The onArticle*() functions are supposed to be a kind of hooks
2222 * which should be called whenever any of the specified actions
2223 * are done.
2224 *
2225 * This is a good place to put code to clear caches, for instance.
2226 *
2227 * This is called on page move and undelete, as well as edit
2228 *
2229 * @param $title Title object
2230 */
2231 public static function onArticleCreate( $title ) {
2232 # Update existence markers on article/talk tabs...
2233 if ( $title->isTalkPage() ) {
2234 $other = $title->getSubjectPage();
2235 } else {
2236 $other = $title->getTalkPage();
2237 }
2238
2239 $other->invalidateCache();
2240 $other->purgeSquid();
2241
2242 $title->touchLinks();
2243 $title->purgeSquid();
2244 $title->deleteTitleProtection();
2245 }
2246
2247 /**
2248 * Clears caches when article is deleted
2249 *
2250 * @param $title Title
2251 */
2252 public static function onArticleDelete( $title ) {
2253 # Update existence markers on article/talk tabs...
2254 if ( $title->isTalkPage() ) {
2255 $other = $title->getSubjectPage();
2256 } else {
2257 $other = $title->getTalkPage();
2258 }
2259
2260 $other->invalidateCache();
2261 $other->purgeSquid();
2262
2263 $title->touchLinks();
2264 $title->purgeSquid();
2265
2266 # File cache
2267 HTMLFileCache::clearFileCache( $title );
2268
2269 # Messages
2270 if ( $title->getNamespace() == NS_MEDIAWIKI ) {
2271 MessageCache::singleton()->replace( $title->getDBkey(), false );
2272 }
2273
2274 # Images
2275 if ( $title->getNamespace() == NS_FILE ) {
2276 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
2277 $update->doUpdate();
2278 }
2279
2280 # User talk pages
2281 if ( $title->getNamespace() == NS_USER_TALK ) {
2282 $user = User::newFromName( $title->getText(), false );
2283 $user->setNewtalk( false );
2284 }
2285
2286 # Image redirects
2287 RepoGroup::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
2288 }
2289
2290 /**
2291 * Purge caches on page update etc
2292 *
2293 * @param $title Title object
2294 * @todo: verify that $title is always a Title object (and never false or null), add Title hint to parameter $title
2295 */
2296 public static function onArticleEdit( $title ) {
2297 // Invalidate caches of articles which include this page
2298 DeferredUpdates::addHTMLCacheUpdate( $title, 'templatelinks' );
2299
2300
2301 // Invalidate the caches of all pages which redirect here
2302 DeferredUpdates::addHTMLCacheUpdate( $title, 'redirect' );
2303
2304 # Purge squid for this page only
2305 $title->purgeSquid();
2306
2307 # Clear file cache for this page only
2308 HTMLFileCache::clearFileCache( $title );
2309 }
2310
2311 /**#@-*/
2312
2313 /**
2314 * Return a list of templates used by this article.
2315 * Uses the templatelinks table
2316 *
2317 * @return Array of Title objects
2318 */
2319 public function getUsedTemplates() {
2320 $result = array();
2321 $id = $this->mTitle->getArticleID();
2322
2323 if ( $id == 0 ) {
2324 return array();
2325 }
2326
2327 $dbr = wfGetDB( DB_SLAVE );
2328 $res = $dbr->select( array( 'templatelinks' ),
2329 array( 'tl_namespace', 'tl_title' ),
2330 array( 'tl_from' => $id ),
2331 __METHOD__ );
2332
2333 if ( $res !== false ) {
2334 foreach ( $res as $row ) {
2335 $result[] = Title::makeTitle( $row->tl_namespace, $row->tl_title );
2336 }
2337 }
2338
2339 return $result;
2340 }
2341
2342 /**
2343 * Returns a list of hidden categories this page is a member of.
2344 * Uses the page_props and categorylinks tables.
2345 *
2346 * @return Array of Title objects
2347 */
2348 public function getHiddenCategories() {
2349 $result = array();
2350 $id = $this->mTitle->getArticleID();
2351
2352 if ( $id == 0 ) {
2353 return array();
2354 }
2355
2356 $dbr = wfGetDB( DB_SLAVE );
2357 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
2358 array( 'cl_to' ),
2359 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
2360 'page_namespace' => NS_CATEGORY, 'page_title=cl_to' ),
2361 __METHOD__ );
2362
2363 if ( $res !== false ) {
2364 foreach ( $res as $row ) {
2365 $result[] = Title::makeTitle( NS_CATEGORY, $row->cl_to );
2366 }
2367 }
2368
2369 return $result;
2370 }
2371
2372 /**
2373 * Return an applicable autosummary if one exists for the given edit.
2374 * @param $oldtext String: the previous text of the page.
2375 * @param $newtext String: The submitted text of the page.
2376 * @param $flags Int bitmask: a bitmask of flags submitted for the edit.
2377 * @return string An appropriate autosummary, or an empty string.
2378 */
2379 public static function getAutosummary( $oldtext, $newtext, $flags ) {
2380 global $wgContLang;
2381
2382 # Decide what kind of autosummary is needed.
2383
2384 # Redirect autosummaries
2385 $ot = Title::newFromRedirect( $oldtext );
2386 $rt = Title::newFromRedirect( $newtext );
2387
2388 if ( is_object( $rt ) && ( !is_object( $ot ) || !$rt->equals( $ot ) || $ot->getFragment() != $rt->getFragment() ) ) {
2389 $truncatedtext = $wgContLang->truncate(
2390 str_replace( "\n", ' ', $newtext ),
2391 max( 0, 250
2392 - strlen( wfMsgForContent( 'autoredircomment' ) )
2393 - strlen( $rt->getFullText() )
2394 ) );
2395 return wfMsgForContent( 'autoredircomment', $rt->getFullText(), $truncatedtext );
2396 }
2397
2398 # New page autosummaries
2399 if ( $flags & EDIT_NEW && strlen( $newtext ) ) {
2400 # If they're making a new article, give its text, truncated, in the summary.
2401
2402 $truncatedtext = $wgContLang->truncate(
2403 str_replace( "\n", ' ', $newtext ),
2404 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new' ) ) ) );
2405
2406 return wfMsgForContent( 'autosumm-new', $truncatedtext );
2407 }
2408
2409 # Blanking autosummaries
2410 if ( $oldtext != '' && $newtext == '' ) {
2411 return wfMsgForContent( 'autosumm-blank' );
2412 } elseif ( strlen( $oldtext ) > 10 * strlen( $newtext ) && strlen( $newtext ) < 500 ) {
2413 # Removing more than 90% of the article
2414
2415 $truncatedtext = $wgContLang->truncate(
2416 $newtext,
2417 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) ) );
2418
2419 return wfMsgForContent( 'autosumm-replace', $truncatedtext );
2420 }
2421
2422 # If we reach this point, there's no applicable autosummary for our case, so our
2423 # autosummary is empty.
2424 return '';
2425 }
2426
2427 /**
2428 * Auto-generates a deletion reason
2429 *
2430 * @param &$hasHistory Boolean: whether the page has a history
2431 * @return mixed String containing deletion reason or empty string, or boolean false
2432 * if no revision occurred
2433 */
2434 public function getAutoDeleteReason( &$hasHistory ) {
2435 global $wgContLang;
2436
2437 $dbw = wfGetDB( DB_MASTER );
2438 // Get the last revision
2439 $rev = Revision::newFromTitle( $this->getTitle() );
2440
2441 if ( is_null( $rev ) ) {
2442 return false;
2443 }
2444
2445 // Get the article's contents
2446 $contents = $rev->getText();
2447 $blank = false;
2448
2449 // If the page is blank, use the text from the previous revision,
2450 // which can only be blank if there's a move/import/protect dummy revision involved
2451 if ( $contents == '' ) {
2452 $prev = $rev->getPrevious();
2453
2454 if ( $prev ) {
2455 $contents = $prev->getText();
2456 $blank = true;
2457 }
2458 }
2459
2460 // Find out if there was only one contributor
2461 // Only scan the last 20 revisions
2462 $res = $dbw->select( 'revision', 'rev_user_text',
2463 array( 'rev_page' => $this->getID(), $dbw->bitAnd( 'rev_deleted', Revision::DELETED_USER ) . ' = 0' ),
2464 __METHOD__,
2465 array( 'LIMIT' => 20 )
2466 );
2467
2468 if ( $res === false ) {
2469 // This page has no revisions, which is very weird
2470 return false;
2471 }
2472
2473 $hasHistory = ( $res->numRows() > 1 );
2474 $row = $dbw->fetchObject( $res );
2475
2476 if ( $row ) { // $row is false if the only contributor is hidden
2477 $onlyAuthor = $row->rev_user_text;
2478 // Try to find a second contributor
2479 foreach ( $res as $row ) {
2480 if ( $row->rev_user_text != $onlyAuthor ) { // Bug 22999
2481 $onlyAuthor = false;
2482 break;
2483 }
2484 }
2485 } else {
2486 $onlyAuthor = false;
2487 }
2488
2489 // Generate the summary with a '$1' placeholder
2490 if ( $blank ) {
2491 // The current revision is blank and the one before is also
2492 // blank. It's just not our lucky day
2493 $reason = wfMsgForContent( 'exbeforeblank', '$1' );
2494 } else {
2495 if ( $onlyAuthor ) {
2496 $reason = wfMsgForContent( 'excontentauthor', '$1', $onlyAuthor );
2497 } else {
2498 $reason = wfMsgForContent( 'excontent', '$1' );
2499 }
2500 }
2501
2502 if ( $reason == '-' ) {
2503 // Allow these UI messages to be blanked out cleanly
2504 return '';
2505 }
2506
2507 // Replace newlines with spaces to prevent uglyness
2508 $contents = preg_replace( "/[\n\r]/", ' ', $contents );
2509 // Calculate the maximum amount of chars to get
2510 // Max content length = max comment length - length of the comment (excl. $1)
2511 $maxLength = 255 - ( strlen( $reason ) - 2 );
2512 $contents = $wgContLang->truncate( $contents, $maxLength );
2513 // Remove possible unfinished links
2514 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
2515 // Now replace the '$1' placeholder
2516 $reason = str_replace( '$1', $contents, $reason );
2517
2518 return $reason;
2519 }
2520
2521 /**
2522 * Get parser options suitable for rendering the primary article wikitext
2523 * @param User|string $user User object or 'canonical'
2524 * @return ParserOptions
2525 */
2526 public function makeParserOptions( $user ) {
2527 global $wgContLang;
2528 if ( $user instanceof User ) { // settings per user (even anons)
2529 $options = ParserOptions::newFromUser( $user );
2530 } else { // canonical settings
2531 $options = ParserOptions::newFromUserAndLang( new User, $wgContLang );
2532 }
2533 $options->enableLimitReport(); // show inclusion/loop reports
2534 $options->setTidy( true ); // fix bad HTML
2535 return $options;
2536 }
2537
2538 /**
2539 * Update all the appropriate counts in the category table, given that
2540 * we've added the categories $added and deleted the categories $deleted.
2541 *
2542 * @param $added array The names of categories that were added
2543 * @param $deleted array The names of categories that were deleted
2544 */
2545 public function updateCategoryCounts( $added, $deleted ) {
2546 $ns = $this->mTitle->getNamespace();
2547 $dbw = wfGetDB( DB_MASTER );
2548
2549 # First make sure the rows exist. If one of the "deleted" ones didn't
2550 # exist, we might legitimately not create it, but it's simpler to just
2551 # create it and then give it a negative value, since the value is bogus
2552 # anyway.
2553 #
2554 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
2555 $insertCats = array_merge( $added, $deleted );
2556 if ( !$insertCats ) {
2557 # Okay, nothing to do
2558 return;
2559 }
2560
2561 $insertRows = array();
2562
2563 foreach ( $insertCats as $cat ) {
2564 $insertRows[] = array(
2565 'cat_id' => $dbw->nextSequenceValue( 'category_cat_id_seq' ),
2566 'cat_title' => $cat
2567 );
2568 }
2569 $dbw->insert( 'category', $insertRows, __METHOD__, 'IGNORE' );
2570
2571 $addFields = array( 'cat_pages = cat_pages + 1' );
2572 $removeFields = array( 'cat_pages = cat_pages - 1' );
2573
2574 if ( $ns == NS_CATEGORY ) {
2575 $addFields[] = 'cat_subcats = cat_subcats + 1';
2576 $removeFields[] = 'cat_subcats = cat_subcats - 1';
2577 } elseif ( $ns == NS_FILE ) {
2578 $addFields[] = 'cat_files = cat_files + 1';
2579 $removeFields[] = 'cat_files = cat_files - 1';
2580 }
2581
2582 if ( $added ) {
2583 $dbw->update(
2584 'category',
2585 $addFields,
2586 array( 'cat_title' => $added ),
2587 __METHOD__
2588 );
2589 }
2590
2591 if ( $deleted ) {
2592 $dbw->update(
2593 'category',
2594 $removeFields,
2595 array( 'cat_title' => $deleted ),
2596 __METHOD__
2597 );
2598 }
2599 }
2600
2601 /**
2602 * Updates cascading protections
2603 *
2604 * @param $parserOutput ParserOutput object for the current version
2605 */
2606 public function doCascadeProtectionUpdates( ParserOutput $parserOutput ) {
2607 if ( wfReadOnly() || !$this->mTitle->areRestrictionsCascading() ) {
2608 return;
2609 }
2610
2611 // templatelinks table may have become out of sync,
2612 // especially if using variable-based transclusions.
2613 // For paranoia, check if things have changed and if
2614 // so apply updates to the database. This will ensure
2615 // that cascaded protections apply as soon as the changes
2616 // are visible.
2617
2618 # Get templates from templatelinks
2619 $id = $this->mTitle->getArticleID();
2620
2621 $tlTemplates = array();
2622
2623 $dbr = wfGetDB( DB_SLAVE );
2624 $res = $dbr->select( array( 'templatelinks' ),
2625 array( 'tl_namespace', 'tl_title' ),
2626 array( 'tl_from' => $id ),
2627 __METHOD__
2628 );
2629
2630 foreach ( $res as $row ) {
2631 $tlTemplates["{$row->tl_namespace}:{$row->tl_title}"] = true;
2632 }
2633
2634 # Get templates from parser output.
2635 $poTemplates = array();
2636 foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
2637 foreach ( $templates as $dbk => $id ) {
2638 $poTemplates["$ns:$dbk"] = true;
2639 }
2640 }
2641
2642 # Get the diff
2643 $templates_diff = array_diff_key( $poTemplates, $tlTemplates );
2644
2645 if ( count( $templates_diff ) > 0 ) {
2646 # Whee, link updates time.
2647 $u = new LinksUpdate( $this->mTitle, $parserOutput, false );
2648 $u->doUpdate();
2649 }
2650 }
2651
2652 /**
2653 * @deprecated since 1.18
2654 */
2655 public function quickEdit( $text, $comment = '', $minor = 0 ) {
2656 global $wgUser;
2657 return $this->doQuickEdit( $text, $wgUser, $comment, $minor );
2658 }
2659
2660 /**
2661 * @deprecated since 1.18
2662 */
2663 public function viewUpdates() {
2664 global $wgUser;
2665 return $this->doViewUpdates( $wgUser );
2666 }
2667
2668 /**
2669 * @deprecated since 1.18
2670 */
2671 public function useParserCache( $oldid ) {
2672 global $wgUser;
2673 return $this->isParserCacheUsed( $wgUser, $oldid );
2674 }
2675 }