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