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