pathologic.module 20 KB

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