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