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