Moved action=rollback to an Action subclass
[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->loadFromRow( $data );
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
341 $this->mTitle->loadFromRow( false );
342 }
343
344 $this->mDataLoaded = true;
345 }
346
347 /**
348 * @return int Page ID
349 */
350 public function getId() {
351 return $this->mTitle->getArticleID();
352 }
353
354 /**
355 * @return bool Whether or not the page exists in the database
356 */
357 public function exists() {
358 return $this->getId() > 0;
359 }
360
361 /**
362 * Check if this page is something we're going to be showing
363 * some sort of sensible content for. If we return false, page
364 * views (plain action=view) will return an HTTP 404 response,
365 * so spiders and robots can know they're following a bad link.
366 *
367 * @return bool
368 */
369 public function hasViewableContent() {
370 return $this->exists() || $this->mTitle->isAlwaysKnown();
371 }
372
373 /**
374 * @return int The view count for the page
375 */
376 public function getCount() {
377 if ( -1 == $this->mCounter ) {
378 $id = $this->getId();
379
380 if ( $id == 0 ) {
381 $this->mCounter = 0;
382 } else {
383 $dbr = wfGetDB( DB_SLAVE );
384 $this->mCounter = $dbr->selectField( 'page',
385 'page_counter',
386 array( 'page_id' => $id ),
387 __METHOD__
388 );
389 }
390 }
391
392 return $this->mCounter;
393 }
394
395 /**
396 * Determine whether a page would be suitable for being counted as an
397 * article in the site_stats table based on the title & its content
398 *
399 * @param $editInfo Object or false: object returned by prepareTextForEdit(),
400 * if false, the current database state will be used
401 * @return Boolean
402 */
403 public function isCountable( $editInfo = false ) {
404 global $wgArticleCountMethod;
405
406 if ( !$this->mTitle->isContentPage() ) {
407 return false;
408 }
409
410 $text = $editInfo ? $editInfo->pst : false;
411
412 if ( $this->isRedirect( $text ) ) {
413 return false;
414 }
415
416 switch ( $wgArticleCountMethod ) {
417 case 'any':
418 return true;
419 case 'comma':
420 if ( $text === false ) {
421 $text = $this->getRawText();
422 }
423 return strpos( $text, ',' ) !== false;
424 case 'link':
425 if ( $editInfo ) {
426 // ParserOutput::getLinks() is a 2D array of page links, so
427 // to be really correct we would need to recurse in the array
428 // but the main array should only have items in it if there are
429 // links.
430 return (bool)count( $editInfo->output->getLinks() );
431 } else {
432 return (bool)wfGetDB( DB_SLAVE )->selectField( 'pagelinks', 1,
433 array( 'pl_from' => $this->getId() ), __METHOD__ );
434 }
435 }
436 }
437
438 /**
439 * Tests if the article text represents a redirect
440 *
441 * @param $text mixed string containing article contents, or boolean
442 * @return bool
443 */
444 public function isRedirect( $text = false ) {
445 if ( $text === false ) {
446 if ( !$this->mDataLoaded ) {
447 $this->loadPageData();
448 }
449
450 return (bool)$this->mIsRedirect;
451 } else {
452 return Title::newFromRedirect( $text ) !== null;
453 }
454 }
455
456 /**
457 * Loads everything except the text
458 * This isn't necessary for all uses, so it's only done if needed.
459 */
460 protected function loadLastEdit() {
461 if ( $this->mLastRevision !== null ) {
462 return; // already loaded
463 }
464
465 $latest = $this->getLatest();
466 if ( !$latest ) {
467 return; // page doesn't exist or is missing page_latest info
468 }
469
470 $revision = Revision::newFromPageId( $this->getId(), $latest );
471 if ( $revision ) { // sanity
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 &&
1283 $this->mTitle->getRestrictionExpiry( $action ) != $expiry[$action] )
1284 {
1285 $changed = true;
1286 }
1287 }
1288 }
1289
1290 $current = self::flattenRestrictions( $current );
1291
1292 $changed = ( $changed || $current != $updated );
1293 $changed = $changed || ( $updated && $this->mTitle->areRestrictionsCascading() != $cascade );
1294 $protect = ( $updated != '' );
1295
1296 # If nothing's changed, do nothing
1297 if ( $changed ) {
1298 if ( wfRunHooks( 'ArticleProtect', array( &$this, &$user, $limit, $reason ) ) ) {
1299 $dbw = wfGetDB( DB_MASTER );
1300
1301 # Prepare a null revision to be added to the history
1302 $modified = $current != '' && $protect;
1303
1304 if ( $protect ) {
1305 $comment_type = $modified ? 'modifiedarticleprotection' : 'protectedarticle';
1306 } else {
1307 $comment_type = 'unprotectedarticle';
1308 }
1309
1310 $comment = $wgContLang->ucfirst( wfMsgForContent( $comment_type, $this->mTitle->getPrefixedText() ) );
1311
1312 # Only restrictions with the 'protect' right can cascade...
1313 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
1314 $editrestriction = isset( $limit['edit'] ) ? array( $limit['edit'] ) : $this->mTitle->getRestrictions( 'edit' );
1315
1316 # The schema allows multiple restrictions
1317 if ( !in_array( 'protect', $editrestriction ) && !in_array( 'sysop', $editrestriction ) ) {
1318 $cascade = false;
1319 }
1320
1321 $cascade_description = '';
1322
1323 if ( $cascade ) {
1324 $cascade_description = ' [' . wfMsgForContent( 'protect-summary-cascade' ) . ']';
1325 }
1326
1327 if ( $reason ) {
1328 $comment .= ": $reason";
1329 }
1330
1331 $editComment = $comment;
1332 $encodedExpiry = array();
1333 $protect_description = '';
1334 foreach ( $limit as $action => $restrictions ) {
1335 if ( !isset( $expiry[$action] ) )
1336 $expiry[$action] = $dbw->getInfinity();
1337
1338 $encodedExpiry[$action] = $dbw->encodeExpiry( $expiry[$action] );
1339 if ( $restrictions != '' ) {
1340 $protect_description .= "[$action=$restrictions] (";
1341 if ( $encodedExpiry[$action] != 'infinity' ) {
1342 $protect_description .= wfMsgForContent( 'protect-expiring',
1343 $wgContLang->timeanddate( $expiry[$action], false, false ) ,
1344 $wgContLang->date( $expiry[$action], false, false ) ,
1345 $wgContLang->time( $expiry[$action], false, false ) );
1346 } else {
1347 $protect_description .= wfMsgForContent( 'protect-expiry-indefinite' );
1348 }
1349
1350 $protect_description .= ') ';
1351 }
1352 }
1353 $protect_description = trim( $protect_description );
1354
1355 if ( $protect_description && $protect ) {
1356 $editComment .= " ($protect_description)";
1357 }
1358
1359 if ( $cascade ) {
1360 $editComment .= "$cascade_description";
1361 }
1362
1363 # Update restrictions table
1364 foreach ( $limit as $action => $restrictions ) {
1365 if ( $restrictions != '' ) {
1366 $dbw->replace( 'page_restrictions', array( array( 'pr_page', 'pr_type' ) ),
1367 array( 'pr_page' => $id,
1368 'pr_type' => $action,
1369 'pr_level' => $restrictions,
1370 'pr_cascade' => ( $cascade && $action == 'edit' ) ? 1 : 0,
1371 'pr_expiry' => $encodedExpiry[$action]
1372 ),
1373 __METHOD__
1374 );
1375 } else {
1376 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
1377 'pr_type' => $action ), __METHOD__ );
1378 }
1379 }
1380
1381 # Insert a null revision
1382 $nullRevision = Revision::newNullRevision( $dbw, $id, $editComment, true );
1383 $nullRevId = $nullRevision->insertOn( $dbw );
1384
1385 $latest = $this->getLatest();
1386 # Update page record
1387 $dbw->update( 'page',
1388 array( /* SET */
1389 'page_touched' => $dbw->timestamp(),
1390 'page_restrictions' => '',
1391 'page_latest' => $nullRevId
1392 ), array( /* WHERE */
1393 'page_id' => $id
1394 ), __METHOD__
1395 );
1396
1397 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $nullRevision, $latest, $user ) );
1398 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$user, $limit, $reason ) );
1399
1400 # Update the protection log
1401 $log = new LogPage( 'protect' );
1402 if ( $protect ) {
1403 $params = array( $protect_description, $cascade ? 'cascade' : '' );
1404 $log->addEntry( $modified ? 'modify' : 'protect', $this->mTitle, trim( $reason ), $params );
1405 } else {
1406 $log->addEntry( 'unprotect', $this->mTitle, $reason );
1407 }
1408 } # End hook
1409 } # End "changed" check
1410
1411 return true;
1412 }
1413
1414 /**
1415 * Take an array of page restrictions and flatten it to a string
1416 * suitable for insertion into the page_restrictions field.
1417 * @param $limit Array
1418 * @return String
1419 */
1420 protected static function flattenRestrictions( $limit ) {
1421 if ( !is_array( $limit ) ) {
1422 throw new MWException( 'WikiPage::flattenRestrictions given non-array restriction set' );
1423 }
1424
1425 $bits = array();
1426 ksort( $limit );
1427
1428 foreach ( $limit as $action => $restrictions ) {
1429 if ( $restrictions != '' ) {
1430 $bits[] = "$action=$restrictions";
1431 }
1432 }
1433
1434 return implode( ':', $bits );
1435 }
1436
1437 /**
1438 * @return bool whether or not the page surpasses $wgDeleteRevisionsLimit revisions
1439 */
1440 public function isBigDeletion() {
1441 global $wgDeleteRevisionsLimit;
1442
1443 if ( $wgDeleteRevisionsLimit ) {
1444 $revCount = $this->estimateRevisionCount();
1445
1446 return $revCount > $wgDeleteRevisionsLimit;
1447 }
1448
1449 return false;
1450 }
1451
1452 /**
1453 * @return int approximate revision count
1454 */
1455 public function estimateRevisionCount() {
1456 $dbr = wfGetDB( DB_SLAVE );
1457
1458 // For an exact count...
1459 // return $dbr->selectField( 'revision', 'COUNT(*)',
1460 // array( 'rev_page' => $this->getId() ), __METHOD__ );
1461 return $dbr->estimateRowCount( 'revision', '*',
1462 array( 'rev_page' => $this->getId() ), __METHOD__ );
1463 }
1464
1465 /**
1466 * Get the last N authors
1467 * @param $num Integer: number of revisions to get
1468 * @param $revLatest String: the latest rev_id, selected from the master (optional)
1469 * @return array Array of authors, duplicates not removed
1470 */
1471 public function getLastNAuthors( $num, $revLatest = 0 ) {
1472 wfProfileIn( __METHOD__ );
1473 // First try the slave
1474 // If that doesn't have the latest revision, try the master
1475 $continue = 2;
1476 $db = wfGetDB( DB_SLAVE );
1477
1478 do {
1479 $res = $db->select( array( 'page', 'revision' ),
1480 array( 'rev_id', 'rev_user_text' ),
1481 array(
1482 'page_namespace' => $this->mTitle->getNamespace(),
1483 'page_title' => $this->mTitle->getDBkey(),
1484 'rev_page = page_id'
1485 ), __METHOD__,
1486 array(
1487 'ORDER BY' => 'rev_timestamp DESC',
1488 'LIMIT' => $num
1489 )
1490 );
1491
1492 if ( !$res ) {
1493 wfProfileOut( __METHOD__ );
1494 return array();
1495 }
1496
1497 $row = $db->fetchObject( $res );
1498
1499 if ( $continue == 2 && $revLatest && $row->rev_id != $revLatest ) {
1500 $db = wfGetDB( DB_MASTER );
1501 $continue--;
1502 } else {
1503 $continue = 0;
1504 }
1505 } while ( $continue );
1506
1507 $authors = array( $row->rev_user_text );
1508
1509 foreach ( $res as $row ) {
1510 $authors[] = $row->rev_user_text;
1511 }
1512
1513 wfProfileOut( __METHOD__ );
1514 return $authors;
1515 }
1516
1517 /**
1518 * Back-end article deletion
1519 * Deletes the article with database consistency, writes logs, purges caches
1520 *
1521 * @param $reason string delete reason for deletion log
1522 * @param suppress bitfield
1523 * Revision::DELETED_TEXT
1524 * Revision::DELETED_COMMENT
1525 * Revision::DELETED_USER
1526 * Revision::DELETED_RESTRICTED
1527 * @param $id int article ID
1528 * @param $commit boolean defaults to true, triggers transaction end
1529 * @param &$errors Array of errors to append to
1530 * @param $user User The relevant user
1531 * @return boolean true if successful
1532 */
1533 public function doDeleteArticle(
1534 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User $user = null
1535 ) {
1536 global $wgDeferredUpdateList, $wgUseTrackbacks, $wgUser;
1537 $user = is_null( $user ) ? $wgUser : $user;
1538
1539 wfDebug( __METHOD__ . "\n" );
1540
1541 if ( ! wfRunHooks( 'ArticleDelete', array( &$this, &$user, &$reason, &$error ) ) ) {
1542 return false;
1543 }
1544 $dbw = wfGetDB( DB_MASTER );
1545 $t = $this->mTitle->getDBkey();
1546 $id = $id ? $id : $this->mTitle->getArticleID( Title::GAID_FOR_UPDATE );
1547
1548 if ( $t === '' || $id == 0 ) {
1549 return false;
1550 }
1551
1552 $u = new SiteStatsUpdate( 0, 1, - (int)$this->isCountable(), -1 );
1553 array_push( $wgDeferredUpdateList, $u );
1554
1555 // Bitfields to further suppress the content
1556 if ( $suppress ) {
1557 $bitfield = 0;
1558 // This should be 15...
1559 $bitfield |= Revision::DELETED_TEXT;
1560 $bitfield |= Revision::DELETED_COMMENT;
1561 $bitfield |= Revision::DELETED_USER;
1562 $bitfield |= Revision::DELETED_RESTRICTED;
1563 } else {
1564 $bitfield = 'rev_deleted';
1565 }
1566
1567 $dbw->begin();
1568 // For now, shunt the revision data into the archive table.
1569 // Text is *not* removed from the text table; bulk storage
1570 // is left intact to avoid breaking block-compression or
1571 // immutable storage schemes.
1572 //
1573 // For backwards compatibility, note that some older archive
1574 // table entries will have ar_text and ar_flags fields still.
1575 //
1576 // In the future, we may keep revisions and mark them with
1577 // the rev_deleted field, which is reserved for this purpose.
1578 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
1579 array(
1580 'ar_namespace' => 'page_namespace',
1581 'ar_title' => 'page_title',
1582 'ar_comment' => 'rev_comment',
1583 'ar_user' => 'rev_user',
1584 'ar_user_text' => 'rev_user_text',
1585 'ar_timestamp' => 'rev_timestamp',
1586 'ar_minor_edit' => 'rev_minor_edit',
1587 'ar_rev_id' => 'rev_id',
1588 'ar_text_id' => 'rev_text_id',
1589 'ar_text' => '\'\'', // Be explicit to appease
1590 'ar_flags' => '\'\'', // MySQL's "strict mode"...
1591 'ar_len' => 'rev_len',
1592 'ar_page_id' => 'page_id',
1593 'ar_deleted' => $bitfield
1594 ), array(
1595 'page_id' => $id,
1596 'page_id = rev_page'
1597 ), __METHOD__
1598 );
1599
1600 # Delete restrictions for it
1601 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__ );
1602
1603 # Now that it's safely backed up, delete it
1604 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__ );
1605 $ok = ( $dbw->affectedRows() > 0 ); // getArticleId() uses slave, could be laggy
1606
1607 if ( !$ok ) {
1608 $dbw->rollback();
1609 return false;
1610 }
1611
1612 # Fix category table counts
1613 $cats = array();
1614 $res = $dbw->select( 'categorylinks', 'cl_to', array( 'cl_from' => $id ), __METHOD__ );
1615
1616 foreach ( $res as $row ) {
1617 $cats [] = $row->cl_to;
1618 }
1619
1620 $this->updateCategoryCounts( array(), $cats );
1621
1622 # If using cascading deletes, we can skip some explicit deletes
1623 if ( !$dbw->cascadingDeletes() ) {
1624 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__ );
1625
1626 if ( $wgUseTrackbacks )
1627 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__ );
1628
1629 # Delete outgoing links
1630 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
1631 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
1632 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
1633 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
1634 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
1635 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
1636 $dbw->delete( 'iwlinks', array( 'iwl_from' => $id ) );
1637 $dbw->delete( 'redirect', array( 'rd_from' => $id ) );
1638 }
1639
1640 # If using cleanup triggers, we can skip some manual deletes
1641 if ( !$dbw->cleanupTriggers() ) {
1642 # Clean up recentchanges entries...
1643 $dbw->delete( 'recentchanges',
1644 array( 'rc_type != ' . RC_LOG,
1645 'rc_namespace' => $this->mTitle->getNamespace(),
1646 'rc_title' => $this->mTitle->getDBkey() ),
1647 __METHOD__ );
1648 $dbw->delete( 'recentchanges',
1649 array( 'rc_type != ' . RC_LOG, 'rc_cur_id' => $id ),
1650 __METHOD__ );
1651 }
1652
1653 # Clear caches
1654 self::onArticleDelete( $this->mTitle );
1655
1656 # Clear the cached article id so the interface doesn't act like we exist
1657 $this->mTitle->resetArticleID( 0 );
1658
1659 # Log the deletion, if the page was suppressed, log it at Oversight instead
1660 $logtype = $suppress ? 'suppress' : 'delete';
1661 $log = new LogPage( $logtype );
1662
1663 # Make sure logging got through
1664 $log->addEntry( 'delete', $this->mTitle, $reason, array() );
1665
1666 if ( $commit ) {
1667 $dbw->commit();
1668 }
1669
1670 wfRunHooks( 'ArticleDeleteComplete', array( &$this, &$user, $reason, $id ) );
1671 return true;
1672 }
1673
1674 /**
1675 * Roll back the most recent consecutive set of edits to a page
1676 * from the same user; fails if there are no eligible edits to
1677 * roll back to, e.g. user is the sole contributor. This function
1678 * performs permissions checks on $user, then calls commitRollback()
1679 * to do the dirty work
1680 *
1681 * @param $fromP String: Name of the user whose edits to rollback.
1682 * @param $summary String: Custom summary. Set to default summary if empty.
1683 * @param $token String: Rollback token.
1684 * @param $bot Boolean: If true, mark all reverted edits as bot.
1685 *
1686 * @param $resultDetails Array: contains result-specific array of additional values
1687 * 'alreadyrolled' : 'current' (rev)
1688 * success : 'summary' (str), 'current' (rev), 'target' (rev)
1689 *
1690 * @param $user User The user performing the rollback
1691 * @return array of errors, each error formatted as
1692 * array(messagekey, param1, param2, ...).
1693 * On success, the array is empty. This array can also be passed to
1694 * OutputPage::showPermissionsErrorPage().
1695 */
1696 public function doRollback(
1697 $fromP, $summary, $token, $bot, &$resultDetails, User $user = null
1698 ) {
1699 global $wgUser;
1700 $user = is_null( $user ) ? $wgUser : $user;
1701
1702 $resultDetails = null;
1703
1704 # Check permissions
1705 $editErrors = $this->mTitle->getUserPermissionsErrors( 'edit', $user );
1706 $rollbackErrors = $this->mTitle->getUserPermissionsErrors( 'rollback', $user );
1707 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
1708
1709 if ( !$user->matchEditToken( $token, array( $this->mTitle->getPrefixedText(), $fromP ) ) ) {
1710 $errors[] = array( 'sessionfailure' );
1711 }
1712
1713 if ( $user->pingLimiter( 'rollback' ) || $user->pingLimiter() ) {
1714 $errors[] = array( 'actionthrottledtext' );
1715 }
1716
1717 # If there were errors, bail out now
1718 if ( !empty( $errors ) ) {
1719 return $errors;
1720 }
1721
1722 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user );
1723 }
1724
1725 /**
1726 * Backend implementation of doRollback(), please refer there for parameter
1727 * and return value documentation
1728 *
1729 * NOTE: This function does NOT check ANY permissions, it just commits the
1730 * rollback to the DB Therefore, you should only call this function direct-
1731 * ly if you want to use custom permissions checks. If you don't, use
1732 * doRollback() instead.
1733 * @param $fromP String: Name of the user whose edits to rollback.
1734 * @param $summary String: Custom summary. Set to default summary if empty.
1735 * @param $bot Boolean: If true, mark all reverted edits as bot.
1736 *
1737 * @param $resultDetails Array: contains result-specific array of additional values
1738 * @param $guser User The user performing the rollback
1739 */
1740 public function commitRollback( $fromP, $summary, $bot, &$resultDetails, User $guser = null ) {
1741 global $wgUseRCPatrol, $wgUser, $wgContLang;
1742 $guser = is_null( $guser ) ? $wgUser : $guser;
1743
1744 $dbw = wfGetDB( DB_MASTER );
1745
1746 if ( wfReadOnly() ) {
1747 return array( array( 'readonlytext' ) );
1748 }
1749
1750 # Get the last editor
1751 $current = Revision::newFromTitle( $this->mTitle );
1752 if ( is_null( $current ) ) {
1753 # Something wrong... no page?
1754 return array( array( 'notanarticle' ) );
1755 }
1756
1757 $from = str_replace( '_', ' ', $fromP );
1758 # User name given should match up with the top revision.
1759 # If the user was deleted then $from should be empty.
1760 if ( $from != $current->getUserText() ) {
1761 $resultDetails = array( 'current' => $current );
1762 return array( array( 'alreadyrolled',
1763 htmlspecialchars( $this->mTitle->getPrefixedText() ),
1764 htmlspecialchars( $fromP ),
1765 htmlspecialchars( $current->getUserText() )
1766 ) );
1767 }
1768
1769 # Get the last edit not by this guy...
1770 # Note: these may not be public values
1771 $user = intval( $current->getRawUser() );
1772 $user_text = $dbw->addQuotes( $current->getRawUserText() );
1773 $s = $dbw->selectRow( 'revision',
1774 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
1775 array( 'rev_page' => $current->getPage(),
1776 "rev_user != {$user} OR rev_user_text != {$user_text}"
1777 ), __METHOD__,
1778 array( 'USE INDEX' => 'page_timestamp',
1779 'ORDER BY' => 'rev_timestamp DESC' )
1780 );
1781 if ( $s === false ) {
1782 # No one else ever edited this page
1783 return array( array( 'cantrollback' ) );
1784 } elseif ( $s->rev_deleted & Revision::DELETED_TEXT || $s->rev_deleted & Revision::DELETED_USER ) {
1785 # Only admins can see this text
1786 return array( array( 'notvisiblerev' ) );
1787 }
1788
1789 $set = array();
1790 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
1791 # Mark all reverted edits as bot
1792 $set['rc_bot'] = 1;
1793 }
1794
1795 if ( $wgUseRCPatrol ) {
1796 # Mark all reverted edits as patrolled
1797 $set['rc_patrolled'] = 1;
1798 }
1799
1800 if ( count( $set ) ) {
1801 $dbw->update( 'recentchanges', $set,
1802 array( /* WHERE */
1803 'rc_cur_id' => $current->getPage(),
1804 'rc_user_text' => $current->getUserText(),
1805 "rc_timestamp > '{$s->rev_timestamp}'",
1806 ), __METHOD__
1807 );
1808 }
1809
1810 # Generate the edit summary if necessary
1811 $target = Revision::newFromId( $s->rev_id );
1812 if ( empty( $summary ) ) {
1813 if ( $from == '' ) { // no public user name
1814 $summary = wfMsgForContent( 'revertpage-nouser' );
1815 } else {
1816 $summary = wfMsgForContent( 'revertpage' );
1817 }
1818 }
1819
1820 # Allow the custom summary to use the same args as the default message
1821 $args = array(
1822 $target->getUserText(), $from, $s->rev_id,
1823 $wgContLang->timeanddate( wfTimestamp( TS_MW, $s->rev_timestamp ) ),
1824 $current->getId(), $wgContLang->timeanddate( $current->getTimestamp() )
1825 );
1826 $summary = wfMsgReplaceArgs( $summary, $args );
1827
1828 # Save
1829 $flags = EDIT_UPDATE;
1830
1831 if ( $guser->isAllowed( 'minoredit' ) ) {
1832 $flags |= EDIT_MINOR;
1833 }
1834
1835 if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
1836 $flags |= EDIT_FORCE_BOT;
1837 }
1838
1839 # Actually store the edit
1840 $status = $this->doEdit( $target->getText(), $summary, $flags, $target->getId() );
1841 if ( !empty( $status->value['revision'] ) ) {
1842 $revId = $status->value['revision']->getId();
1843 } else {
1844 $revId = false;
1845 }
1846
1847 wfRunHooks( 'ArticleRollbackComplete', array( $this, $guser, $target, $current ) );
1848
1849 $resultDetails = array(
1850 'summary' => $summary,
1851 'current' => $current,
1852 'target' => $target,
1853 'newid' => $revId
1854 );
1855
1856 return array();
1857 }
1858
1859 /**
1860 * Do standard deferred updates after page view
1861 * @param $user User The relevant user
1862 */
1863 public function doViewUpdates( User $user ) {
1864 global $wgDeferredUpdateList, $wgDisableCounters;
1865 if ( wfReadOnly() ) {
1866 return;
1867 }
1868
1869 # Don't update page view counters on views from bot users (bug 14044)
1870 if ( !$wgDisableCounters && !$user->isAllowed( 'bot' ) && $this->getId() ) {
1871 $wgDeferredUpdateList[] = new ViewCountUpdate( $this->getId() );
1872 $wgDeferredUpdateList[] = new SiteStatsUpdate( 1, 0, 0 );
1873 }
1874
1875 # Update newtalk / watchlist notification status
1876 $user->clearNotification( $this->mTitle );
1877 }
1878
1879 /**
1880 * Prepare text which is about to be saved.
1881 * Returns a stdclass with source, pst and output members
1882 */
1883 public function prepareTextForEdit( $text, $revid = null, User $user = null ) {
1884 global $wgParser, $wgUser;
1885 $user = is_null( $user ) ? $wgUser : $user;
1886 // @TODO fixme: check $user->getId() here???
1887 if ( $this->mPreparedEdit
1888 && $this->mPreparedEdit->newText == $text
1889 && $this->mPreparedEdit->revid == $revid
1890 ) {
1891 // Already prepared
1892 return $this->mPreparedEdit;
1893 }
1894
1895 $popts = ParserOptions::newFromUser( $user );
1896 wfRunHooks( 'ArticlePrepareTextForEdit', array( $this, $popts ) );
1897
1898 $edit = (object)array();
1899 $edit->revid = $revid;
1900 $edit->newText = $text;
1901 $edit->pst = $this->preSaveTransform( $text, $user, $popts );
1902 $edit->popts = $this->getParserOptions( true );
1903 $edit->output = $wgParser->parse( $edit->pst, $this->mTitle, $edit->popts, true, true, $revid );
1904 $edit->oldText = $this->getRawText();
1905
1906 $this->mPreparedEdit = $edit;
1907
1908 return $edit;
1909 }
1910
1911 /**
1912 * Do standard deferred updates after page edit.
1913 * Update links tables, site stats, search index and message cache.
1914 * Purges pages that include this page if the text was changed here.
1915 * Every 100th edit, prune the recent changes table.
1916 *
1917 * @private
1918 * @param $revision Revision object
1919 * @param $user User object that did the revision
1920 * @param $options Array of options, following indexes are used:
1921 * - changed: boolean, whether the revision changed the content (default true)
1922 * - created: boolean, whether the revision created the page (default false)
1923 * - oldcountable: boolean or null (default null):
1924 * - boolean: whether the page was counted as an article before that
1925 * revision, only used in changed is true and created is false
1926 * - null: don't change the article count
1927 */
1928 public function doEditUpdates( Revision $revision, User $user, array $options = array() ) {
1929 global $wgDeferredUpdateList, $wgEnableParserCache;
1930
1931 wfProfileIn( __METHOD__ );
1932
1933 $options += array( 'changed' => true, 'created' => false, 'oldcountable' => null );
1934 $text = $revision->getText();
1935
1936 # Parse the text
1937 # Be careful not to double-PST: $text is usually already PST-ed once
1938 if ( !$this->mPreparedEdit || $this->mPreparedEdit->output->getFlag( 'vary-revision' ) ) {
1939 wfDebug( __METHOD__ . ": No prepared edit or vary-revision is set...\n" );
1940 $editInfo = $this->prepareTextForEdit( $text, $revision->getId(), $user );
1941 } else {
1942 wfDebug( __METHOD__ . ": No vary-revision, using prepared edit...\n" );
1943 $editInfo = $this->mPreparedEdit;
1944 }
1945
1946 # Save it to the parser cache
1947 if ( $wgEnableParserCache ) {
1948 $parserCache = ParserCache::singleton();
1949 $parserCache->save( $editInfo->output, $this, $editInfo->popts );
1950 }
1951
1952 # Update the links tables
1953 $u = new LinksUpdate( $this->mTitle, $editInfo->output );
1954 $u->doUpdate();
1955
1956 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $options['changed'] ) );
1957
1958 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
1959 if ( 0 == mt_rand( 0, 99 ) ) {
1960 // Flush old entries from the `recentchanges` table; we do this on
1961 // random requests so as to avoid an increase in writes for no good reason
1962 global $wgRCMaxAge;
1963
1964 $dbw = wfGetDB( DB_MASTER );
1965 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
1966 $dbw->delete(
1967 'recentchanges',
1968 array( "rc_timestamp < '$cutoff'" ),
1969 __METHOD__
1970 );
1971 }
1972 }
1973
1974 $id = $this->getId();
1975 $title = $this->mTitle->getPrefixedDBkey();
1976 $shortTitle = $this->mTitle->getDBkey();
1977
1978 if ( 0 == $id ) {
1979 wfProfileOut( __METHOD__ );
1980 return;
1981 }
1982
1983 if ( !$options['changed'] ) {
1984 $good = 0;
1985 $total = 0;
1986 } elseif ( $options['created'] ) {
1987 $good = (int)$this->isCountable( $editInfo );
1988 $total = 1;
1989 } elseif ( $options['oldcountable'] !== null ) {
1990 $good = (int)$this->isCountable( $editInfo ) - (int)$options['oldcountable'];
1991 $total = 0;
1992 } else {
1993 $good = 0;
1994 $total = 0;
1995 }
1996
1997 $wgDeferredUpdateList[] = new SiteStatsUpdate( 0, 1, $good, $total );
1998 $wgDeferredUpdateList[] = new SearchUpdate( $id, $title, $text );
1999
2000 # If this is another user's talk page, update newtalk.
2001 # Don't do this if $options['changed'] = false (null-edits) nor if
2002 # it's a minor edit and the user doesn't want notifications for those.
2003 if ( $options['changed']
2004 && $this->mTitle->getNamespace() == NS_USER_TALK
2005 && $shortTitle != $user->getTitleKey()
2006 && !( $revision->isMinor() && $user->isAllowed( 'nominornewtalk' ) )
2007 ) {
2008 if ( wfRunHooks( 'ArticleEditUpdateNewTalk', array( &$this ) ) ) {
2009 $other = User::newFromName( $shortTitle, false );
2010 if ( !$other ) {
2011 wfDebug( __METHOD__ . ": invalid username\n" );
2012 } elseif ( User::isIP( $shortTitle ) ) {
2013 // An anonymous user
2014 $other->setNewtalk( true );
2015 } elseif ( $other->isLoggedIn() ) {
2016 $other->setNewtalk( true );
2017 } else {
2018 wfDebug( __METHOD__ . ": don't need to notify a nonexistent user\n" );
2019 }
2020 }
2021 }
2022
2023 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
2024 MessageCache::singleton()->replace( $shortTitle, $text );
2025 }
2026
2027 if( $options['created'] ) {
2028 self::onArticleCreate( $this->mTitle );
2029 } else {
2030 self::onArticleEdit( $this->mTitle );
2031 }
2032
2033 wfProfileOut( __METHOD__ );
2034 }
2035
2036 /**
2037 * Perform article updates on a special page creation.
2038 *
2039 * @param $rev Revision object
2040 *
2041 * @todo This is a shitty interface function. Kill it and replace the
2042 * other shitty functions like doEditUpdates and such so it's not needed
2043 * anymore.
2044 * @deprecated since 1.19, use doEditUpdates()
2045 */
2046 public function createUpdates( $rev ) {
2047 global $wgUser;
2048 $this->doEditUpdates( $rev, $wgUser, array( 'created' => true ) );
2049 }
2050
2051 /**
2052 * This function is called right before saving the wikitext,
2053 * so we can do things like signatures and links-in-context.
2054 *
2055 * @param $text String article contents
2056 * @param $user User object: user doing the edit
2057 * @param $popts ParserOptions object: parser options, default options for
2058 * the user loaded if null given
2059 * @return string article contents with altered wikitext markup (signatures
2060 * converted, {{subst:}}, templates, etc.)
2061 */
2062 public function preSaveTransform( $text, User $user = null, ParserOptions $popts = null ) {
2063 global $wgParser, $wgUser;
2064 $user = is_null( $user ) ? $wgUser : $user;
2065
2066 if ( $popts === null ) {
2067 $popts = ParserOptions::newFromUser( $user );
2068 }
2069
2070 return $wgParser->preSaveTransform( $text, $this->mTitle, $user, $popts );
2071 }
2072
2073 /**
2074 * Loads page_touched and returns a value indicating if it should be used
2075 * @return boolean true if not a redirect
2076 */
2077 public function checkTouched() {
2078 if ( !$this->mDataLoaded ) {
2079 $this->loadPageData();
2080 }
2081 return !$this->mIsRedirect;
2082 }
2083
2084 /**
2085 * Get the page_touched field
2086 * @return string containing GMT timestamp
2087 */
2088 public function getTouched() {
2089 if ( !$this->mDataLoaded ) {
2090 $this->loadPageData();
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 return (int)$this->mLatest;
2104 }
2105
2106 /**
2107 * Edit an article without doing all that other stuff
2108 * The article must already exist; link tables etc
2109 * are not updated, caches are not flushed.
2110 *
2111 * @param $text String: text submitted
2112 * @param $user User The relevant user
2113 * @param $comment String: comment submitted
2114 * @param $minor Boolean: whereas it's a minor modification
2115 */
2116 public function doQuickEdit( $text, User $user, $comment = '', $minor = 0 ) {
2117 wfProfileIn( __METHOD__ );
2118
2119 $dbw = wfGetDB( DB_MASTER );
2120 $revision = new Revision( array(
2121 'page' => $this->getId(),
2122 'text' => $text,
2123 'comment' => $comment,
2124 'minor_edit' => $minor ? 1 : 0,
2125 ) );
2126 $revision->insertOn( $dbw );
2127 $this->updateRevisionOn( $dbw, $revision );
2128
2129 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
2130
2131 wfProfileOut( __METHOD__ );
2132 }
2133
2134 /**
2135 * The onArticle*() functions are supposed to be a kind of hooks
2136 * which should be called whenever any of the specified actions
2137 * are done.
2138 *
2139 * This is a good place to put code to clear caches, for instance.
2140 *
2141 * This is called on page move and undelete, as well as edit
2142 *
2143 * @param $title Title object
2144 */
2145 public static function onArticleCreate( $title ) {
2146 # Update existence markers on article/talk tabs...
2147 if ( $title->isTalkPage() ) {
2148 $other = $title->getSubjectPage();
2149 } else {
2150 $other = $title->getTalkPage();
2151 }
2152
2153 $other->invalidateCache();
2154 $other->purgeSquid();
2155
2156 $title->touchLinks();
2157 $title->purgeSquid();
2158 $title->deleteTitleProtection();
2159 }
2160
2161 /**
2162 * Clears caches when article is deleted
2163 *
2164 * @param $title Title
2165 */
2166 public static function onArticleDelete( $title ) {
2167 # Update existence markers on article/talk tabs...
2168 if ( $title->isTalkPage() ) {
2169 $other = $title->getSubjectPage();
2170 } else {
2171 $other = $title->getTalkPage();
2172 }
2173
2174 $other->invalidateCache();
2175 $other->purgeSquid();
2176
2177 $title->touchLinks();
2178 $title->purgeSquid();
2179
2180 # File cache
2181 HTMLFileCache::clearFileCache( $title );
2182
2183 # Messages
2184 if ( $title->getNamespace() == NS_MEDIAWIKI ) {
2185 MessageCache::singleton()->replace( $title->getDBkey(), false );
2186 }
2187
2188 # Images
2189 if ( $title->getNamespace() == NS_FILE ) {
2190 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
2191 $update->doUpdate();
2192 }
2193
2194 # User talk pages
2195 if ( $title->getNamespace() == NS_USER_TALK ) {
2196 $user = User::newFromName( $title->getText(), false );
2197 $user->setNewtalk( false );
2198 }
2199
2200 # Image redirects
2201 RepoGroup::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
2202 }
2203
2204 /**
2205 * Purge caches on page update etc
2206 *
2207 * @param $title Title object
2208 * @todo: verify that $title is always a Title object (and never false or null), add Title hint to parameter $title
2209 */
2210 public static function onArticleEdit( $title ) {
2211 global $wgDeferredUpdateList;
2212
2213 // Invalidate caches of articles which include this page
2214 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'templatelinks' );
2215
2216 // Invalidate the caches of all pages which redirect here
2217 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'redirect' );
2218
2219 # Purge squid for this page only
2220 $title->purgeSquid();
2221
2222 # Clear file cache for this page only
2223 HTMLFileCache::clearFileCache( $title );
2224 }
2225
2226 /**#@-*/
2227
2228 /**
2229 * Return a list of templates used by this article.
2230 * Uses the templatelinks table
2231 *
2232 * @return Array of Title objects
2233 */
2234 public function getUsedTemplates() {
2235 $result = array();
2236 $id = $this->mTitle->getArticleID();
2237
2238 if ( $id == 0 ) {
2239 return array();
2240 }
2241
2242 $dbr = wfGetDB( DB_SLAVE );
2243 $res = $dbr->select( array( 'templatelinks' ),
2244 array( 'tl_namespace', 'tl_title' ),
2245 array( 'tl_from' => $id ),
2246 __METHOD__ );
2247
2248 if ( $res !== false ) {
2249 foreach ( $res as $row ) {
2250 $result[] = Title::makeTitle( $row->tl_namespace, $row->tl_title );
2251 }
2252 }
2253
2254 return $result;
2255 }
2256
2257 /**
2258 * Returns a list of hidden categories this page is a member of.
2259 * Uses the page_props and categorylinks tables.
2260 *
2261 * @return Array of Title objects
2262 */
2263 public function getHiddenCategories() {
2264 $result = array();
2265 $id = $this->mTitle->getArticleID();
2266
2267 if ( $id == 0 ) {
2268 return array();
2269 }
2270
2271 $dbr = wfGetDB( DB_SLAVE );
2272 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
2273 array( 'cl_to' ),
2274 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
2275 'page_namespace' => NS_CATEGORY, 'page_title=cl_to' ),
2276 __METHOD__ );
2277
2278 if ( $res !== false ) {
2279 foreach ( $res as $row ) {
2280 $result[] = Title::makeTitle( NS_CATEGORY, $row->cl_to );
2281 }
2282 }
2283
2284 return $result;
2285 }
2286
2287 /**
2288 * Return an applicable autosummary if one exists for the given edit.
2289 * @param $oldtext String: the previous text of the page.
2290 * @param $newtext String: The submitted text of the page.
2291 * @param $flags Int bitmask: a bitmask of flags submitted for the edit.
2292 * @return string An appropriate autosummary, or an empty string.
2293 */
2294 public static function getAutosummary( $oldtext, $newtext, $flags ) {
2295 global $wgContLang;
2296
2297 # Decide what kind of autosummary is needed.
2298
2299 # Redirect autosummaries
2300 $ot = Title::newFromRedirect( $oldtext );
2301 $rt = Title::newFromRedirect( $newtext );
2302
2303 if ( is_object( $rt ) && ( !is_object( $ot ) || !$rt->equals( $ot ) || $ot->getFragment() != $rt->getFragment() ) ) {
2304 return wfMsgForContent( 'autoredircomment', $rt->getFullText() );
2305 }
2306
2307 # New page autosummaries
2308 if ( $flags & EDIT_NEW && strlen( $newtext ) ) {
2309 # If they're making a new article, give its text, truncated, in the summary.
2310
2311 $truncatedtext = $wgContLang->truncate(
2312 str_replace( "\n", ' ', $newtext ),
2313 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new' ) ) ) );
2314
2315 return wfMsgForContent( 'autosumm-new', $truncatedtext );
2316 }
2317
2318 # Blanking autosummaries
2319 if ( $oldtext != '' && $newtext == '' ) {
2320 return wfMsgForContent( 'autosumm-blank' );
2321 } elseif ( strlen( $oldtext ) > 10 * strlen( $newtext ) && strlen( $newtext ) < 500 ) {
2322 # Removing more than 90% of the article
2323
2324 $truncatedtext = $wgContLang->truncate(
2325 $newtext,
2326 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) ) );
2327
2328 return wfMsgForContent( 'autosumm-replace', $truncatedtext );
2329 }
2330
2331 # If we reach this point, there's no applicable autosummary for our case, so our
2332 # autosummary is empty.
2333 return '';
2334 }
2335
2336 /**
2337 * Get parser options suitable for rendering the primary article wikitext
2338 * @param $canonical boolean Determines that the generated options must not depend on user preferences (see bug 14404)
2339 * @return mixed ParserOptions object or boolean false
2340 */
2341 public function getParserOptions( $canonical = false ) {
2342 global $wgUser, $wgLanguageCode;
2343
2344 if ( !$this->mParserOptions || $canonical ) {
2345 $user = !$canonical ? $wgUser : new User;
2346 $parserOptions = new ParserOptions( $user );
2347 $parserOptions->setTidy( true );
2348 $parserOptions->enableLimitReport();
2349
2350 if ( $canonical ) {
2351 $parserOptions->setUserLang( $wgLanguageCode ); # Must be set explicitely
2352 return $parserOptions;
2353 }
2354 $this->mParserOptions = $parserOptions;
2355 }
2356 // Clone to allow modifications of the return value without affecting cache
2357 return clone $this->mParserOptions;
2358 }
2359
2360 /**
2361 * Get parser options suitable for rendering the primary article wikitext
2362 * @param User $user
2363 * @return ParserOptions
2364 */
2365 public function makeParserOptions( User $user ) {
2366 $options = ParserOptions::newFromUser( $user );
2367 $options->enableLimitReport(); // show inclusion/loop reports
2368 $options->setTidy( true ); // fix bad HTML
2369 return $options;
2370 }
2371
2372 /**
2373 * Update all the appropriate counts in the category table, given that
2374 * we've added the categories $added and deleted the categories $deleted.
2375 *
2376 * @param $added array The names of categories that were added
2377 * @param $deleted array The names of categories that were deleted
2378 */
2379 public function updateCategoryCounts( $added, $deleted ) {
2380 $ns = $this->mTitle->getNamespace();
2381 $dbw = wfGetDB( DB_MASTER );
2382
2383 # First make sure the rows exist. If one of the "deleted" ones didn't
2384 # exist, we might legitimately not create it, but it's simpler to just
2385 # create it and then give it a negative value, since the value is bogus
2386 # anyway.
2387 #
2388 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
2389 $insertCats = array_merge( $added, $deleted );
2390 if ( !$insertCats ) {
2391 # Okay, nothing to do
2392 return;
2393 }
2394
2395 $insertRows = array();
2396
2397 foreach ( $insertCats as $cat ) {
2398 $insertRows[] = array(
2399 'cat_id' => $dbw->nextSequenceValue( 'category_cat_id_seq' ),
2400 'cat_title' => $cat
2401 );
2402 }
2403 $dbw->insert( 'category', $insertRows, __METHOD__, 'IGNORE' );
2404
2405 $addFields = array( 'cat_pages = cat_pages + 1' );
2406 $removeFields = array( 'cat_pages = cat_pages - 1' );
2407
2408 if ( $ns == NS_CATEGORY ) {
2409 $addFields[] = 'cat_subcats = cat_subcats + 1';
2410 $removeFields[] = 'cat_subcats = cat_subcats - 1';
2411 } elseif ( $ns == NS_FILE ) {
2412 $addFields[] = 'cat_files = cat_files + 1';
2413 $removeFields[] = 'cat_files = cat_files - 1';
2414 }
2415
2416 if ( $added ) {
2417 $dbw->update(
2418 'category',
2419 $addFields,
2420 array( 'cat_title' => $added ),
2421 __METHOD__
2422 );
2423 }
2424
2425 if ( $deleted ) {
2426 $dbw->update(
2427 'category',
2428 $removeFields,
2429 array( 'cat_title' => $deleted ),
2430 __METHOD__
2431 );
2432 }
2433 }
2434
2435 /*
2436 * @deprecated since 1.19
2437 */
2438 public function quickEdit( $text, $comment = '', $minor = 0 ) {
2439 global $wgUser;
2440 return $this->doQuickEdit( $text, $wgUser, $comment, $minor );
2441 }
2442
2443 /*
2444 * @deprecated since 1.19
2445 */
2446 public function viewUpdates() {
2447 global $wgUser;
2448 return $this->doViewUpdates( $wgUser );
2449 }
2450
2451 /*
2452 * @deprecated since 1.19
2453 */
2454 public function useParserCache( $oldid ) {
2455 global $wgUser;
2456 return $this->isParserCacheUsed( $wgUser, $oldid );
2457 }
2458 }