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