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