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