00001 <?php
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026 if (!defined('MEDIAWIKI')) {
00027
00028 require_once ("ApiQueryBase.php");
00029 }
00030
00039 class ApiQueryBacklinks extends ApiQueryGeneratorBase {
00040
00041 private $params, $rootTitle, $contRedirs, $contLevel, $contTitle, $contID, $redirID, $redirect;
00042 private $bl_ns, $bl_from, $bl_table, $bl_code, $bl_title, $bl_sort, $bl_fields, $hasNS;
00043 private $pageMap, $resultArr;
00044
00045
00046 private $backlinksSettings = array (
00047 'backlinks' => array (
00048 'code' => 'bl',
00049 'prefix' => 'pl',
00050 'linktbl' => 'pagelinks'
00051 ),
00052 'embeddedin' => array (
00053 'code' => 'ei',
00054 'prefix' => 'tl',
00055 'linktbl' => 'templatelinks'
00056 ),
00057 'imageusage' => array (
00058 'code' => 'iu',
00059 'prefix' => 'il',
00060 'linktbl' => 'imagelinks'
00061 )
00062 );
00063
00064 public function __construct($query, $moduleName) {
00065 extract($this->backlinksSettings[$moduleName]);
00066 $this->resultArr = array();
00067
00068 parent :: __construct($query, $moduleName, $code);
00069 $this->bl_ns = $prefix . '_namespace';
00070 $this->bl_from = $prefix . '_from';
00071 $this->bl_table = $linktbl;
00072 $this->bl_code = $code;
00073
00074 $this->hasNS = $moduleName !== 'imageusage';
00075 if ($this->hasNS) {
00076 $this->bl_title = $prefix . '_title';
00077 $this->bl_sort = "{$this->bl_ns}, {$this->bl_title}, {$this->bl_from}";
00078 $this->bl_fields = array (
00079 $this->bl_ns,
00080 $this->bl_title
00081 );
00082 } else {
00083 $this->bl_title = $prefix . '_to';
00084 $this->bl_sort = "{$this->bl_title}, {$this->bl_from}";
00085 $this->bl_fields = array (
00086 $this->bl_title
00087 );
00088 }
00089 }
00090
00091 public function execute() {
00092 $this->run();
00093 }
00094
00095 public function getCacheMode( $params ) {
00096 return 'public';
00097 }
00098
00099 public function executeGenerator($resultPageSet) {
00100 $this->run($resultPageSet);
00101 }
00102
00103 private function prepareFirstQuery($resultPageSet = null) {
00104
00105
00106
00107
00108
00109 $db = $this->getDB();
00110 $this->addTables(array('page', $this->bl_table));
00111 $this->addWhere("{$this->bl_from}=page_id");
00112 if(is_null($resultPageSet))
00113 $this->addFields(array('page_id', 'page_title', 'page_namespace'));
00114 else
00115 $this->addFields($resultPageSet->getPageTableFields());
00116 $this->addFields('page_is_redirect');
00117 $this->addWhereFld($this->bl_title, $this->rootTitle->getDBKey());
00118 if($this->hasNS)
00119 $this->addWhereFld($this->bl_ns, $this->rootTitle->getNamespace());
00120 $this->addWhereFld('page_namespace', $this->params['namespace']);
00121 if(!is_null($this->contID))
00122 $this->addWhere("{$this->bl_from}>={$this->contID}");
00123 if($this->params['filterredir'] == 'redirects')
00124 $this->addWhereFld('page_is_redirect', 1);
00125 if($this->params['filterredir'] == 'nonredirects')
00126 $this->addWhereFld('page_is_redirect', 0);
00127 $this->addOption('LIMIT', $this->params['limit'] + 1);
00128 $this->addOption('ORDER BY', $this->bl_from);
00129 }
00130
00131 private function prepareSecondQuery($resultPageSet = null) {
00132
00133
00134
00135
00136
00137 $db = $this->getDB();
00138 $this->addTables(array('page', $this->bl_table));
00139 $this->addWhere("{$this->bl_from}=page_id");
00140 if(is_null($resultPageSet))
00141 $this->addFields(array('page_id', 'page_title', 'page_namespace', 'page_is_redirect'));
00142 else
00143 $this->addFields($resultPageSet->getPageTableFields());
00144 $this->addFields($this->bl_title);
00145 if($this->hasNS)
00146 $this->addFields($this->bl_ns);
00147
00148 $titleWhere = array();
00149 foreach($this->redirTitles as $t)
00150 $titleWhere[] = "{$this->bl_title} = ".$db->addQuotes($t->getDBKey()).
00151 ($this->hasNS ? " AND {$this->bl_ns} = '{$t->getNamespace()}'" : "");
00152 $this->addWhere($db->makeList($titleWhere, LIST_OR));
00153 $this->addWhereFld('page_namespace', $this->params['namespace']);
00154 if(!is_null($this->redirID))
00155 {
00156 $first = $this->redirTitles[0];
00157 $title = $db->strencode($first->getDBKey());
00158 $ns = $first->getNamespace();
00159 $from = $this->redirID;
00160 if($this->hasNS)
00161 $this->addWhere("{$this->bl_ns} > $ns OR ".
00162 "({$this->bl_ns} = $ns AND ".
00163 "({$this->bl_title} > '$title' OR ".
00164 "({$this->bl_title} = '$title' AND ".
00165 "{$this->bl_from} >= $from)))");
00166 else
00167 $this->addWhere("{$this->bl_title} > '$title' OR ".
00168 "({$this->bl_title} = '$title' AND ".
00169 "{$this->bl_from} >= $from)");
00170
00171 }
00172 if($this->params['filterredir'] == 'redirects')
00173 $this->addWhereFld('page_is_redirect', 1);
00174 if($this->params['filterredir'] == 'nonredirects')
00175 $this->addWhereFld('page_is_redirect', 0);
00176 $this->addOption('LIMIT', $this->params['limit'] + 1);
00177 $this->addOption('ORDER BY', $this->bl_sort);
00178 $this->addOption('USE INDEX', array('page' => 'PRIMARY'));
00179 }
00180
00181 private function run($resultPageSet = null) {
00182 $this->params = $this->extractRequestParams(false);
00183 $this->redirect = isset($this->params['redirect']) && $this->params['redirect'];
00184 $userMax = ( $this->redirect ? ApiBase::LIMIT_BIG1/2 : ApiBase::LIMIT_BIG1 );
00185 $botMax = ( $this->redirect ? ApiBase::LIMIT_BIG2/2 : ApiBase::LIMIT_BIG2 );
00186 if( $this->params['limit'] == 'max' ) {
00187 $this->params['limit'] = $this->getMain()->canApiHighLimits() ? $botMax : $userMax;
00188 $this->getResult()->addValue( 'limits', $this->getModuleName(), $this->params['limit'] );
00189 }
00190
00191 $this->processContinue();
00192 $this->prepareFirstQuery($resultPageSet);
00193
00194 $db = $this->getDB();
00195 $res = $this->select(__METHOD__.'::firstQuery');
00196
00197 $count = 0;
00198 $this->pageMap = array();
00199 $this->continueStr = null;
00200 $this->redirTitles = array();
00201 while ($row = $db->fetchObject($res)) {
00202 if (++ $count > $this->params['limit']) {
00203
00204
00205 $this->continueStr = $this->getContinueStr($row->page_id);
00206 break;
00207 }
00208
00209 if (is_null($resultPageSet))
00210 $this->extractRowInfo($row);
00211 else
00212 {
00213 $this->pageMap[$row->page_namespace][$row->page_title] = $row->page_id;
00214 if($row->page_is_redirect)
00215 $this->redirTitles[] = Title::makeTitle($row->page_namespace, $row->page_title);
00216 $resultPageSet->processDbRow($row);
00217 }
00218 }
00219 $db->freeResult($res);
00220
00221 if($this->redirect && count($this->redirTitles))
00222 {
00223 $this->resetQueryParams();
00224 $this->prepareSecondQuery($resultPageSet);
00225 $res = $this->select(__METHOD__.'::secondQuery');
00226 $count = 0;
00227 while($row = $db->fetchObject($res))
00228 {
00229 if(++$count > $this->params['limit'])
00230 {
00231
00232
00233 if($this->hasNS)
00234 $parentID = $this->pageMap[$row->{$this->bl_ns}][$row->{$this->bl_title}];
00235 else
00236 $parentID = $this->pageMap[NS_IMAGE][$row->{$this->bl_title}];
00237 $this->continueStr = $this->getContinueRedirStr($parentID, $row->page_id);
00238 break;
00239 }
00240
00241 if(is_null($resultPageSet))
00242 $this->extractRedirRowInfo($row);
00243 else
00244 $resultPageSet->processDbRow($row);
00245 }
00246 $db->freeResult($res);
00247 }
00248 if (is_null($resultPageSet)) {
00249
00250 $fit = $this->getResult()->addValue('query', $this->getModuleName(), array_values($this->resultArr));
00251 if(!$fit)
00252 {
00253
00254
00255 foreach($this->resultArr as $pageID => $arr)
00256 {
00257
00258 $fit = $this->getResult()->addValue(
00259 array('query', $this->getModuleName()),
00260 null, array_diff_key($arr, array('redirlinks' => '')));
00261 if(!$fit)
00262 {
00263 $this->continueStr = $this->getContinueStr($pageID);
00264 break;
00265 }
00266
00267 $hasRedirs = false;
00268 foreach((array)@$arr['redirlinks'] as $key => $redir)
00269 {
00270 $fit = $this->getResult()->addValue(
00271 array('query', $this->getModuleName(), $pageID, 'redirlinks'),
00272 $key, $redir);
00273 if(!$fit)
00274 {
00275 $this->continueStr = $this->getContinueRedirStr($pageID, $redir['pageid']);
00276 break;
00277 }
00278 $hasRedirs = true;
00279 }
00280 if($hasRedirs)
00281 $this->getResult()->setIndexedTagName_internal(
00282 array('query', $this->getModuleName(), $pageID, 'redirlinks'),
00283 $this->bl_code);
00284 if(!$fit)
00285 break;
00286 }
00287 }
00288
00289 $this->getResult()->setIndexedTagName_internal(
00290 array('query', $this->getModuleName()),
00291 $this->bl_code);
00292 }
00293 if(!is_null($this->continueStr))
00294 $this->setContinueEnumParameter('continue', $this->continueStr);
00295 }
00296
00297 private function extractRowInfo($row) {
00298 $this->pageMap[$row->page_namespace][$row->page_title] = $row->page_id;
00299 $t = Title::makeTitle($row->page_namespace, $row->page_title);
00300 $a = array('pageid' => intval($row->page_id));
00301 ApiQueryBase::addTitleInfo($a, $t);
00302 if($row->page_is_redirect)
00303 {
00304 $a['redirect'] = '';
00305 $this->redirTitles[] = $t;
00306 }
00307
00308 $this->resultArr[$a['pageid']] = $a;
00309 }
00310
00311 private function extractRedirRowInfo($row)
00312 {
00313 $a['pageid'] = intval($row->page_id);
00314 ApiQueryBase::addTitleInfo($a, Title::makeTitle($row->page_namespace, $row->page_title));
00315 if($row->page_is_redirect)
00316 $a['redirect'] = '';
00317 $ns = $this->hasNS ? $row->{$this->bl_ns} : NS_FILE;
00318 $parentID = $this->pageMap[$ns][$row->{$this->bl_title}];
00319
00320 $this->resultArr[$parentID]['redirlinks'][] = $a;
00321 $this->getResult()->setIndexedTagName($this->resultArr[$parentID]['redirlinks'], $this->bl_code);
00322 }
00323
00324 protected function processContinue() {
00325 if (!is_null($this->params['continue']))
00326 $this->parseContinueParam();
00327 else {
00328 if ( $this->params['title'] !== "" ) {
00329 $title = Title::newFromText( $this->params['title'] );
00330 if ( !$title ) {
00331 $this->dieUsageMsg(array('invalidtitle', $this->params['title']));
00332 } else {
00333 $this->rootTitle = $title;
00334 }
00335 } else {
00336 $this->dieUsageMsg(array('missingparam', 'title'));
00337 }
00338 }
00339
00340
00341 if (!$this->hasNS && $this->rootTitle->getNamespace() !== NS_FILE)
00342 $this->dieUsage("The title for {$this->getModuleName()} query must be an image", 'bad_image_title');
00343 }
00344
00345 protected function parseContinueParam() {
00346 $continueList = explode('|', $this->params['continue']);
00347
00348
00349
00350
00351
00352
00353
00354 $this->rootTitle = $this->contID = $this->redirID = null;
00355 $rootNs = intval($continueList[0]);
00356 if($rootNs === 0 && $continueList[0] !== '0')
00357
00358 $this->dieUsage("Invalid continue param. You should pass the original value returned by the previous query", "_badcontinue");
00359 $this->rootTitle = Title::makeTitleSafe($rootNs, $continueList[1]);
00360 if(!$this->rootTitle)
00361 $this->dieUsage("Invalid continue param. You should pass the original value returned by the previous query", "_badcontinue");
00362 $contID = intval($continueList[2]);
00363 if($contID === 0 && $continueList[2] !== '0')
00364 $this->dieUsage("Invalid continue param. You should pass the original value returned by the previous query", "_badcontinue");
00365 $this->contID = $contID;
00366 $redirID = intval(@$continueList[3]);
00367 if($redirID === 0 && @$continueList[3] !== '0')
00368
00369 return;
00370 $this->redirID = $redirID;
00371
00372 }
00373
00374 protected function getContinueStr($lastPageID) {
00375 return $this->rootTitle->getNamespace() .
00376 '|' . $this->rootTitle->getDBkey() .
00377 '|' . $lastPageID;
00378 }
00379
00380 protected function getContinueRedirStr($lastPageID, $lastRedirID) {
00381 return $this->getContinueStr($lastPageID) . '|' . $lastRedirID;
00382 }
00383
00384 public function getAllowedParams() {
00385 $retval = array (
00386 'title' => null,
00387 'continue' => null,
00388 'namespace' => array (
00389 ApiBase :: PARAM_ISMULTI => true,
00390 ApiBase :: PARAM_TYPE => 'namespace'
00391 ),
00392 'filterredir' => array(
00393 ApiBase :: PARAM_DFLT => 'all',
00394 ApiBase :: PARAM_TYPE => array(
00395 'all',
00396 'redirects',
00397 'nonredirects'
00398 )
00399 ),
00400 'limit' => array (
00401 ApiBase :: PARAM_DFLT => 10,
00402 ApiBase :: PARAM_TYPE => 'limit',
00403 ApiBase :: PARAM_MIN => 1,
00404 ApiBase :: PARAM_MAX => ApiBase :: LIMIT_BIG1,
00405 ApiBase :: PARAM_MAX2 => ApiBase :: LIMIT_BIG2
00406 )
00407 );
00408 if($this->getModuleName() == 'embeddedin')
00409 return $retval;
00410 $retval['redirect'] = false;
00411 return $retval;
00412 }
00413
00414 public function getParamDescription() {
00415 $retval = array (
00416 'title' => 'Title to search. If null, titles= parameter will be used instead, but will be obsolete soon.',
00417 'continue' => 'When more results are available, use this to continue.',
00418 'namespace' => 'The namespace to enumerate.',
00419 'filterredir' => 'How to filter for redirects'
00420 );
00421 if($this->getModuleName() != 'embeddedin')
00422 return array_merge($retval, array(
00423 'redirect' => 'If linking page is a redirect, find all pages that link to that redirect as well. Maximum limit is halved.',
00424 'limit' => "How many total pages to return. If {$this->bl_code}redirect is enabled, limit applies to each level separately."
00425 ));
00426 return array_merge($retval, array(
00427 'limit' => "How many total pages to return."
00428 ));
00429 }
00430
00431 public function getDescription() {
00432 switch ($this->getModuleName()) {
00433 case 'backlinks' :
00434 return 'Find all pages that link to the given page';
00435 case 'embeddedin' :
00436 return 'Find all pages that embed (transclude) the given title';
00437 case 'imageusage' :
00438 return 'Find all pages that use the given image title.';
00439 default :
00440 ApiBase :: dieDebug(__METHOD__, 'Unknown module name');
00441 }
00442 }
00443
00444 protected function getExamples() {
00445 static $examples = array (
00446 'backlinks' => array (
00447 "api.php?action=query&list=backlinks&bltitle=Main%20Page",
00448 "api.php?action=query&generator=backlinks&gbltitle=Main%20Page&prop=info"
00449 ),
00450 'embeddedin' => array (
00451 "api.php?action=query&list=embeddedin&eititle=Template:Stub",
00452 "api.php?action=query&generator=embeddedin&geititle=Template:Stub&prop=info"
00453 ),
00454 'imageusage' => array (
00455 "api.php?action=query&list=imageusage&iutitle=File:Albert%20Einstein%20Head.jpg",
00456 "api.php?action=query&generator=imageusage&giutitle=File:Albert%20Einstein%20Head.jpg&prop=info"
00457 )
00458 );
00459
00460 return $examples[$this->getModuleName()];
00461 }
00462
00463 public function getVersion() {
00464 return __CLASS__ . ': $Id: ApiQueryBacklinks.php 69986 2010-07-27 03:57:39Z tstarling $';
00465 }
00466 }