pathologic.module 21 KB

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