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