ApiQueryBase.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  1. <?php
  2. /*
  3. * Created on Sep 7, 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 ('ApiBase.php');
  27. }
  28. /**
  29. * This is a base class for all Query modules.
  30. * It provides some common functionality such as constructing various SQL
  31. * queries.
  32. *
  33. * @ingroup API
  34. */
  35. abstract class ApiQueryBase extends ApiBase {
  36. private $mQueryModule, $mDb, $tables, $where, $fields, $options, $join_conds;
  37. public function __construct($query, $moduleName, $paramPrefix = '') {
  38. parent :: __construct($query->getMain(), $moduleName, $paramPrefix);
  39. $this->mQueryModule = $query;
  40. $this->mDb = null;
  41. $this->resetQueryParams();
  42. }
  43. /**
  44. * Blank the internal arrays with query parameters
  45. */
  46. protected function resetQueryParams() {
  47. $this->tables = array ();
  48. $this->where = array ();
  49. $this->fields = array ();
  50. $this->options = array ();
  51. $this->join_conds = array ();
  52. }
  53. /**
  54. * Add a set of tables to the internal array
  55. * @param $tables mixed Table name or array of table names
  56. * @param $alias mixed Table alias, or null for no alias. Cannot be
  57. * used with multiple tables
  58. */
  59. protected function addTables($tables, $alias = null) {
  60. if (is_array($tables)) {
  61. if (!is_null($alias))
  62. ApiBase :: dieDebug(__METHOD__, 'Multiple table aliases not supported');
  63. $this->tables = array_merge($this->tables, $tables);
  64. } else {
  65. if (!is_null($alias))
  66. $tables = $this->getAliasedName($tables, $alias);
  67. $this->tables[] = $tables;
  68. }
  69. }
  70. /**
  71. * Get the SQL for a table name with alias
  72. * @param $table string Table name
  73. * @param $alias string Alias
  74. * @return string SQL
  75. */
  76. protected function getAliasedName($table, $alias) {
  77. return $this->getDB()->tableName($table) . ' ' . $alias;
  78. }
  79. /**
  80. * Add a set of JOIN conditions to the internal array
  81. *
  82. * JOIN conditions are formatted as array( tablename => array(jointype,
  83. * conditions) e.g. array('page' => array('LEFT JOIN',
  84. * 'page_id=rev_page')) . conditions may be a string or an
  85. * addWhere()-style array
  86. * @param $join_conds array JOIN conditions
  87. */
  88. protected function addJoinConds($join_conds) {
  89. if(!is_array($join_conds))
  90. ApiBase::dieDebug(__METHOD__, 'Join conditions have to be arrays');
  91. $this->join_conds = array_merge($this->join_conds, $join_conds);
  92. }
  93. /**
  94. * Add a set of fields to select to the internal array
  95. * @param $value mixed Field name or array of field names
  96. */
  97. protected function addFields($value) {
  98. if (is_array($value))
  99. $this->fields = array_merge($this->fields, $value);
  100. else
  101. $this->fields[] = $value;
  102. }
  103. /**
  104. * Same as addFields(), but add the fields only if a condition is met
  105. * @param $value mixed See addFields()
  106. * @param $condition bool If false, do nothing
  107. * @return bool $condition
  108. */
  109. protected function addFieldsIf($value, $condition) {
  110. if ($condition) {
  111. $this->addFields($value);
  112. return true;
  113. }
  114. return false;
  115. }
  116. /**
  117. * Add a set of WHERE clauses to the internal array.
  118. * Clauses can be formatted as 'foo=bar' or array('foo' => 'bar'),
  119. * the latter only works if the value is a constant (i.e. not another field)
  120. *
  121. * If $value is an empty array, this function does nothing.
  122. *
  123. * For example, array('foo=bar', 'baz' => 3, 'bla' => 'foo') translates
  124. * to "foo=bar AND baz='3' AND bla='foo'"
  125. * @param $value mixed String or array
  126. */
  127. protected function addWhere($value) {
  128. if (is_array($value)) {
  129. // Sanity check: don't insert empty arrays,
  130. // Database::makeList() chokes on them
  131. if ( count( $value ) )
  132. $this->where = array_merge($this->where, $value);
  133. }
  134. else
  135. $this->where[] = $value;
  136. }
  137. /**
  138. * Same as addWhere(), but add the WHERE clauses only if a condition is met
  139. * @param $value mixed See addWhere()
  140. * @param $condition boolIf false, do nothing
  141. * @return bool $condition
  142. */
  143. protected function addWhereIf($value, $condition) {
  144. if ($condition) {
  145. $this->addWhere($value);
  146. return true;
  147. }
  148. return false;
  149. }
  150. /**
  151. * Equivalent to addWhere(array($field => $value))
  152. * @param $field string Field name
  153. * @param $value string Value; ignored if null or empty array;
  154. */
  155. protected function addWhereFld($field, $value) {
  156. // Use count() to its full documented capabilities to simultaneously
  157. // test for null, empty array or empty countable object
  158. if ( count( $value ) )
  159. $this->where[$field] = $value;
  160. }
  161. /**
  162. * Add a WHERE clause corresponding to a range, and an ORDER BY
  163. * clause to sort in the right direction
  164. * @param $field string Field name
  165. * @param $dir string If 'newer', sort in ascending order, otherwise
  166. * sort in descending order
  167. * @param $start string Value to start the list at. If $dir == 'newer'
  168. * this is the lower boundary, otherwise it's the upper boundary
  169. * @param $end string Value to end the list at. If $dir == 'newer' this
  170. * is the upper boundary, otherwise it's the lower boundary
  171. * @param $sort bool If false, don't add an ORDER BY clause
  172. */
  173. protected function addWhereRange($field, $dir, $start, $end, $sort = true) {
  174. $isDirNewer = ($dir === 'newer');
  175. $after = ($isDirNewer ? '>=' : '<=');
  176. $before = ($isDirNewer ? '<=' : '>=');
  177. $db = $this->getDB();
  178. if (!is_null($start))
  179. $this->addWhere($field . $after . $db->addQuotes($start));
  180. if (!is_null($end))
  181. $this->addWhere($field . $before . $db->addQuotes($end));
  182. if ($sort) {
  183. $order = $field . ($isDirNewer ? '' : ' DESC');
  184. if (!isset($this->options['ORDER BY']))
  185. $this->addOption('ORDER BY', $order);
  186. else
  187. $this->addOption('ORDER BY', $this->options['ORDER BY'] . ', ' . $order);
  188. }
  189. }
  190. /**
  191. * Add an option such as LIMIT or USE INDEX. If an option was set
  192. * before, the old value will be overwritten
  193. * @param $name string Option name
  194. * @param $value string Option value
  195. */
  196. protected function addOption($name, $value = null) {
  197. if (is_null($value))
  198. $this->options[] = $name;
  199. else
  200. $this->options[$name] = $value;
  201. }
  202. /**
  203. * Execute a SELECT query based on the values in the internal arrays
  204. * @param $method string Function the query should be attributed to.
  205. * You should usually use __METHOD__ here
  206. * @return ResultWrapper
  207. */
  208. protected function select($method) {
  209. // getDB has its own profileDBIn/Out calls
  210. $db = $this->getDB();
  211. $this->profileDBIn();
  212. $res = $db->select($this->tables, $this->fields, $this->where, $method, $this->options, $this->join_conds);
  213. $this->profileDBOut();
  214. return $res;
  215. }
  216. /**
  217. * Estimate the row count for the SELECT query that would be run if we
  218. * called select() right now, and check if it's acceptable.
  219. * @return bool true if acceptable, false otherwise
  220. */
  221. protected function checkRowCount() {
  222. $db = $this->getDB();
  223. $this->profileDBIn();
  224. $rowcount = $db->estimateRowCount($this->tables, $this->fields, $this->where, __METHOD__, $this->options);
  225. $this->profileDBOut();
  226. global $wgAPIMaxDBRows;
  227. if($rowcount > $wgAPIMaxDBRows)
  228. return false;
  229. return true;
  230. }
  231. /**
  232. * Add information (title and namespace) about a Title object to a
  233. * result array
  234. * @param $arr array Result array à la ApiResult
  235. * @param $title Title
  236. * @param $prefix string Module prefix
  237. */
  238. public static function addTitleInfo(&$arr, $title, $prefix='') {
  239. $arr[$prefix . 'ns'] = intval($title->getNamespace());
  240. $arr[$prefix . 'title'] = $title->getPrefixedText();
  241. }
  242. /**
  243. * Override this method to request extra fields from the pageSet
  244. * using $pageSet->requestField('fieldName')
  245. * @param $pageSet ApiPageSet
  246. */
  247. public function requestExtraData($pageSet) {
  248. }
  249. /**
  250. * Get the main Query module
  251. * @return ApiQuery
  252. */
  253. public function getQuery() {
  254. return $this->mQueryModule;
  255. }
  256. /**
  257. * Add a sub-element under the page element with the given page ID
  258. * @param $pageId int Page ID
  259. * @param $data array Data array à la ApiResult
  260. * @return bool Whether the element fit in the result
  261. */
  262. protected function addPageSubItems($pageId, $data) {
  263. $result = $this->getResult();
  264. $result->setIndexedTagName($data, $this->getModulePrefix());
  265. return $result->addValue(array('query', 'pages', intval($pageId)),
  266. $this->getModuleName(),
  267. $data);
  268. }
  269. /**
  270. * Same as addPageSubItems(), but one element of $data at a time
  271. * @param $pageId int Page ID
  272. * @param $data array Data array à la ApiResult
  273. * @param $elemname string XML element name. If null, getModuleName()
  274. * is used
  275. * @return bool Whether the element fit in the result
  276. */
  277. protected function addPageSubItem($pageId, $item, $elemname = null) {
  278. if(is_null($elemname))
  279. $elemname = $this->getModulePrefix();
  280. $result = $this->getResult();
  281. $fit = $result->addValue(array('query', 'pages', $pageId,
  282. $this->getModuleName()), null, $item);
  283. if(!$fit)
  284. return false;
  285. $result->setIndexedTagName_internal(array('query', 'pages', $pageId,
  286. $this->getModuleName()), $elemname);
  287. return true;
  288. }
  289. /**
  290. * Set a query-continue value
  291. * @param $paramName string Parameter name
  292. * @param $paramValue string Parameter value
  293. */
  294. protected function setContinueEnumParameter($paramName, $paramValue) {
  295. $paramName = $this->encodeParamName($paramName);
  296. $msg = array( $paramName => $paramValue );
  297. $this->getResult()->disableSizeCheck();
  298. $this->getResult()->addValue('query-continue', $this->getModuleName(), $msg);
  299. $this->getResult()->enableSizeCheck();
  300. }
  301. /**
  302. * Get the Query database connection (read-only)
  303. * @return Database
  304. */
  305. protected function getDB() {
  306. if (is_null($this->mDb))
  307. $this->mDb = $this->getQuery()->getDB();
  308. return $this->mDb;
  309. }
  310. /**
  311. * Selects the query database connection with the given name.
  312. * See ApiQuery::getNamedDB() for more information
  313. * @param $name string Name to assign to the database connection
  314. * @param $db int One of the DB_* constants
  315. * @param $groups array Query groups
  316. * @return Database
  317. */
  318. public function selectNamedDB($name, $db, $groups) {
  319. $this->mDb = $this->getQuery()->getNamedDB($name, $db, $groups);
  320. }
  321. /**
  322. * Get the PageSet object to work on
  323. * @return ApiPageSet
  324. */
  325. protected function getPageSet() {
  326. return $this->getQuery()->getPageSet();
  327. }
  328. /**
  329. * Convert a title to a DB key
  330. * @param $title string Page title with spaces
  331. * @return string Page title with underscores
  332. */
  333. public function titleToKey($title) {
  334. # Don't throw an error if we got an empty string
  335. if(trim($title) == '')
  336. return '';
  337. $t = Title::newFromText($title);
  338. if(!$t)
  339. $this->dieUsageMsg(array('invalidtitle', $title));
  340. return $t->getPrefixedDbKey();
  341. }
  342. /**
  343. * The inverse of titleToKey()
  344. * @param $key string Page title with underscores
  345. * @return string Page title with spaces
  346. */
  347. public function keyToTitle($key) {
  348. # Don't throw an error if we got an empty string
  349. if(trim($key) == '')
  350. return '';
  351. $t = Title::newFromDbKey($key);
  352. # This really shouldn't happen but we gotta check anyway
  353. if(!$t)
  354. $this->dieUsageMsg(array('invalidtitle', $key));
  355. return $t->getPrefixedText();
  356. }
  357. /**
  358. * An alternative to titleToKey() that doesn't trim trailing spaces
  359. * @param $titlePart string Title part with spaces
  360. * @return string Title part with underscores
  361. */
  362. public function titlePartToKey($titlePart) {
  363. return substr($this->titleToKey($titlePart . 'x'), 0, -1);
  364. }
  365. /**
  366. * An alternative to keyToTitle() that doesn't trim trailing spaces
  367. * @param $keyPart string Key part with spaces
  368. * @return string Key part with underscores
  369. */
  370. public function keyPartToTitle($keyPart) {
  371. return substr($this->keyToTitle($keyPart . 'x'), 0, -1);
  372. }
  373. /**
  374. * Get version string for use in the API help output
  375. * @return string
  376. */
  377. public static function getBaseVersion() {
  378. return __CLASS__ . ': $Id: ApiQueryBase.php 47450 2009-02-18 15:26:09Z catrope $';
  379. }
  380. }
  381. /**
  382. * @ingroup API
  383. */
  384. abstract class ApiQueryGeneratorBase extends ApiQueryBase {
  385. private $mIsGenerator;
  386. public function __construct($query, $moduleName, $paramPrefix = '') {
  387. parent :: __construct($query, $moduleName, $paramPrefix);
  388. $this->mIsGenerator = false;
  389. }
  390. /**
  391. * Switch this module to generator mode. By default, generator mode is
  392. * switched off and the module acts like a normal query module.
  393. */
  394. public function setGeneratorMode() {
  395. $this->mIsGenerator = true;
  396. }
  397. /**
  398. * Overrides base class to prepend 'g' to every generator parameter
  399. * @param $paramNames string Parameter name
  400. * @return string Prefixed parameter name
  401. */
  402. public function encodeParamName($paramName) {
  403. if ($this->mIsGenerator)
  404. return 'g' . parent :: encodeParamName($paramName);
  405. else
  406. return parent :: encodeParamName($paramName);
  407. }
  408. /**
  409. * Execute this module as a generator
  410. * @param $resultPageSet ApiPageSet: All output should be appended to
  411. * this object
  412. */
  413. public abstract function executeGenerator($resultPageSet);
  414. }