Merge "Only need one check for is_dir"
[lhc/web/wiklou.git] / includes / specials / SpecialLinkSearch.php
1 <?php
2 /**
3 * Implements Special:LinkSearch
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 * @ingroup SpecialPage
22 * @author Brion Vibber
23 */
24
25 /**
26 * Special:LinkSearch to search the external-links table.
27 * @ingroup SpecialPage
28 */
29 class LinkSearchPage extends QueryPage {
30 /** @var array|bool */
31 private $mungedQuery = false;
32
33 /**
34 * @var PageLinkRenderer
35 */
36 protected $linkRenderer = null;
37
38 function setParams( $params ) {
39 $this->mQuery = $params['query'];
40 $this->mNs = $params['namespace'];
41 $this->mProt = $params['protocol'];
42 }
43
44 function __construct( $name = 'LinkSearch' ) {
45 parent::__construct( $name );
46
47 // Since we don't control the constructor parameters, we can't inject services that way.
48 // Instead, we initialize services in the execute() method, and allow them to be overridden
49 // using the setServices() method.
50 }
51
52 /**
53 * Initialize or override the PageLinkRenderer LinkSearchPage collaborates with.
54 * Useful mainly for testing.
55 *
56 * @todo query logic and rendering logic should be split and also injected
57 *
58 * @param PageLinkRenderer $linkRenderer
59 */
60 public function setPageLinkRenderer(
61 PageLinkRenderer $linkRenderer
62 ) {
63 $this->linkRenderer = $linkRenderer;
64 }
65
66 /**
67 * Initialize any services we'll need (unless it has already been provided via a setter).
68 * This allows for dependency injection even though we don't control object creation.
69 */
70 private function initServices() {
71 global $wgLanguageCode;
72 if ( !$this->linkRenderer ) {
73 $lang = Language::factory( $wgLanguageCode );
74 $titleFormatter = new MediaWikiTitleCodec( $lang, GenderCache::singleton() );
75 $this->linkRenderer = new MediaWikiPageLinkRenderer( $titleFormatter );
76 }
77 }
78
79 function isCacheable() {
80 return false;
81 }
82
83 function execute( $par ) {
84 $this->initServices();
85
86 $this->setHeaders();
87 $this->outputHeader();
88
89 $out = $this->getOutput();
90 $out->allowClickjacking();
91
92 $request = $this->getRequest();
93 $target = $request->getVal( 'target', $par );
94 $namespace = $request->getIntOrNull( 'namespace', null );
95
96 $protocols_list = array();
97 foreach ( $this->getConfig()->get( 'UrlProtocols' ) as $prot ) {
98 if ( $prot !== '//' ) {
99 $protocols_list[] = $prot;
100 }
101 }
102
103 $target2 = $target;
104 // Get protocol, default is http://
105 $protocol = 'http://';
106 $bits = wfParseUrl( $target );
107 if ( isset( $bits['scheme'] ) && isset( $bits['delimiter'] ) ) {
108 $protocol = $bits['scheme'] . $bits['delimiter'];
109 // Make sure wfParseUrl() didn't make some well-intended correction in the
110 // protocol
111 if ( strcasecmp( $protocol, substr( $target, 0, strlen( $protocol ) ) ) === 0 ) {
112 $target2 = substr( $target, strlen( $protocol ) );
113 } else {
114 // If it did, let LinkFilter::makeLikeArray() handle this
115 $protocol = '';
116 }
117 }
118
119 $out->addWikiMsg(
120 'linksearch-text',
121 '<nowiki>' . $this->getLanguage()->commaList( $protocols_list ) . '</nowiki>',
122 count( $protocols_list )
123 );
124 $s = Html::openElement(
125 'form',
126 array( 'id' => 'mw-linksearch-form', 'method' => 'get', 'action' => wfScript() )
127 ) . "\n" .
128 Html::hidden( 'title', $this->getPageTitle()->getPrefixedDBkey() ) . "\n" .
129 Html::openElement( 'fieldset' ) . "\n" .
130 Html::element( 'legend', array(), $this->msg( 'linksearch' )->text() ) . "\n" .
131 Xml::inputLabel(
132 $this->msg( 'linksearch-pat' )->text(),
133 'target',
134 'target',
135 50,
136 $target,
137 array(
138 // URLs are always ltr
139 'dir' => 'ltr',
140 )
141 ) . "\n";
142
143 if ( !$this->getConfig()->get( 'MiserMode' ) ) {
144 $s .= Html::namespaceSelector(
145 array(
146 'selected' => $namespace,
147 'all' => '',
148 'label' => $this->msg( 'linksearch-ns' )->text()
149 ), array(
150 'name' => 'namespace',
151 'id' => 'namespace',
152 'class' => 'namespaceselector',
153 )
154 );
155 }
156
157 $s .= Xml::submitButton( $this->msg( 'linksearch-ok' )->text() ) . "\n" .
158 Html::closeElement( 'fieldset' ) . "\n" .
159 Html::closeElement( 'form' ) . "\n";
160 $out->addHTML( $s );
161
162 if ( $target != '' ) {
163 $this->setParams( array(
164 'query' => $target2,
165 'namespace' => $namespace,
166 'protocol' => $protocol ) );
167 parent::execute( $par );
168 if ( $this->mungedQuery === false ) {
169 $out->addWikiMsg( 'linksearch-error' );
170 }
171 }
172 }
173
174 /**
175 * Disable RSS/Atom feeds
176 * @return bool
177 */
178 function isSyndicated() {
179 return false;
180 }
181
182 /**
183 * Return an appropriately formatted LIKE query and the clause
184 *
185 * @param string $query Search pattern to search for
186 * @param string $prot Protocol, e.g. 'http://'
187 *
188 * @return array
189 */
190 static function mungeQuery( $query, $prot ) {
191 $field = 'el_index';
192 $dbr = wfGetDB( DB_SLAVE );
193
194 if ( $query === '*' && $prot !== '' ) {
195 // Allow queries like 'ftp://*' to find all ftp links
196 $rv = array( $prot, $dbr->anyString() );
197 } else {
198 $rv = LinkFilter::makeLikeArray( $query, $prot );
199 }
200
201 if ( $rv === false ) {
202 // LinkFilter doesn't handle wildcard in IP, so we'll have to munge here.
203 $pattern = '/^(:?[0-9]{1,3}\.)+\*\s*$|^(:?[0-9]{1,3}\.){3}[0-9]{1,3}:[0-9]*\*\s*$/';
204 if ( preg_match( $pattern, $query ) ) {
205 $rv = array( $prot . rtrim( $query, " \t*" ), $dbr->anyString() );
206 $field = 'el_to';
207 }
208 }
209
210 return array( $rv, $field );
211 }
212
213 function linkParameters() {
214 $params = array();
215 $params['target'] = $this->mProt . $this->mQuery;
216 if ( $this->mNs !== null && !$this->getConfig()->get( 'MiserMode' ) ) {
217 $params['namespace'] = $this->mNs;
218 }
219
220 return $params;
221 }
222
223 function getQueryInfo() {
224 $dbr = wfGetDB( DB_SLAVE );
225 // strip everything past first wildcard, so that
226 // index-based-only lookup would be done
227 list( $this->mungedQuery, $clause ) = self::mungeQuery( $this->mQuery, $this->mProt );
228 if ( $this->mungedQuery === false ) {
229 // Invalid query; return no results
230 return array( 'tables' => 'page', 'fields' => 'page_id', 'conds' => '0=1' );
231 }
232
233 $stripped = LinkFilter::keepOneWildcard( $this->mungedQuery );
234 $like = $dbr->buildLike( $stripped );
235 $retval = array(
236 'tables' => array( 'page', 'externallinks' ),
237 'fields' => array(
238 'namespace' => 'page_namespace',
239 'title' => 'page_title',
240 'value' => 'el_index',
241 'url' => 'el_to'
242 ),
243 'conds' => array(
244 'page_id = el_from',
245 "$clause $like"
246 ),
247 'options' => array( 'USE INDEX' => $clause )
248 );
249
250 if ( $this->mNs !== null && !$this->getConfig()->get( 'MiserMode' ) ) {
251 $retval['conds']['page_namespace'] = $this->mNs;
252 }
253
254 return $retval;
255 }
256
257 /**
258 * Pre-fill the link cache
259 *
260 * @param IDatabase $db
261 * @param ResultWrapper $res
262 */
263 function preprocessResults( $db, $res ) {
264 if ( $res->numRows() > 0 ) {
265 $linkBatch = new LinkBatch();
266
267 foreach ( $res as $row ) {
268 $linkBatch->add( $row->namespace, $row->title );
269 }
270
271 $res->seek( 0 );
272 $linkBatch->execute();
273 }
274 }
275
276 /**
277 * @param Skin $skin
278 * @param object $result Result row
279 * @return string
280 */
281 function formatResult( $skin, $result ) {
282 $title = new TitleValue( (int)$result->namespace, $result->title );
283 $pageLink = $this->linkRenderer->renderHtmlLink( $title );
284
285 $url = $result->url;
286 $urlLink = Linker::makeExternalLink( $url, $url );
287
288 return $this->msg( 'linksearch-line' )->rawParams( $urlLink, $pageLink )->escaped();
289 }
290
291 /**
292 * Override to squash the ORDER BY.
293 * We do a truncated index search, so the optimizer won't trust
294 * it as good enough for optimizing sort. The implicit ordering
295 * from the scan will usually do well enough for our needs.
296 * @return array
297 */
298 function getOrderFields() {
299 return array();
300 }
301
302 protected function getGroupName() {
303 return 'redirects';
304 }
305 }