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