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