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