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