ApiPageSet.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698
  1. <?php
  2. /*
  3. * Created on Sep 24, 2006
  4. *
  5. * API for MediaWiki 1.8+
  6. *
  7. * Copyright (C) 2006 Yuri Astrakhan <Firstname><Lastname>@gmail.com
  8. *
  9. * This program is free software; you can redistribute it and/or modify
  10. * it under the terms of the GNU General Public License as published by
  11. * the Free Software Foundation; either version 2 of the License, or
  12. * (at your option) any later version.
  13. *
  14. * This program is distributed in the hope that it will be useful,
  15. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. * GNU General Public License for more details.
  18. *
  19. * You should have received a copy of the GNU General Public License along
  20. * with this program; if not, write to the Free Software Foundation, Inc.,
  21. * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
  22. * http://www.gnu.org/copyleft/gpl.html
  23. */
  24. if (!defined('MEDIAWIKI')) {
  25. // Eclipse helper - will be ignored in production
  26. require_once ('ApiQueryBase.php');
  27. }
  28. /**
  29. * This class contains a list of pages that the client has requested.
  30. * Initially, when the client passes in titles=, pageids=, or revisions=
  31. * parameter, an instance of the ApiPageSet class will normalize titles,
  32. * determine if the pages/revisions exist, and prefetch any additional page
  33. * data requested.
  34. *
  35. * When a generator is used, the result of the generator will become the input
  36. * for the second instance of this class, and all subsequent actions will use
  37. * the second instance for all their work.
  38. *
  39. * @ingroup API
  40. */
  41. class ApiPageSet extends ApiQueryBase {
  42. private $mAllPages; // [ns][dbkey] => page_id or negative when missing
  43. private $mTitles, $mGoodTitles, $mMissingTitles, $mInvalidTitles;
  44. private $mMissingPageIDs, $mRedirectTitles;
  45. private $mNormalizedTitles, $mInterwikiTitles;
  46. private $mResolveRedirects, $mPendingRedirectIDs;
  47. private $mGoodRevIDs, $mMissingRevIDs;
  48. private $mFakePageId;
  49. private $mRequestedPageFields;
  50. /**
  51. * Constructor
  52. * @param $query ApiQuery
  53. * @param $resolveRedirects bool Whether redirects should be resolved
  54. */
  55. public function __construct($query, $resolveRedirects = false) {
  56. parent :: __construct($query, 'query');
  57. $this->mAllPages = array ();
  58. $this->mTitles = array();
  59. $this->mGoodTitles = array ();
  60. $this->mMissingTitles = array ();
  61. $this->mInvalidTitles = array ();
  62. $this->mMissingPageIDs = array ();
  63. $this->mRedirectTitles = array ();
  64. $this->mNormalizedTitles = array ();
  65. $this->mInterwikiTitles = array ();
  66. $this->mGoodRevIDs = array();
  67. $this->mMissingRevIDs = array();
  68. $this->mRequestedPageFields = array ();
  69. $this->mResolveRedirects = $resolveRedirects;
  70. if($resolveRedirects)
  71. $this->mPendingRedirectIDs = array();
  72. $this->mFakePageId = -1;
  73. }
  74. /**
  75. * Check whether this PageSet is resolving redirects
  76. * @return bool
  77. */
  78. public function isResolvingRedirects() {
  79. return $this->mResolveRedirects;
  80. }
  81. /**
  82. * Request an additional field from the page table. Must be called
  83. * before execute()
  84. * @param $fieldName string Field name
  85. */
  86. public function requestField($fieldName) {
  87. $this->mRequestedPageFields[$fieldName] = null;
  88. }
  89. /**
  90. * Get the value of a custom field previously requested through
  91. * requestField()
  92. * @param $fieldName string Field name
  93. * @return mixed Field value
  94. */
  95. public function getCustomField($fieldName) {
  96. return $this->mRequestedPageFields[$fieldName];
  97. }
  98. /**
  99. * Get the fields that have to be queried from the page table:
  100. * the ones requested through requestField() and a few basic ones
  101. * we always need
  102. * @return array of field names
  103. */
  104. public function getPageTableFields() {
  105. // Ensure we get minimum required fields
  106. // DON'T change this order
  107. $pageFlds = array (
  108. 'page_namespace' => null,
  109. 'page_title' => null,
  110. 'page_id' => null,
  111. );
  112. if ($this->mResolveRedirects)
  113. $pageFlds['page_is_redirect'] = null;
  114. // only store non-default fields
  115. $this->mRequestedPageFields = array_diff_key($this->mRequestedPageFields, $pageFlds);
  116. $pageFlds = array_merge($pageFlds, $this->mRequestedPageFields);
  117. return array_keys($pageFlds);
  118. }
  119. /**
  120. * Returns an array [ns][dbkey] => page_id for all requested titles.
  121. * page_id is a unique negative number in case title was not found.
  122. * Invalid titles will also have negative page IDs and will be in namespace 0
  123. * @return array
  124. */
  125. public function getAllTitlesByNamespace() {
  126. return $this->mAllPages;
  127. }
  128. /**
  129. * All Title objects provided.
  130. * @return array of Title objects
  131. */
  132. public function getTitles() {
  133. return $this->mTitles;
  134. }
  135. /**
  136. * Returns the number of unique pages (not revisions) in the set.
  137. * @return int
  138. */
  139. public function getTitleCount() {
  140. return count($this->mTitles);
  141. }
  142. /**
  143. * Title objects that were found in the database.
  144. * @return array page_id (int) => Title (obj)
  145. */
  146. public function getGoodTitles() {
  147. return $this->mGoodTitles;
  148. }
  149. /**
  150. * Returns the number of found unique pages (not revisions) in the set.
  151. * @return int
  152. */
  153. public function getGoodTitleCount() {
  154. return count($this->mGoodTitles);
  155. }
  156. /**
  157. * Title objects that were NOT found in the database.
  158. * The array's index will be negative for each item
  159. * @return array of Title objects
  160. */
  161. public function getMissingTitles() {
  162. return $this->mMissingTitles;
  163. }
  164. /**
  165. * Titles that were deemed invalid by Title::newFromText()
  166. * The array's index will be unique and negative for each item
  167. * @return array of strings (not Title objects)
  168. */
  169. public function getInvalidTitles() {
  170. return $this->mInvalidTitles;
  171. }
  172. /**
  173. * Page IDs that were not found in the database
  174. * @return array of page IDs
  175. */
  176. public function getMissingPageIDs() {
  177. return $this->mMissingPageIDs;
  178. }
  179. /**
  180. * Get a list of redirect resolutions - maps a title to its redirect
  181. * target.
  182. * @return array prefixed_title (string) => prefixed_title (string)
  183. */
  184. public function getRedirectTitles() {
  185. return $this->mRedirectTitles;
  186. }
  187. /**
  188. * Get a list of title normalizations - maps a title to its normalized
  189. * version.
  190. * @return array raw_prefixed_title (string) => prefixed_title (string)
  191. */
  192. public function getNormalizedTitles() {
  193. return $this->mNormalizedTitles;
  194. }
  195. /**
  196. * Get a list of interwiki titles - maps a title to its interwiki
  197. * prefix.
  198. * @return array raw_prefixed_title (string) => interwiki_prefix (string)
  199. */
  200. public function getInterwikiTitles() {
  201. return $this->mInterwikiTitles;
  202. }
  203. /**
  204. * Get the list of revision IDs (requested with the revids= parameter)
  205. * @return array revID (int) => pageID (int)
  206. */
  207. public function getRevisionIDs() {
  208. return $this->mGoodRevIDs;
  209. }
  210. /**
  211. * Revision IDs that were not found in the database
  212. * @return array of revision IDs
  213. */
  214. public function getMissingRevisionIDs() {
  215. return $this->mMissingRevIDs;
  216. }
  217. /**
  218. * Returns the number of revisions (requested with revids= parameter)\
  219. * @return int
  220. */
  221. public function getRevisionCount() {
  222. return count($this->getRevisionIDs());
  223. }
  224. /**
  225. * Populate the PageSet from the request parameters.
  226. */
  227. public function execute() {
  228. $this->profileIn();
  229. $params = $this->extractRequestParams();
  230. // Only one of the titles/pageids/revids is allowed at the same time
  231. $dataSource = null;
  232. if (isset ($params['titles']))
  233. $dataSource = 'titles';
  234. if (isset ($params['pageids'])) {
  235. if (isset ($dataSource))
  236. $this->dieUsage("Cannot use 'pageids' at the same time as '$dataSource'", 'multisource');
  237. $dataSource = 'pageids';
  238. }
  239. if (isset ($params['revids'])) {
  240. if (isset ($dataSource))
  241. $this->dieUsage("Cannot use 'revids' at the same time as '$dataSource'", 'multisource');
  242. $dataSource = 'revids';
  243. }
  244. switch ($dataSource) {
  245. case 'titles' :
  246. $this->initFromTitles($params['titles']);
  247. break;
  248. case 'pageids' :
  249. $this->initFromPageIds($params['pageids']);
  250. break;
  251. case 'revids' :
  252. if($this->mResolveRedirects)
  253. $this->setWarning('Redirect resolution cannot be used together with the revids= parameter. '.
  254. 'Any redirects the revids= point to have not been resolved.');
  255. $this->mResolveRedirects = false;
  256. $this->initFromRevIDs($params['revids']);
  257. break;
  258. default :
  259. // Do nothing - some queries do not need any of the data sources.
  260. break;
  261. }
  262. $this->profileOut();
  263. }
  264. /**
  265. * Populate this PageSet from a list of Titles
  266. * @param $titles array of Title objects
  267. */
  268. public function populateFromTitles($titles) {
  269. $this->profileIn();
  270. $this->initFromTitles($titles);
  271. $this->profileOut();
  272. }
  273. /**
  274. * Populate this PageSet from a list of page IDs
  275. * @param $pageIDs array of page IDs
  276. */
  277. public function populateFromPageIDs($pageIDs) {
  278. $this->profileIn();
  279. $this->initFromPageIds($pageIDs);
  280. $this->profileOut();
  281. }
  282. /**
  283. * Populate this PageSet from a rowset returned from the database
  284. * @param $db Database object
  285. * @param $queryResult Query result object
  286. */
  287. public function populateFromQueryResult($db, $queryResult) {
  288. $this->profileIn();
  289. $this->initFromQueryResult($db, $queryResult);
  290. $this->profileOut();
  291. }
  292. /**
  293. * Populate this PageSet from a list of revision IDs
  294. * @param $revIDs array of revision IDs
  295. */
  296. public function populateFromRevisionIDs($revIDs) {
  297. $this->profileIn();
  298. $this->initFromRevIDs($revIDs);
  299. $this->profileOut();
  300. }
  301. /**
  302. * Extract all requested fields from the row received from the database
  303. * @param $row Result row
  304. */
  305. public function processDbRow($row) {
  306. // Store Title object in various data structures
  307. $title = Title :: makeTitle($row->page_namespace, $row->page_title);
  308. $pageId = intval($row->page_id);
  309. $this->mAllPages[$row->page_namespace][$row->page_title] = $pageId;
  310. $this->mTitles[] = $title;
  311. if ($this->mResolveRedirects && $row->page_is_redirect == '1') {
  312. $this->mPendingRedirectIDs[$pageId] = $title;
  313. } else {
  314. $this->mGoodTitles[$pageId] = $title;
  315. }
  316. foreach ($this->mRequestedPageFields as $fieldName => & $fieldValues)
  317. $fieldValues[$pageId] = $row-> $fieldName;
  318. }
  319. /**
  320. * Resolve redirects, if applicable
  321. */
  322. public function finishPageSetGeneration() {
  323. $this->profileIn();
  324. $this->resolvePendingRedirects();
  325. $this->profileOut();
  326. }
  327. /**
  328. * This method populates internal variables with page information
  329. * based on the given array of title strings.
  330. *
  331. * Steps:
  332. * #1 For each title, get data from `page` table
  333. * #2 If page was not found in the DB, store it as missing
  334. *
  335. * Additionally, when resolving redirects:
  336. * #3 If no more redirects left, stop.
  337. * #4 For each redirect, get its target from the `redirect` table.
  338. * #5 Substitute the original LinkBatch object with the new list
  339. * #6 Repeat from step #1
  340. *
  341. * @param $titles array of Title objects or strings
  342. */
  343. private function initFromTitles($titles) {
  344. // Get validated and normalized title objects
  345. $linkBatch = $this->processTitlesArray($titles);
  346. if($linkBatch->isEmpty())
  347. return;
  348. $db = $this->getDB();
  349. $set = $linkBatch->constructSet('page', $db);
  350. // Get pageIDs data from the `page` table
  351. $this->profileDBIn();
  352. $res = $db->select('page', $this->getPageTableFields(), $set,
  353. __METHOD__);
  354. $this->profileDBOut();
  355. // Hack: get the ns:titles stored in array(ns => array(titles)) format
  356. $this->initFromQueryResult($db, $res, $linkBatch->data, true); // process Titles
  357. // Resolve any found redirects
  358. $this->resolvePendingRedirects();
  359. }
  360. /**
  361. * Does the same as initFromTitles(), but is based on page IDs instead
  362. * @param $pageids array of page IDs
  363. */
  364. private function initFromPageIds($pageids) {
  365. if(!count($pageids))
  366. return;
  367. $pageids = array_map('intval', $pageids); // paranoia
  368. $set = array (
  369. 'page_id' => $pageids
  370. );
  371. $db = $this->getDB();
  372. // Get pageIDs data from the `page` table
  373. $this->profileDBIn();
  374. $res = $db->select('page', $this->getPageTableFields(), $set,
  375. __METHOD__);
  376. $this->profileDBOut();
  377. $remaining = array_flip($pageids);
  378. $this->initFromQueryResult($db, $res, $remaining, false); // process PageIDs
  379. // Resolve any found redirects
  380. $this->resolvePendingRedirects();
  381. }
  382. /**
  383. * Iterate through the result of the query on 'page' table,
  384. * and for each row create and store title object and save any extra fields requested.
  385. * @param $db Database
  386. * @param $res DB Query result
  387. * @param $remaining array of either pageID or ns/title elements (optional).
  388. * If given, any missing items will go to $mMissingPageIDs and $mMissingTitles
  389. * @param $processTitles bool Must be provided together with $remaining.
  390. * If true, treat $remaining as an array of [ns][title]
  391. * If false, treat it as an array of [pageIDs]
  392. */
  393. private function initFromQueryResult($db, $res, &$remaining = null, $processTitles = null) {
  394. if (!is_null($remaining) && is_null($processTitles))
  395. ApiBase :: dieDebug(__METHOD__, 'Missing $processTitles parameter when $remaining is provided');
  396. while ($row = $db->fetchObject($res)) {
  397. $pageId = intval($row->page_id);
  398. // Remove found page from the list of remaining items
  399. if (isset($remaining)) {
  400. if ($processTitles)
  401. unset ($remaining[$row->page_namespace][$row->page_title]);
  402. else
  403. unset ($remaining[$pageId]);
  404. }
  405. // Store any extra fields requested by modules
  406. $this->processDbRow($row);
  407. }
  408. $db->freeResult($res);
  409. if(isset($remaining)) {
  410. // Any items left in the $remaining list are added as missing
  411. if($processTitles) {
  412. // The remaining titles in $remaining are non-existent pages
  413. foreach ($remaining as $ns => $dbkeys) {
  414. foreach ( $dbkeys as $dbkey => $unused ) {
  415. $title = Title :: makeTitle($ns, $dbkey);
  416. $this->mAllPages[$ns][$dbkey] = $this->mFakePageId;
  417. $this->mMissingTitles[$this->mFakePageId] = $title;
  418. $this->mFakePageId--;
  419. $this->mTitles[] = $title;
  420. }
  421. }
  422. }
  423. else
  424. {
  425. // The remaining pageids do not exist
  426. if(!$this->mMissingPageIDs)
  427. $this->mMissingPageIDs = array_keys($remaining);
  428. else
  429. $this->mMissingPageIDs = array_merge($this->mMissingPageIDs, array_keys($remaining));
  430. }
  431. }
  432. }
  433. /**
  434. * Does the same as initFromTitles(), but is based on revision IDs
  435. * instead
  436. * @param $revids array of revision IDs
  437. */
  438. private function initFromRevIDs($revids) {
  439. if(!count($revids))
  440. return;
  441. $revids = array_map('intval', $revids); // paranoia
  442. $db = $this->getDB();
  443. $pageids = array();
  444. $remaining = array_flip($revids);
  445. $tables = array('revision', 'page');
  446. $fields = array('rev_id', 'rev_page');
  447. $where = array('rev_id' => $revids, 'rev_page = page_id');
  448. // Get pageIDs data from the `page` table
  449. $this->profileDBIn();
  450. $res = $db->select($tables, $fields, $where, __METHOD__);
  451. while ($row = $db->fetchObject($res)) {
  452. $revid = intval($row->rev_id);
  453. $pageid = intval($row->rev_page);
  454. $this->mGoodRevIDs[$revid] = $pageid;
  455. $pageids[$pageid] = '';
  456. unset($remaining[$revid]);
  457. }
  458. $db->freeResult($res);
  459. $this->profileDBOut();
  460. $this->mMissingRevIDs = array_keys($remaining);
  461. // Populate all the page information
  462. $this->initFromPageIds(array_keys($pageids));
  463. }
  464. /**
  465. * Resolve any redirects in the result if redirect resolution was
  466. * requested. This function is called repeatedly until all redirects
  467. * have been resolved.
  468. */
  469. private function resolvePendingRedirects() {
  470. if($this->mResolveRedirects) {
  471. $db = $this->getDB();
  472. $pageFlds = $this->getPageTableFields();
  473. // Repeat until all redirects have been resolved
  474. // The infinite loop is prevented by keeping all known pages in $this->mAllPages
  475. while ($this->mPendingRedirectIDs) {
  476. // Resolve redirects by querying the pagelinks table, and repeat the process
  477. // Create a new linkBatch object for the next pass
  478. $linkBatch = $this->getRedirectTargets();
  479. if ($linkBatch->isEmpty())
  480. break;
  481. $set = $linkBatch->constructSet('page', $db);
  482. if($set === false)
  483. break;
  484. // Get pageIDs data from the `page` table
  485. $this->profileDBIn();
  486. $res = $db->select('page', $pageFlds, $set, __METHOD__);
  487. $this->profileDBOut();
  488. // Hack: get the ns:titles stored in array(ns => array(titles)) format
  489. $this->initFromQueryResult($db, $res, $linkBatch->data, true);
  490. }
  491. }
  492. }
  493. /**
  494. * Get the targets of the pending redirects from the database
  495. *
  496. * Also creates entries in the redirect table for redirects that don't
  497. * have one.
  498. * @return LinkBatch
  499. */
  500. private function getRedirectTargets() {
  501. $lb = new LinkBatch();
  502. $db = $this->getDB();
  503. $this->profileDBIn();
  504. $res = $db->select('redirect', array(
  505. 'rd_from',
  506. 'rd_namespace',
  507. 'rd_title'
  508. ), array('rd_from' => array_keys($this->mPendingRedirectIDs)),
  509. __METHOD__
  510. );
  511. $this->profileDBOut();
  512. while($row = $db->fetchObject($res))
  513. {
  514. $rdfrom = intval($row->rd_from);
  515. $from = $this->mPendingRedirectIDs[$rdfrom]->getPrefixedText();
  516. $to = Title::makeTitle($row->rd_namespace, $row->rd_title)->getPrefixedText();
  517. unset($this->mPendingRedirectIDs[$rdfrom]);
  518. if(!isset($this->mAllPages[$row->rd_namespace][$row->rd_title]))
  519. $lb->add($row->rd_namespace, $row->rd_title);
  520. $this->mRedirectTitles[$from] = $to;
  521. }
  522. $db->freeResult($res);
  523. if($this->mPendingRedirectIDs)
  524. {
  525. # We found pages that aren't in the redirect table
  526. # Add them
  527. foreach($this->mPendingRedirectIDs as $id => $title)
  528. {
  529. $article = new Article($title);
  530. $rt = $article->insertRedirect();
  531. if(!$rt)
  532. # What the hell. Let's just ignore this
  533. continue;
  534. $lb->addObj($rt);
  535. $this->mRedirectTitles[$title->getPrefixedText()] = $rt->getPrefixedText();
  536. unset($this->mPendingRedirectIDs[$id]);
  537. }
  538. }
  539. return $lb;
  540. }
  541. /**
  542. * Given an array of title strings, convert them into Title objects.
  543. * Alternativelly, an array of Title objects may be given.
  544. * This method validates access rights for the title,
  545. * and appends normalization values to the output.
  546. *
  547. * @param $titles array of Title objects or strings
  548. * @return LinkBatch
  549. */
  550. private function processTitlesArray($titles) {
  551. $linkBatch = new LinkBatch();
  552. foreach ($titles as $title) {
  553. $titleObj = is_string($title) ? Title :: newFromText($title) : $title;
  554. if (!$titleObj)
  555. {
  556. # Handle invalid titles gracefully
  557. $this->mAllpages[0][$title] = $this->mFakePageId;
  558. $this->mInvalidTitles[$this->mFakePageId] = $title;
  559. $this->mFakePageId--;
  560. continue; // There's nothing else we can do
  561. }
  562. $iw = $titleObj->getInterwiki();
  563. if (strval($iw) !== '') {
  564. // This title is an interwiki link.
  565. $this->mInterwikiTitles[$titleObj->getPrefixedText()] = $iw;
  566. } else {
  567. // Validation
  568. if ($titleObj->getNamespace() < 0)
  569. $this->setWarning("No support for special pages has been implemented");
  570. else
  571. $linkBatch->addObj($titleObj);
  572. }
  573. // Make sure we remember the original title that was
  574. // given to us. This way the caller can correlate new
  575. // titles with the originally requested when e.g. the
  576. // namespace is localized or the capitalization is
  577. // different
  578. if (is_string($title) && $title !== $titleObj->getPrefixedText()) {
  579. $this->mNormalizedTitles[$title] = $titleObj->getPrefixedText();
  580. }
  581. }
  582. return $linkBatch;
  583. }
  584. protected function getAllowedParams() {
  585. return array (
  586. 'titles' => array (
  587. ApiBase :: PARAM_ISMULTI => true
  588. ),
  589. 'pageids' => array (
  590. ApiBase :: PARAM_TYPE => 'integer',
  591. ApiBase :: PARAM_ISMULTI => true
  592. ),
  593. 'revids' => array (
  594. ApiBase :: PARAM_TYPE => 'integer',
  595. ApiBase :: PARAM_ISMULTI => true
  596. )
  597. );
  598. }
  599. protected function getParamDescription() {
  600. return array (
  601. 'titles' => 'A list of titles to work on',
  602. 'pageids' => 'A list of page IDs to work on',
  603. 'revids' => 'A list of revision IDs to work on'
  604. );
  605. }
  606. public function getVersion() {
  607. return __CLASS__ . ': $Id: ApiPageSet.php 47424 2009-02-18 05:29:11Z werdna $';
  608. }
  609. }