PageRenderTime 52ms CodeModel.GetById 1ms RepoModel.GetById 1ms app.codeStats 0ms

/includes/WikiPage.php

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