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