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