comparison sites/all/modules/pathologic/pathologic.module @ 4:ce11bbd8f642

added modules
author danieleb <danielebarchiesi@me.com>
date Thu, 19 Sep 2013 10:38:44 +0100
parents
children
comparison
equal deleted inserted replaced
3:b28be78d8160 4:ce11bbd8f642
1 <?php
2
3 /**
4 * @file
5 * Pathologic text filter for Drupal.
6 *
7 * This input filter attempts to make sure that link and image paths will
8 * always be correct, even when domain names change, content is moved from one
9 * server to another, the Clean URLs feature is toggled, etc.
10 */
11
12 /**
13 * Implements hook_filter_info().
14 */
15 function pathologic_filter_info() {
16 return array(
17 'pathologic' => array(
18 'title' => t('Correct URLs with Pathologic'),
19 'process callback' => '_pathologic_filter',
20 'settings callback' => '_pathologic_settings',
21 'default settings' => array(
22 'local_paths' => '',
23 'protocol_style' => 'full',
24 ),
25 // Set weight to 50 so that it will hopefully appear at the bottom of
26 // filter lists by default. 50 is the maximum value of the weight menu
27 // for each row in the filter table (the menu is hidden by JavaScript to
28 // use table row dragging instead when JS is enabled).
29 'weight' => 50,
30 )
31 );
32 }
33
34 /**
35 * Settings callback for Pathologic.
36 */
37 function _pathologic_settings($form, &$form_state, $filter, $format, $defaults, $filters) {
38 return array(
39 'reminder' => array(
40 '#type' => 'item',
41 '#title' => t('In most cases, Pathologic should be the <em>last</em> filter in the &ldquo;Filter processing order&rdquo; list.'),
42 '#weight' => -10,
43 ),
44 'protocol_style' => array(
45 '#type' => 'radios',
46 '#title' => t('Processed URL format'),
47 '#default_value' => isset($filter->settings['protocol_style']) ? $filter->settings['protocol_style'] : $defaults['protocol_style'],
48 '#options' => array(
49 'full' => t('Full URL (<code>http://example.com/foo/bar</code>)'),
50 'proto-rel' => t('Protocol relative URL (<code>//example.com/foo/bar</code>)'),
51 'path' => t('Path relative to server root (<code>/foo/bar</code>)'),
52 ),
53 '#description' => t('The <em>Full URL</em> option is best for stopping broken images and links in syndicated content (such as in RSS feeds), but will likely lead to problems if your site is accessible by both HTTP and HTTPS. Paths output with the <em>Protocol relative URL</em> option will avoid such problems, but feed readers and other software not using up-to-date standards may be confused by the paths. The <em>Path relative to server root</em> option will avoid problems with sites accessible by both HTTP and HTTPS with no compatibility concerns, but will absolutely not fix broken images and links in syndicated content.'),
54 '#weight' => 10,
55 ),
56 'local_paths' => array(
57 '#type' => 'textarea',
58 '#title' => t('All base paths for this site'),
59 '#default_value' => isset($filter->settings['local_paths']) ? $filter->settings['local_paths'] : $defaults['local_paths'],
60 '#description' => t('If this site is or was available at more than one base path or URL, enter them here, separated by line breaks. For example, if this site is live at <code>http://example.com/</code> but has a staging version at <code>http://dev.example.org/staging/</code>, you would enter both those URLs here. If confused, please read <a href="!docs">Pathologic&rsquo;s documentation</a> for more information about this option and what it affects.', array('!docs' => 'http://drupal.org/node/257026')),
61 '#weight' => 20,
62 ),
63 );
64 }
65
66 /**
67 * Pathologic filter callback.
68 *
69 * Previous versions of this module worked (or, rather, failed) under the
70 * assumption that $langcode contained the language code of the node. Sadly,
71 * this isn't the case.
72 * @see http://drupal.org/node/1812264
73 * However, it turns out that the language of the current node isn't as
74 * important as the language of the node we're linking to, and even then only
75 * if language path prefixing (eg /ja/node/123) is in use. REMEMBER THIS IN THE
76 * FUTURE, ALBRIGHT.
77 *
78 * @todo Can we do the parsing of the local path settings somehow when the
79 * settings form is submitted instead of doing it here?
80 */
81 function _pathologic_filter($text, $filter, $format, $langcode, $cache, $cache_id) {
82 // Get the base URL and explode it into component parts. We add these parts
83 // to the exploded local paths settings later.
84 global $base_url;
85 $base_url_parts = parse_url($base_url . '/');
86 // Since we have to do some gnarly processing even before we do the *really*
87 // gnarly processing, let's static save the settings - it'll speed things up
88 // if, for example, we're importing many nodes, and not slow things down too
89 // much if it's just a one-off. But since different input formats will have
90 // different settings, we build an array of settings, keyed by format ID.
91 $settings = &drupal_static(__FUNCTION__, array());
92 if (!isset($settings[$filter->format])) {
93 $filter->settings['local_paths_exploded'] = array();
94 if ($filter->settings['local_paths'] !== '') {
95 // Build an array of the exploded local paths for this format's settings.
96 // array_filter() below is filtering out items from the array which equal
97 // FALSE - so empty strings (which were causing problems.
98 // @see http://drupal.org/node/1727492
99 $local_paths = array_filter(array_map('trim', explode("\n", $filter->settings['local_paths'])));
100 foreach ($local_paths as $local) {
101 $parts = parse_url($local);
102 // Okay, what the hellish "if" statement is doing below is checking to
103 // make sure we aren't about to add a path to our array of exploded
104 // local paths which matches the current "local" path. We consider it
105 // not a match, if…
106 // @todo: This is pretty horrible. Can this be simplified?
107 if (
108 (
109 // If this URI has a host, and…
110 isset($parts['host']) &&
111 (
112 // Either the host is different from the current host…
113 $parts['host'] !== $base_url_parts['host']
114 // Or, if the hosts are the same, but the paths are different…
115 // @see http://drupal.org/node/1875406
116 || (
117 // Noobs (like me): "xor" means "true if one or the other are
118 // true, but not both."
119 (isset($parts['path']) xor isset($base_url_parts['path']))
120 || (isset($parts['path']) && isset($base_url_parts['path']) && $parts['path'] !== $base_url_parts['path'])
121 )
122 )
123 ) ||
124 // Or…
125 (
126 // The URI doesn't have a host…
127 !isset($parts['host'])
128 ) &&
129 // And the path parts don't match (if either doesn't have a path
130 // part, they can't match)…
131 (
132 !isset($parts['path']) ||
133 !isset($base_url_parts['path']) ||
134 $parts['path'] !== $base_url_parts['path']
135 )
136 ) {
137 // Add it to the list.
138 $filter->settings['local_paths_exploded'][] = $parts;
139 }
140 }
141 }
142 // Now add local paths based on "this" server URL.
143 $filter->settings['local_paths_exploded'][] = array('path' => $base_url_parts['path']);
144 $filter->settings['local_paths_exploded'][] = array('path' => $base_url_parts['path'], 'host' => $base_url_parts['host']);
145 // We'll also just store the host part separately for easy access.
146 $filter->settings['base_url_host'] = $base_url_parts['host'];
147
148 $settings[$filter->format] = $filter->settings;
149 }
150 // Get the language code for the text we're about to process.
151 $settings['langcode'] = $langcode;
152 // And also take note of which settings in the settings array should apply.
153 $settings['current_settings'] = &$settings[$filter->format];
154
155 // Now that we have all of our settings prepared, attempt to process all
156 // paths in href, src, action or longdesc HTML attributes. The pattern below
157 // is not perfect, but the callback will do more checking to make sure the
158 // paths it receives make sense to operate upon, and just return the original
159 // paths if not.
160 return preg_replace_callback('~(href|src|action|longdesc)="([^"]+)~i', '_pathologic_replace', $text);
161 }
162
163 /**
164 * Process and replace paths. preg_replace_callback() callback.
165 */
166 function _pathologic_replace($matches) {
167 // Get the settings for the filter. Since we can't pass extra parameters
168 // through to a callback called by preg_replace_callback(), there's basically
169 // three ways to do this that I can determine: use eval() and friends; abuse
170 // globals; or abuse drupal_static(). The latter is the least offensive, I
171 // guess… Note that we don't do the & thing here so that we can modify
172 // $settings later and not have the changes be "permanent."
173 $settings = drupal_static('_pathologic_filter');
174 // If it appears the path is a scheme-less URL, prepend a scheme to it.
175 // parse_url() cannot properly parse scheme-less URLs. Don't worry; if it
176 // looks like Pathologic can't handle the URL, it will return the scheme-less
177 // original.
178
179 // @see https://drupal.org/node/1617944
180 // @see https://drupal.org/node/2030789
181 if (strpos($matches[2], '//') === 0) {
182 if (isset($_SERVER['https']) && strtolower($_SERVER['https']) === 'on') {
183 $matches[2] = 'https:' . $matches[2];
184 }
185 else {
186 $matches[2] = 'http:' . $matches[2];
187 }
188 }
189 // Now parse the URL after reverting HTML character encoding.
190 // @see http://drupal.org/node/1672932
191 $original_url = htmlspecialchars_decode($matches[2]);
192 // …and parse the URL
193 $parts = parse_url($original_url);
194 // Do some more early tests to see if we should just give up now.
195 if (
196 // If parse_url() failed, give up.
197 $parts === FALSE
198 || (
199 // If there's a scheme part and it doesn't look useful, bail out.
200 isset($parts['scheme'])
201 // We allow for the storage of permitted schemes in a variable, though we
202 // don't actually give the user any way to edit it at this point. This
203 // allows developers to set this array if they have unusual needs where
204 // they don't want Pathologic to trip over a URL with an unusual scheme.
205 // @see http://drupal.org/node/1834308
206 // "files" and "internal" are for Path Filter compatibility.
207 && !in_array($parts['scheme'], variable_get('pathologic_scheme_whitelist', array('http', 'https', 'files', 'internal')))
208 )
209 // Bail out if it looks like there's only a fragment part.
210 || (isset($parts['fragment']) && count($parts) === 1)
211 ) {
212 // Give up by "replacing" the original with the same.
213 return $matches[0];
214 }
215
216 if (isset($parts['path'])) {
217 // Undo possible URL encoding in the path.
218 // @see http://drupal.org/node/1672932
219 $parts['path'] = rawurldecode($parts['path']);
220 }
221 else {
222 $parts['path'] = '';
223 }
224
225 // Check to see if we're dealing with a file.
226 // @todo Should we still try to do path correction on these files too?
227 if (isset($parts['scheme']) && $parts['scheme'] === 'files') {
228 // Path Filter "files:" support. What we're basically going to do here is
229 // rebuild $parts from the full URL of the file.
230 $new_parts = parse_url(file_create_url(file_default_scheme() . '://' . $parts['path']));
231 // If there were query parts from the original parsing, copy them over.
232 if (!empty($parts['query'])) {
233 $new_parts['query'] = $parts['query'];
234 }
235 $new_parts['path'] = rawurldecode($new_parts['path']);
236 $parts = $new_parts;
237 // Don't do language handling for file paths.
238 $settings['is_file'] = TRUE;
239 }
240 else {
241 $settings['is_file'] = FALSE;
242 }
243
244 // Let's also bail out of this doesn't look like a local path.
245 $found = FALSE;
246 // Cycle through local paths and find one with a host and a path that matches;
247 // or just a host if that's all we have; or just a starting path if that's
248 // what we have.
249 foreach ($settings['current_settings']['local_paths_exploded'] as $exploded) {
250 // If a path is available in both…
251 if (isset($exploded['path']) && isset($parts['path'])
252 // And the paths match…
253 && strpos($parts['path'], $exploded['path']) === 0
254 // And either they have the same host, or both have no host…
255 && (
256 (isset($exploded['host']) && isset($parts['host']) && $exploded['host'] === $parts['host'])
257 || (!isset($exploded['host']) && !isset($parts['host']))
258 )
259 ) {
260 // Remove the shared path from the path. This is because the "Also local"
261 // path was something like http://foo/bar and this URL is something like
262 // http://foo/bar/baz; or the "Also local" was something like /bar and
263 // this URL is something like /bar/baz. And we only care about the /baz
264 // part.
265 $parts['path'] = drupal_substr($parts['path'], drupal_strlen($exploded['path']));
266 $found = TRUE;
267 // Break out of the foreach loop
268 break;
269 }
270 // Okay, we didn't match on path alone, or host and path together. Can we
271 // match on just host? Note that for this one we are looking for paths which
272 // are just hosts; not hosts with paths.
273 elseif ((isset($parts['host']) && !isset($exploded['path']) && isset($exploded['host']) && $exploded['host'] === $parts['host'])) {
274 // No further editing; just continue
275 $found = TRUE;
276 // Break out of foreach loop
277 break;
278 }
279 // Is this is a root-relative url (no host) that didn't match above?
280 // Allow a match if local path has no path,
281 // but don't "break" because we'd prefer to keep checking for a local url
282 // that might more fully match the beginning of our url's path
283 // e.g.: if our url is /foo/bar we'll mark this as a match for
284 // http://example.com but want to keep searching and would prefer a match
285 // to http://example.com/foo if that's configured as a local path
286 elseif (!isset($parts['host']) && (!isset($exploded['path']) || $exploded['path'] == '/')) {
287 $found = TRUE;
288 }
289 }
290
291 // If the path is not within the drupal root return original url, unchanged
292 if (!$found) {
293 return $matches[0];
294 }
295
296 // Okay, format the URL.
297 // If there's still a slash lingering at the start of the path, chop it off.
298 $parts['path'] = ltrim($parts['path'],'/');
299
300 // Examine the query part of the URL. Break it up and look through it; if it
301 // has a value for "q", we want to use that as our trimmed path, and remove it
302 // from the array. If any of its values are empty strings (that will be the
303 // case for "bar" if a string like "foo=3&bar&baz=4" is passed through
304 // parse_str()), replace them with NULL so that url() (or, more
305 // specifically, drupal_http_build_query()) can still handle it.
306 if (isset($parts['query'])) {
307 parse_str($parts['query'], $parts['qparts']);
308 foreach ($parts['qparts'] as $key => $value) {
309 if ($value === '') {
310 $parts['qparts'][$key] = NULL;
311 }
312 elseif ($key === 'q') {
313 $parts['path'] = $value;
314 unset($parts['qparts']['q']);
315 }
316 }
317 }
318 else {
319 $parts['qparts'] = NULL;
320 }
321
322 // If we don't have a path yet, bail out.
323 if (!isset($parts['path'])) {
324 return $matches[0];
325 }
326
327 // If we didn't previously identify this as a file, check to see if the file
328 // exists now that we have the correct path relative to DRUPAL_ROOT
329 if (!$settings['is_file']){
330 $settings['is_file'] = !empty($parts['path']) && is_file(DRUPAL_ROOT . '/'. $parts['path']);
331 }
332
333 // Okay, deal with language stuff.
334 if ($settings['is_file']) {
335 // If we're linking to a file, use a fake LANGUAGE_NONE language object.
336 // Otherwise, the path may get prefixed with the "current" language prefix
337 // (eg, /ja/misc/message-24-ok.png)
338 $parts['language_obj'] = (object) array('language' => LANGUAGE_NONE, 'prefix' => '');
339 }
340 else {
341 // Let's see if we can split off a language prefix from the path.
342 if (module_exists('locale')) {
343 // Sometimes this file will be require_once-d by the locale module before
344 // this point, and sometimes not. We require_once it ourselves to be sure.
345 require_once DRUPAL_ROOT . '/includes/language.inc';
346 list($language_obj, $path) = language_url_split_prefix($parts['path'], language_list());
347 if ($language_obj) {
348 $parts['path'] = $path;
349 $parts['language_obj'] = $language_obj;
350 }
351 }
352 }
353
354 // If we get to this point and $parts['path'] is now an empty string (which
355 // will be the case if the path was originally just "/"), then we
356 // want to link to <front>.
357 if ($parts['path'] === '') {
358 $parts['path'] = '<front>';
359 }
360 // Build the parameters we will send to url()
361 $url_params = array(
362 'path' => $parts['path'],
363 'options' => array(
364 'query' => $parts['qparts'],
365 'fragment' => isset($parts['fragment']) ? $parts['fragment'] : NULL,
366 // Create an absolute URL if protocol_style is 'full' or 'proto-rel', but
367 // not if it's 'path'.
368 'absolute' => $settings['current_settings']['protocol_style'] !== 'path',
369 // If we seem to have found a language for the path, pass it along to
370 // url(). Otherwise, ignore the 'language' parameter.
371 'language' => isset($parts['language_obj']) ? $parts['language_obj'] : NULL,
372 // A special parameter not actually used by url(), but we use it to see if
373 // an alter hook implementation wants us to just pass through the original
374 // URL.
375 'use_original' => FALSE,
376 ),
377 );
378
379 // Add the original URL to the parts array
380 $parts['original'] = $original_url;
381
382 // Now alter!
383 // @see http://drupal.org/node/1762022
384 drupal_alter('pathologic', $url_params, $parts, $settings);
385
386 // If any of the alter hooks asked us to just pass along the original URL,
387 // then do so.
388 if ($url_params['options']['use_original']) {
389 return $matches[0];
390 }
391
392 // If the path is for a file and clean URLs are disabled, then the path that
393 // url() will create will have a q= query fragment, which won't work for
394 // files. To avoid that, we use this trick to temporarily turn clean URLs on.
395 // This is horrible, but it seems to be the sanest way to do this.
396 // @see http://drupal.org/node/1672430
397 // @todo Submit core patch allowing clean URLs to be toggled by option sent
398 // to url()?
399 if (!empty($settings['is_file'])) {
400 $settings['orig_clean_url'] = !empty($GLOBALS['conf']['clean_url']);
401 if (!$settings['orig_clean_url']) {
402 $GLOBALS['conf']['clean_url'] = TRUE;
403 }
404 }
405
406 // Now for the url() call. Drumroll, please…
407 $url = url($url_params['path'], $url_params['options']);
408
409 // If we turned clean URLs on before to create a path to a file, turn them
410 // back off.
411 if ($settings['is_file'] && !$settings['orig_clean_url']) {
412 $GLOBALS['conf']['clean_url'] = FALSE;
413 }
414
415 // If we need to create a protocol-relative URL, then convert the absolute
416 // URL we have now.
417 if ($settings['current_settings']['protocol_style'] === 'proto-rel') {
418 // Now, what might have happened here is that url() returned a URL which
419 // isn't on "this" server due to a hook_url_outbound_alter() implementation.
420 // We don't want to convert the URL in that case. So what we're going to
421 // do is cycle through the local paths again and see if the host part of
422 // $url matches with the host of one of those, and only alter in that case.
423 $url_parts = parse_url($url);
424 if (!empty($url_parts['host']) && $url_parts['host'] === $settings['current_settings']['base_url_host']) {
425 $url = _pathologic_url_to_protocol_relative($url);
426 }
427 }
428
429 // Apply HTML character encoding, as is required for HTML attributes.
430 // @see http://drupal.org/node/1672932
431 $url = check_plain($url);
432 // $matches[1] will be the tag attribute; src, href, etc.
433 return "{$matches[1]}=\"{$url}";
434 }
435
436 /**
437 * Convert a full URL with a protocol to a protocol-relative URL.
438 *
439 * As the Drupal core url() function doesn't support protocol-relative URLs, we
440 * work around it by just creating a full URL and then running it through this
441 * to strip off the protocol.
442 *
443 * Though this is just a one-liner, it's placed in its own function so that it
444 * can be called independently from our test code.
445 */
446 function _pathologic_url_to_protocol_relative($url) {
447 return preg_replace('~^https?://~', '//', $url);
448 }