PageRenderTime 63ms CodeModel.GetById 24ms 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

Large files files are truncated, but you can click here to view the full file

  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)

Large files files are truncated, but you can click here to view the full file