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