Reverted r108743 per CR comment. This should at least be discussed first.
[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 && $lastRevIsRedirect === false ) {
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 wfProfileOut( __METHOD__ );
1121 return null;
1122 }
1123 } else {
1124 $dbw = wfGetDB( DB_MASTER );
1125 $rev = Revision::loadFromTimestamp( $dbw, $this->mTitle, $edittime );
1126
1127 if ( !$rev ) {
1128 wfDebug( "WikiPage::replaceSection asked for bogus section (page: " .
1129 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1130 wfProfileOut( __METHOD__ );
1131 return null;
1132 }
1133
1134 $oldtext = $rev->getText();
1135 }
1136
1137 if ( $section == 'new' ) {
1138 # Inserting a new section
1139 $subject = $sectionTitle ? wfMsgForContent( 'newsectionheaderdefaultlevel', $sectionTitle ) . "\n\n" : '';
1140 if ( wfRunHooks( 'PlaceNewSection', array( $this, $oldtext, $subject, &$text ) ) ) {
1141 $text = strlen( trim( $oldtext ) ) > 0
1142 ? "{$oldtext}\n\n{$subject}{$text}"
1143 : "{$subject}{$text}";
1144 }
1145 } else {
1146 # Replacing an existing section; roll out the big guns
1147 global $wgParser;
1148
1149 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1150 }
1151 }
1152
1153 wfProfileOut( __METHOD__ );
1154 return $text;
1155 }
1156
1157 /**
1158 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1159 * @param $flags Int
1160 * @return Int updated $flags
1161 */
1162 function checkFlags( $flags ) {
1163 if ( !( $flags & EDIT_NEW ) && !( $flags & EDIT_UPDATE ) ) {
1164 if ( $this->mTitle->getArticleID() ) {
1165 $flags |= EDIT_UPDATE;
1166 } else {
1167 $flags |= EDIT_NEW;
1168 }
1169 }
1170
1171 return $flags;
1172 }
1173
1174 /**
1175 * Change an existing article or create a new article. Updates RC and all necessary caches,
1176 * optionally via the deferred update array.
1177 *
1178 * @param $text String: new text
1179 * @param $summary String: edit summary
1180 * @param $flags Integer bitfield:
1181 * EDIT_NEW
1182 * Article is known or assumed to be non-existent, create a new one
1183 * EDIT_UPDATE
1184 * Article is known or assumed to be pre-existing, update it
1185 * EDIT_MINOR
1186 * Mark this edit minor, if the user is allowed to do so
1187 * EDIT_SUPPRESS_RC
1188 * Do not log the change in recentchanges
1189 * EDIT_FORCE_BOT
1190 * Mark the edit a "bot" edit regardless of user rights
1191 * EDIT_DEFER_UPDATES
1192 * Defer some of the updates until the end of index.php
1193 * EDIT_AUTOSUMMARY
1194 * Fill in blank summaries with generated text where possible
1195 *
1196 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1197 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return an
1198 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1199 * edit-already-exists error will be returned. These two conditions are also possible with
1200 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1201 *
1202 * @param $baseRevId the revision ID this edit was based off, if any
1203 * @param $user User the user doing the edit
1204 *
1205 * @return Status object. Possible errors:
1206 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1207 * edit-gone-missing: In update mode, but the article didn't exist
1208 * edit-conflict: In update mode, the article changed unexpectedly
1209 * edit-no-change: Warning that the text was the same as before
1210 * edit-already-exists: In creation mode, but the article already exists
1211 *
1212 * Extensions may define additional errors.
1213 *
1214 * $return->value will contain an associative array with members as follows:
1215 * new: Boolean indicating if the function attempted to create a new article
1216 * revision: The revision object for the inserted revision, or null
1217 *
1218 * Compatibility note: this function previously returned a boolean value indicating success/failure
1219 */
1220 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
1221 global $wgUser, $wgDBtransactions, $wgUseAutomaticEditSummaries;
1222
1223 # Low-level sanity check
1224 if ( $this->mTitle->getText() === '' ) {
1225 throw new MWException( 'Something is trying to edit an article with an empty title' );
1226 }
1227
1228 wfProfileIn( __METHOD__ );
1229
1230 $user = is_null( $user ) ? $wgUser : $user;
1231 $status = Status::newGood( array() );
1232
1233 # Load $this->mTitle->getArticleID() and $this->mLatest if it's not already
1234 $this->loadPageData( 'fromdbmaster' );
1235
1236 $flags = $this->checkFlags( $flags );
1237
1238 if ( !wfRunHooks( 'ArticleSave', array( &$this, &$user, &$text, &$summary,
1239 $flags & EDIT_MINOR, null, null, &$flags, &$status ) ) )
1240 {
1241 wfDebug( __METHOD__ . ": ArticleSave hook aborted save!\n" );
1242
1243 if ( $status->isOK() ) {
1244 $status->fatal( 'edit-hook-aborted' );
1245 }
1246
1247 wfProfileOut( __METHOD__ );
1248 return $status;
1249 }
1250
1251 # Silently ignore EDIT_MINOR if not allowed
1252 $isminor = ( $flags & EDIT_MINOR ) && $user->isAllowed( 'minoredit' );
1253 $bot = $flags & EDIT_FORCE_BOT;
1254
1255 $oldtext = $this->getRawText(); // current revision
1256 $oldsize = strlen( $oldtext );
1257 $oldid = $this->getLatest();
1258 $oldIsRedirect = $this->isRedirect();
1259 $oldcountable = $this->isCountable();
1260
1261 # Provide autosummaries if one is not provided and autosummaries are enabled.
1262 if ( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY && $summary == '' ) {
1263 $summary = self::getAutosummary( $oldtext, $text, $flags );
1264 }
1265
1266 $editInfo = $this->prepareTextForEdit( $text, null, $user );
1267 $text = $editInfo->pst;
1268 $newsize = strlen( $text );
1269
1270 $dbw = wfGetDB( DB_MASTER );
1271 $now = wfTimestampNow();
1272 $this->mTimestamp = $now;
1273
1274 if ( $flags & EDIT_UPDATE ) {
1275 # Update article, but only if changed.
1276 $status->value['new'] = false;
1277
1278 # Make sure the revision is either completely inserted or not inserted at all
1279 if ( !$wgDBtransactions ) {
1280 $userAbort = ignore_user_abort( true );
1281 }
1282
1283 $revision = new Revision( array(
1284 'page' => $this->getId(),
1285 'comment' => $summary,
1286 'minor_edit' => $isminor,
1287 'text' => $text,
1288 'parent_id' => $oldid,
1289 'user' => $user->getId(),
1290 'user_text' => $user->getName(),
1291 'timestamp' => $now
1292 ) );
1293
1294 $changed = ( strcmp( $text, $oldtext ) != 0 );
1295
1296 if ( $changed ) {
1297 if ( !$this->mLatest ) {
1298 # Article gone missing
1299 wfDebug( __METHOD__ . ": EDIT_UPDATE specified but article doesn't exist\n" );
1300 $status->fatal( 'edit-gone-missing' );
1301
1302 wfProfileOut( __METHOD__ );
1303 return $status;
1304 }
1305
1306 $dbw->begin();
1307 $revisionId = $revision->insertOn( $dbw );
1308
1309 # Update page
1310 #
1311 # Note that we use $this->mLatest instead of fetching a value from the master DB
1312 # during the course of this function. This makes sure that EditPage can detect
1313 # edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
1314 # before this function is called. A previous function used a separate query, this
1315 # creates a window where concurrent edits can cause an ignored edit conflict.
1316 $ok = $this->updateRevisionOn( $dbw, $revision, $oldid, $oldIsRedirect );
1317
1318 if ( !$ok ) {
1319 /* Belated edit conflict! Run away!! */
1320 $status->fatal( 'edit-conflict' );
1321
1322 # Delete the invalid revision if the DB is not transactional
1323 if ( !$wgDBtransactions ) {
1324 $dbw->delete( 'revision', array( 'rev_id' => $revisionId ), __METHOD__ );
1325 }
1326
1327 $revisionId = 0;
1328 $dbw->rollback();
1329 } else {
1330 global $wgUseRCPatrol;
1331 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId, $user ) );
1332 # Update recentchanges
1333 if ( !( $flags & EDIT_SUPPRESS_RC ) ) {
1334 # Mark as patrolled if the user can do so
1335 $patrolled = $wgUseRCPatrol && !count(
1336 $this->mTitle->getUserPermissionsErrors( 'autopatrol', $user ) );
1337 # Add RC row to the DB
1338 $rc = RecentChange::notifyEdit( $now, $this->mTitle, $isminor, $user, $summary,
1339 $oldid, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1340 $revisionId, $patrolled
1341 );
1342
1343 # Log auto-patrolled edits
1344 if ( $patrolled ) {
1345 PatrolLog::record( $rc, true );
1346 }
1347 }
1348 $user->incEditCount();
1349 $dbw->commit();
1350 }
1351 }
1352
1353 if ( !$wgDBtransactions ) {
1354 ignore_user_abort( $userAbort );
1355 }
1356
1357 // Now that ignore_user_abort is restored, we can respond to fatal errors
1358 if ( !$status->isOK() ) {
1359 wfProfileOut( __METHOD__ );
1360 return $status;
1361 }
1362
1363 # Update links tables, site stats, etc.
1364 $this->doEditUpdates( $revision, $user, array( 'changed' => $changed,
1365 'oldcountable' => $oldcountable ) );
1366
1367 if ( !$changed ) {
1368 $status->warning( 'edit-no-change' );
1369 $revision = null;
1370 // Keep the same revision ID, but do some updates on it
1371 $revisionId = $this->getLatest();
1372 // Update page_touched, this is usually implicit in the page update
1373 // Other cache updates are done in onArticleEdit()
1374 $this->mTitle->invalidateCache();
1375 }
1376 } else {
1377 # Create new article
1378 $status->value['new'] = true;
1379
1380 $dbw->begin();
1381
1382 # Add the page record; stake our claim on this title!
1383 # This will return false if the article already exists
1384 $newid = $this->insertOn( $dbw );
1385
1386 if ( $newid === false ) {
1387 $dbw->rollback();
1388 $status->fatal( 'edit-already-exists' );
1389
1390 wfProfileOut( __METHOD__ );
1391 return $status;
1392 }
1393
1394 # Save the revision text...
1395 $revision = new Revision( array(
1396 'page' => $newid,
1397 'comment' => $summary,
1398 'minor_edit' => $isminor,
1399 'text' => $text,
1400 'user' => $user->getId(),
1401 'user_text' => $user->getName(),
1402 'timestamp' => $now
1403 ) );
1404 $revisionId = $revision->insertOn( $dbw );
1405
1406 # Update the page record with revision data
1407 $this->updateRevisionOn( $dbw, $revision, 0 );
1408
1409 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1410
1411 # Update recentchanges
1412 if ( !( $flags & EDIT_SUPPRESS_RC ) ) {
1413 global $wgUseRCPatrol, $wgUseNPPatrol;
1414
1415 # Mark as patrolled if the user can do so
1416 $patrolled = ( $wgUseRCPatrol || $wgUseNPPatrol ) && !count(
1417 $this->mTitle->getUserPermissionsErrors( 'autopatrol', $user ) );
1418 # Add RC row to the DB
1419 $rc = RecentChange::notifyNew( $now, $this->mTitle, $isminor, $user, $summary, $bot,
1420 '', strlen( $text ), $revisionId, $patrolled );
1421
1422 # Log auto-patrolled edits
1423 if ( $patrolled ) {
1424 PatrolLog::record( $rc, true );
1425 }
1426 }
1427 $user->incEditCount();
1428 $dbw->commit();
1429
1430 # Update links, etc.
1431 $this->doEditUpdates( $revision, $user, array( 'created' => true ) );
1432
1433 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$user, $text, $summary,
1434 $flags & EDIT_MINOR, null, null, &$flags, $revision ) );
1435 }
1436
1437 # Do updates right now unless deferral was requested
1438 if ( !( $flags & EDIT_DEFER_UPDATES ) ) {
1439 DeferredUpdates::doUpdates();
1440 }
1441
1442 // Return the new revision (or null) to the caller
1443 $status->value['revision'] = $revision;
1444
1445 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $text, $summary,
1446 $flags & EDIT_MINOR, null, null, &$flags, $revision, &$status, $baseRevId ) );
1447
1448 # Promote user to any groups they meet the criteria for
1449 $user->addAutopromoteOnceGroups( 'onEdit' );
1450
1451 wfProfileOut( __METHOD__ );
1452 return $status;
1453 }
1454
1455 /**
1456 * Get parser options suitable for rendering the primary article wikitext
1457 * @param User|string $user User object or 'canonical'
1458 * @return ParserOptions
1459 */
1460 public function makeParserOptions( $user ) {
1461 global $wgContLang;
1462 if ( $user instanceof User ) { // settings per user (even anons)
1463 $options = ParserOptions::newFromUser( $user );
1464 } else { // canonical settings
1465 $options = ParserOptions::newFromUserAndLang( new User, $wgContLang );
1466 }
1467 $options->enableLimitReport(); // show inclusion/loop reports
1468 $options->setTidy( true ); // fix bad HTML
1469 return $options;
1470 }
1471
1472 /**
1473 * Prepare text which is about to be saved.
1474 * Returns a stdclass with source, pst and output members
1475 */
1476 public function prepareTextForEdit( $text, $revid = null, User $user = null ) {
1477 global $wgParser, $wgContLang, $wgUser;
1478 $user = is_null( $user ) ? $wgUser : $user;
1479 // @TODO fixme: check $user->getId() here???
1480 if ( $this->mPreparedEdit
1481 && $this->mPreparedEdit->newText == $text
1482 && $this->mPreparedEdit->revid == $revid
1483 ) {
1484 // Already prepared
1485 return $this->mPreparedEdit;
1486 }
1487
1488 $popts = ParserOptions::newFromUserAndLang( $user, $wgContLang );
1489 wfRunHooks( 'ArticlePrepareTextForEdit', array( $this, $popts ) );
1490
1491 $edit = (object)array();
1492 $edit->revid = $revid;
1493 $edit->newText = $text;
1494 $edit->pst = $wgParser->preSaveTransform( $text, $this->mTitle, $user, $popts );
1495 $edit->popts = $this->makeParserOptions( 'canonical' );
1496 $edit->output = $wgParser->parse( $edit->pst, $this->mTitle, $edit->popts, true, true, $revid );
1497 $edit->oldText = $this->getRawText();
1498
1499 $this->mPreparedEdit = $edit;
1500
1501 return $edit;
1502 }
1503
1504 /**
1505 * Do standard deferred updates after page edit.
1506 * Update links tables, site stats, search index and message cache.
1507 * Purges pages that include this page if the text was changed here.
1508 * Every 100th edit, prune the recent changes table.
1509 *
1510 * @private
1511 * @param $revision Revision object
1512 * @param $user User object that did the revision
1513 * @param $options Array of options, following indexes are used:
1514 * - changed: boolean, whether the revision changed the content (default true)
1515 * - created: boolean, whether the revision created the page (default false)
1516 * - oldcountable: boolean or null (default null):
1517 * - boolean: whether the page was counted as an article before that
1518 * revision, only used in changed is true and created is false
1519 * - null: don't change the article count
1520 */
1521 public function doEditUpdates( Revision $revision, User $user, array $options = array() ) {
1522 global $wgEnableParserCache;
1523
1524 wfProfileIn( __METHOD__ );
1525
1526 $options += array( 'changed' => true, 'created' => false, 'oldcountable' => null );
1527 $text = $revision->getText();
1528
1529 # Parse the text
1530 # Be careful not to double-PST: $text is usually already PST-ed once
1531 if ( !$this->mPreparedEdit || $this->mPreparedEdit->output->getFlag( 'vary-revision' ) ) {
1532 wfDebug( __METHOD__ . ": No prepared edit or vary-revision is set...\n" );
1533 $editInfo = $this->prepareTextForEdit( $text, $revision->getId(), $user );
1534 } else {
1535 wfDebug( __METHOD__ . ": No vary-revision, using prepared edit...\n" );
1536 $editInfo = $this->mPreparedEdit;
1537 }
1538
1539 # Save it to the parser cache
1540 if ( $wgEnableParserCache ) {
1541 $parserCache = ParserCache::singleton();
1542 $parserCache->save( $editInfo->output, $this, $editInfo->popts );
1543 }
1544
1545 # Update the links tables
1546 $u = new LinksUpdate( $this->mTitle, $editInfo->output );
1547 $u->doUpdate();
1548
1549 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $options['changed'] ) );
1550
1551 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
1552 if ( 0 == mt_rand( 0, 99 ) ) {
1553 // Flush old entries from the `recentchanges` table; we do this on
1554 // random requests so as to avoid an increase in writes for no good reason
1555 global $wgRCMaxAge;
1556
1557 $dbw = wfGetDB( DB_MASTER );
1558 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
1559 $dbw->delete(
1560 'recentchanges',
1561 array( "rc_timestamp < '$cutoff'" ),
1562 __METHOD__
1563 );
1564 }
1565 }
1566
1567 if ( !$this->mTitle->exists() ) {
1568 wfProfileOut( __METHOD__ );
1569 return;
1570 }
1571
1572 $id = $this->getId();
1573 $title = $this->mTitle->getPrefixedDBkey();
1574 $shortTitle = $this->mTitle->getDBkey();
1575
1576 if ( !$options['changed'] ) {
1577 $good = 0;
1578 $total = 0;
1579 } elseif ( $options['created'] ) {
1580 $good = (int)$this->isCountable( $editInfo );
1581 $total = 1;
1582 } elseif ( $options['oldcountable'] !== null ) {
1583 $good = (int)$this->isCountable( $editInfo ) - (int)$options['oldcountable'];
1584 $total = 0;
1585 } else {
1586 $good = 0;
1587 $total = 0;
1588 }
1589
1590 DeferredUpdates::addUpdate( new SiteStatsUpdate( 0, 1, $good, $total ) );
1591 DeferredUpdates::addUpdate( new SearchUpdate( $id, $title, $text ) );
1592
1593 # If this is another user's talk page, update newtalk.
1594 # Don't do this if $options['changed'] = false (null-edits) nor if
1595 # it's a minor edit and the user doesn't want notifications for those.
1596 if ( $options['changed']
1597 && $this->mTitle->getNamespace() == NS_USER_TALK
1598 && $shortTitle != $user->getTitleKey()
1599 && !( $revision->isMinor() && $user->isAllowed( 'nominornewtalk' ) )
1600 ) {
1601 if ( wfRunHooks( 'ArticleEditUpdateNewTalk', array( &$this ) ) ) {
1602 $other = User::newFromName( $shortTitle, false );
1603 if ( !$other ) {
1604 wfDebug( __METHOD__ . ": invalid username\n" );
1605 } elseif ( User::isIP( $shortTitle ) ) {
1606 // An anonymous user
1607 $other->setNewtalk( true );
1608 } elseif ( $other->isLoggedIn() ) {
1609 $other->setNewtalk( true );
1610 } else {
1611 wfDebug( __METHOD__ . ": don't need to notify a nonexistent user\n" );
1612 }
1613 }
1614 }
1615
1616 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
1617 MessageCache::singleton()->replace( $shortTitle, $text );
1618 }
1619
1620 if( $options['created'] ) {
1621 self::onArticleCreate( $this->mTitle );
1622 } else {
1623 self::onArticleEdit( $this->mTitle );
1624 }
1625
1626 wfProfileOut( __METHOD__ );
1627 }
1628
1629 /**
1630 * Edit an article without doing all that other stuff
1631 * The article must already exist; link tables etc
1632 * are not updated, caches are not flushed.
1633 *
1634 * @param $text String: text submitted
1635 * @param $user User The relevant user
1636 * @param $comment String: comment submitted
1637 * @param $minor Boolean: whereas it's a minor modification
1638 */
1639 public function doQuickEdit( $text, User $user, $comment = '', $minor = 0 ) {
1640 wfProfileIn( __METHOD__ );
1641
1642 $dbw = wfGetDB( DB_MASTER );
1643 $revision = new Revision( array(
1644 'page' => $this->getId(),
1645 'text' => $text,
1646 'comment' => $comment,
1647 'minor_edit' => $minor ? 1 : 0,
1648 ) );
1649 $revision->insertOn( $dbw );
1650 $this->updateRevisionOn( $dbw, $revision );
1651
1652 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1653
1654 wfProfileOut( __METHOD__ );
1655 }
1656
1657 /**
1658 * Update the article's restriction field, and leave a log entry.
1659 * This works for protection both existing and non-existing pages.
1660 *
1661 * @param $limit Array: set of restriction keys
1662 * @param $reason String
1663 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
1664 * @param $expiry Array: per restriction type expiration
1665 * @param $user User The user updating the restrictions
1666 * @return bool true on success
1667 */
1668 public function doUpdateRestrictions( array $limit, array $expiry, &$cascade, $reason, User $user ) {
1669 global $wgContLang;
1670
1671 if ( wfReadOnly() ) {
1672 return Status::newFatal( 'readonlytext', wfReadOnlyReason() );
1673 }
1674
1675 $restrictionTypes = $this->mTitle->getRestrictionTypes();
1676
1677 $id = $this->mTitle->getArticleID();
1678
1679 if ( !$cascade ) {
1680 $cascade = false;
1681 }
1682
1683 // Take this opportunity to purge out expired restrictions
1684 Title::purgeExpiredRestrictions();
1685
1686 # @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
1687 # we expect a single selection, but the schema allows otherwise.
1688 $isProtected = false;
1689 $protect = false;
1690 $changed = false;
1691
1692 $dbw = wfGetDB( DB_MASTER );
1693
1694 foreach ( $restrictionTypes as $action ) {
1695 if ( !isset( $expiry[$action] ) ) {
1696 $expiry[$action] = $dbw->getInfinity();
1697 }
1698 if ( !isset( $limit[$action] ) ) {
1699 $limit[$action] = '';
1700 } elseif ( $limit[$action] != '' ) {
1701 $protect = true;
1702 }
1703
1704 # Get current restrictions on $action
1705 $current = implode( '', $this->mTitle->getRestrictions( $action ) );
1706 if ( $current != '' ) {
1707 $isProtected = true;
1708 }
1709
1710 if ( $limit[$action] != $current ) {
1711 $changed = true;
1712 } elseif ( $limit[$action] != '' ) {
1713 # Only check expiry change if the action is actually being
1714 # protected, since expiry does nothing on an not-protected
1715 # action.
1716 if ( $this->mTitle->getRestrictionExpiry( $action ) != $expiry[$action] ) {
1717 $changed = true;
1718 }
1719 }
1720 }
1721
1722 if ( !$changed && $protect && $this->mTitle->areRestrictionsCascading() != $cascade ) {
1723 $changed = true;
1724 }
1725
1726 # If nothing's changed, do nothing
1727 if ( !$changed ) {
1728 return Status::newGood();
1729 }
1730
1731 if ( !$protect ) { # No protection at all means unprotection
1732 $revCommentMsg = 'unprotectedarticle';
1733 $logAction = 'unprotect';
1734 } elseif ( $isProtected ) {
1735 $revCommentMsg = 'modifiedarticleprotection';
1736 $logAction = 'modify';
1737 } else {
1738 $revCommentMsg = 'protectedarticle';
1739 $logAction = 'protect';
1740 }
1741
1742 $encodedExpiry = array();
1743 $protectDescription = '';
1744 foreach ( $limit as $action => $restrictions ) {
1745 $encodedExpiry[$action] = $dbw->encodeExpiry( $expiry[$action] );
1746 if ( $restrictions != '' ) {
1747 $protectDescription .= $wgContLang->getDirMark() . "[$action=$restrictions] (";
1748 if ( $encodedExpiry[$action] != 'infinity' ) {
1749 $protectDescription .= wfMsgForContent( 'protect-expiring',
1750 $wgContLang->timeanddate( $expiry[$action], false, false ) ,
1751 $wgContLang->date( $expiry[$action], false, false ) ,
1752 $wgContLang->time( $expiry[$action], false, false ) );
1753 } else {
1754 $protectDescription .= wfMsgForContent( 'protect-expiry-indefinite' );
1755 }
1756
1757 $protectDescription .= ') ';
1758 }
1759 }
1760 $protectDescription = trim( $protectDescription );
1761
1762 if ( $id ) { # Protection of existing page
1763 if ( !wfRunHooks( 'ArticleProtect', array( &$this, &$user, $limit, $reason ) ) ) {
1764 return Status::newGood();
1765 }
1766
1767 # Only restrictions with the 'protect' right can cascade...
1768 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
1769 $editrestriction = isset( $limit['edit'] ) ? array( $limit['edit'] ) : $this->mTitle->getRestrictions( 'edit' );
1770
1771 # The schema allows multiple restrictions
1772 if ( !in_array( 'protect', $editrestriction ) && !in_array( 'sysop', $editrestriction ) ) {
1773 $cascade = false;
1774 }
1775
1776 # Update restrictions table
1777 foreach ( $limit as $action => $restrictions ) {
1778 if ( $restrictions != '' ) {
1779 $dbw->replace( 'page_restrictions', array( array( 'pr_page', 'pr_type' ) ),
1780 array( 'pr_page' => $id,
1781 'pr_type' => $action,
1782 'pr_level' => $restrictions,
1783 'pr_cascade' => ( $cascade && $action == 'edit' ) ? 1 : 0,
1784 'pr_expiry' => $encodedExpiry[$action]
1785 ),
1786 __METHOD__
1787 );
1788 } else {
1789 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
1790 'pr_type' => $action ), __METHOD__ );
1791 }
1792 }
1793
1794 # Prepare a null revision to be added to the history
1795 $editComment = $wgContLang->ucfirst( wfMsgForContent( $revCommentMsg, $this->mTitle->getPrefixedText() ) );
1796 if ( $reason ) {
1797 $editComment .= ": $reason";
1798 }
1799 if ( $protectDescription ) {
1800 $editComment .= " ($protectDescription)";
1801 }
1802 if ( $cascade ) {
1803 $editComment .= ' [' . wfMsgForContent( 'protect-summary-cascade' ) . ']';
1804 }
1805
1806 # Insert a null revision
1807 $nullRevision = Revision::newNullRevision( $dbw, $id, $editComment, true );
1808 $nullRevId = $nullRevision->insertOn( $dbw );
1809
1810 $latest = $this->getLatest();
1811 # Update page record
1812 $dbw->update( 'page',
1813 array( /* SET */
1814 'page_touched' => $dbw->timestamp(),
1815 'page_restrictions' => '',
1816 'page_latest' => $nullRevId
1817 ), array( /* WHERE */
1818 'page_id' => $id
1819 ), __METHOD__
1820 );
1821
1822 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $nullRevision, $latest, $user ) );
1823 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$user, $limit, $reason ) );
1824 } else { # Protection of non-existing page (also known as "title protection")
1825 # Cascade protection is meaningless in this case
1826 $cascade = false;
1827
1828 if ( $limit['create'] != '' ) {
1829 $dbw->replace( 'protected_titles',
1830 array( array( 'pt_namespace', 'pt_title' ) ),
1831 array(
1832 'pt_namespace' => $this->mTitle->getNamespace(),
1833 'pt_title' => $this->mTitle->getDBkey(),
1834 'pt_create_perm' => $limit['create'],
1835 'pt_timestamp' => $dbw->encodeExpiry( wfTimestampNow() ),
1836 'pt_expiry' => $encodedExpiry['create'],
1837 'pt_user' => $user->getId(),
1838 'pt_reason' => $reason,
1839 ), __METHOD__
1840 );
1841 } else {
1842 $dbw->delete( 'protected_titles',
1843 array(
1844 'pt_namespace' => $this->mTitle->getNamespace(),
1845 'pt_title' => $this->mTitle->getDBkey()
1846 ), __METHOD__
1847 );
1848 }
1849 }
1850
1851 $this->mTitle->flushRestrictions();
1852
1853 if ( $logAction == 'unprotect' ) {
1854 $logParams = array();
1855 } else {
1856 $logParams = array( $protectDescription, $cascade ? 'cascade' : '' );
1857 }
1858
1859 # Update the protection log
1860 $log = new LogPage( 'protect' );
1861 $log->addEntry( $logAction, $this->mTitle, trim( $reason ), $logParams, $user );
1862
1863 return Status::newGood();
1864 }
1865
1866 /**
1867 * Take an array of page restrictions and flatten it to a string
1868 * suitable for insertion into the page_restrictions field.
1869 * @param $limit Array
1870 * @return String
1871 */
1872 protected static function flattenRestrictions( $limit ) {
1873 if ( !is_array( $limit ) ) {
1874 throw new MWException( 'WikiPage::flattenRestrictions given non-array restriction set' );
1875 }
1876
1877 $bits = array();
1878 ksort( $limit );
1879
1880 foreach ( $limit as $action => $restrictions ) {
1881 if ( $restrictions != '' ) {
1882 $bits[] = "$action=$restrictions";
1883 }
1884 }
1885
1886 return implode( ':', $bits );
1887 }
1888
1889 /**
1890 * Back-end article deletion
1891 * Deletes the article with database consistency, writes logs, purges caches
1892 *
1893 * @param $reason string delete reason for deletion log
1894 * @param $suppress bitfield
1895 * Revision::DELETED_TEXT
1896 * Revision::DELETED_COMMENT
1897 * Revision::DELETED_USER
1898 * Revision::DELETED_RESTRICTED
1899 * @param $id int article ID
1900 * @param $commit boolean defaults to true, triggers transaction end
1901 * @param &$errors Array of errors to append to
1902 * @param $user User The relevant user
1903 * @return boolean true if successful
1904 */
1905 public function doDeleteArticle(
1906 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User $user = null
1907 ) {
1908 global $wgUser;
1909 $user = is_null( $user ) ? $wgUser : $user;
1910
1911 wfDebug( __METHOD__ . "\n" );
1912
1913 if ( ! wfRunHooks( 'ArticleDelete', array( &$this, &$user, &$reason, &$error ) ) ) {
1914 return false;
1915 }
1916 $dbw = wfGetDB( DB_MASTER );
1917 $t = $this->mTitle->getDBkey();
1918 $id = $id ? $id : $this->mTitle->getArticleID( Title::GAID_FOR_UPDATE );
1919
1920 if ( $t === '' || $id == 0 ) {
1921 return false;
1922 }
1923
1924 // Bitfields to further suppress the content
1925 if ( $suppress ) {
1926 $bitfield = 0;
1927 // This should be 15...
1928 $bitfield |= Revision::DELETED_TEXT;
1929 $bitfield |= Revision::DELETED_COMMENT;
1930 $bitfield |= Revision::DELETED_USER;
1931 $bitfield |= Revision::DELETED_RESTRICTED;
1932 } else {
1933 $bitfield = 'rev_deleted';
1934 }
1935
1936 $dbw->begin();
1937 // For now, shunt the revision data into the archive table.
1938 // Text is *not* removed from the text table; bulk storage
1939 // is left intact to avoid breaking block-compression or
1940 // immutable storage schemes.
1941 //
1942 // For backwards compatibility, note that some older archive
1943 // table entries will have ar_text and ar_flags fields still.
1944 //
1945 // In the future, we may keep revisions and mark them with
1946 // the rev_deleted field, which is reserved for this purpose.
1947 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
1948 array(
1949 'ar_namespace' => 'page_namespace',
1950 'ar_title' => 'page_title',
1951 'ar_comment' => 'rev_comment',
1952 'ar_user' => 'rev_user',
1953 'ar_user_text' => 'rev_user_text',
1954 'ar_timestamp' => 'rev_timestamp',
1955 'ar_minor_edit' => 'rev_minor_edit',
1956 'ar_rev_id' => 'rev_id',
1957 'ar_parent_id' => 'rev_parent_id',
1958 'ar_text_id' => 'rev_text_id',
1959 'ar_text' => '\'\'', // Be explicit to appease
1960 'ar_flags' => '\'\'', // MySQL's "strict mode"...
1961 'ar_len' => 'rev_len',
1962 'ar_page_id' => 'page_id',
1963 'ar_deleted' => $bitfield,
1964 'ar_sha1' => 'rev_sha1'
1965 ), array(
1966 'page_id' => $id,
1967 'page_id = rev_page'
1968 ), __METHOD__
1969 );
1970
1971 # Now that it's safely backed up, delete it
1972 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__ );
1973 $ok = ( $dbw->affectedRows() > 0 ); // getArticleId() uses slave, could be laggy
1974
1975 if ( !$ok ) {
1976 $dbw->rollback();
1977 return false;
1978 }
1979
1980 $this->doDeleteUpdates( $id );
1981
1982 # Log the deletion, if the page was suppressed, log it at Oversight instead
1983 $logtype = $suppress ? 'suppress' : 'delete';
1984
1985 $logEntry = new ManualLogEntry( $logtype, 'delete' );
1986 $logEntry->setPerformer( $user );
1987 $logEntry->setTarget( $this->mTitle );
1988 $logEntry->setComment( $reason );
1989 $logid = $logEntry->insert();
1990 $logEntry->publish( $logid );
1991
1992 if ( $commit ) {
1993 $dbw->commit();
1994 }
1995
1996 wfRunHooks( 'ArticleDeleteComplete', array( &$this, &$user, $reason, $id ) );
1997 return true;
1998 }
1999
2000 /**
2001 * Do some database updates after deletion
2002 *
2003 * @param $id Int: page_id value of the page being deleted
2004 */
2005 public function doDeleteUpdates( $id ) {
2006 DeferredUpdates::addUpdate( new SiteStatsUpdate( 0, 1, - (int)$this->isCountable(), -1 ) );
2007
2008 $dbw = wfGetDB( DB_MASTER );
2009
2010 # Delete restrictions for it
2011 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__ );
2012
2013 # Fix category table counts
2014 $cats = array();
2015 $res = $dbw->select( 'categorylinks', 'cl_to', array( 'cl_from' => $id ), __METHOD__ );
2016
2017 foreach ( $res as $row ) {
2018 $cats [] = $row->cl_to;
2019 }
2020
2021 $this->updateCategoryCounts( array(), $cats );
2022
2023 # If using cascading deletes, we can skip some explicit deletes
2024 if ( !$dbw->cascadingDeletes() ) {
2025 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__ );
2026
2027 # Delete outgoing links
2028 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ), __METHOD__ );
2029 $dbw->delete( 'imagelinks', array( 'il_from' => $id ), __METHOD__ );
2030 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ), __METHOD__ );
2031 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ), __METHOD__ );
2032 $dbw->delete( 'externallinks', array( 'el_from' => $id ), __METHOD__ );
2033 $dbw->delete( 'langlinks', array( 'll_from' => $id ), __METHOD__ );
2034 $dbw->delete( 'iwlinks', array( 'iwl_from' => $id ), __METHOD__ );
2035 $dbw->delete( 'redirect', array( 'rd_from' => $id ), __METHOD__ );
2036 $dbw->delete( 'page_props', array( 'pp_page' => $id ), __METHOD__ );
2037 }
2038
2039 # If using cleanup triggers, we can skip some manual deletes
2040 if ( !$dbw->cleanupTriggers() ) {
2041 # Clean up recentchanges entries...
2042 $dbw->delete( 'recentchanges',
2043 array( 'rc_type != ' . RC_LOG,
2044 'rc_namespace' => $this->mTitle->getNamespace(),
2045 'rc_title' => $this->mTitle->getDBkey() ),
2046 __METHOD__ );
2047 $dbw->delete( 'recentchanges',
2048 array( 'rc_type != ' . RC_LOG, 'rc_cur_id' => $id ),
2049 __METHOD__ );
2050 }
2051
2052 # Clear caches
2053 self::onArticleDelete( $this->mTitle );
2054
2055 # Clear the cached article id so the interface doesn't act like we exist
2056 $this->mTitle->resetArticleID( 0 );
2057 }
2058
2059 /**
2060 * Roll back the most recent consecutive set of edits to a page
2061 * from the same user; fails if there are no eligible edits to
2062 * roll back to, e.g. user is the sole contributor. This function
2063 * performs permissions checks on $user, then calls commitRollback()
2064 * to do the dirty work
2065 *
2066 * @todo: seperate the business/permission stuff out from backend code
2067 *
2068 * @param $fromP String: Name of the user whose edits to rollback.
2069 * @param $summary String: Custom summary. Set to default summary if empty.
2070 * @param $token String: Rollback token.
2071 * @param $bot Boolean: If true, mark all reverted edits as bot.
2072 *
2073 * @param $resultDetails Array: contains result-specific array of additional values
2074 * 'alreadyrolled' : 'current' (rev)
2075 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2076 *
2077 * @param $user User The user performing the rollback
2078 * @return array of errors, each error formatted as
2079 * array(messagekey, param1, param2, ...).
2080 * On success, the array is empty. This array can also be passed to
2081 * OutputPage::showPermissionsErrorPage().
2082 */
2083 public function doRollback(
2084 $fromP, $summary, $token, $bot, &$resultDetails, User $user
2085 ) {
2086 $resultDetails = null;
2087
2088 # Check permissions
2089 $editErrors = $this->mTitle->getUserPermissionsErrors( 'edit', $user );
2090 $rollbackErrors = $this->mTitle->getUserPermissionsErrors( 'rollback', $user );
2091 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
2092
2093 if ( !$user->matchEditToken( $token, array( $this->mTitle->getPrefixedText(), $fromP ) ) ) {
2094 $errors[] = array( 'sessionfailure' );
2095 }
2096
2097 if ( $user->pingLimiter( 'rollback' ) || $user->pingLimiter() ) {
2098 $errors[] = array( 'actionthrottledtext' );
2099 }
2100
2101 # If there were errors, bail out now
2102 if ( !empty( $errors ) ) {
2103 return $errors;
2104 }
2105
2106 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user );
2107 }
2108
2109 /**
2110 * Backend implementation of doRollback(), please refer there for parameter
2111 * and return value documentation
2112 *
2113 * NOTE: This function does NOT check ANY permissions, it just commits the
2114 * rollback to the DB. Therefore, you should only call this function direct-
2115 * ly if you want to use custom permissions checks. If you don't, use
2116 * doRollback() instead.
2117 * @param $fromP String: Name of the user whose edits to rollback.
2118 * @param $summary String: Custom summary. Set to default summary if empty.
2119 * @param $bot Boolean: If true, mark all reverted edits as bot.
2120 *
2121 * @param $resultDetails Array: contains result-specific array of additional values
2122 * @param $guser User The user performing the rollback
2123 */
2124 public function commitRollback( $fromP, $summary, $bot, &$resultDetails, User $guser ) {
2125 global $wgUseRCPatrol, $wgContLang;
2126
2127 $dbw = wfGetDB( DB_MASTER );
2128
2129 if ( wfReadOnly() ) {
2130 return array( array( 'readonlytext' ) );
2131 }
2132
2133 # Get the last editor
2134 $current = Revision::newFromTitle( $this->mTitle );
2135 if ( is_null( $current ) ) {
2136 # Something wrong... no page?
2137 return array( array( 'notanarticle' ) );
2138 }
2139
2140 $from = str_replace( '_', ' ', $fromP );
2141 # User name given should match up with the top revision.
2142 # If the user was deleted then $from should be empty.
2143 if ( $from != $current->getUserText() ) {
2144 $resultDetails = array( 'current' => $current );
2145 return array( array( 'alreadyrolled',
2146 htmlspecialchars( $this->mTitle->getPrefixedText() ),
2147 htmlspecialchars( $fromP ),
2148 htmlspecialchars( $current->getUserText() )
2149 ) );
2150 }
2151
2152 # Get the last edit not by this guy...
2153 # Note: these may not be public values
2154 $user = intval( $current->getRawUser() );
2155 $user_text = $dbw->addQuotes( $current->getRawUserText() );
2156 $s = $dbw->selectRow( 'revision',
2157 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
2158 array( 'rev_page' => $current->getPage(),
2159 "rev_user != {$user} OR rev_user_text != {$user_text}"
2160 ), __METHOD__,
2161 array( 'USE INDEX' => 'page_timestamp',
2162 'ORDER BY' => 'rev_timestamp DESC' )
2163 );
2164 if ( $s === false ) {
2165 # No one else ever edited this page
2166 return array( array( 'cantrollback' ) );
2167 } elseif ( $s->rev_deleted & Revision::DELETED_TEXT || $s->rev_deleted & Revision::DELETED_USER ) {
2168 # Only admins can see this text
2169 return array( array( 'notvisiblerev' ) );
2170 }
2171
2172 $set = array();
2173 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
2174 # Mark all reverted edits as bot
2175 $set['rc_bot'] = 1;
2176 }
2177
2178 if ( $wgUseRCPatrol ) {
2179 # Mark all reverted edits as patrolled
2180 $set['rc_patrolled'] = 1;
2181 }
2182
2183 if ( count( $set ) ) {
2184 $dbw->update( 'recentchanges', $set,
2185 array( /* WHERE */
2186 'rc_cur_id' => $current->getPage(),
2187 'rc_user_text' => $current->getUserText(),
2188 "rc_timestamp > '{$s->rev_timestamp}'",
2189 ), __METHOD__
2190 );
2191 }
2192
2193 # Generate the edit summary if necessary
2194 $target = Revision::newFromId( $s->rev_id );
2195 if ( empty( $summary ) ) {
2196 if ( $from == '' ) { // no public user name
2197 $summary = wfMsgForContent( 'revertpage-nouser' );
2198 } else {
2199 $summary = wfMsgForContent( 'revertpage' );
2200 }
2201 }
2202
2203 # Allow the custom summary to use the same args as the default message
2204 $args = array(
2205 $target->getUserText(), $from, $s->rev_id,
2206 $wgContLang->timeanddate( wfTimestamp( TS_MW, $s->rev_timestamp ) ),
2207 $current->getId(), $wgContLang->timeanddate( $current->getTimestamp() )
2208 );
2209 $summary = wfMsgReplaceArgs( $summary, $args );
2210
2211 # Save
2212 $flags = EDIT_UPDATE;
2213
2214 if ( $guser->isAllowed( 'minoredit' ) ) {
2215 $flags |= EDIT_MINOR;
2216 }
2217
2218 if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
2219 $flags |= EDIT_FORCE_BOT;
2220 }
2221
2222 # Actually store the edit
2223 $status = $this->doEdit( $target->getText(), $summary, $flags, $target->getId() );
2224 if ( !empty( $status->value['revision'] ) ) {
2225 $revId = $status->value['revision']->getId();
2226 } else {
2227 $revId = false;
2228 }
2229
2230 wfRunHooks( 'ArticleRollbackComplete', array( $this, $guser, $target, $current ) );
2231
2232 $resultDetails = array(
2233 'summary' => $summary,
2234 'current' => $current,
2235 'target' => $target,
2236 'newid' => $revId
2237 );
2238
2239 return array();
2240 }
2241
2242 /**
2243 * The onArticle*() functions are supposed to be a kind of hooks
2244 * which should be called whenever any of the specified actions
2245 * are done.
2246 *
2247 * This is a good place to put code to clear caches, for instance.
2248 *
2249 * This is called on page move and undelete, as well as edit
2250 *
2251 * @param $title Title object
2252 */
2253 public static function onArticleCreate( $title ) {
2254 # Update existence markers on article/talk tabs...
2255 if ( $title->isTalkPage() ) {
2256 $other = $title->getSubjectPage();
2257 } else {
2258 $other = $title->getTalkPage();
2259 }
2260
2261 $other->invalidateCache();
2262 $other->purgeSquid();
2263
2264 $title->touchLinks();
2265 $title->purgeSquid();
2266 $title->deleteTitleProtection();
2267 }
2268
2269 /**
2270 * Clears caches when article is deleted
2271 *
2272 * @param $title Title
2273 */
2274 public static function onArticleDelete( $title ) {
2275 # Update existence markers on article/talk tabs...
2276 if ( $title->isTalkPage() ) {
2277 $other = $title->getSubjectPage();
2278 } else {
2279 $other = $title->getTalkPage();
2280 }
2281
2282 $other->invalidateCache();
2283 $other->purgeSquid();
2284
2285 $title->touchLinks();
2286 $title->purgeSquid();
2287
2288 # File cache
2289 HTMLFileCache::clearFileCache( $title );
2290
2291 # Messages
2292 if ( $title->getNamespace() == NS_MEDIAWIKI ) {
2293 MessageCache::singleton()->replace( $title->getDBkey(), false );
2294 }
2295
2296 # Images
2297 if ( $title->getNamespace() == NS_FILE ) {
2298 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
2299 $update->doUpdate();
2300 }
2301
2302 # User talk pages
2303 if ( $title->getNamespace() == NS_USER_TALK ) {
2304 $user = User::newFromName( $title->getText(), false );
2305 if ( $user ) {
2306 $user->setNewtalk( false );
2307 }
2308 }
2309
2310 # Image redirects
2311 RepoGroup::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
2312 }
2313
2314 /**
2315 * Purge caches on page update etc
2316 *
2317 * @param $title Title object
2318 * @todo: verify that $title is always a Title object (and never false or null), add Title hint to parameter $title
2319 */
2320 public static function onArticleEdit( $title ) {
2321 // Invalidate caches of articles which include this page
2322 DeferredUpdates::addHTMLCacheUpdate( $title, 'templatelinks' );
2323
2324
2325 // Invalidate the caches of all pages which redirect here
2326 DeferredUpdates::addHTMLCacheUpdate( $title, 'redirect' );
2327
2328 # Purge squid for this page only
2329 $title->purgeSquid();
2330
2331 # Clear file cache for this page only
2332 HTMLFileCache::clearFileCache( $title );
2333 }
2334
2335 /**#@-*/
2336
2337 /**
2338 * Returns a list of hidden categories this page is a member of.
2339 * Uses the page_props and categorylinks tables.
2340 *
2341 * @return Array of Title objects
2342 */
2343 public function getHiddenCategories() {
2344 $result = array();
2345 $id = $this->mTitle->getArticleID();
2346
2347 if ( $id == 0 ) {
2348 return array();
2349 }
2350
2351 $dbr = wfGetDB( DB_SLAVE );
2352 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
2353 array( 'cl_to' ),
2354 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
2355 'page_namespace' => NS_CATEGORY, 'page_title=cl_to' ),
2356 __METHOD__ );
2357
2358 if ( $res !== false ) {
2359 foreach ( $res as $row ) {
2360 $result[] = Title::makeTitle( NS_CATEGORY, $row->cl_to );
2361 }
2362 }
2363
2364 return $result;
2365 }
2366
2367 /**
2368 * Return an applicable autosummary if one exists for the given edit.
2369 * @param $oldtext String: the previous text of the page.
2370 * @param $newtext String: The submitted text of the page.
2371 * @param $flags Int bitmask: a bitmask of flags submitted for the edit.
2372 * @return string An appropriate autosummary, or an empty string.
2373 */
2374 public static function getAutosummary( $oldtext, $newtext, $flags ) {
2375 global $wgContLang;
2376
2377 # Decide what kind of autosummary is needed.
2378
2379 # Redirect autosummaries
2380 $ot = Title::newFromRedirect( $oldtext );
2381 $rt = Title::newFromRedirect( $newtext );
2382
2383 if ( is_object( $rt ) && ( !is_object( $ot ) || !$rt->equals( $ot ) || $ot->getFragment() != $rt->getFragment() ) ) {
2384 $truncatedtext = $wgContLang->truncate(
2385 str_replace( "\n", ' ', $newtext ),
2386 max( 0, 250
2387 - strlen( wfMsgForContent( 'autoredircomment' ) )
2388 - strlen( $rt->getFullText() )
2389 ) );
2390 return wfMsgForContent( 'autoredircomment', $rt->getFullText(), $truncatedtext );
2391 }
2392
2393 # New page autosummaries
2394 if ( $flags & EDIT_NEW && strlen( $newtext ) ) {
2395 # If they're making a new article, give its text, truncated, in the summary.
2396
2397 $truncatedtext = $wgContLang->truncate(
2398 str_replace( "\n", ' ', $newtext ),
2399 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new' ) ) ) );
2400
2401 return wfMsgForContent( 'autosumm-new', $truncatedtext );
2402 }
2403
2404 # Blanking autosummaries
2405 if ( $oldtext != '' && $newtext == '' ) {
2406 return wfMsgForContent( 'autosumm-blank' );
2407 } elseif ( strlen( $oldtext ) > 10 * strlen( $newtext ) && strlen( $newtext ) < 500 ) {
2408 # Removing more than 90% of the article
2409
2410 $truncatedtext = $wgContLang->truncate(
2411 $newtext,
2412 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) ) );
2413
2414 return wfMsgForContent( 'autosumm-replace', $truncatedtext );
2415 }
2416
2417 # If we reach this point, there's no applicable autosummary for our case, so our
2418 # autosummary is empty.
2419 return '';
2420 }
2421
2422 /**
2423 * Auto-generates a deletion reason
2424 *
2425 * @param &$hasHistory Boolean: whether the page has a history
2426 * @return mixed String containing deletion reason or empty string, or boolean false
2427 * if no revision occurred
2428 */
2429 public function getAutoDeleteReason( &$hasHistory ) {
2430 global $wgContLang;
2431
2432 $dbw = wfGetDB( DB_MASTER );
2433 // Get the last revision
2434 $rev = Revision::newFromTitle( $this->getTitle() );
2435
2436 if ( is_null( $rev ) ) {
2437 return false;
2438 }
2439
2440 // Get the article's contents
2441 $contents = $rev->getText();
2442 $blank = false;
2443
2444 // If the page is blank, use the text from the previous revision,
2445 // which can only be blank if there's a move/import/protect dummy revision involved
2446 if ( $contents == '' ) {
2447 $prev = $rev->getPrevious();
2448
2449 if ( $prev ) {
2450 $contents = $prev->getText();
2451 $blank = true;
2452 }
2453 }
2454
2455 // Find out if there was only one contributor
2456 // Only scan the last 20 revisions
2457 $res = $dbw->select( 'revision', 'rev_user_text',
2458 array( 'rev_page' => $this->getID(), $dbw->bitAnd( 'rev_deleted', Revision::DELETED_USER ) . ' = 0' ),
2459 __METHOD__,
2460 array( 'LIMIT' => 20 )
2461 );
2462
2463 if ( $res === false ) {
2464 // This page has no revisions, which is very weird
2465 return false;
2466 }
2467
2468 $hasHistory = ( $res->numRows() > 1 );
2469 $row = $dbw->fetchObject( $res );
2470
2471 if ( $row ) { // $row is false if the only contributor is hidden
2472 $onlyAuthor = $row->rev_user_text;
2473 // Try to find a second contributor
2474 foreach ( $res as $row ) {
2475 if ( $row->rev_user_text != $onlyAuthor ) { // Bug 22999
2476 $onlyAuthor = false;
2477 break;
2478 }
2479 }
2480 } else {
2481 $onlyAuthor = false;
2482 }
2483
2484 // Generate the summary with a '$1' placeholder
2485 if ( $blank ) {
2486 // The current revision is blank and the one before is also
2487 // blank. It's just not our lucky day
2488 $reason = wfMsgForContent( 'exbeforeblank', '$1' );
2489 } else {
2490 if ( $onlyAuthor ) {
2491 $reason = wfMsgForContent( 'excontentauthor', '$1', $onlyAuthor );
2492 } else {
2493 $reason = wfMsgForContent( 'excontent', '$1' );
2494 }
2495 }
2496
2497 if ( $reason == '-' ) {
2498 // Allow these UI messages to be blanked out cleanly
2499 return '';
2500 }
2501
2502 // Replace newlines with spaces to prevent uglyness
2503 $contents = preg_replace( "/[\n\r]/", ' ', $contents );
2504 // Calculate the maximum amount of chars to get
2505 // Max content length = max comment length - length of the comment (excl. $1)
2506 $maxLength = 255 - ( strlen( $reason ) - 2 );
2507 $contents = $wgContLang->truncate( $contents, $maxLength );
2508 // Remove possible unfinished links
2509 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
2510 // Now replace the '$1' placeholder
2511 $reason = str_replace( '$1', $contents, $reason );
2512
2513 return $reason;
2514 }
2515
2516 /**
2517 * Update all the appropriate counts in the category table, given that
2518 * we've added the categories $added and deleted the categories $deleted.
2519 *
2520 * @param $added array The names of categories that were added
2521 * @param $deleted array The names of categories that were deleted
2522 */
2523 public function updateCategoryCounts( $added, $deleted ) {
2524 $ns = $this->mTitle->getNamespace();
2525 $dbw = wfGetDB( DB_MASTER );
2526
2527 # First make sure the rows exist. If one of the "deleted" ones didn't
2528 # exist, we might legitimately not create it, but it's simpler to just
2529 # create it and then give it a negative value, since the value is bogus
2530 # anyway.
2531 #
2532 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
2533 $insertCats = array_merge( $added, $deleted );
2534 if ( !$insertCats ) {
2535 # Okay, nothing to do
2536 return;
2537 }
2538
2539 $insertRows = array();
2540
2541 foreach ( $insertCats as $cat ) {
2542 $insertRows[] = array(
2543 'cat_id' => $dbw->nextSequenceValue( 'category_cat_id_seq' ),
2544 'cat_title' => $cat
2545 );
2546 }
2547 $dbw->insert( 'category', $insertRows, __METHOD__, 'IGNORE' );
2548
2549 $addFields = array( 'cat_pages = cat_pages + 1' );
2550 $removeFields = array( 'cat_pages = cat_pages - 1' );
2551
2552 if ( $ns == NS_CATEGORY ) {
2553 $addFields[] = 'cat_subcats = cat_subcats + 1';
2554 $removeFields[] = 'cat_subcats = cat_subcats - 1';
2555 } elseif ( $ns == NS_FILE ) {
2556 $addFields[] = 'cat_files = cat_files + 1';
2557 $removeFields[] = 'cat_files = cat_files - 1';
2558 }
2559
2560 if ( $added ) {
2561 $dbw->update(
2562 'category',
2563 $addFields,
2564 array( 'cat_title' => $added ),
2565 __METHOD__
2566 );
2567 }
2568
2569 if ( $deleted ) {
2570 $dbw->update(
2571 'category',
2572 $removeFields,
2573 array( 'cat_title' => $deleted ),
2574 __METHOD__
2575 );
2576 }
2577 }
2578
2579 /**
2580 * Updates cascading protections
2581 *
2582 * @param $parserOutput ParserOutput object for the current version
2583 */
2584 public function doCascadeProtectionUpdates( ParserOutput $parserOutput ) {
2585 if ( wfReadOnly() || !$this->mTitle->areRestrictionsCascading() ) {
2586 return;
2587 }
2588
2589 // templatelinks table may have become out of sync,
2590 // especially if using variable-based transclusions.
2591 // For paranoia, check if things have changed and if
2592 // so apply updates to the database. This will ensure
2593 // that cascaded protections apply as soon as the changes
2594 // are visible.
2595
2596 # Get templates from templatelinks
2597 $id = $this->mTitle->getArticleID();
2598
2599 $tlTemplates = array();
2600
2601 $dbr = wfGetDB( DB_SLAVE );
2602 $res = $dbr->select( array( 'templatelinks' ),
2603 array( 'tl_namespace', 'tl_title' ),
2604 array( 'tl_from' => $id ),
2605 __METHOD__
2606 );
2607
2608 foreach ( $res as $row ) {
2609 $tlTemplates["{$row->tl_namespace}:{$row->tl_title}"] = true;
2610 }
2611
2612 # Get templates from parser output.
2613 $poTemplates = array();
2614 foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
2615 foreach ( $templates as $dbk => $id ) {
2616 $poTemplates["$ns:$dbk"] = true;
2617 }
2618 }
2619
2620 # Get the diff
2621 $templates_diff = array_diff_key( $poTemplates, $tlTemplates );
2622
2623 if ( count( $templates_diff ) > 0 ) {
2624 # Whee, link updates time.
2625 $u = new LinksUpdate( $this->mTitle, $parserOutput, false );
2626 $u->doUpdate();
2627 }
2628 }
2629
2630 /**
2631 * Return a list of templates used by this article.
2632 * Uses the templatelinks table
2633 *
2634 * @deprecated in 1.19; use Title::getTemplateLinksFrom()
2635 * @return Array of Title objects
2636 */
2637 public function getUsedTemplates() {
2638 return $this->mTitle->getTemplateLinksFrom();
2639 }
2640
2641 /**
2642 * Perform article updates on a special page creation.
2643 *
2644 * @param $rev Revision object
2645 *
2646 * @todo This is a shitty interface function. Kill it and replace the
2647 * other shitty functions like doEditUpdates and such so it's not needed
2648 * anymore.
2649 * @deprecated since 1.18, use doEditUpdates()
2650 */
2651 public function createUpdates( $rev ) {
2652 wfDeprecated( __METHOD__, '1.18' );
2653 global $wgUser;
2654 $this->doEditUpdates( $rev, $wgUser, array( 'created' => true ) );
2655 }
2656
2657 /**
2658 * This function is called right before saving the wikitext,
2659 * so we can do things like signatures and links-in-context.
2660 *
2661 * @deprecated in 1.19; use Parser::preSaveTransform() instead
2662 * @param $text String article contents
2663 * @param $user User object: user doing the edit
2664 * @param $popts ParserOptions object: parser options, default options for
2665 * the user loaded if null given
2666 * @return string article contents with altered wikitext markup (signatures
2667 * converted, {{subst:}}, templates, etc.)
2668 */
2669 public function preSaveTransform( $text, User $user = null, ParserOptions $popts = null ) {
2670 global $wgParser, $wgUser;
2671
2672 wfDeprecated( __METHOD__, '1.19' );
2673
2674 $user = is_null( $user ) ? $wgUser : $user;
2675
2676 if ( $popts === null ) {
2677 $popts = ParserOptions::newFromUser( $user );
2678 }
2679
2680 return $wgParser->preSaveTransform( $text, $this->mTitle, $user, $popts );
2681 }
2682
2683 /**
2684 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
2685 *
2686 * @deprecated in 1.19; use Title::isBigDeletion() instead.
2687 * @return bool
2688 */
2689 public function isBigDeletion() {
2690 wfDeprecated( __METHOD__, '1.19' );
2691 return $this->mTitle->isBigDeletion();
2692 }
2693
2694 /**
2695 * Get the approximate revision count of this page.
2696 *
2697 * @deprecated in 1.19; use Title::estimateRevisionCount() instead.
2698 * @return int
2699 */
2700 public function estimateRevisionCount() {
2701 wfDeprecated( __METHOD__, '1.19' );
2702 return $this->mTitle->estimateRevisionCount();
2703 }
2704
2705 /**
2706 * Update the article's restriction field, and leave a log entry.
2707 *
2708 * @deprecated since 1.19
2709 * @param $limit Array: set of restriction keys
2710 * @param $reason String
2711 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
2712 * @param $expiry Array: per restriction type expiration
2713 * @param $user User The user updating the restrictions
2714 * @return bool true on success
2715 */
2716 public function updateRestrictions(
2717 $limit = array(), $reason = '', &$cascade = 0, $expiry = array(), User $user = null
2718 ) {
2719 global $wgUser;
2720
2721 $user = is_null( $user ) ? $wgUser : $user;
2722
2723 return $this->doUpdateRestrictions( $limit, $expiry, $cascade, $reason, $user )->isOK();
2724 }
2725
2726 /**
2727 * @deprecated since 1.18
2728 */
2729 public function quickEdit( $text, $comment = '', $minor = 0 ) {
2730 wfDeprecated( __METHOD__, '1.18' );
2731 global $wgUser;
2732 return $this->doQuickEdit( $text, $wgUser, $comment, $minor );
2733 }
2734
2735 /**
2736 * @deprecated since 1.18
2737 */
2738 public function viewUpdates() {
2739 wfDeprecated( __METHOD__, '1.18' );
2740 global $wgUser;
2741 return $this->doViewUpdates( $wgUser );
2742 }
2743
2744 /**
2745 * @deprecated since 1.18
2746 */
2747 public function useParserCache( $oldid ) {
2748 wfDeprecated( __METHOD__, '1.18' );
2749 global $wgUser;
2750 return $this->isParserCacheUsed( ParserOptions::newFromUser( $wgUser ), $oldid );
2751 }
2752 }
2753
2754 class PoolWorkArticleView extends PoolCounterWork {
2755
2756 /**
2757 * @var Page
2758 */
2759 private $page;
2760
2761 /**
2762 * @var string
2763 */
2764 private $cacheKey;
2765
2766 /**
2767 * @var integer
2768 */
2769 private $revid;
2770
2771 /**
2772 * @var ParserOptions
2773 */
2774 private $parserOptions;
2775
2776 /**
2777 * @var string|null
2778 */
2779 private $text;
2780
2781 /**
2782 * @var ParserOutput|false
2783 */
2784 private $parserOutput = false;
2785
2786 /**
2787 * @var bool
2788 */
2789 private $isDirty = false;
2790
2791 /**
2792 * @var Status|false
2793 */
2794 private $error = false;
2795
2796 /**
2797 * Constructor
2798 *
2799 * @param $page Page
2800 * @param $revid Integer: ID of the revision being parsed
2801 * @param $useParserCache Boolean: whether to use the parser cache
2802 * @param $parserOptions parserOptions to use for the parse operation
2803 * @param $text String: text to parse or null to load it
2804 */
2805 function __construct( Page $page, ParserOptions $parserOptions, $revid, $useParserCache, $text = null ) {
2806 $this->page = $page;
2807 $this->revid = $revid;
2808 $this->cacheable = $useParserCache;
2809 $this->parserOptions = $parserOptions;
2810 $this->text = $text;
2811 $this->cacheKey = ParserCache::singleton()->getKey( $page, $parserOptions );
2812 parent::__construct( 'ArticleView', $this->cacheKey . ':revid:' . $revid );
2813 }
2814
2815 /**
2816 * Get the ParserOutput from this object, or false in case of failure
2817 *
2818 * @return ParserOutput
2819 */
2820 public function getParserOutput() {
2821 return $this->parserOutput;
2822 }
2823
2824 /**
2825 * Get whether the ParserOutput is a dirty one (i.e. expired)
2826 *
2827 * @return bool
2828 */
2829 public function getIsDirty() {
2830 return $this->isDirty;
2831 }
2832
2833 /**
2834 * Get a Status object in case of error or false otherwise
2835 *
2836 * @return Status|false
2837 */
2838 public function getError() {
2839 return $this->error;
2840 }
2841
2842 /**
2843 * @return bool
2844 */
2845 function doWork() {
2846 global $wgParser, $wgUseFileCache;
2847
2848 $isCurrent = $this->revid === $this->page->getLatest();
2849
2850 if ( $this->text !== null ) {
2851 $text = $this->text;
2852 } elseif ( $isCurrent ) {
2853 $text = $this->page->getRawText();
2854 } else {
2855 $rev = Revision::newFromTitle( $this->page->getTitle(), $this->revid );
2856 if ( $rev === null ) {
2857 return false;
2858 }
2859 $text = $rev->getText();
2860 }
2861
2862 $time = - wfTime();
2863 $this->parserOutput = $wgParser->parse( $text, $this->page->getTitle(),
2864 $this->parserOptions, true, true, $this->revid );
2865 $time += wfTime();
2866
2867 # Timing hack
2868 if ( $time > 3 ) {
2869 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
2870 $this->page->getTitle()->getPrefixedDBkey() ) );
2871 }
2872
2873 if ( $this->cacheable && $this->parserOutput->isCacheable() ) {
2874 ParserCache::singleton()->save( $this->parserOutput, $this->page, $this->parserOptions );
2875 }
2876
2877 // Make sure file cache is not used on uncacheable content.
2878 // Output that has magic words in it can still use the parser cache
2879 // (if enabled), though it will generally expire sooner.
2880 if ( !$this->parserOutput->isCacheable() || $this->parserOutput->containsOldMagic() ) {
2881 $wgUseFileCache = false;
2882 }
2883
2884 if ( $isCurrent ) {
2885 $this->page->doCascadeProtectionUpdates( $this->parserOutput );
2886 }
2887
2888 return true;
2889 }
2890
2891 /**
2892 * @return bool
2893 */
2894 function getCachedWork() {
2895 $this->parserOutput = ParserCache::singleton()->get( $this->page, $this->parserOptions );
2896
2897 if ( $this->parserOutput === false ) {
2898 wfDebug( __METHOD__ . ": parser cache miss\n" );
2899 return false;
2900 } else {
2901 wfDebug( __METHOD__ . ": parser cache hit\n" );
2902 return true;
2903 }
2904 }
2905
2906 /**
2907 * @return bool
2908 */
2909 function fallback() {
2910 $this->parserOutput = ParserCache::singleton()->getDirty( $this->page, $this->parserOptions );
2911
2912 if ( $this->parserOutput === false ) {
2913 wfDebugLog( 'dirty', "dirty missing\n" );
2914 wfDebug( __METHOD__ . ": no dirty cache\n" );
2915 return false;
2916 } else {
2917 wfDebug( __METHOD__ . ": sending dirty output\n" );
2918 wfDebugLog( 'dirty', "dirty output {$this->cacheKey}\n" );
2919 $this->isDirty = true;
2920 return true;
2921 }
2922 }
2923
2924 /**
2925 * @param $status Status
2926 */
2927 function error( $status ) {
2928 $this->error = $status;
2929 return false;
2930 }
2931 }