Merge "Fix type hint in HistoryAction::getArticle"
[lhc/web/wiklou.git] / includes / page / WikiPage.php
1 <?php
2 /**
3 * Base representation for a MediaWiki page.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 */
22
23 /**
24 * Abstract class for type hinting (accepts WikiPage, Article, ImagePage, CategoryPage)
25 */
26 interface Page {
27 }
28
29 /**
30 * Class representing a MediaWiki article and history.
31 *
32 * Some fields are public only for backwards-compatibility. Use accessors.
33 * In the past, this class was part of Article.php and everything was public.
34 *
35 * @internal documentation reviewed 15 Mar 2010
36 */
37 class WikiPage implements Page, IDBAccessObject {
38 // Constants for $mDataLoadedFrom and related
39
40 /**
41 * @var Title
42 */
43 public $mTitle = null;
44
45 /**@{{
46 * @protected
47 */
48 public $mDataLoaded = false; // !< Boolean
49 public $mIsRedirect = false; // !< Boolean
50 public $mLatest = false; // !< Integer (false means "not loaded")
51 /**@}}*/
52
53 /** @var stdClass Map of cache fields (text, parser output, ect) for a proposed/new edit */
54 public $mPreparedEdit = false;
55
56 /**
57 * @var int
58 */
59 protected $mId = null;
60
61 /**
62 * @var int One of the READ_* constants
63 */
64 protected $mDataLoadedFrom = self::READ_NONE;
65
66 /**
67 * @var Title
68 */
69 protected $mRedirectTarget = null;
70
71 /**
72 * @var Revision
73 */
74 protected $mLastRevision = null;
75
76 /**
77 * @var string Timestamp of the current revision or empty string if not loaded
78 */
79 protected $mTimestamp = '';
80
81 /**
82 * @var string
83 */
84 protected $mTouched = '19700101000000';
85
86 /**
87 * @var string
88 */
89 protected $mLinksUpdated = '19700101000000';
90
91 /**
92 * Constructor and clear the article
93 * @param Title $title Reference to a Title object.
94 */
95 public function __construct( Title $title ) {
96 $this->mTitle = $title;
97 }
98
99 /**
100 * Create a WikiPage object of the appropriate class for the given title.
101 *
102 * @param Title $title
103 *
104 * @throws MWException
105 * @return WikiPage Object of the appropriate type
106 */
107 public static function factory( Title $title ) {
108 $ns = $title->getNamespace();
109
110 if ( $ns == NS_MEDIA ) {
111 throw new MWException( "NS_MEDIA is a virtual namespace; use NS_FILE." );
112 } elseif ( $ns < 0 ) {
113 throw new MWException( "Invalid or virtual namespace $ns given." );
114 }
115
116 switch ( $ns ) {
117 case NS_FILE:
118 $page = new WikiFilePage( $title );
119 break;
120 case NS_CATEGORY:
121 $page = new WikiCategoryPage( $title );
122 break;
123 default:
124 $page = new WikiPage( $title );
125 }
126
127 return $page;
128 }
129
130 /**
131 * Constructor from a page id
132 *
133 * @param int $id Article ID to load
134 * @param string|int $from One of the following values:
135 * - "fromdb" or WikiPage::READ_NORMAL to select from a slave database
136 * - "fromdbmaster" or WikiPage::READ_LATEST to select from the master database
137 *
138 * @return WikiPage|null
139 */
140 public static function newFromID( $id, $from = 'fromdb' ) {
141 // page id's are never 0 or negative, see bug 61166
142 if ( $id < 1 ) {
143 return null;
144 }
145
146 $from = self::convertSelectType( $from );
147 $db = wfGetDB( $from === self::READ_LATEST ? DB_MASTER : DB_SLAVE );
148 $row = $db->selectRow( 'page', self::selectFields(), array( 'page_id' => $id ), __METHOD__ );
149 if ( !$row ) {
150 return null;
151 }
152 return self::newFromRow( $row, $from );
153 }
154
155 /**
156 * Constructor from a database row
157 *
158 * @since 1.20
159 * @param object $row Database row containing at least fields returned by selectFields().
160 * @param string|int $from Source of $data:
161 * - "fromdb" or WikiPage::READ_NORMAL: from a slave DB
162 * - "fromdbmaster" or WikiPage::READ_LATEST: from the master DB
163 * - "forupdate" or WikiPage::READ_LOCKING: from the master DB using SELECT FOR UPDATE
164 * @return WikiPage
165 */
166 public static function newFromRow( $row, $from = 'fromdb' ) {
167 $page = self::factory( Title::newFromRow( $row ) );
168 $page->loadFromRow( $row, $from );
169 return $page;
170 }
171
172 /**
173 * Convert 'fromdb', 'fromdbmaster' and 'forupdate' to READ_* constants.
174 *
175 * @param object|string|int $type
176 * @return mixed
177 */
178 private static function convertSelectType( $type ) {
179 switch ( $type ) {
180 case 'fromdb':
181 return self::READ_NORMAL;
182 case 'fromdbmaster':
183 return self::READ_LATEST;
184 case 'forupdate':
185 return self::READ_LOCKING;
186 default:
187 // It may already be an integer or whatever else
188 return $type;
189 }
190 }
191
192 /**
193 * Returns overrides for action handlers.
194 * Classes listed here will be used instead of the default one when
195 * (and only when) $wgActions[$action] === true. This allows subclasses
196 * to override the default behavior.
197 *
198 * @todo Move this UI stuff somewhere else
199 *
200 * @return array
201 */
202 public function getActionOverrides() {
203 $content_handler = $this->getContentHandler();
204 return $content_handler->getActionOverrides();
205 }
206
207 /**
208 * Returns the ContentHandler instance to be used to deal with the content of this WikiPage.
209 *
210 * Shorthand for ContentHandler::getForModelID( $this->getContentModel() );
211 *
212 * @return ContentHandler
213 *
214 * @since 1.21
215 */
216 public function getContentHandler() {
217 return ContentHandler::getForModelID( $this->getContentModel() );
218 }
219
220 /**
221 * Get the title object of the article
222 * @return Title Title object of this page
223 */
224 public function getTitle() {
225 return $this->mTitle;
226 }
227
228 /**
229 * Clear the object
230 * @return void
231 */
232 public function clear() {
233 $this->mDataLoaded = false;
234 $this->mDataLoadedFrom = self::READ_NONE;
235
236 $this->clearCacheFields();
237 }
238
239 /**
240 * Clear the object cache fields
241 * @return void
242 */
243 protected function clearCacheFields() {
244 $this->mId = null;
245 $this->mRedirectTarget = null; // Title object if set
246 $this->mLastRevision = null; // Latest revision
247 $this->mTouched = '19700101000000';
248 $this->mLinksUpdated = '19700101000000';
249 $this->mTimestamp = '';
250 $this->mIsRedirect = false;
251 $this->mLatest = false;
252 // Bug 57026: do not clear mPreparedEdit since prepareTextForEdit() already checks
253 // the requested rev ID and content against the cached one for equality. For most
254 // content types, the output should not change during the lifetime of this cache.
255 // Clearing it can cause extra parses on edit for no reason.
256 }
257
258 /**
259 * Clear the mPreparedEdit cache field, as may be needed by mutable content types
260 * @return void
261 * @since 1.23
262 */
263 public function clearPreparedEdit() {
264 $this->mPreparedEdit = false;
265 }
266
267 /**
268 * Return the list of revision fields that should be selected to create
269 * a new page.
270 *
271 * @return array
272 */
273 public static function selectFields() {
274 global $wgContentHandlerUseDB, $wgPageLanguageUseDB;
275
276 $fields = array(
277 'page_id',
278 'page_namespace',
279 'page_title',
280 'page_restrictions',
281 'page_is_redirect',
282 'page_is_new',
283 'page_random',
284 'page_touched',
285 'page_links_updated',
286 'page_latest',
287 'page_len',
288 );
289
290 if ( $wgContentHandlerUseDB ) {
291 $fields[] = 'page_content_model';
292 }
293
294 if ( $wgPageLanguageUseDB ) {
295 $fields[] = 'page_lang';
296 }
297
298 return $fields;
299 }
300
301 /**
302 * Fetch a page record with the given conditions
303 * @param DatabaseBase $dbr
304 * @param array $conditions
305 * @param array $options
306 * @return object|bool Database result resource, or false on failure
307 */
308 protected function pageData( $dbr, $conditions, $options = array() ) {
309 $fields = self::selectFields();
310
311 Hooks::run( 'ArticlePageDataBefore', array( &$this, &$fields ) );
312
313 $row = $dbr->selectRow( 'page', $fields, $conditions, __METHOD__, $options );
314
315 Hooks::run( 'ArticlePageDataAfter', array( &$this, &$row ) );
316
317 return $row;
318 }
319
320 /**
321 * Fetch a page record matching the Title object's namespace and title
322 * using a sanitized title string
323 *
324 * @param DatabaseBase $dbr
325 * @param Title $title
326 * @param array $options
327 * @return object|bool Database result resource, or false on failure
328 */
329 public function pageDataFromTitle( $dbr, $title, $options = array() ) {
330 return $this->pageData( $dbr, array(
331 'page_namespace' => $title->getNamespace(),
332 'page_title' => $title->getDBkey() ), $options );
333 }
334
335 /**
336 * Fetch a page record matching the requested ID
337 *
338 * @param DatabaseBase $dbr
339 * @param int $id
340 * @param array $options
341 * @return object|bool Database result resource, or false on failure
342 */
343 public function pageDataFromId( $dbr, $id, $options = array() ) {
344 return $this->pageData( $dbr, array( 'page_id' => $id ), $options );
345 }
346
347 /**
348 * Load the object from a given source by title
349 *
350 * @param object|string|int $from One of the following:
351 * - A DB query result object.
352 * - "fromdb" or WikiPage::READ_NORMAL to get from a slave DB.
353 * - "fromdbmaster" or WikiPage::READ_LATEST to get from the master DB.
354 * - "forupdate" or WikiPage::READ_LOCKING to get from the master DB
355 * using SELECT FOR UPDATE.
356 *
357 * @return void
358 */
359 public function loadPageData( $from = 'fromdb' ) {
360 $from = self::convertSelectType( $from );
361 if ( is_int( $from ) && $from <= $this->mDataLoadedFrom ) {
362 // We already have the data from the correct location, no need to load it twice.
363 return;
364 }
365
366 if ( $from === self::READ_LOCKING ) {
367 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER ), $this->mTitle, array( 'FOR UPDATE' ) );
368 } elseif ( $from === self::READ_LATEST ) {
369 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER ), $this->mTitle );
370 } elseif ( $from === self::READ_NORMAL ) {
371 $data = $this->pageDataFromTitle( wfGetDB( DB_SLAVE ), $this->mTitle );
372 // Use a "last rev inserted" timestamp key to diminish the issue of slave lag.
373 // Note that DB also stores the master position in the session and checks it.
374 $touched = $this->getCachedLastEditTime();
375 if ( $touched ) { // key set
376 if ( !$data || $touched > wfTimestamp( TS_MW, $data->page_touched ) ) {
377 $from = self::READ_LATEST;
378 $data = $this->pageDataFromTitle( wfGetDB( DB_MASTER ), $this->mTitle );
379 }
380 }
381 } else {
382 // No idea from where the caller got this data, assume slave database.
383 $data = $from;
384 $from = self::READ_NORMAL;
385 }
386
387 $this->loadFromRow( $data, $from );
388 }
389
390 /**
391 * Load the object from a database row
392 *
393 * @since 1.20
394 * @param object $data Database row containing at least fields returned by selectFields()
395 * @param string|int $from One of the following:
396 * - "fromdb" or WikiPage::READ_NORMAL if the data comes from a slave DB
397 * - "fromdbmaster" or WikiPage::READ_LATEST if the data comes from the master DB
398 * - "forupdate" or WikiPage::READ_LOCKING if the data comes from
399 * the master DB using SELECT FOR UPDATE
400 */
401 public function loadFromRow( $data, $from ) {
402 $lc = LinkCache::singleton();
403 $lc->clearLink( $this->mTitle );
404
405 if ( $data ) {
406 $lc->addGoodLinkObjFromRow( $this->mTitle, $data );
407
408 $this->mTitle->loadFromRow( $data );
409
410 // Old-fashioned restrictions
411 $this->mTitle->loadRestrictions( $data->page_restrictions );
412
413 $this->mId = intval( $data->page_id );
414 $this->mTouched = wfTimestamp( TS_MW, $data->page_touched );
415 $this->mLinksUpdated = wfTimestampOrNull( TS_MW, $data->page_links_updated );
416 $this->mIsRedirect = intval( $data->page_is_redirect );
417 $this->mLatest = intval( $data->page_latest );
418 // Bug 37225: $latest may no longer match the cached latest Revision object.
419 // Double-check the ID of any cached latest Revision object for consistency.
420 if ( $this->mLastRevision && $this->mLastRevision->getId() != $this->mLatest ) {
421 $this->mLastRevision = null;
422 $this->mTimestamp = '';
423 }
424 } else {
425 $lc->addBadLinkObj( $this->mTitle );
426
427 $this->mTitle->loadFromRow( false );
428
429 $this->clearCacheFields();
430
431 $this->mId = 0;
432 }
433
434 $this->mDataLoaded = true;
435 $this->mDataLoadedFrom = self::convertSelectType( $from );
436 }
437
438 /**
439 * @return int Page ID
440 */
441 public function getId() {
442 if ( !$this->mDataLoaded ) {
443 $this->loadPageData();
444 }
445 return $this->mId;
446 }
447
448 /**
449 * @return bool Whether or not the page exists in the database
450 */
451 public function exists() {
452 if ( !$this->mDataLoaded ) {
453 $this->loadPageData();
454 }
455 return $this->mId > 0;
456 }
457
458 /**
459 * Check if this page is something we're going to be showing
460 * some sort of sensible content for. If we return false, page
461 * views (plain action=view) will return an HTTP 404 response,
462 * so spiders and robots can know they're following a bad link.
463 *
464 * @return bool
465 */
466 public function hasViewableContent() {
467 return $this->exists() || $this->mTitle->isAlwaysKnown();
468 }
469
470 /**
471 * Tests if the article content represents a redirect
472 *
473 * @return bool
474 */
475 public function isRedirect() {
476 $content = $this->getContent();
477 if ( !$content ) {
478 return false;
479 }
480
481 return $content->isRedirect();
482 }
483
484 /**
485 * Returns the page's content model id (see the CONTENT_MODEL_XXX constants).
486 *
487 * Will use the revisions actual content model if the page exists,
488 * and the page's default if the page doesn't exist yet.
489 *
490 * @return string
491 *
492 * @since 1.21
493 */
494 public function getContentModel() {
495 if ( $this->exists() ) {
496 // look at the revision's actual content model
497 $rev = $this->getRevision();
498
499 if ( $rev !== null ) {
500 return $rev->getContentModel();
501 } else {
502 $title = $this->mTitle->getPrefixedDBkey();
503 wfWarn( "Page $title exists but has no (visible) revisions!" );
504 }
505 }
506
507 // use the default model for this page
508 return $this->mTitle->getContentModel();
509 }
510
511 /**
512 * Loads page_touched and returns a value indicating if it should be used
513 * @return bool True if not a redirect
514 */
515 public function checkTouched() {
516 if ( !$this->mDataLoaded ) {
517 $this->loadPageData();
518 }
519 return !$this->mIsRedirect;
520 }
521
522 /**
523 * Get the page_touched field
524 * @return string Containing GMT timestamp
525 */
526 public function getTouched() {
527 if ( !$this->mDataLoaded ) {
528 $this->loadPageData();
529 }
530 return $this->mTouched;
531 }
532
533 /**
534 * Get the page_links_updated field
535 * @return string|null Containing GMT timestamp
536 */
537 public function getLinksTimestamp() {
538 if ( !$this->mDataLoaded ) {
539 $this->loadPageData();
540 }
541 return $this->mLinksUpdated;
542 }
543
544 /**
545 * Get the page_latest field
546 * @return int The rev_id of current revision
547 */
548 public function getLatest() {
549 if ( !$this->mDataLoaded ) {
550 $this->loadPageData();
551 }
552 return (int)$this->mLatest;
553 }
554
555 /**
556 * Get the Revision object of the oldest revision
557 * @return Revision|null
558 */
559 public function getOldestRevision() {
560
561 // Try using the slave database first, then try the master
562 $continue = 2;
563 $db = wfGetDB( DB_SLAVE );
564 $revSelectFields = Revision::selectFields();
565
566 $row = null;
567 while ( $continue ) {
568 $row = $db->selectRow(
569 array( 'page', 'revision' ),
570 $revSelectFields,
571 array(
572 'page_namespace' => $this->mTitle->getNamespace(),
573 'page_title' => $this->mTitle->getDBkey(),
574 'rev_page = page_id'
575 ),
576 __METHOD__,
577 array(
578 'ORDER BY' => 'rev_timestamp ASC'
579 )
580 );
581
582 if ( $row ) {
583 $continue = 0;
584 } else {
585 $db = wfGetDB( DB_MASTER );
586 $continue--;
587 }
588 }
589
590 return $row ? Revision::newFromRow( $row ) : null;
591 }
592
593 /**
594 * Loads everything except the text
595 * This isn't necessary for all uses, so it's only done if needed.
596 */
597 protected function loadLastEdit() {
598 if ( $this->mLastRevision !== null ) {
599 return; // already loaded
600 }
601
602 $latest = $this->getLatest();
603 if ( !$latest ) {
604 return; // page doesn't exist or is missing page_latest info
605 }
606
607 // Bug 37225: if session S1 loads the page row FOR UPDATE, the result always includes the
608 // latest changes committed. This is true even within REPEATABLE-READ transactions, where
609 // S1 normally only sees changes committed before the first S1 SELECT. Thus we need S1 to
610 // also gets the revision row FOR UPDATE; otherwise, it may not find it since a page row
611 // UPDATE and revision row INSERT by S2 may have happened after the first S1 SELECT.
612 // http://dev.mysql.com/doc/refman/5.0/en/set-transaction.html#isolevel_repeatable-read.
613 $flags = ( $this->mDataLoadedFrom == self::READ_LOCKING ) ? Revision::READ_LOCKING : 0;
614 $revision = Revision::newFromPageId( $this->getId(), $latest, $flags );
615 if ( $revision ) { // sanity
616 $this->setLastEdit( $revision );
617 }
618 }
619
620 /**
621 * Set the latest revision
622 * @param Revision $revision
623 */
624 protected function setLastEdit( Revision $revision ) {
625 $this->mLastRevision = $revision;
626 $this->mTimestamp = $revision->getTimestamp();
627 }
628
629 /**
630 * Get the latest revision
631 * @return Revision|null
632 */
633 public function getRevision() {
634 $this->loadLastEdit();
635 if ( $this->mLastRevision ) {
636 return $this->mLastRevision;
637 }
638 return null;
639 }
640
641 /**
642 * Get the content of the current revision. No side-effects...
643 *
644 * @param int $audience One of:
645 * Revision::FOR_PUBLIC to be displayed to all users
646 * Revision::FOR_THIS_USER to be displayed to $wgUser
647 * Revision::RAW get the text regardless of permissions
648 * @param User $user User object to check for, only if FOR_THIS_USER is passed
649 * to the $audience parameter
650 * @return Content|null The content of the current revision
651 *
652 * @since 1.21
653 */
654 public function getContent( $audience = Revision::FOR_PUBLIC, User $user = null ) {
655 $this->loadLastEdit();
656 if ( $this->mLastRevision ) {
657 return $this->mLastRevision->getContent( $audience, $user );
658 }
659 return null;
660 }
661
662 /**
663 * Get the text of the current revision. No side-effects...
664 *
665 * @param int $audience One of:
666 * Revision::FOR_PUBLIC to be displayed to all users
667 * Revision::FOR_THIS_USER to be displayed to the given user
668 * Revision::RAW get the text regardless of permissions
669 * @param User $user User object to check for, only if FOR_THIS_USER is passed
670 * to the $audience parameter
671 * @return string|bool The text of the current revision
672 * @deprecated since 1.21, getContent() should be used instead.
673 */
674 public function getText( $audience = Revision::FOR_PUBLIC, User $user = null ) {
675 ContentHandler::deprecated( __METHOD__, '1.21' );
676
677 $this->loadLastEdit();
678 if ( $this->mLastRevision ) {
679 return $this->mLastRevision->getText( $audience, $user );
680 }
681 return false;
682 }
683
684 /**
685 * Get the text of the current revision. No side-effects...
686 *
687 * @return string|bool The text of the current revision. False on failure
688 * @deprecated since 1.21, getContent() should be used instead.
689 */
690 public function getRawText() {
691 ContentHandler::deprecated( __METHOD__, '1.21' );
692
693 return $this->getText( Revision::RAW );
694 }
695
696 /**
697 * @return string MW timestamp of last article revision
698 */
699 public function getTimestamp() {
700 // Check if the field has been filled by WikiPage::setTimestamp()
701 if ( !$this->mTimestamp ) {
702 $this->loadLastEdit();
703 }
704
705 return wfTimestamp( TS_MW, $this->mTimestamp );
706 }
707
708 /**
709 * Set the page timestamp (use only to avoid DB queries)
710 * @param string $ts MW timestamp of last article revision
711 * @return void
712 */
713 public function setTimestamp( $ts ) {
714 $this->mTimestamp = wfTimestamp( TS_MW, $ts );
715 }
716
717 /**
718 * @param int $audience One of:
719 * Revision::FOR_PUBLIC to be displayed to all users
720 * Revision::FOR_THIS_USER to be displayed to the given user
721 * Revision::RAW get the text regardless of permissions
722 * @param User $user User object to check for, only if FOR_THIS_USER is passed
723 * to the $audience parameter
724 * @return int User ID for the user that made the last article revision
725 */
726 public function getUser( $audience = Revision::FOR_PUBLIC, User $user = null ) {
727 $this->loadLastEdit();
728 if ( $this->mLastRevision ) {
729 return $this->mLastRevision->getUser( $audience, $user );
730 } else {
731 return -1;
732 }
733 }
734
735 /**
736 * Get the User object of the user who created the page
737 * @param int $audience One of:
738 * Revision::FOR_PUBLIC to be displayed to all users
739 * Revision::FOR_THIS_USER to be displayed to the given user
740 * Revision::RAW get the text regardless of permissions
741 * @param User $user User object to check for, only if FOR_THIS_USER is passed
742 * to the $audience parameter
743 * @return User|null
744 */
745 public function getCreator( $audience = Revision::FOR_PUBLIC, User $user = null ) {
746 $revision = $this->getOldestRevision();
747 if ( $revision ) {
748 $userName = $revision->getUserText( $audience, $user );
749 return User::newFromName( $userName, false );
750 } else {
751 return null;
752 }
753 }
754
755 /**
756 * @param int $audience One of:
757 * Revision::FOR_PUBLIC to be displayed to all users
758 * Revision::FOR_THIS_USER to be displayed to the given user
759 * Revision::RAW get the text regardless of permissions
760 * @param User $user User object to check for, only if FOR_THIS_USER is passed
761 * to the $audience parameter
762 * @return string Username of the user that made the last article revision
763 */
764 public function getUserText( $audience = Revision::FOR_PUBLIC, User $user = null ) {
765 $this->loadLastEdit();
766 if ( $this->mLastRevision ) {
767 return $this->mLastRevision->getUserText( $audience, $user );
768 } else {
769 return '';
770 }
771 }
772
773 /**
774 * @param int $audience One of:
775 * Revision::FOR_PUBLIC to be displayed to all users
776 * Revision::FOR_THIS_USER to be displayed to the given user
777 * Revision::RAW get the text regardless of permissions
778 * @param User $user User object to check for, only if FOR_THIS_USER is passed
779 * to the $audience parameter
780 * @return string Comment stored for the last article revision
781 */
782 public function getComment( $audience = Revision::FOR_PUBLIC, User $user = null ) {
783 $this->loadLastEdit();
784 if ( $this->mLastRevision ) {
785 return $this->mLastRevision->getComment( $audience, $user );
786 } else {
787 return '';
788 }
789 }
790
791 /**
792 * Returns true if last revision was marked as "minor edit"
793 *
794 * @return bool Minor edit indicator for the last article revision.
795 */
796 public function getMinorEdit() {
797 $this->loadLastEdit();
798 if ( $this->mLastRevision ) {
799 return $this->mLastRevision->isMinor();
800 } else {
801 return false;
802 }
803 }
804
805 /**
806 * Get the cached timestamp for the last time the page changed.
807 * This is only used to help handle slave lag by comparing to page_touched.
808 * @return string MW timestamp
809 */
810 protected function getCachedLastEditTime() {
811 global $wgMemc;
812 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle->getPrefixedDBkey() ) );
813 return $wgMemc->get( $key );
814 }
815
816 /**
817 * Set the cached timestamp for the last time the page changed.
818 * This is only used to help handle slave lag by comparing to page_touched.
819 * @param string $timestamp
820 * @return void
821 */
822 public function setCachedLastEditTime( $timestamp ) {
823 global $wgMemc;
824 $key = wfMemcKey( 'page-lastedit', md5( $this->mTitle->getPrefixedDBkey() ) );
825 $wgMemc->set( $key, wfTimestamp( TS_MW, $timestamp ), 60 * 15 );
826 }
827
828 /**
829 * Determine whether a page would be suitable for being counted as an
830 * article in the site_stats table based on the title & its content
831 *
832 * @param object|bool $editInfo (false): object returned by prepareTextForEdit(),
833 * if false, the current database state will be used
834 * @return bool
835 */
836 public function isCountable( $editInfo = false ) {
837 global $wgArticleCountMethod;
838
839 if ( !$this->mTitle->isContentPage() ) {
840 return false;
841 }
842
843 if ( $editInfo ) {
844 $content = $editInfo->pstContent;
845 } else {
846 $content = $this->getContent();
847 }
848
849 if ( !$content || $content->isRedirect() ) {
850 return false;
851 }
852
853 $hasLinks = null;
854
855 if ( $wgArticleCountMethod === 'link' ) {
856 // nasty special case to avoid re-parsing to detect links
857
858 if ( $editInfo ) {
859 // ParserOutput::getLinks() is a 2D array of page links, so
860 // to be really correct we would need to recurse in the array
861 // but the main array should only have items in it if there are
862 // links.
863 $hasLinks = (bool)count( $editInfo->output->getLinks() );
864 } else {
865 $hasLinks = (bool)wfGetDB( DB_SLAVE )->selectField( 'pagelinks', 1,
866 array( 'pl_from' => $this->getId() ), __METHOD__ );
867 }
868 }
869
870 return $content->isCountable( $hasLinks );
871 }
872
873 /**
874 * If this page is a redirect, get its target
875 *
876 * The target will be fetched from the redirect table if possible.
877 * If this page doesn't have an entry there, call insertRedirect()
878 * @return Title|null Title object, or null if this page is not a redirect
879 */
880 public function getRedirectTarget() {
881 if ( !$this->mTitle->isRedirect() ) {
882 return null;
883 }
884
885 if ( $this->mRedirectTarget !== null ) {
886 return $this->mRedirectTarget;
887 }
888
889 // Query the redirect table
890 $dbr = wfGetDB( DB_SLAVE );
891 $row = $dbr->selectRow( 'redirect',
892 array( 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ),
893 array( 'rd_from' => $this->getId() ),
894 __METHOD__
895 );
896
897 // rd_fragment and rd_interwiki were added later, populate them if empty
898 if ( $row && !is_null( $row->rd_fragment ) && !is_null( $row->rd_interwiki ) ) {
899 $this->mRedirectTarget = Title::makeTitle(
900 $row->rd_namespace, $row->rd_title,
901 $row->rd_fragment, $row->rd_interwiki );
902 return $this->mRedirectTarget;
903 }
904
905 // This page doesn't have an entry in the redirect table
906 $this->mRedirectTarget = $this->insertRedirect();
907 return $this->mRedirectTarget;
908 }
909
910 /**
911 * Insert an entry for this page into the redirect table.
912 *
913 * Don't call this function directly unless you know what you're doing.
914 * @return Title|null Title object or null if not a redirect
915 */
916 public function insertRedirect() {
917 // recurse through to only get the final target
918 $content = $this->getContent();
919 $retval = $content ? $content->getUltimateRedirectTarget() : null;
920 if ( !$retval ) {
921 return null;
922 }
923 $this->insertRedirectEntry( $retval );
924 return $retval;
925 }
926
927 /**
928 * Insert or update the redirect table entry for this page to indicate
929 * it redirects to $rt .
930 * @param Title $rt Redirect target
931 */
932 public function insertRedirectEntry( $rt ) {
933 $dbw = wfGetDB( DB_MASTER );
934 $dbw->replace( 'redirect', array( 'rd_from' ),
935 array(
936 'rd_from' => $this->getId(),
937 'rd_namespace' => $rt->getNamespace(),
938 'rd_title' => $rt->getDBkey(),
939 'rd_fragment' => $rt->getFragment(),
940 'rd_interwiki' => $rt->getInterwiki(),
941 ),
942 __METHOD__
943 );
944 }
945
946 /**
947 * Get the Title object or URL this page redirects to
948 *
949 * @return bool|Title|string False, Title of in-wiki target, or string with URL
950 */
951 public function followRedirect() {
952 return $this->getRedirectURL( $this->getRedirectTarget() );
953 }
954
955 /**
956 * Get the Title object or URL to use for a redirect. We use Title
957 * objects for same-wiki, non-special redirects and URLs for everything
958 * else.
959 * @param Title $rt Redirect target
960 * @return bool|Title|string False, Title object of local target, or string with URL
961 */
962 public function getRedirectURL( $rt ) {
963 if ( !$rt ) {
964 return false;
965 }
966
967 if ( $rt->isExternal() ) {
968 if ( $rt->isLocal() ) {
969 // Offsite wikis need an HTTP redirect.
970 //
971 // This can be hard to reverse and may produce loops,
972 // so they may be disabled in the site configuration.
973 $source = $this->mTitle->getFullURL( 'redirect=no' );
974 return $rt->getFullURL( array( 'rdfrom' => $source ) );
975 } else {
976 // External pages without "local" bit set are not valid
977 // redirect targets
978 return false;
979 }
980 }
981
982 if ( $rt->isSpecialPage() ) {
983 // Gotta handle redirects to special pages differently:
984 // Fill the HTTP response "Location" header and ignore
985 // the rest of the page we're on.
986 //
987 // Some pages are not valid targets
988 if ( $rt->isValidRedirectTarget() ) {
989 return $rt->getFullURL();
990 } else {
991 return false;
992 }
993 }
994
995 return $rt;
996 }
997
998 /**
999 * Get a list of users who have edited this article, not including the user who made
1000 * the most recent revision, which you can get from $article->getUser() if you want it
1001 * @return UserArrayFromResult
1002 */
1003 public function getContributors() {
1004 // @todo FIXME: This is expensive; cache this info somewhere.
1005
1006 $dbr = wfGetDB( DB_SLAVE );
1007
1008 if ( $dbr->implicitGroupby() ) {
1009 $realNameField = 'user_real_name';
1010 } else {
1011 $realNameField = 'MIN(user_real_name) AS user_real_name';
1012 }
1013
1014 $tables = array( 'revision', 'user' );
1015
1016 $fields = array(
1017 'user_id' => 'rev_user',
1018 'user_name' => 'rev_user_text',
1019 $realNameField,
1020 'timestamp' => 'MAX(rev_timestamp)',
1021 );
1022
1023 $conds = array( 'rev_page' => $this->getId() );
1024
1025 // The user who made the top revision gets credited as "this page was last edited by
1026 // John, based on contributions by Tom, Dick and Harry", so don't include them twice.
1027 $user = $this->getUser();
1028 if ( $user ) {
1029 $conds[] = "rev_user != $user";
1030 } else {
1031 $conds[] = "rev_user_text != {$dbr->addQuotes( $this->getUserText() )}";
1032 }
1033
1034 $conds[] = "{$dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER )} = 0"; // username hidden?
1035
1036 $jconds = array(
1037 'user' => array( 'LEFT JOIN', 'rev_user = user_id' ),
1038 );
1039
1040 $options = array(
1041 'GROUP BY' => array( 'rev_user', 'rev_user_text' ),
1042 'ORDER BY' => 'timestamp DESC',
1043 );
1044
1045 $res = $dbr->select( $tables, $fields, $conds, __METHOD__, $options, $jconds );
1046 return new UserArrayFromResult( $res );
1047 }
1048
1049 /**
1050 * Get the last N authors
1051 * @param int $num Number of revisions to get
1052 * @param int|string $revLatest The latest rev_id, selected from the master (optional)
1053 * @return array Array of authors, duplicates not removed
1054 */
1055 public function getLastNAuthors( $num, $revLatest = 0 ) {
1056 // First try the slave
1057 // If that doesn't have the latest revision, try the master
1058 $continue = 2;
1059 $db = wfGetDB( DB_SLAVE );
1060
1061 do {
1062 $res = $db->select( array( 'page', 'revision' ),
1063 array( 'rev_id', 'rev_user_text' ),
1064 array(
1065 'page_namespace' => $this->mTitle->getNamespace(),
1066 'page_title' => $this->mTitle->getDBkey(),
1067 'rev_page = page_id'
1068 ), __METHOD__,
1069 array(
1070 'ORDER BY' => 'rev_timestamp DESC',
1071 'LIMIT' => $num
1072 )
1073 );
1074
1075 if ( !$res ) {
1076 return array();
1077 }
1078
1079 $row = $db->fetchObject( $res );
1080
1081 if ( $continue == 2 && $revLatest && $row->rev_id != $revLatest ) {
1082 $db = wfGetDB( DB_MASTER );
1083 $continue--;
1084 } else {
1085 $continue = 0;
1086 }
1087 } while ( $continue );
1088
1089 $authors = array( $row->rev_user_text );
1090
1091 foreach ( $res as $row ) {
1092 $authors[] = $row->rev_user_text;
1093 }
1094
1095 return $authors;
1096 }
1097
1098 /**
1099 * Should the parser cache be used?
1100 *
1101 * @param ParserOptions $parserOptions ParserOptions to check
1102 * @param int $oldid
1103 * @return bool
1104 */
1105 public function isParserCacheUsed( ParserOptions $parserOptions, $oldid ) {
1106 global $wgEnableParserCache;
1107
1108 return $wgEnableParserCache
1109 && $parserOptions->getStubThreshold() == 0
1110 && $this->exists()
1111 && ( $oldid === null || $oldid === 0 || $oldid === $this->getLatest() )
1112 && $this->getContentHandler()->isParserCacheSupported();
1113 }
1114
1115 /**
1116 * Get a ParserOutput for the given ParserOptions and revision ID.
1117 * The parser cache will be used if possible.
1118 *
1119 * @since 1.19
1120 * @param ParserOptions $parserOptions ParserOptions to use for the parse operation
1121 * @param null|int $oldid Revision ID to get the text from, passing null or 0 will
1122 * get the current revision (default value)
1123 *
1124 * @return ParserOutput|bool ParserOutput or false if the revision was not found
1125 */
1126 public function getParserOutput( ParserOptions $parserOptions, $oldid = null ) {
1127
1128 $useParserCache = $this->isParserCacheUsed( $parserOptions, $oldid );
1129 wfDebug( __METHOD__ . ': using parser cache: ' . ( $useParserCache ? 'yes' : 'no' ) . "\n" );
1130 if ( $parserOptions->getStubThreshold() ) {
1131 wfIncrStats( 'pcache_miss_stub' );
1132 }
1133
1134 if ( $useParserCache ) {
1135 $parserOutput = ParserCache::singleton()->get( $this, $parserOptions );
1136 if ( $parserOutput !== false ) {
1137 return $parserOutput;
1138 }
1139 }
1140
1141 if ( $oldid === null || $oldid === 0 ) {
1142 $oldid = $this->getLatest();
1143 }
1144
1145 $pool = new PoolWorkArticleView( $this, $parserOptions, $oldid, $useParserCache );
1146 $pool->execute();
1147
1148 return $pool->getParserOutput();
1149 }
1150
1151 /**
1152 * Do standard deferred updates after page view (existing or missing page)
1153 * @param User $user The relevant user
1154 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
1155 */
1156 public function doViewUpdates( User $user, $oldid = 0 ) {
1157 if ( wfReadOnly() ) {
1158 return;
1159 }
1160
1161 // Update newtalk / watchlist notification status
1162 $user->clearNotification( $this->mTitle, $oldid );
1163 }
1164
1165 /**
1166 * Perform the actions of a page purging
1167 * @return bool
1168 */
1169 public function doPurge() {
1170 global $wgUseSquid;
1171
1172 if ( !Hooks::run( 'ArticlePurge', array( &$this ) ) ) {
1173 return false;
1174 }
1175
1176 // Invalidate the cache
1177 $this->mTitle->invalidateCache();
1178
1179 if ( $wgUseSquid ) {
1180 // Commit the transaction before the purge is sent
1181 $dbw = wfGetDB( DB_MASTER );
1182 $dbw->commit( __METHOD__ );
1183
1184 // Send purge
1185 $update = SquidUpdate::newSimplePurge( $this->mTitle );
1186 $update->doUpdate();
1187 }
1188
1189 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
1190 // @todo move this logic to MessageCache
1191
1192 if ( $this->exists() ) {
1193 // NOTE: use transclusion text for messages.
1194 // This is consistent with MessageCache::getMsgFromNamespace()
1195
1196 $content = $this->getContent();
1197 $text = $content === null ? null : $content->getWikitextForTransclusion();
1198
1199 if ( $text === null ) {
1200 $text = false;
1201 }
1202 } else {
1203 $text = false;
1204 }
1205
1206 MessageCache::singleton()->replace( $this->mTitle->getDBkey(), $text );
1207 }
1208 return true;
1209 }
1210
1211 /**
1212 * Insert a new empty page record for this article.
1213 * This *must* be followed up by creating a revision
1214 * and running $this->updateRevisionOn( ... );
1215 * or else the record will be left in a funky state.
1216 * Best if all done inside a transaction.
1217 *
1218 * @param DatabaseBase $dbw
1219 * @return int The newly created page_id key, or false if the title already existed
1220 */
1221 public function insertOn( $dbw ) {
1222
1223 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1224 $dbw->insert( 'page', array(
1225 'page_id' => $page_id,
1226 'page_namespace' => $this->mTitle->getNamespace(),
1227 'page_title' => $this->mTitle->getDBkey(),
1228 'page_restrictions' => '',
1229 'page_is_redirect' => 0, // Will set this shortly...
1230 'page_is_new' => 1,
1231 'page_random' => wfRandom(),
1232 'page_touched' => $dbw->timestamp(),
1233 'page_latest' => 0, // Fill this in shortly...
1234 'page_len' => 0, // Fill this in shortly...
1235 ), __METHOD__, 'IGNORE' );
1236
1237 $affected = $dbw->affectedRows();
1238
1239 if ( $affected ) {
1240 $newid = $dbw->insertId();
1241 $this->mId = $newid;
1242 $this->mTitle->resetArticleID( $newid );
1243 }
1244
1245 return $affected ? $newid : false;
1246 }
1247
1248 /**
1249 * Update the page record to point to a newly saved revision.
1250 *
1251 * @param DatabaseBase $dbw
1252 * @param Revision $revision For ID number, and text used to set
1253 * length and redirect status fields
1254 * @param int $lastRevision If given, will not overwrite the page field
1255 * when different from the currently set value.
1256 * Giving 0 indicates the new page flag should be set on.
1257 * @param bool $lastRevIsRedirect If given, will optimize adding and
1258 * removing rows in redirect table.
1259 * @return bool True on success, false on failure
1260 */
1261 public function updateRevisionOn( $dbw, $revision, $lastRevision = null,
1262 $lastRevIsRedirect = null
1263 ) {
1264 global $wgContentHandlerUseDB;
1265
1266 $content = $revision->getContent();
1267 $len = $content ? $content->getSize() : 0;
1268 $rt = $content ? $content->getUltimateRedirectTarget() : null;
1269
1270 $conditions = array( 'page_id' => $this->getId() );
1271
1272 if ( !is_null( $lastRevision ) ) {
1273 // An extra check against threads stepping on each other
1274 $conditions['page_latest'] = $lastRevision;
1275 }
1276
1277 $now = wfTimestampNow();
1278 $row = array( /* SET */
1279 'page_latest' => $revision->getId(),
1280 'page_touched' => $dbw->timestamp( $now ),
1281 'page_is_new' => ( $lastRevision === 0 ) ? 1 : 0,
1282 'page_is_redirect' => $rt !== null ? 1 : 0,
1283 'page_len' => $len,
1284 );
1285
1286 if ( $wgContentHandlerUseDB ) {
1287 $row['page_content_model'] = $revision->getContentModel();
1288 }
1289
1290 $dbw->update( 'page',
1291 $row,
1292 $conditions,
1293 __METHOD__ );
1294
1295 $result = $dbw->affectedRows() > 0;
1296 if ( $result ) {
1297 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1298 $this->setLastEdit( $revision );
1299 $this->setCachedLastEditTime( $now );
1300 $this->mLatest = $revision->getId();
1301 $this->mIsRedirect = (bool)$rt;
1302 // Update the LinkCache.
1303 LinkCache::singleton()->addGoodLinkObj( $this->getId(), $this->mTitle, $len, $this->mIsRedirect,
1304 $this->mLatest, $revision->getContentModel() );
1305 }
1306
1307 return $result;
1308 }
1309
1310 /**
1311 * Add row to the redirect table if this is a redirect, remove otherwise.
1312 *
1313 * @param DatabaseBase $dbw
1314 * @param Title $redirectTitle Title object pointing to the redirect target,
1315 * or NULL if this is not a redirect
1316 * @param null|bool $lastRevIsRedirect If given, will optimize adding and
1317 * removing rows in redirect table.
1318 * @return bool True on success, false on failure
1319 * @private
1320 */
1321 public function updateRedirectOn( $dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1322 // Always update redirects (target link might have changed)
1323 // Update/Insert if we don't know if the last revision was a redirect or not
1324 // Delete if changing from redirect to non-redirect
1325 $isRedirect = !is_null( $redirectTitle );
1326
1327 if ( !$isRedirect && $lastRevIsRedirect === false ) {
1328 return true;
1329 }
1330
1331 if ( $isRedirect ) {
1332 $this->insertRedirectEntry( $redirectTitle );
1333 } else {
1334 // This is not a redirect, remove row from redirect table
1335 $where = array( 'rd_from' => $this->getId() );
1336 $dbw->delete( 'redirect', $where, __METHOD__ );
1337 }
1338
1339 if ( $this->getTitle()->getNamespace() == NS_FILE ) {
1340 RepoGroup::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1341 }
1342
1343 return ( $dbw->affectedRows() != 0 );
1344 }
1345
1346 /**
1347 * If the given revision is newer than the currently set page_latest,
1348 * update the page record. Otherwise, do nothing.
1349 *
1350 * @deprecated since 1.24, use updateRevisionOn instead
1351 *
1352 * @param DatabaseBase $dbw
1353 * @param Revision $revision
1354 * @return bool
1355 */
1356 public function updateIfNewerOn( $dbw, $revision ) {
1357
1358 $row = $dbw->selectRow(
1359 array( 'revision', 'page' ),
1360 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1361 array(
1362 'page_id' => $this->getId(),
1363 'page_latest=rev_id' ),
1364 __METHOD__ );
1365
1366 if ( $row ) {
1367 if ( wfTimestamp( TS_MW, $row->rev_timestamp ) >= $revision->getTimestamp() ) {
1368 return false;
1369 }
1370 $prev = $row->rev_id;
1371 $lastRevIsRedirect = (bool)$row->page_is_redirect;
1372 } else {
1373 // No or missing previous revision; mark the page as new
1374 $prev = 0;
1375 $lastRevIsRedirect = null;
1376 }
1377
1378 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1379
1380 return $ret;
1381 }
1382
1383 /**
1384 * Get the content that needs to be saved in order to undo all revisions
1385 * between $undo and $undoafter. Revisions must belong to the same page,
1386 * must exist and must not be deleted
1387 * @param Revision $undo
1388 * @param Revision $undoafter Must be an earlier revision than $undo
1389 * @return mixed String on success, false on failure
1390 * @since 1.21
1391 * Before we had the Content object, this was done in getUndoText
1392 */
1393 public function getUndoContent( Revision $undo, Revision $undoafter = null ) {
1394 $handler = $undo->getContentHandler();
1395 return $handler->getUndoContent( $this->getRevision(), $undo, $undoafter );
1396 }
1397
1398 /**
1399 * Get the text that needs to be saved in order to undo all revisions
1400 * between $undo and $undoafter. Revisions must belong to the same page,
1401 * must exist and must not be deleted
1402 * @param Revision $undo
1403 * @param Revision $undoafter Must be an earlier revision than $undo
1404 * @return string|bool String on success, false on failure
1405 * @deprecated since 1.21: use ContentHandler::getUndoContent() instead.
1406 */
1407 public function getUndoText( Revision $undo, Revision $undoafter = null ) {
1408 ContentHandler::deprecated( __METHOD__, '1.21' );
1409
1410 $this->loadLastEdit();
1411
1412 if ( $this->mLastRevision ) {
1413 if ( is_null( $undoafter ) ) {
1414 $undoafter = $undo->getPrevious();
1415 }
1416
1417 $handler = $this->getContentHandler();
1418 $undone = $handler->getUndoContent( $this->mLastRevision, $undo, $undoafter );
1419
1420 if ( !$undone ) {
1421 return false;
1422 } else {
1423 return ContentHandler::getContentText( $undone );
1424 }
1425 }
1426
1427 return false;
1428 }
1429
1430 /**
1431 * @param string|number|null|bool $sectionId Section identifier as a number or string
1432 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1433 * or 'new' for a new section.
1434 * @param string $text New text of the section.
1435 * @param string $sectionTitle New section's subject, only if $section is "new".
1436 * @param string $edittime Revision timestamp or null to use the current revision.
1437 *
1438 * @throws MWException
1439 * @return string New complete article text, or null if error.
1440 *
1441 * @deprecated since 1.21, use replaceSectionAtRev() instead
1442 */
1443 public function replaceSection( $sectionId, $text, $sectionTitle = '',
1444 $edittime = null
1445 ) {
1446 ContentHandler::deprecated( __METHOD__, '1.21' );
1447
1448 //NOTE: keep condition in sync with condition in replaceSectionContent!
1449 if ( strval( $sectionId ) === '' ) {
1450 // Whole-page edit; let the whole text through
1451 return $text;
1452 }
1453
1454 if ( !$this->supportsSections() ) {
1455 throw new MWException( "sections not supported for content model " .
1456 $this->getContentHandler()->getModelID() );
1457 }
1458
1459 // could even make section title, but that's not required.
1460 $sectionContent = ContentHandler::makeContent( $text, $this->getTitle() );
1461
1462 $newContent = $this->replaceSectionContent( $sectionId, $sectionContent, $sectionTitle,
1463 $edittime );
1464
1465 return ContentHandler::getContentText( $newContent );
1466 }
1467
1468 /**
1469 * Returns true if this page's content model supports sections.
1470 *
1471 * @return bool
1472 *
1473 * @todo The skin should check this and not offer section functionality if
1474 * sections are not supported.
1475 * @todo The EditPage should check this and not offer section functionality
1476 * if sections are not supported.
1477 */
1478 public function supportsSections() {
1479 return $this->getContentHandler()->supportsSections();
1480 }
1481
1482 /**
1483 * @param string|number|null|bool $sectionId Section identifier as a number or string
1484 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1485 * or 'new' for a new section.
1486 * @param Content $sectionContent New content of the section.
1487 * @param string $sectionTitle New section's subject, only if $section is "new".
1488 * @param string $edittime Revision timestamp or null to use the current revision.
1489 *
1490 * @throws MWException
1491 * @return Content New complete article content, or null if error.
1492 *
1493 * @since 1.21
1494 * @deprecated since 1.24, use replaceSectionAtRev instead
1495 */
1496 public function replaceSectionContent( $sectionId, Content $sectionContent, $sectionTitle = '',
1497 $edittime = null ) {
1498
1499 $baseRevId = null;
1500 if ( $edittime && $sectionId !== 'new' ) {
1501 $dbw = wfGetDB( DB_MASTER );
1502 $rev = Revision::loadFromTimestamp( $dbw, $this->mTitle, $edittime );
1503 if ( $rev ) {
1504 $baseRevId = $rev->getId();
1505 }
1506 }
1507
1508 return $this->replaceSectionAtRev( $sectionId, $sectionContent, $sectionTitle, $baseRevId );
1509 }
1510
1511 /**
1512 * @param string|number|null|bool $sectionId Section identifier as a number or string
1513 * (e.g. 0, 1 or 'T-1'), null/false or an empty string for the whole page
1514 * or 'new' for a new section.
1515 * @param Content $sectionContent New content of the section.
1516 * @param string $sectionTitle New section's subject, only if $section is "new".
1517 * @param int|null $baseRevId
1518 *
1519 * @throws MWException
1520 * @return Content New complete article content, or null if error.
1521 *
1522 * @since 1.24
1523 */
1524 public function replaceSectionAtRev( $sectionId, Content $sectionContent,
1525 $sectionTitle = '', $baseRevId = null
1526 ) {
1527
1528 if ( strval( $sectionId ) === '' ) {
1529 // Whole-page edit; let the whole text through
1530 $newContent = $sectionContent;
1531 } else {
1532 if ( !$this->supportsSections() ) {
1533 throw new MWException( "sections not supported for content model " .
1534 $this->getContentHandler()->getModelID() );
1535 }
1536
1537 // Bug 30711: always use current version when adding a new section
1538 if ( is_null( $baseRevId ) || $sectionId === 'new' ) {
1539 $oldContent = $this->getContent();
1540 } else {
1541 // TODO: try DB_SLAVE first
1542 $dbw = wfGetDB( DB_MASTER );
1543 $rev = Revision::loadFromId( $dbw, $baseRevId );
1544
1545 if ( !$rev ) {
1546 wfDebug( __METHOD__ . " asked for bogus section (page: " .
1547 $this->getId() . "; section: $sectionId)\n" );
1548 return null;
1549 }
1550
1551 $oldContent = $rev->getContent();
1552 }
1553
1554 if ( !$oldContent ) {
1555 wfDebug( __METHOD__ . ": no page text\n" );
1556 return null;
1557 }
1558
1559 $newContent = $oldContent->replaceSection( $sectionId, $sectionContent, $sectionTitle );
1560 }
1561
1562 return $newContent;
1563 }
1564
1565 /**
1566 * Check flags and add EDIT_NEW or EDIT_UPDATE to them as needed.
1567 * @param int $flags
1568 * @return int Updated $flags
1569 */
1570 public function checkFlags( $flags ) {
1571 if ( !( $flags & EDIT_NEW ) && !( $flags & EDIT_UPDATE ) ) {
1572 if ( $this->exists() ) {
1573 $flags |= EDIT_UPDATE;
1574 } else {
1575 $flags |= EDIT_NEW;
1576 }
1577 }
1578
1579 return $flags;
1580 }
1581
1582 /**
1583 * Change an existing article or create a new article. Updates RC and all necessary caches,
1584 * optionally via the deferred update array.
1585 *
1586 * @param string $text New text
1587 * @param string $summary Edit summary
1588 * @param int $flags Bitfield:
1589 * EDIT_NEW
1590 * Article is known or assumed to be non-existent, create a new one
1591 * EDIT_UPDATE
1592 * Article is known or assumed to be pre-existing, update it
1593 * EDIT_MINOR
1594 * Mark this edit minor, if the user is allowed to do so
1595 * EDIT_SUPPRESS_RC
1596 * Do not log the change in recentchanges
1597 * EDIT_FORCE_BOT
1598 * Mark the edit a "bot" edit regardless of user rights
1599 * EDIT_DEFER_UPDATES
1600 * Defer some of the updates until the end of index.php
1601 * EDIT_AUTOSUMMARY
1602 * Fill in blank summaries with generated text where possible
1603 *
1604 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the
1605 * article will be detected. If EDIT_UPDATE is specified and the article
1606 * doesn't exist, the function will return an edit-gone-missing error. If
1607 * EDIT_NEW is specified and the article does exist, an edit-already-exists
1608 * error will be returned. These two conditions are also possible with
1609 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1610 *
1611 * @param bool|int $baseRevId The revision ID this edit was based off, if any
1612 * @param User $user The user doing the edit
1613 *
1614 * @throws MWException
1615 * @return Status Possible errors:
1616 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't
1617 * set the fatal flag of $status
1618 * edit-gone-missing: In update mode, but the article didn't exist.
1619 * edit-conflict: In update mode, the article changed unexpectedly.
1620 * edit-no-change: Warning that the text was the same as before.
1621 * edit-already-exists: In creation mode, but the article already exists.
1622 *
1623 * Extensions may define additional errors.
1624 *
1625 * $return->value will contain an associative array with members as follows:
1626 * new: Boolean indicating if the function attempted to create a new article.
1627 * revision: The revision object for the inserted revision, or null.
1628 *
1629 * Compatibility note: this function previously returned a boolean value
1630 * indicating success/failure
1631 *
1632 * @deprecated since 1.21: use doEditContent() instead.
1633 */
1634 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
1635 ContentHandler::deprecated( __METHOD__, '1.21' );
1636
1637 $content = ContentHandler::makeContent( $text, $this->getTitle() );
1638
1639 return $this->doEditContent( $content, $summary, $flags, $baseRevId, $user );
1640 }
1641
1642 /**
1643 * Change an existing article or create a new article. Updates RC and all necessary caches,
1644 * optionally via the deferred update array.
1645 *
1646 * @param Content $content New content
1647 * @param string $summary Edit summary
1648 * @param int $flags Bitfield:
1649 * EDIT_NEW
1650 * Article is known or assumed to be non-existent, create a new one
1651 * EDIT_UPDATE
1652 * Article is known or assumed to be pre-existing, update it
1653 * EDIT_MINOR
1654 * Mark this edit minor, if the user is allowed to do so
1655 * EDIT_SUPPRESS_RC
1656 * Do not log the change in recentchanges
1657 * EDIT_FORCE_BOT
1658 * Mark the edit a "bot" edit regardless of user rights
1659 * EDIT_DEFER_UPDATES
1660 * Defer some of the updates until the end of index.php
1661 * EDIT_AUTOSUMMARY
1662 * Fill in blank summaries with generated text where possible
1663 *
1664 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the
1665 * article will be detected. If EDIT_UPDATE is specified and the article
1666 * doesn't exist, the function will return an edit-gone-missing error. If
1667 * EDIT_NEW is specified and the article does exist, an edit-already-exists
1668 * error will be returned. These two conditions are also possible with
1669 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1670 *
1671 * @param bool|int $baseRevId The revision ID this edit was based off, if any
1672 * @param User $user The user doing the edit
1673 * @param string $serialFormat Format for storing the content in the
1674 * database.
1675 *
1676 * @throws MWException
1677 * @return Status Possible errors:
1678 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't
1679 * set the fatal flag of $status.
1680 * edit-gone-missing: In update mode, but the article didn't exist.
1681 * edit-conflict: In update mode, the article changed unexpectedly.
1682 * edit-no-change: Warning that the text was the same as before.
1683 * edit-already-exists: In creation mode, but the article already exists.
1684 *
1685 * Extensions may define additional errors.
1686 *
1687 * $return->value will contain an associative array with members as follows:
1688 * new: Boolean indicating if the function attempted to create a new article.
1689 * revision: The revision object for the inserted revision, or null.
1690 *
1691 * @since 1.21
1692 */
1693 public function doEditContent( Content $content, $summary, $flags = 0, $baseRevId = false,
1694 User $user = null, $serialFormat = null
1695 ) {
1696 global $wgUser, $wgUseAutomaticEditSummaries, $wgUseRCPatrol, $wgUseNPPatrol;
1697
1698 // Low-level sanity check
1699 if ( $this->mTitle->getText() === '' ) {
1700 throw new MWException( 'Something is trying to edit an article with an empty title' );
1701 }
1702
1703 if ( !$content->getContentHandler()->canBeUsedOn( $this->getTitle() ) ) {
1704 return Status::newFatal( 'content-not-allowed-here',
1705 ContentHandler::getLocalizedName( $content->getModel() ),
1706 $this->getTitle()->getPrefixedText() );
1707 }
1708
1709 $user = is_null( $user ) ? $wgUser : $user;
1710 $status = Status::newGood( array() );
1711
1712 // Load the data from the master database if needed.
1713 // The caller may already loaded it from the master or even loaded it using
1714 // SELECT FOR UPDATE, so do not override that using clear().
1715 $this->loadPageData( 'fromdbmaster' );
1716
1717 $flags = $this->checkFlags( $flags );
1718
1719 // handle hook
1720 $hook_args = array( &$this, &$user, &$content, &$summary,
1721 $flags & EDIT_MINOR, null, null, &$flags, &$status );
1722
1723 if ( !Hooks::run( 'PageContentSave', $hook_args )
1724 || !ContentHandler::runLegacyHooks( 'ArticleSave', $hook_args ) ) {
1725
1726 wfDebug( __METHOD__ . ": ArticleSave or ArticleSaveContent hook aborted save!\n" );
1727
1728 if ( $status->isOK() ) {
1729 $status->fatal( 'edit-hook-aborted' );
1730 }
1731
1732 return $status;
1733 }
1734
1735 // Silently ignore EDIT_MINOR if not allowed
1736 $isminor = ( $flags & EDIT_MINOR ) && $user->isAllowed( 'minoredit' );
1737 $bot = $flags & EDIT_FORCE_BOT;
1738
1739 $old_content = $this->getContent( Revision::RAW ); // current revision's content
1740
1741 $oldsize = $old_content ? $old_content->getSize() : 0;
1742 $oldid = $this->getLatest();
1743 $oldIsRedirect = $this->isRedirect();
1744 $oldcountable = $this->isCountable();
1745
1746 $handler = $content->getContentHandler();
1747
1748 // Provide autosummaries if one is not provided and autosummaries are enabled.
1749 if ( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY && $summary == '' ) {
1750 if ( !$old_content ) {
1751 $old_content = null;
1752 }
1753 $summary = $handler->getAutosummary( $old_content, $content, $flags );
1754 }
1755
1756 $editInfo = $this->prepareContentForEdit( $content, null, $user, $serialFormat );
1757 $serialized = $editInfo->pst;
1758
1759 /**
1760 * @var Content $content
1761 */
1762 $content = $editInfo->pstContent;
1763 $newsize = $content->getSize();
1764
1765 $dbw = wfGetDB( DB_MASTER );
1766 $now = wfTimestampNow();
1767 $this->mTimestamp = $now;
1768
1769 if ( $flags & EDIT_UPDATE ) {
1770 // Update article, but only if changed.
1771 $status->value['new'] = false;
1772
1773 if ( !$oldid ) {
1774 // Article gone missing
1775 wfDebug( __METHOD__ . ": EDIT_UPDATE specified but article doesn't exist\n" );
1776 $status->fatal( 'edit-gone-missing' );
1777
1778 return $status;
1779 } elseif ( !$old_content ) {
1780 // Sanity check for bug 37225
1781 throw new MWException( "Could not find text for current revision {$oldid}." );
1782 }
1783
1784 $revision = new Revision( array(
1785 'page' => $this->getId(),
1786 'title' => $this->getTitle(), // for determining the default content model
1787 'comment' => $summary,
1788 'minor_edit' => $isminor,
1789 'text' => $serialized,
1790 'len' => $newsize,
1791 'parent_id' => $oldid,
1792 'user' => $user->getId(),
1793 'user_text' => $user->getName(),
1794 'timestamp' => $now,
1795 'content_model' => $content->getModel(),
1796 'content_format' => $serialFormat,
1797 ) ); // XXX: pass content object?!
1798
1799 $changed = !$content->equals( $old_content );
1800
1801 if ( $changed ) {
1802 $dbw->begin( __METHOD__ );
1803 try {
1804
1805 $prepStatus = $content->prepareSave( $this, $flags, $baseRevId, $user );
1806 $status->merge( $prepStatus );
1807
1808 if ( !$status->isOK() ) {
1809 $dbw->rollback( __METHOD__ );
1810
1811 return $status;
1812 }
1813 $revisionId = $revision->insertOn( $dbw );
1814
1815 // Update page
1816 //
1817 // We check for conflicts by comparing $oldid with the current latest revision ID.
1818 $ok = $this->updateRevisionOn( $dbw, $revision, $oldid, $oldIsRedirect );
1819
1820 if ( !$ok ) {
1821 // Belated edit conflict! Run away!!
1822 $status->fatal( 'edit-conflict' );
1823
1824 $dbw->rollback( __METHOD__ );
1825
1826 return $status;
1827 }
1828
1829 Hooks::run( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId, $user ) );
1830 // Update recentchanges
1831 if ( !( $flags & EDIT_SUPPRESS_RC ) ) {
1832 // Mark as patrolled if the user can do so
1833 $patrolled = $wgUseRCPatrol && !count(
1834 $this->mTitle->getUserPermissionsErrors( 'autopatrol', $user ) );
1835 // Add RC row to the DB
1836 $rc = RecentChange::notifyEdit( $now, $this->mTitle, $isminor, $user, $summary,
1837 $oldid, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1838 $revisionId, $patrolled
1839 );
1840
1841 // Log auto-patrolled edits
1842 if ( $patrolled ) {
1843 PatrolLog::record( $rc, true, $user );
1844 }
1845 }
1846 $user->incEditCount();
1847 } catch ( Exception $e ) {
1848 $dbw->rollback( __METHOD__ );
1849 // Question: Would it perhaps be better if this method turned all
1850 // exceptions into $status's?
1851 throw $e;
1852 }
1853 $dbw->commit( __METHOD__ );
1854 } else {
1855 // Bug 32948: revision ID must be set to page {{REVISIONID}} and
1856 // related variables correctly
1857 $revision->setId( $this->getLatest() );
1858 }
1859
1860 // Update links tables, site stats, etc.
1861 $this->doEditUpdates(
1862 $revision,
1863 $user,
1864 array(
1865 'changed' => $changed,
1866 'oldcountable' => $oldcountable
1867 )
1868 );
1869
1870 if ( !$changed ) {
1871 $status->warning( 'edit-no-change' );
1872 $revision = null;
1873 // Update page_touched, this is usually implicit in the page update
1874 // Other cache updates are done in onArticleEdit()
1875 $this->mTitle->invalidateCache();
1876 }
1877 } else {
1878 // Create new article
1879 $status->value['new'] = true;
1880
1881 $dbw->begin( __METHOD__ );
1882 try {
1883
1884 $prepStatus = $content->prepareSave( $this, $flags, $baseRevId, $user );
1885 $status->merge( $prepStatus );
1886
1887 if ( !$status->isOK() ) {
1888 $dbw->rollback( __METHOD__ );
1889
1890 return $status;
1891 }
1892
1893 $status->merge( $prepStatus );
1894
1895 // Add the page record; stake our claim on this title!
1896 // This will return false if the article already exists
1897 $newid = $this->insertOn( $dbw );
1898
1899 if ( $newid === false ) {
1900 $dbw->rollback( __METHOD__ );
1901 $status->fatal( 'edit-already-exists' );
1902
1903 return $status;
1904 }
1905
1906 // Save the revision text...
1907 $revision = new Revision( array(
1908 'page' => $newid,
1909 'title' => $this->getTitle(), // for determining the default content model
1910 'comment' => $summary,
1911 'minor_edit' => $isminor,
1912 'text' => $serialized,
1913 'len' => $newsize,
1914 'user' => $user->getId(),
1915 'user_text' => $user->getName(),
1916 'timestamp' => $now,
1917 'content_model' => $content->getModel(),
1918 'content_format' => $serialFormat,
1919 ) );
1920 $revisionId = $revision->insertOn( $dbw );
1921
1922 // Bug 37225: use accessor to get the text as Revision may trim it
1923 $content = $revision->getContent(); // sanity; get normalized version
1924
1925 if ( $content ) {
1926 $newsize = $content->getSize();
1927 }
1928
1929 // Update the page record with revision data
1930 $this->updateRevisionOn( $dbw, $revision, 0 );
1931
1932 Hooks::run( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
1933
1934 // Update recentchanges
1935 if ( !( $flags & EDIT_SUPPRESS_RC ) ) {
1936 // Mark as patrolled if the user can do so
1937 $patrolled = ( $wgUseRCPatrol || $wgUseNPPatrol ) && !count(
1938 $this->mTitle->getUserPermissionsErrors( 'autopatrol', $user ) );
1939 // Add RC row to the DB
1940 $rc = RecentChange::notifyNew( $now, $this->mTitle, $isminor, $user, $summary, $bot,
1941 '', $newsize, $revisionId, $patrolled );
1942
1943 // Log auto-patrolled edits
1944 if ( $patrolled ) {
1945 PatrolLog::record( $rc, true, $user );
1946 }
1947 }
1948 $user->incEditCount();
1949
1950 } catch ( Exception $e ) {
1951 $dbw->rollback( __METHOD__ );
1952 throw $e;
1953 }
1954 $dbw->commit( __METHOD__ );
1955
1956 // Update links, etc.
1957 $this->doEditUpdates( $revision, $user, array( 'created' => true ) );
1958
1959 $hook_args = array( &$this, &$user, $content, $summary,
1960 $flags & EDIT_MINOR, null, null, &$flags, $revision );
1961
1962 ContentHandler::runLegacyHooks( 'ArticleInsertComplete', $hook_args );
1963 Hooks::run( 'PageContentInsertComplete', $hook_args );
1964 }
1965
1966 // Do updates right now unless deferral was requested
1967 if ( !( $flags & EDIT_DEFER_UPDATES ) ) {
1968 DeferredUpdates::doUpdates();
1969 }
1970
1971 // Return the new revision (or null) to the caller
1972 $status->value['revision'] = $revision;
1973
1974 $hook_args = array( &$this, &$user, $content, $summary,
1975 $flags & EDIT_MINOR, null, null, &$flags, $revision, &$status, $baseRevId );
1976
1977 ContentHandler::runLegacyHooks( 'ArticleSaveComplete', $hook_args );
1978 Hooks::run( 'PageContentSaveComplete', $hook_args );
1979
1980 // Promote user to any groups they meet the criteria for
1981 $dbw->onTransactionIdle( function () use ( $user ) {
1982 $user->addAutopromoteOnceGroups( 'onEdit' );
1983 } );
1984
1985 return $status;
1986 }
1987
1988 /**
1989 * Get parser options suitable for rendering the primary article wikitext
1990 *
1991 * @see ContentHandler::makeParserOptions
1992 *
1993 * @param IContextSource|User|string $context One of the following:
1994 * - IContextSource: Use the User and the Language of the provided
1995 * context
1996 * - User: Use the provided User object and $wgLang for the language,
1997 * so use an IContextSource object if possible.
1998 * - 'canonical': Canonical options (anonymous user with default
1999 * preferences and content language).
2000 * @return ParserOptions
2001 */
2002 public function makeParserOptions( $context ) {
2003 $options = $this->getContentHandler()->makeParserOptions( $context );
2004
2005 if ( $this->getTitle()->isConversionTable() ) {
2006 // @todo ConversionTable should become a separate content model, so
2007 // we don't need special cases like this one.
2008 $options->disableContentConversion();
2009 }
2010
2011 return $options;
2012 }
2013
2014 /**
2015 * Prepare text which is about to be saved.
2016 * Returns a stdClass with source, pst and output members
2017 *
2018 * @deprecated since 1.21: use prepareContentForEdit instead.
2019 * @return object
2020 */
2021 public function prepareTextForEdit( $text, $revid = null, User $user = null ) {
2022 ContentHandler::deprecated( __METHOD__, '1.21' );
2023 $content = ContentHandler::makeContent( $text, $this->getTitle() );
2024 return $this->prepareContentForEdit( $content, $revid, $user );
2025 }
2026
2027 /**
2028 * Prepare content which is about to be saved.
2029 * Returns a stdClass with source, pst and output members
2030 *
2031 * @param Content $content
2032 * @param Revision|int|null $revision Revision object. For backwards compatibility, a
2033 * revision ID is also accepted, but this is deprecated.
2034 * @param User|null $user
2035 * @param string|null $serialFormat
2036 * @param bool $useCache Check shared prepared edit cache
2037 *
2038 * @return object
2039 *
2040 * @since 1.21
2041 */
2042 public function prepareContentForEdit(
2043 Content $content, $revision = null, User $user = null, $serialFormat = null, $useCache = true
2044 ) {
2045 global $wgContLang, $wgUser, $wgAjaxEditStash;
2046
2047 if ( is_object( $revision ) ) {
2048 $revid = $revision->getId();
2049 } else {
2050 $revid = $revision;
2051 // This code path is deprecated, and nothing is known to
2052 // use it, so performance here shouldn't be a worry.
2053 if ( $revid !== null ) {
2054 $revision = Revision::newFromId( $revid, Revision::READ_LATEST );
2055 } else {
2056 $revision = null;
2057 }
2058 }
2059
2060 $user = is_null( $user ) ? $wgUser : $user;
2061 //XXX: check $user->getId() here???
2062
2063 // Use a sane default for $serialFormat, see bug 57026
2064 if ( $serialFormat === null ) {
2065 $serialFormat = $content->getContentHandler()->getDefaultFormat();
2066 }
2067
2068 if ( $this->mPreparedEdit
2069 && $this->mPreparedEdit->newContent
2070 && $this->mPreparedEdit->newContent->equals( $content )
2071 && $this->mPreparedEdit->revid == $revid
2072 && $this->mPreparedEdit->format == $serialFormat
2073 // XXX: also check $user here?
2074 ) {
2075 // Already prepared
2076 return $this->mPreparedEdit;
2077 }
2078
2079 // The edit may have already been prepared via api.php?action=stashedit
2080 $cachedEdit = $useCache && $wgAjaxEditStash
2081 ? ApiStashEdit::checkCache( $this->getTitle(), $content, $user )
2082 : false;
2083
2084 $popts = ParserOptions::newFromUserAndLang( $user, $wgContLang );
2085 Hooks::run( 'ArticlePrepareTextForEdit', array( $this, $popts ) );
2086
2087 $edit = (object)array();
2088 if ( $cachedEdit ) {
2089 $edit->timestamp = $cachedEdit->timestamp;
2090 } else {
2091 $edit->timestamp = wfTimestampNow();
2092 }
2093 // @note: $cachedEdit is not used if the rev ID was referenced in the text
2094 $edit->revid = $revid;
2095
2096 if ( $cachedEdit ) {
2097 $edit->pstContent = $cachedEdit->pstContent;
2098 } else {
2099 $edit->pstContent = $content
2100 ? $content->preSaveTransform( $this->mTitle, $user, $popts )
2101 : null;
2102 }
2103
2104 $edit->format = $serialFormat;
2105 $edit->popts = $this->makeParserOptions( 'canonical' );
2106 if ( $cachedEdit ) {
2107 $edit->output = $cachedEdit->output;
2108 } else {
2109 if ( $revision ) {
2110 // We get here if vary-revision is set. This means that this page references
2111 // itself (such as via self-transclusion). In this case, we need to make sure
2112 // that any such self-references refer to the newly-saved revision, and not
2113 // to the previous one, which could otherwise happen due to slave lag.
2114 $oldCallback = $edit->popts->setCurrentRevisionCallback(
2115 function ( $title, $parser = false ) use ( $revision, &$oldCallback ) {
2116 if ( $title->equals( $revision->getTitle() ) ) {
2117 return $revision;
2118 } else {
2119 return call_user_func(
2120 $oldCallback,
2121 $title,
2122 $parser
2123 );
2124 }
2125 }
2126 );
2127 }
2128 $edit->output = $edit->pstContent
2129 ? $edit->pstContent->getParserOutput( $this->mTitle, $revid, $edit->popts )
2130 : null;
2131 }
2132
2133 $edit->newContent = $content;
2134 $edit->oldContent = $this->getContent( Revision::RAW );
2135
2136 // NOTE: B/C for hooks! don't use these fields!
2137 $edit->newText = $edit->newContent ? ContentHandler::getContentText( $edit->newContent ) : '';
2138 $edit->oldText = $edit->oldContent ? ContentHandler::getContentText( $edit->oldContent ) : '';
2139 $edit->pst = $edit->pstContent ? $edit->pstContent->serialize( $serialFormat ) : '';
2140
2141 $this->mPreparedEdit = $edit;
2142 return $edit;
2143 }
2144
2145 /**
2146 * Do standard deferred updates after page edit.
2147 * Update links tables, site stats, search index and message cache.
2148 * Purges pages that include this page if the text was changed here.
2149 * Every 100th edit, prune the recent changes table.
2150 *
2151 * @param Revision $revision
2152 * @param User $user User object that did the revision
2153 * @param array $options Array of options, following indexes are used:
2154 * - changed: boolean, whether the revision changed the content (default true)
2155 * - created: boolean, whether the revision created the page (default false)
2156 * - moved: boolean, whether the page was moved (default false)
2157 * - oldcountable: boolean or null (default null):
2158 * - boolean: whether the page was counted as an article before that
2159 * revision, only used in changed is true and created is false
2160 * - null: don't change the article count
2161 */
2162 public function doEditUpdates( Revision $revision, User $user, array $options = array() ) {
2163 global $wgEnableParserCache;
2164
2165 $options += array(
2166 'changed' => true,
2167 'created' => false,
2168 'moved' => false,
2169 'oldcountable' => null
2170 );
2171 $content = $revision->getContent();
2172
2173 // Parse the text
2174 // Be careful not to do pre-save transform twice: $text is usually
2175 // already pre-save transformed once.
2176 if ( !$this->mPreparedEdit || $this->mPreparedEdit->output->getFlag( 'vary-revision' ) ) {
2177 wfDebug( __METHOD__ . ": No prepared edit or vary-revision is set...\n" );
2178 $editInfo = $this->prepareContentForEdit( $content, $revision, $user );
2179 } else {
2180 wfDebug( __METHOD__ . ": No vary-revision, using prepared edit...\n" );
2181 $editInfo = $this->mPreparedEdit;
2182 }
2183
2184 // Save it to the parser cache
2185 if ( $wgEnableParserCache ) {
2186 $parserCache = ParserCache::singleton();
2187 $parserCache->save(
2188 $editInfo->output, $this, $editInfo->popts, $editInfo->timestamp, $editInfo->revid
2189 );
2190 }
2191
2192 // Update the links tables and other secondary data
2193 if ( $content ) {
2194 $recursive = $options['changed']; // bug 50785
2195 $updates = $content->getSecondaryDataUpdates(
2196 $this->getTitle(), null, $recursive, $editInfo->output );
2197 DataUpdate::runUpdates( $updates );
2198 }
2199
2200 Hooks::run( 'ArticleEditUpdates', array( &$this, &$editInfo, $options['changed'] ) );
2201
2202 if ( Hooks::run( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2203 if ( 0 == mt_rand( 0, 99 ) ) {
2204 // Flush old entries from the `recentchanges` table; we do this on
2205 // random requests so as to avoid an increase in writes for no good reason
2206 RecentChange::purgeExpiredChanges();
2207 }
2208 }
2209
2210 if ( !$this->exists() ) {
2211 return;
2212 }
2213
2214 $id = $this->getId();
2215 $title = $this->mTitle->getPrefixedDBkey();
2216 $shortTitle = $this->mTitle->getDBkey();
2217
2218 if ( !$options['changed'] && !$options['moved'] ) {
2219 $good = 0;
2220 } elseif ( $options['created'] ) {
2221 $good = (int)$this->isCountable( $editInfo );
2222 } elseif ( $options['oldcountable'] !== null ) {
2223 $good = (int)$this->isCountable( $editInfo ) - (int)$options['oldcountable'];
2224 } else {
2225 $good = 0;
2226 }
2227 $edits = $options['changed'] ? 1 : 0;
2228 $total = $options['created'] ? 1 : 0;
2229
2230 DeferredUpdates::addUpdate( new SiteStatsUpdate( 0, $edits, $good, $total ) );
2231 DeferredUpdates::addUpdate( new SearchUpdate( $id, $title, $content ) );
2232
2233 // If this is another user's talk page, update newtalk.
2234 // Don't do this if $options['changed'] = false (null-edits) nor if
2235 // it's a minor edit and the user doesn't want notifications for those.
2236 if ( $options['changed']
2237 && $this->mTitle->getNamespace() == NS_USER_TALK
2238 && $shortTitle != $user->getTitleKey()
2239 && !( $revision->isMinor() && $user->isAllowed( 'nominornewtalk' ) )
2240 ) {
2241 $recipient = User::newFromName( $shortTitle, false );
2242 if ( !$recipient ) {
2243 wfDebug( __METHOD__ . ": invalid username\n" );
2244 } else {
2245 // Allow extensions to prevent user notification when a new message is added to their talk page
2246 if ( Hooks::run( 'ArticleEditUpdateNewTalk', array( &$this, $recipient ) ) ) {
2247 if ( User::isIP( $shortTitle ) ) {
2248 // An anonymous user
2249 $recipient->setNewtalk( true, $revision );
2250 } elseif ( $recipient->isLoggedIn() ) {
2251 $recipient->setNewtalk( true, $revision );
2252 } else {
2253 wfDebug( __METHOD__ . ": don't need to notify a nonexistent user\n" );
2254 }
2255 }
2256 }
2257 }
2258
2259 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
2260 // XXX: could skip pseudo-messages like js/css here, based on content model.
2261 $msgtext = $content ? $content->getWikitextForTransclusion() : null;
2262 if ( $msgtext === false || $msgtext === null ) {
2263 $msgtext = '';
2264 }
2265
2266 MessageCache::singleton()->replace( $shortTitle, $msgtext );
2267 }
2268
2269 if ( $options['created'] ) {
2270 self::onArticleCreate( $this->mTitle );
2271 } elseif ( $options['changed'] ) { // bug 50785
2272 self::onArticleEdit( $this->mTitle );
2273 }
2274
2275 }
2276
2277 /**
2278 * Edit an article without doing all that other stuff
2279 * The article must already exist; link tables etc
2280 * are not updated, caches are not flushed.
2281 *
2282 * @param string $text Text submitted
2283 * @param User $user The relevant user
2284 * @param string $comment Comment submitted
2285 * @param bool $minor Whereas it's a minor modification
2286 *
2287 * @deprecated since 1.21, use doEditContent() instead.
2288 */
2289 public function doQuickEdit( $text, User $user, $comment = '', $minor = 0 ) {
2290 ContentHandler::deprecated( __METHOD__, "1.21" );
2291
2292 $content = ContentHandler::makeContent( $text, $this->getTitle() );
2293 $this->doQuickEditContent( $content, $user, $comment, $minor );
2294 }
2295
2296 /**
2297 * Edit an article without doing all that other stuff
2298 * The article must already exist; link tables etc
2299 * are not updated, caches are not flushed.
2300 *
2301 * @param Content $content Content submitted
2302 * @param User $user The relevant user
2303 * @param string $comment Comment submitted
2304 * @param bool $minor Whereas it's a minor modification
2305 * @param string $serialFormat Format for storing the content in the database
2306 */
2307 public function doQuickEditContent( Content $content, User $user, $comment = '', $minor = false,
2308 $serialFormat = null
2309 ) {
2310
2311 $serialized = $content->serialize( $serialFormat );
2312
2313 $dbw = wfGetDB( DB_MASTER );
2314 $revision = new Revision( array(
2315 'title' => $this->getTitle(), // for determining the default content model
2316 'page' => $this->getId(),
2317 'user_text' => $user->getName(),
2318 'user' => $user->getId(),
2319 'text' => $serialized,
2320 'length' => $content->getSize(),
2321 'comment' => $comment,
2322 'minor_edit' => $minor ? 1 : 0,
2323 ) ); // XXX: set the content object?
2324 $revision->insertOn( $dbw );
2325 $this->updateRevisionOn( $dbw, $revision );
2326
2327 Hooks::run( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
2328
2329 }
2330
2331 /**
2332 * Update the article's restriction field, and leave a log entry.
2333 * This works for protection both existing and non-existing pages.
2334 *
2335 * @param array $limit Set of restriction keys
2336 * @param array $expiry Per restriction type expiration
2337 * @param int &$cascade Set to false if cascading protection isn't allowed.
2338 * @param string $reason
2339 * @param User $user The user updating the restrictions
2340 * @return Status
2341 */
2342 public function doUpdateRestrictions( array $limit, array $expiry,
2343 &$cascade, $reason, User $user
2344 ) {
2345 global $wgCascadingRestrictionLevels, $wgContLang;
2346
2347 if ( wfReadOnly() ) {
2348 return Status::newFatal( 'readonlytext', wfReadOnlyReason() );
2349 }
2350
2351 $this->loadPageData( 'fromdbmaster' );
2352 $restrictionTypes = $this->mTitle->getRestrictionTypes();
2353 $id = $this->getId();
2354
2355 if ( !$cascade ) {
2356 $cascade = false;
2357 }
2358
2359 // Take this opportunity to purge out expired restrictions
2360 Title::purgeExpiredRestrictions();
2361
2362 // @todo FIXME: Same limitations as described in ProtectionForm.php (line 37);
2363 // we expect a single selection, but the schema allows otherwise.
2364 $isProtected = false;
2365 $protect = false;
2366 $changed = false;
2367
2368 $dbw = wfGetDB( DB_MASTER );
2369
2370 foreach ( $restrictionTypes as $action ) {
2371 if ( !isset( $expiry[$action] ) ) {
2372 $expiry[$action] = $dbw->getInfinity();
2373 }
2374 if ( !isset( $limit[$action] ) ) {
2375 $limit[$action] = '';
2376 } elseif ( $limit[$action] != '' ) {
2377 $protect = true;
2378 }
2379
2380 // Get current restrictions on $action
2381 $current = implode( '', $this->mTitle->getRestrictions( $action ) );
2382 if ( $current != '' ) {
2383 $isProtected = true;
2384 }
2385
2386 if ( $limit[$action] != $current ) {
2387 $changed = true;
2388 } elseif ( $limit[$action] != '' ) {
2389 // Only check expiry change if the action is actually being
2390 // protected, since expiry does nothing on an not-protected
2391 // action.
2392 if ( $this->mTitle->getRestrictionExpiry( $action ) != $expiry[$action] ) {
2393 $changed = true;
2394 }
2395 }
2396 }
2397
2398 if ( !$changed && $protect && $this->mTitle->areRestrictionsCascading() != $cascade ) {
2399 $changed = true;
2400 }
2401
2402 // If nothing has changed, do nothing
2403 if ( !$changed ) {
2404 return Status::newGood();
2405 }
2406
2407 if ( !$protect ) { // No protection at all means unprotection
2408 $revCommentMsg = 'unprotectedarticle';
2409 $logAction = 'unprotect';
2410 } elseif ( $isProtected ) {
2411 $revCommentMsg = 'modifiedarticleprotection';
2412 $logAction = 'modify';
2413 } else {
2414 $revCommentMsg = 'protectedarticle';
2415 $logAction = 'protect';
2416 }
2417
2418 // Truncate for whole multibyte characters
2419 $reason = $wgContLang->truncate( $reason, 255 );
2420
2421 $logRelationsValues = array();
2422 $logRelationsField = null;
2423
2424 if ( $id ) { // Protection of existing page
2425 if ( !Hooks::run( 'ArticleProtect', array( &$this, &$user, $limit, $reason ) ) ) {
2426 return Status::newGood();
2427 }
2428
2429 // Only certain restrictions can cascade...
2430 $editrestriction = isset( $limit['edit'] )
2431 ? array( $limit['edit'] )
2432 : $this->mTitle->getRestrictions( 'edit' );
2433 foreach ( array_keys( $editrestriction, 'sysop' ) as $key ) {
2434 $editrestriction[$key] = 'editprotected'; // backwards compatibility
2435 }
2436 foreach ( array_keys( $editrestriction, 'autoconfirmed' ) as $key ) {
2437 $editrestriction[$key] = 'editsemiprotected'; // backwards compatibility
2438 }
2439
2440 $cascadingRestrictionLevels = $wgCascadingRestrictionLevels;
2441 foreach ( array_keys( $cascadingRestrictionLevels, 'sysop' ) as $key ) {
2442 $cascadingRestrictionLevels[$key] = 'editprotected'; // backwards compatibility
2443 }
2444 foreach ( array_keys( $cascadingRestrictionLevels, 'autoconfirmed' ) as $key ) {
2445 $cascadingRestrictionLevels[$key] = 'editsemiprotected'; // backwards compatibility
2446 }
2447
2448 // The schema allows multiple restrictions
2449 if ( !array_intersect( $editrestriction, $cascadingRestrictionLevels ) ) {
2450 $cascade = false;
2451 }
2452
2453 // insert null revision to identify the page protection change as edit summary
2454 $latest = $this->getLatest();
2455 $nullRevision = $this->insertProtectNullRevision(
2456 $revCommentMsg,
2457 $limit,
2458 $expiry,
2459 $cascade,
2460 $reason,
2461 $user
2462 );
2463
2464 if ( $nullRevision === null ) {
2465 return Status::newFatal( 'no-null-revision', $this->mTitle->getPrefixedText() );
2466 }
2467
2468 $logRelationsField = 'pr_id';
2469
2470 // Update restrictions table
2471 foreach ( $limit as $action => $restrictions ) {
2472 $dbw->delete(
2473 'page_restrictions',
2474 array(
2475 'pr_page' => $id,
2476 'pr_type' => $action
2477 ),
2478 __METHOD__
2479 );
2480 if ( $restrictions != '' ) {
2481 $dbw->insert(
2482 'page_restrictions',
2483 array(
2484 'pr_id' => $dbw->nextSequenceValue( 'page_restrictions_pr_id_seq' ),
2485 'pr_page' => $id,
2486 'pr_type' => $action,
2487 'pr_level' => $restrictions,
2488 'pr_cascade' => ( $cascade && $action == 'edit' ) ? 1 : 0,
2489 'pr_expiry' => $dbw->encodeExpiry( $expiry[$action] )
2490 ),
2491 __METHOD__
2492 );
2493 $logRelationsValues[] = $dbw->insertId();
2494 }
2495 }
2496
2497 // Clear out legacy restriction fields
2498 $dbw->update(
2499 'page',
2500 array( 'page_restrictions' => '' ),
2501 array( 'page_id' => $id ),
2502 __METHOD__
2503 );
2504
2505 Hooks::run( 'NewRevisionFromEditComplete', array( $this, $nullRevision, $latest, $user ) );
2506 Hooks::run( 'ArticleProtectComplete', array( &$this, &$user, $limit, $reason ) );
2507 } else { // Protection of non-existing page (also known as "title protection")
2508 // Cascade protection is meaningless in this case
2509 $cascade = false;
2510
2511 if ( $limit['create'] != '' ) {
2512 $dbw->replace( 'protected_titles',
2513 array( array( 'pt_namespace', 'pt_title' ) ),
2514 array(
2515 'pt_namespace' => $this->mTitle->getNamespace(),
2516 'pt_title' => $this->mTitle->getDBkey(),
2517 'pt_create_perm' => $limit['create'],
2518 'pt_timestamp' => $dbw->timestamp(),
2519 'pt_expiry' => $dbw->encodeExpiry( $expiry['create'] ),
2520 'pt_user' => $user->getId(),
2521 'pt_reason' => $reason,
2522 ), __METHOD__
2523 );
2524 } else {
2525 $dbw->delete( 'protected_titles',
2526 array(
2527 'pt_namespace' => $this->mTitle->getNamespace(),
2528 'pt_title' => $this->mTitle->getDBkey()
2529 ), __METHOD__
2530 );
2531 }
2532 }
2533
2534 $this->mTitle->flushRestrictions();
2535 InfoAction::invalidateCache( $this->mTitle );
2536
2537 if ( $logAction == 'unprotect' ) {
2538 $params = array();
2539 } else {
2540 $protectDescriptionLog = $this->protectDescriptionLog( $limit, $expiry );
2541 $params = array( $protectDescriptionLog, $cascade ? 'cascade' : '' );
2542 }
2543
2544 // Update the protection log
2545 $log = new LogPage( 'protect' );
2546 $logId = $log->addEntry( $logAction, $this->mTitle, $reason, $params, $user );
2547 if ( $logRelationsField !== null && count( $logRelationsValues ) ) {
2548 $log->addRelations( $logRelationsField, $logRelationsValues, $logId );
2549 }
2550
2551 return Status::newGood();
2552 }
2553
2554 /**
2555 * Insert a new null revision for this page.
2556 *
2557 * @param string $revCommentMsg Comment message key for the revision
2558 * @param array $limit Set of restriction keys
2559 * @param array $expiry Per restriction type expiration
2560 * @param int $cascade Set to false if cascading protection isn't allowed.
2561 * @param string $reason
2562 * @param User|null $user
2563 * @return Revision|null Null on error
2564 */
2565 public function insertProtectNullRevision( $revCommentMsg, array $limit,
2566 array $expiry, $cascade, $reason, $user = null
2567 ) {
2568 global $wgContLang;
2569 $dbw = wfGetDB( DB_MASTER );
2570
2571 // Prepare a null revision to be added to the history
2572 $editComment = $wgContLang->ucfirst(
2573 wfMessage(
2574 $revCommentMsg,
2575 $this->mTitle->getPrefixedText()
2576 )->inContentLanguage()->text()
2577 );
2578 if ( $reason ) {
2579 $editComment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
2580 }
2581 $protectDescription = $this->protectDescription( $limit, $expiry );
2582 if ( $protectDescription ) {
2583 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2584 $editComment .= wfMessage( 'parentheses' )->params( $protectDescription )
2585 ->inContentLanguage()->text();
2586 }
2587 if ( $cascade ) {
2588 $editComment .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2589 $editComment .= wfMessage( 'brackets' )->params(
2590 wfMessage( 'protect-summary-cascade' )->inContentLanguage()->text()
2591 )->inContentLanguage()->text();
2592 }
2593
2594 $nullRev = Revision::newNullRevision( $dbw, $this->getId(), $editComment, true, $user );
2595 if ( $nullRev ) {
2596 $nullRev->insertOn( $dbw );
2597
2598 // Update page record and touch page
2599 $oldLatest = $nullRev->getParentId();
2600 $this->updateRevisionOn( $dbw, $nullRev, $oldLatest );
2601 }
2602
2603 return $nullRev;
2604 }
2605
2606 /**
2607 * @param string $expiry 14-char timestamp or "infinity", or false if the input was invalid
2608 * @return string
2609 */
2610 protected function formatExpiry( $expiry ) {
2611 global $wgContLang;
2612 $dbr = wfGetDB( DB_SLAVE );
2613
2614 $encodedExpiry = $dbr->encodeExpiry( $expiry );
2615 if ( $encodedExpiry != 'infinity' ) {
2616 return wfMessage(
2617 'protect-expiring',
2618 $wgContLang->timeanddate( $expiry, false, false ),
2619 $wgContLang->date( $expiry, false, false ),
2620 $wgContLang->time( $expiry, false, false )
2621 )->inContentLanguage()->text();
2622 } else {
2623 return wfMessage( 'protect-expiry-indefinite' )
2624 ->inContentLanguage()->text();
2625 }
2626 }
2627
2628 /**
2629 * Builds the description to serve as comment for the edit.
2630 *
2631 * @param array $limit Set of restriction keys
2632 * @param array $expiry Per restriction type expiration
2633 * @return string
2634 */
2635 public function protectDescription( array $limit, array $expiry ) {
2636 $protectDescription = '';
2637
2638 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2639 # $action is one of $wgRestrictionTypes = array( 'create', 'edit', 'move', 'upload' ).
2640 # All possible message keys are listed here for easier grepping:
2641 # * restriction-create
2642 # * restriction-edit
2643 # * restriction-move
2644 # * restriction-upload
2645 $actionText = wfMessage( 'restriction-' . $action )->inContentLanguage()->text();
2646 # $restrictions is one of $wgRestrictionLevels = array( '', 'autoconfirmed', 'sysop' ),
2647 # with '' filtered out. All possible message keys are listed below:
2648 # * protect-level-autoconfirmed
2649 # * protect-level-sysop
2650 $restrictionsText = wfMessage( 'protect-level-' . $restrictions )->inContentLanguage()->text();
2651
2652 $expiryText = $this->formatExpiry( $expiry[$action] );
2653
2654 if ( $protectDescription !== '' ) {
2655 $protectDescription .= wfMessage( 'word-separator' )->inContentLanguage()->text();
2656 }
2657 $protectDescription .= wfMessage( 'protect-summary-desc' )
2658 ->params( $actionText, $restrictionsText, $expiryText )
2659 ->inContentLanguage()->text();
2660 }
2661
2662 return $protectDescription;
2663 }
2664
2665 /**
2666 * Builds the description to serve as comment for the log entry.
2667 *
2668 * Some bots may parse IRC lines, which are generated from log entries which contain plain
2669 * protect description text. Keep them in old format to avoid breaking compatibility.
2670 * TODO: Fix protection log to store structured description and format it on-the-fly.
2671 *
2672 * @param array $limit Set of restriction keys
2673 * @param array $expiry Per restriction type expiration
2674 * @return string
2675 */
2676 public function protectDescriptionLog( array $limit, array $expiry ) {
2677 global $wgContLang;
2678
2679 $protectDescriptionLog = '';
2680
2681 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2682 $expiryText = $this->formatExpiry( $expiry[$action] );
2683 $protectDescriptionLog .= $wgContLang->getDirMark() . "[$action=$restrictions] ($expiryText)";
2684 }
2685
2686 return trim( $protectDescriptionLog );
2687 }
2688
2689 /**
2690 * Take an array of page restrictions and flatten it to a string
2691 * suitable for insertion into the page_restrictions field.
2692 *
2693 * @param string[] $limit
2694 *
2695 * @throws MWException
2696 * @return string
2697 */
2698 protected static function flattenRestrictions( $limit ) {
2699 if ( !is_array( $limit ) ) {
2700 throw new MWException( 'WikiPage::flattenRestrictions given non-array restriction set' );
2701 }
2702
2703 $bits = array();
2704 ksort( $limit );
2705
2706 foreach ( array_filter( $limit ) as $action => $restrictions ) {
2707 $bits[] = "$action=$restrictions";
2708 }
2709
2710 return implode( ':', $bits );
2711 }
2712
2713 /**
2714 * Same as doDeleteArticleReal(), but returns a simple boolean. This is kept around for
2715 * backwards compatibility, if you care about error reporting you should use
2716 * doDeleteArticleReal() instead.
2717 *
2718 * Deletes the article with database consistency, writes logs, purges caches
2719 *
2720 * @param string $reason Delete reason for deletion log
2721 * @param bool $suppress Suppress all revisions and log the deletion in
2722 * the suppression log instead of the deletion log
2723 * @param int $id Article ID
2724 * @param bool $commit Defaults to true, triggers transaction end
2725 * @param array &$error Array of errors to append to
2726 * @param User $user The deleting user
2727 * @return bool True if successful
2728 */
2729 public function doDeleteArticle(
2730 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User $user = null
2731 ) {
2732 $status = $this->doDeleteArticleReal( $reason, $suppress, $id, $commit, $error, $user );
2733 return $status->isGood();
2734 }
2735
2736 /**
2737 * Back-end article deletion
2738 * Deletes the article with database consistency, writes logs, purges caches
2739 *
2740 * @since 1.19
2741 *
2742 * @param string $reason Delete reason for deletion log
2743 * @param bool $suppress Suppress all revisions and log the deletion in
2744 * the suppression log instead of the deletion log
2745 * @param int $id Article ID
2746 * @param bool $commit Defaults to true, triggers transaction end
2747 * @param array &$error Array of errors to append to
2748 * @param User $user The deleting user
2749 * @return Status Status object; if successful, $status->value is the log_id of the
2750 * deletion log entry. If the page couldn't be deleted because it wasn't
2751 * found, $status is a non-fatal 'cannotdelete' error
2752 */
2753 public function doDeleteArticleReal(
2754 $reason, $suppress = false, $id = 0, $commit = true, &$error = '', User $user = null
2755 ) {
2756 global $wgUser, $wgContentHandlerUseDB;
2757
2758 wfDebug( __METHOD__ . "\n" );
2759
2760 $status = Status::newGood();
2761
2762 if ( $this->mTitle->getDBkey() === '' ) {
2763 $status->error( 'cannotdelete', wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2764 return $status;
2765 }
2766
2767 $user = is_null( $user ) ? $wgUser : $user;
2768 if ( !Hooks::run( 'ArticleDelete', array( &$this, &$user, &$reason, &$error, &$status ) ) ) {
2769 if ( $status->isOK() ) {
2770 // Hook aborted but didn't set a fatal status
2771 $status->fatal( 'delete-hook-aborted' );
2772 }
2773 return $status;
2774 }
2775
2776 $dbw = wfGetDB( DB_MASTER );
2777 $dbw->begin( __METHOD__ );
2778
2779 if ( $id == 0 ) {
2780 $this->loadPageData( 'forupdate' );
2781 $id = $this->getID();
2782 if ( $id == 0 ) {
2783 $dbw->rollback( __METHOD__ );
2784 $status->error( 'cannotdelete', wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2785 return $status;
2786 }
2787 }
2788
2789 // we need to remember the old content so we can use it to generate all deletion updates.
2790 $content = $this->getContent( Revision::RAW );
2791
2792 // Bitfields to further suppress the content
2793 if ( $suppress ) {
2794 $bitfield = 0;
2795 // This should be 15...
2796 $bitfield |= Revision::DELETED_TEXT;
2797 $bitfield |= Revision::DELETED_COMMENT;
2798 $bitfield |= Revision::DELETED_USER;
2799 $bitfield |= Revision::DELETED_RESTRICTED;
2800 } else {
2801 $bitfield = 'rev_deleted';
2802 }
2803
2804 // For now, shunt the revision data into the archive table.
2805 // Text is *not* removed from the text table; bulk storage
2806 // is left intact to avoid breaking block-compression or
2807 // immutable storage schemes.
2808 //
2809 // For backwards compatibility, note that some older archive
2810 // table entries will have ar_text and ar_flags fields still.
2811 //
2812 // In the future, we may keep revisions and mark them with
2813 // the rev_deleted field, which is reserved for this purpose.
2814
2815 $row = array(
2816 'ar_namespace' => 'page_namespace',
2817 'ar_title' => 'page_title',
2818 'ar_comment' => 'rev_comment',
2819 'ar_user' => 'rev_user',
2820 'ar_user_text' => 'rev_user_text',
2821 'ar_timestamp' => 'rev_timestamp',
2822 'ar_minor_edit' => 'rev_minor_edit',
2823 'ar_rev_id' => 'rev_id',
2824 'ar_parent_id' => 'rev_parent_id',
2825 'ar_text_id' => 'rev_text_id',
2826 'ar_text' => '\'\'', // Be explicit to appease
2827 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2828 'ar_len' => 'rev_len',
2829 'ar_page_id' => 'page_id',
2830 'ar_deleted' => $bitfield,
2831 'ar_sha1' => 'rev_sha1',
2832 );
2833
2834 if ( $wgContentHandlerUseDB ) {
2835 $row['ar_content_model'] = 'rev_content_model';
2836 $row['ar_content_format'] = 'rev_content_format';
2837 }
2838
2839 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2840 $row,
2841 array(
2842 'page_id' => $id,
2843 'page_id = rev_page'
2844 ), __METHOD__
2845 );
2846
2847 // Now that it's safely backed up, delete it
2848 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__ );
2849 $ok = ( $dbw->affectedRows() > 0 ); // $id could be laggy
2850
2851 if ( !$ok ) {
2852 $dbw->rollback( __METHOD__ );
2853 $status->error( 'cannotdelete', wfEscapeWikiText( $this->getTitle()->getPrefixedText() ) );
2854 return $status;
2855 }
2856
2857 if ( !$dbw->cascadingDeletes() ) {
2858 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__ );
2859 }
2860
2861 // Clone the title, so we have the information we need when we log
2862 $logTitle = clone $this->mTitle;
2863
2864 // Log the deletion, if the page was suppressed, log it at Oversight instead
2865 $logtype = $suppress ? 'suppress' : 'delete';
2866
2867 $logEntry = new ManualLogEntry( $logtype, 'delete' );
2868 $logEntry->setPerformer( $user );
2869 $logEntry->setTarget( $logTitle );
2870 $logEntry->setComment( $reason );
2871 $logid = $logEntry->insert();
2872
2873 $dbw->onTransactionPreCommitOrIdle( function () use ( $dbw, $logEntry, $logid ) {
2874 // Bug 56776: avoid deadlocks (especially from FileDeleteForm)
2875 $logEntry->publish( $logid );
2876 } );
2877
2878 if ( $commit ) {
2879 $dbw->commit( __METHOD__ );
2880 }
2881
2882 $this->doDeleteUpdates( $id, $content );
2883
2884 Hooks::run( 'ArticleDeleteComplete', array( &$this, &$user, $reason, $id, $content, $logEntry ) );
2885 $status->value = $logid;
2886 return $status;
2887 }
2888
2889 /**
2890 * Do some database updates after deletion
2891 *
2892 * @param int $id The page_id value of the page being deleted
2893 * @param Content $content Optional page content to be used when determining
2894 * the required updates. This may be needed because $this->getContent()
2895 * may already return null when the page proper was deleted.
2896 */
2897 public function doDeleteUpdates( $id, Content $content = null ) {
2898 // update site status
2899 DeferredUpdates::addUpdate( new SiteStatsUpdate( 0, 1, - (int)$this->isCountable(), -1 ) );
2900
2901 // remove secondary indexes, etc
2902 $updates = $this->getDeletionUpdates( $content );
2903 DataUpdate::runUpdates( $updates );
2904
2905 // Reparse any pages transcluding this page
2906 LinksUpdate::queueRecursiveJobsForTable( $this->mTitle, 'templatelinks' );
2907
2908 // Reparse any pages including this image
2909 if ( $this->mTitle->getNamespace() == NS_FILE ) {
2910 LinksUpdate::queueRecursiveJobsForTable( $this->mTitle, 'imagelinks' );
2911 }
2912
2913 // Clear caches
2914 WikiPage::onArticleDelete( $this->mTitle );
2915
2916 // Reset this object and the Title object
2917 $this->loadFromRow( false, self::READ_LATEST );
2918
2919 // Search engine
2920 DeferredUpdates::addUpdate( new SearchUpdate( $id, $this->mTitle ) );
2921 }
2922
2923 /**
2924 * Roll back the most recent consecutive set of edits to a page
2925 * from the same user; fails if there are no eligible edits to
2926 * roll back to, e.g. user is the sole contributor. This function
2927 * performs permissions checks on $user, then calls commitRollback()
2928 * to do the dirty work
2929 *
2930 * @todo Separate the business/permission stuff out from backend code
2931 *
2932 * @param string $fromP Name of the user whose edits to rollback.
2933 * @param string $summary Custom summary. Set to default summary if empty.
2934 * @param string $token Rollback token.
2935 * @param bool $bot If true, mark all reverted edits as bot.
2936 *
2937 * @param array $resultDetails Array contains result-specific array of additional values
2938 * 'alreadyrolled' : 'current' (rev)
2939 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2940 *
2941 * @param User $user The user performing the rollback
2942 * @return array Array of errors, each error formatted as
2943 * array(messagekey, param1, param2, ...).
2944 * On success, the array is empty. This array can also be passed to
2945 * OutputPage::showPermissionsErrorPage().
2946 */
2947 public function doRollback(
2948 $fromP, $summary, $token, $bot, &$resultDetails, User $user
2949 ) {
2950 $resultDetails = null;
2951
2952 // Check permissions
2953 $editErrors = $this->mTitle->getUserPermissionsErrors( 'edit', $user );
2954 $rollbackErrors = $this->mTitle->getUserPermissionsErrors( 'rollback', $user );
2955 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
2956
2957 if ( !$user->matchEditToken( $token, array( $this->mTitle->getPrefixedText(), $fromP ) ) ) {
2958 $errors[] = array( 'sessionfailure' );
2959 }
2960
2961 if ( $user->pingLimiter( 'rollback' ) || $user->pingLimiter() ) {
2962 $errors[] = array( 'actionthrottledtext' );
2963 }
2964
2965 // If there were errors, bail out now
2966 if ( !empty( $errors ) ) {
2967 return $errors;
2968 }
2969
2970 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails, $user );
2971 }
2972
2973 /**
2974 * Backend implementation of doRollback(), please refer there for parameter
2975 * and return value documentation
2976 *
2977 * NOTE: This function does NOT check ANY permissions, it just commits the
2978 * rollback to the DB. Therefore, you should only call this function direct-
2979 * ly if you want to use custom permissions checks. If you don't, use
2980 * doRollback() instead.
2981 * @param string $fromP Name of the user whose edits to rollback.
2982 * @param string $summary Custom summary. Set to default summary if empty.
2983 * @param bool $bot If true, mark all reverted edits as bot.
2984 *
2985 * @param array $resultDetails Contains result-specific array of additional values
2986 * @param User $guser The user performing the rollback
2987 * @return array
2988 */
2989 public function commitRollback( $fromP, $summary, $bot, &$resultDetails, User $guser ) {
2990 global $wgUseRCPatrol, $wgContLang;
2991
2992 $dbw = wfGetDB( DB_MASTER );
2993
2994 if ( wfReadOnly() ) {
2995 return array( array( 'readonlytext' ) );
2996 }
2997
2998 // Get the last editor
2999 $current = $this->getRevision();
3000 if ( is_null( $current ) ) {
3001 // Something wrong... no page?
3002 return array( array( 'notanarticle' ) );
3003 }
3004
3005 $from = str_replace( '_', ' ', $fromP );
3006 // User name given should match up with the top revision.
3007 // If the user was deleted then $from should be empty.
3008 if ( $from != $current->getUserText() ) {
3009 $resultDetails = array( 'current' => $current );
3010 return array( array( 'alreadyrolled',
3011 htmlspecialchars( $this->mTitle->getPrefixedText() ),
3012 htmlspecialchars( $fromP ),
3013 htmlspecialchars( $current->getUserText() )
3014 ) );
3015 }
3016
3017 // Get the last edit not by this guy...
3018 // Note: these may not be public values
3019 $user = intval( $current->getUser( Revision::RAW ) );
3020 $user_text = $dbw->addQuotes( $current->getUserText( Revision::RAW ) );
3021 $s = $dbw->selectRow( 'revision',
3022 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
3023 array( 'rev_page' => $current->getPage(),
3024 "rev_user != {$user} OR rev_user_text != {$user_text}"
3025 ), __METHOD__,
3026 array( 'USE INDEX' => 'page_timestamp',
3027 'ORDER BY' => 'rev_timestamp DESC' )
3028 );
3029 if ( $s === false ) {
3030 // No one else ever edited this page
3031 return array( array( 'cantrollback' ) );
3032 } elseif ( $s->rev_deleted & Revision::DELETED_TEXT
3033 || $s->rev_deleted & Revision::DELETED_USER
3034 ) {
3035 // Only admins can see this text
3036 return array( array( 'notvisiblerev' ) );
3037 }
3038
3039 // Set patrolling and bot flag on the edits, which gets rollbacked.
3040 // This is done before the rollback edit to have patrolling also on failure (bug 62157).
3041 $set = array();
3042 if ( $bot && $guser->isAllowed( 'markbotedits' ) ) {
3043 // Mark all reverted edits as bot
3044 $set['rc_bot'] = 1;
3045 }
3046
3047 if ( $wgUseRCPatrol ) {
3048 // Mark all reverted edits as patrolled
3049 $set['rc_patrolled'] = 1;
3050 }
3051
3052 if ( count( $set ) ) {
3053 $dbw->update( 'recentchanges', $set,
3054 array( /* WHERE */
3055 'rc_cur_id' => $current->getPage(),
3056 'rc_user_text' => $current->getUserText(),
3057 'rc_timestamp > ' . $dbw->addQuotes( $s->rev_timestamp ),
3058 ), __METHOD__
3059 );
3060 }
3061
3062 // Generate the edit summary if necessary
3063 $target = Revision::newFromId( $s->rev_id );
3064 if ( empty( $summary ) ) {
3065 if ( $from == '' ) { // no public user name
3066 $summary = wfMessage( 'revertpage-nouser' );
3067 } else {
3068 $summary = wfMessage( 'revertpage' );
3069 }
3070 }
3071
3072 // Allow the custom summary to use the same args as the default message
3073 $args = array(
3074 $target->getUserText(), $from, $s->rev_id,
3075 $wgContLang->timeanddate( wfTimestamp( TS_MW, $s->rev_timestamp ) ),
3076 $current->getId(), $wgContLang->timeanddate( $current->getTimestamp() )
3077 );
3078 if ( $summary instanceof Message ) {
3079 $summary = $summary->params( $args )->inContentLanguage()->text();
3080 } else {
3081 $summary = wfMsgReplaceArgs( $summary, $args );
3082 }
3083
3084 // Trim spaces on user supplied text
3085 $summary = trim( $summary );
3086
3087 // Truncate for whole multibyte characters.
3088 $summary = $wgContLang->truncate( $summary, 255 );
3089
3090 // Save
3091 $flags = EDIT_UPDATE;
3092
3093 if ( $guser->isAllowed( 'minoredit' ) ) {
3094 $flags |= EDIT_MINOR;
3095 }
3096
3097 if ( $bot && ( $guser->isAllowedAny( 'markbotedits', 'bot' ) ) ) {
3098 $flags |= EDIT_FORCE_BOT;
3099 }
3100
3101 // Actually store the edit
3102 $status = $this->doEditContent(
3103 $target->getContent(),
3104 $summary,
3105 $flags,
3106 $target->getId(),
3107 $guser
3108 );
3109
3110 if ( !$status->isOK() ) {
3111 return $status->getErrorsArray();
3112 }
3113
3114 // raise error, when the edit is an edit without a new version
3115 if ( empty( $status->value['revision'] ) ) {
3116 $resultDetails = array( 'current' => $current );
3117 return array( array( 'alreadyrolled',
3118 htmlspecialchars( $this->mTitle->getPrefixedText() ),
3119 htmlspecialchars( $fromP ),
3120 htmlspecialchars( $current->getUserText() )
3121 ) );
3122 }
3123
3124 $revId = $status->value['revision']->getId();
3125
3126 Hooks::run( 'ArticleRollbackComplete', array( $this, $guser, $target, $current ) );
3127
3128 $resultDetails = array(
3129 'summary' => $summary,
3130 'current' => $current,
3131 'target' => $target,
3132 'newid' => $revId
3133 );
3134
3135 return array();
3136 }
3137
3138 /**
3139 * The onArticle*() functions are supposed to be a kind of hooks
3140 * which should be called whenever any of the specified actions
3141 * are done.
3142 *
3143 * This is a good place to put code to clear caches, for instance.
3144 *
3145 * This is called on page move and undelete, as well as edit
3146 *
3147 * @param Title $title
3148 */
3149 public static function onArticleCreate( Title $title ) {
3150 // Update existence markers on article/talk tabs...
3151 $other = $title->getOtherPage();
3152
3153 $other->invalidateCache();
3154 $other->purgeSquid();
3155
3156 $title->touchLinks();
3157 $title->purgeSquid();
3158 $title->deleteTitleProtection();
3159 }
3160
3161 /**
3162 * Clears caches when article is deleted
3163 *
3164 * @param Title $title
3165 */
3166 public static function onArticleDelete( Title $title ) {
3167 // Update existence markers on article/talk tabs...
3168 $other = $title->getOtherPage();
3169
3170 $other->invalidateCache();
3171 $other->purgeSquid();
3172
3173 $title->touchLinks();
3174 $title->purgeSquid();
3175
3176 // File cache
3177 HTMLFileCache::clearFileCache( $title );
3178 InfoAction::invalidateCache( $title );
3179
3180 // Messages
3181 if ( $title->getNamespace() == NS_MEDIAWIKI ) {
3182 MessageCache::singleton()->replace( $title->getDBkey(), false );
3183 }
3184
3185 // Images
3186 if ( $title->getNamespace() == NS_FILE ) {
3187 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
3188 $update->doUpdate();
3189 }
3190
3191 // User talk pages
3192 if ( $title->getNamespace() == NS_USER_TALK ) {
3193 $user = User::newFromName( $title->getText(), false );
3194 if ( $user ) {
3195 $user->setNewtalk( false );
3196 }
3197 }
3198
3199 // Image redirects
3200 RepoGroup::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
3201 }
3202
3203 /**
3204 * Purge caches on page update etc
3205 *
3206 * @param Title $title
3207 */
3208 public static function onArticleEdit( Title $title ) {
3209 // Invalidate caches of articles which include this page
3210 DeferredUpdates::addHTMLCacheUpdate( $title, 'templatelinks' );
3211
3212 // Invalidate the caches of all pages which redirect here
3213 DeferredUpdates::addHTMLCacheUpdate( $title, 'redirect' );
3214
3215 // Purge squid for this page only
3216 $title->purgeSquid();
3217
3218 // Clear file cache for this page only
3219 HTMLFileCache::clearFileCache( $title );
3220 InfoAction::invalidateCache( $title );
3221 }
3222
3223 /**#@-*/
3224
3225 /**
3226 * Returns a list of categories this page is a member of.
3227 * Results will include hidden categories
3228 *
3229 * @return TitleArray
3230 */
3231 public function getCategories() {
3232 $id = $this->getId();
3233 if ( $id == 0 ) {
3234 return TitleArray::newFromResult( new FakeResultWrapper( array() ) );
3235 }
3236
3237 $dbr = wfGetDB( DB_SLAVE );
3238 $res = $dbr->select( 'categorylinks',
3239 array( 'cl_to AS page_title, ' . NS_CATEGORY . ' AS page_namespace' ),
3240 // Have to do that since DatabaseBase::fieldNamesWithAlias treats numeric indexes
3241 // as not being aliases, and NS_CATEGORY is numeric
3242 array( 'cl_from' => $id ),
3243 __METHOD__ );
3244
3245 return TitleArray::newFromResult( $res );
3246 }
3247
3248 /**
3249 * Returns a list of hidden categories this page is a member of.
3250 * Uses the page_props and categorylinks tables.
3251 *
3252 * @return array Array of Title objects
3253 */
3254 public function getHiddenCategories() {
3255 $result = array();
3256 $id = $this->getId();
3257
3258 if ( $id == 0 ) {
3259 return array();
3260 }
3261
3262 $dbr = wfGetDB( DB_SLAVE );
3263 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
3264 array( 'cl_to' ),
3265 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3266 'page_namespace' => NS_CATEGORY, 'page_title=cl_to' ),
3267 __METHOD__ );
3268
3269 if ( $res !== false ) {
3270 foreach ( $res as $row ) {
3271 $result[] = Title::makeTitle( NS_CATEGORY, $row->cl_to );
3272 }
3273 }
3274
3275 return $result;
3276 }
3277
3278 /**
3279 * Return an applicable autosummary if one exists for the given edit.
3280 * @param string|null $oldtext The previous text of the page.
3281 * @param string|null $newtext The submitted text of the page.
3282 * @param int $flags Bitmask: a bitmask of flags submitted for the edit.
3283 * @return string An appropriate autosummary, or an empty string.
3284 *
3285 * @deprecated since 1.21, use ContentHandler::getAutosummary() instead
3286 */
3287 public static function getAutosummary( $oldtext, $newtext, $flags ) {
3288 // NOTE: stub for backwards-compatibility. assumes the given text is
3289 // wikitext. will break horribly if it isn't.
3290
3291 ContentHandler::deprecated( __METHOD__, '1.21' );
3292
3293 $handler = ContentHandler::getForModelID( CONTENT_MODEL_WIKITEXT );
3294 $oldContent = is_null( $oldtext ) ? null : $handler->unserializeContent( $oldtext );
3295 $newContent = is_null( $newtext ) ? null : $handler->unserializeContent( $newtext );
3296
3297 return $handler->getAutosummary( $oldContent, $newContent, $flags );
3298 }
3299
3300 /**
3301 * Auto-generates a deletion reason
3302 *
3303 * @param bool &$hasHistory Whether the page has a history
3304 * @return string|bool String containing deletion reason or empty string, or boolean false
3305 * if no revision occurred
3306 */
3307 public function getAutoDeleteReason( &$hasHistory ) {
3308 return $this->getContentHandler()->getAutoDeleteReason( $this->getTitle(), $hasHistory );
3309 }
3310
3311 /**
3312 * Update all the appropriate counts in the category table, given that
3313 * we've added the categories $added and deleted the categories $deleted.
3314 *
3315 * @param array $added The names of categories that were added
3316 * @param array $deleted The names of categories that were deleted
3317 */
3318 public function updateCategoryCounts( array $added, array $deleted ) {
3319 $that = $this;
3320 $method = __METHOD__;
3321 $dbw = wfGetDB( DB_MASTER );
3322
3323 // Do this at the end of the commit to reduce lock wait timeouts
3324 $dbw->onTransactionPreCommitOrIdle(
3325 function () use ( $dbw, $that, $method, $added, $deleted ) {
3326 $ns = $that->getTitle()->getNamespace();
3327
3328 $addFields = array( 'cat_pages = cat_pages + 1' );
3329 $removeFields = array( 'cat_pages = cat_pages - 1' );
3330 if ( $ns == NS_CATEGORY ) {
3331 $addFields[] = 'cat_subcats = cat_subcats + 1';
3332 $removeFields[] = 'cat_subcats = cat_subcats - 1';
3333 } elseif ( $ns == NS_FILE ) {
3334 $addFields[] = 'cat_files = cat_files + 1';
3335 $removeFields[] = 'cat_files = cat_files - 1';
3336 }
3337
3338 if ( count( $added ) ) {
3339 $insertRows = array();
3340 foreach ( $added as $cat ) {
3341 $insertRows[] = array(
3342 'cat_title' => $cat,
3343 'cat_pages' => 1,
3344 'cat_subcats' => ( $ns == NS_CATEGORY ) ? 1 : 0,
3345 'cat_files' => ( $ns == NS_FILE ) ? 1 : 0,
3346 );
3347 }
3348 $dbw->upsert(
3349 'category',
3350 $insertRows,
3351 array( 'cat_title' ),
3352 $addFields,
3353 $method
3354 );
3355 }
3356
3357 if ( count( $deleted ) ) {
3358 $dbw->update(
3359 'category',
3360 $removeFields,
3361 array( 'cat_title' => $deleted ),
3362 $method
3363 );
3364 }
3365
3366 foreach ( $added as $catName ) {
3367 $cat = Category::newFromName( $catName );
3368 Hooks::run( 'CategoryAfterPageAdded', array( $cat, $that ) );
3369 }
3370
3371 foreach ( $deleted as $catName ) {
3372 $cat = Category::newFromName( $catName );
3373 Hooks::run( 'CategoryAfterPageRemoved', array( $cat, $that ) );
3374 }
3375 }
3376 );
3377 }
3378
3379 /**
3380 * Updates cascading protections
3381 *
3382 * @param ParserOutput $parserOutput ParserOutput object for the current version
3383 */
3384 public function doCascadeProtectionUpdates( ParserOutput $parserOutput ) {
3385 if ( wfReadOnly() || !$this->mTitle->areRestrictionsCascading() ) {
3386 return;
3387 }
3388
3389 // templatelinks or imagelinks tables may have become out of sync,
3390 // especially if using variable-based transclusions.
3391 // For paranoia, check if things have changed and if
3392 // so apply updates to the database. This will ensure
3393 // that cascaded protections apply as soon as the changes
3394 // are visible.
3395
3396 // Get templates from templatelinks and images from imagelinks
3397 $id = $this->getId();
3398
3399 $dbLinks = array();
3400
3401 $dbr = wfGetDB( DB_SLAVE );
3402 $res = $dbr->select( array( 'templatelinks' ),
3403 array( 'tl_namespace', 'tl_title' ),
3404 array( 'tl_from' => $id ),
3405 __METHOD__
3406 );
3407
3408 foreach ( $res as $row ) {
3409 $dbLinks["{$row->tl_namespace}:{$row->tl_title}"] = true;
3410 }
3411
3412 $dbr = wfGetDB( DB_SLAVE );
3413 $res = $dbr->select( array( 'imagelinks' ),
3414 array( 'il_to' ),
3415 array( 'il_from' => $id ),
3416 __METHOD__
3417 );
3418
3419 foreach ( $res as $row ) {
3420 $dbLinks[NS_FILE . ":{$row->il_to}"] = true;
3421 }
3422
3423 // Get templates and images from parser output.
3424 $poLinks = array();
3425 foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
3426 foreach ( $templates as $dbk => $id ) {
3427 $poLinks["$ns:$dbk"] = true;
3428 }
3429 }
3430 foreach ( $parserOutput->getImages() as $dbk => $id ) {
3431 $poLinks[NS_FILE . ":$dbk"] = true;
3432 }
3433
3434 // Get the diff
3435 $links_diff = array_diff_key( $poLinks, $dbLinks );
3436
3437 if ( count( $links_diff ) > 0 ) {
3438 // Whee, link updates time.
3439 // Note: we are only interested in links here. We don't need to get
3440 // other DataUpdate items from the parser output.
3441 $u = new LinksUpdate( $this->mTitle, $parserOutput, false );
3442 $u->doUpdate();
3443 }
3444 }
3445
3446 /**
3447 * Return a list of templates used by this article.
3448 * Uses the templatelinks table
3449 *
3450 * @deprecated since 1.19; use Title::getTemplateLinksFrom()
3451 * @return array Array of Title objects
3452 */
3453 public function getUsedTemplates() {
3454 return $this->mTitle->getTemplateLinksFrom();
3455 }
3456
3457 /**
3458 * This function is called right before saving the wikitext,
3459 * so we can do things like signatures and links-in-context.
3460 *
3461 * @deprecated since 1.19; use Parser::preSaveTransform() instead
3462 * @param string $text Article contents
3463 * @param User $user User doing the edit
3464 * @param ParserOptions $popts Parser options, default options for
3465 * the user loaded if null given
3466 * @return string Article contents with altered wikitext markup (signatures
3467 * converted, {{subst:}}, templates, etc.)
3468 */
3469 public function preSaveTransform( $text, User $user = null, ParserOptions $popts = null ) {
3470 global $wgParser, $wgUser;
3471
3472 wfDeprecated( __METHOD__, '1.19' );
3473
3474 $user = is_null( $user ) ? $wgUser : $user;
3475
3476 if ( $popts === null ) {
3477 $popts = ParserOptions::newFromUser( $user );
3478 }
3479
3480 return $wgParser->preSaveTransform( $text, $this->mTitle, $user, $popts );
3481 }
3482
3483 /**
3484 * Update the article's restriction field, and leave a log entry.
3485 *
3486 * @deprecated since 1.19
3487 * @param array $limit Set of restriction keys
3488 * @param string $reason
3489 * @param int &$cascade Set to false if cascading protection isn't allowed.
3490 * @param array $expiry Per restriction type expiration
3491 * @param User $user The user updating the restrictions
3492 * @return bool True on success
3493 */
3494 public function updateRestrictions(
3495 $limit = array(), $reason = '', &$cascade = 0, $expiry = array(), User $user = null
3496 ) {
3497 global $wgUser;
3498
3499 $user = is_null( $user ) ? $wgUser : $user;
3500
3501 return $this->doUpdateRestrictions( $limit, $expiry, $cascade, $reason, $user )->isOK();
3502 }
3503
3504 /**
3505 * Returns a list of updates to be performed when this page is deleted. The
3506 * updates should remove any information about this page from secondary data
3507 * stores such as links tables.
3508 *
3509 * @param Content|null $content Optional Content object for determining the
3510 * necessary updates.
3511 * @return array An array of DataUpdates objects
3512 */
3513 public function getDeletionUpdates( Content $content = null ) {
3514 if ( !$content ) {
3515 // load content object, which may be used to determine the necessary updates
3516 // XXX: the content may not be needed to determine the updates, then this would be overhead.
3517 $content = $this->getContent( Revision::RAW );
3518 }
3519
3520 if ( !$content ) {
3521 $updates = array();
3522 } else {
3523 $updates = $content->getDeletionUpdates( $this );
3524 }
3525
3526 Hooks::run( 'WikiPageDeletionUpdates', array( $this, $content, &$updates ) );
3527 return $updates;
3528 }
3529 }