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