UrlHelper.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  11. * @link https://cakephp.org CakePHP(tm) Project
  12. * @since 3.0.0
  13. * @license https://opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\View\Helper;
  16. use Cake\Core\Configure;
  17. use Cake\Core\Plugin;
  18. use Cake\Routing\Router;
  19. use Cake\Utility\Inflector;
  20. use Cake\View\Helper;
  21. /**
  22. * UrlHelper class for generating URLs.
  23. */
  24. class UrlHelper extends Helper
  25. {
  26. /**
  27. * Returns a URL based on provided parameters.
  28. *
  29. * ### Options:
  30. *
  31. * - `escape`: If false, the URL will be returned unescaped, do only use if it is manually
  32. * escaped afterwards before being displayed.
  33. * - `fullBase`: If true, the full base URL will be prepended to the result
  34. *
  35. * @param string|array|null $url Either a relative string URL like `/products/view/23` or
  36. * an array of URL parameters. Using an array for URLs will allow you to leverage
  37. * the reverse routing features of CakePHP.
  38. * @param array|bool $options Array of options; bool `full` for BC reasons.
  39. * @return string Full translated URL with base path.
  40. */
  41. public function build($url = null, $options = false)
  42. {
  43. $defaults = [
  44. 'fullBase' => false,
  45. 'escape' => true,
  46. ];
  47. if (!is_array($options)) {
  48. $options = ['fullBase' => $options];
  49. }
  50. $options += $defaults;
  51. /** @var string $url */
  52. $url = Router::url($url, $options['fullBase']);
  53. if ($options['escape']) {
  54. /** @var string $url */
  55. $url = h($url);
  56. }
  57. return $url;
  58. }
  59. /**
  60. * Generates URL for given image file.
  61. *
  62. * Depending on options passed provides full URL with domain name. Also calls
  63. * `Helper::assetTimestamp()` to add timestamp to local files.
  64. *
  65. * @param string|array $path Path string or URL array
  66. * @param array $options Options array. Possible keys:
  67. * `fullBase` Return full URL with domain name
  68. * `pathPrefix` Path prefix for relative URLs
  69. * `plugin` False value will prevent parsing path as a plugin
  70. * `timestamp` Overrides the value of `Asset.timestamp` in Configure.
  71. * Set to false to skip timestamp generation.
  72. * Set to true to apply timestamps when debug is true. Set to 'force' to always
  73. * enable timestamping regardless of debug value.
  74. * @return string Generated URL
  75. */
  76. public function image($path, array $options = [])
  77. {
  78. $pathPrefix = Configure::read('App.imageBaseUrl');
  79. return $this->assetUrl($path, $options + compact('pathPrefix'));
  80. }
  81. /**
  82. * Generates URL for given CSS file.
  83. *
  84. * Depending on options passed provides full URL with domain name. Also calls
  85. * `Helper::assetTimestamp()` to add timestamp to local files.
  86. *
  87. * @param string|array $path Path string or URL array
  88. * @param array $options Options array. Possible keys:
  89. * `fullBase` Return full URL with domain name
  90. * `pathPrefix` Path prefix for relative URLs
  91. * `ext` Asset extension to append
  92. * `plugin` False value will prevent parsing path as a plugin
  93. * `timestamp` Overrides the value of `Asset.timestamp` in Configure.
  94. * Set to false to skip timestamp generation.
  95. * Set to true to apply timestamps when debug is true. Set to 'force' to always
  96. * enable timestamping regardless of debug value.
  97. * @return string Generated URL
  98. */
  99. public function css($path, array $options = [])
  100. {
  101. $pathPrefix = Configure::read('App.cssBaseUrl');
  102. $ext = '.css';
  103. return $this->assetUrl($path, $options + compact('pathPrefix', 'ext'));
  104. }
  105. /**
  106. * Generates URL for given javascript file.
  107. *
  108. * Depending on options passed provides full URL with domain name. Also calls
  109. * `Helper::assetTimestamp()` to add timestamp to local files.
  110. *
  111. * @param string|array $path Path string or URL array
  112. * @param array $options Options array. Possible keys:
  113. * `fullBase` Return full URL with domain name
  114. * `pathPrefix` Path prefix for relative URLs
  115. * `ext` Asset extension to append
  116. * `plugin` False value will prevent parsing path as a plugin
  117. * `timestamp` Overrides the value of `Asset.timestamp` in Configure.
  118. * Set to false to skip timestamp generation.
  119. * Set to true to apply timestamps when debug is true. Set to 'force' to always
  120. * enable timestamping regardless of debug value.
  121. * @return string Generated URL
  122. */
  123. public function script($path, array $options = [])
  124. {
  125. $pathPrefix = Configure::read('App.jsBaseUrl');
  126. $ext = '.js';
  127. return $this->assetUrl($path, $options + compact('pathPrefix', 'ext'));
  128. }
  129. /**
  130. * Generates URL for given asset file.
  131. *
  132. * Depending on options passed provides full URL with domain name. Also calls
  133. * `Helper::assetTimestamp()` to add timestamp to local files.
  134. *
  135. * @param string|array $path Path string or URL array
  136. * @param array $options Options array. Possible keys:
  137. * `fullBase` Return full URL with domain name
  138. * `pathPrefix` Path prefix for relative URLs
  139. * `ext` Asset extension to append
  140. * `plugin` False value will prevent parsing path as a plugin
  141. * `timestamp` Overrides the value of `Asset.timestamp` in Configure.
  142. * Set to false to skip timestamp generation.
  143. * Set to true to apply timestamps when debug is true. Set to 'force' to always
  144. * enable timestamping regardless of debug value.
  145. * @return string Generated URL
  146. */
  147. public function assetUrl($path, array $options = [])
  148. {
  149. if (is_array($path)) {
  150. return $this->build($path, !empty($options['fullBase']));
  151. }
  152. // data URIs only require HTML escaping
  153. if (preg_match('/^data:[a-z]+\/[a-z]+;/', $path)) {
  154. return h($path);
  155. }
  156. if (strpos($path, '://') !== false || preg_match('/^[a-z]+:/i', $path)) {
  157. return ltrim($this->build($path), '/');
  158. }
  159. if (!array_key_exists('plugin', $options) || $options['plugin'] !== false) {
  160. list($plugin, $path) = $this->_View->pluginSplit($path, false);
  161. }
  162. if (!empty($options['pathPrefix']) && $path[0] !== '/') {
  163. $path = $options['pathPrefix'] . $path;
  164. }
  165. if (!empty($options['ext']) &&
  166. strpos($path, '?') === false &&
  167. substr($path, -strlen($options['ext'])) !== $options['ext']
  168. ) {
  169. $path .= $options['ext'];
  170. }
  171. if (preg_match('|^([a-z0-9]+:)?//|', $path)) {
  172. return $this->build($path);
  173. }
  174. if (isset($plugin)) {
  175. $path = Inflector::underscore($plugin) . '/' . $path;
  176. }
  177. $optionTimestamp = null;
  178. if (array_key_exists('timestamp', $options)) {
  179. $optionTimestamp = $options['timestamp'];
  180. }
  181. $webPath = $this->assetTimestamp($this->webroot($path), $optionTimestamp);
  182. $path = $this->_encodeUrl($webPath);
  183. if (!empty($options['fullBase'])) {
  184. $path = rtrim(Router::fullBaseUrl(), '/') . '/' . ltrim($path, '/');
  185. }
  186. return $path;
  187. }
  188. /**
  189. * Encodes a URL for use in HTML attributes.
  190. *
  191. * @param string $url The URL to encode.
  192. * @return string The URL encoded for both URL & HTML contexts.
  193. */
  194. protected function _encodeUrl($url)
  195. {
  196. $path = parse_url($url, PHP_URL_PATH);
  197. $parts = array_map('rawurldecode', explode('/', $path));
  198. $parts = array_map('rawurlencode', $parts);
  199. $encoded = implode('/', $parts);
  200. /** @var string $url */
  201. $url = h(str_replace($path, $encoded, $url));
  202. return $url;
  203. }
  204. /**
  205. * Adds a timestamp to a file based resource based on the value of `Asset.timestamp` in
  206. * Configure. If Asset.timestamp is true and debug is true, or Asset.timestamp === 'force'
  207. * a timestamp will be added.
  208. *
  209. * @param string $path The file path to timestamp, the path must be inside WWW_ROOT
  210. * @param bool|string $timestamp If set will overrule the value of `Asset.timestamp` in Configure.
  211. * @return string Path with a timestamp added, or not.
  212. */
  213. public function assetTimestamp($path, $timestamp = null)
  214. {
  215. if ($timestamp === null) {
  216. $timestamp = Configure::read('Asset.timestamp');
  217. }
  218. $timestampEnabled = $timestamp === 'force' || ($timestamp === true && Configure::read('debug'));
  219. if ($timestampEnabled && strpos($path, '?') === false) {
  220. $filepath = preg_replace(
  221. '/^' . preg_quote($this->_View->getRequest()->getAttribute('webroot'), '/') . '/',
  222. '',
  223. urldecode($path)
  224. );
  225. $webrootPath = WWW_ROOT . str_replace('/', DIRECTORY_SEPARATOR, $filepath);
  226. if (file_exists($webrootPath)) {
  227. return $path . '?' . filemtime($webrootPath);
  228. }
  229. $segments = explode('/', ltrim($filepath, '/'));
  230. $plugin = Inflector::camelize($segments[0]);
  231. if (Plugin::isLoaded($plugin)) {
  232. unset($segments[0]);
  233. $pluginPath = Plugin::path($plugin) . 'webroot' . DIRECTORY_SEPARATOR . implode(DIRECTORY_SEPARATOR, $segments);
  234. if (file_exists($pluginPath)) {
  235. return $path . '?' . filemtime($pluginPath);
  236. }
  237. }
  238. }
  239. return $path;
  240. }
  241. /**
  242. * Checks if a file exists when theme is used, if no file is found default location is returned
  243. *
  244. * @param string $file The file to create a webroot path to.
  245. * @return string Web accessible path to file.
  246. */
  247. public function webroot($file)
  248. {
  249. $request = $this->_View->getRequest();
  250. $asset = explode('?', $file);
  251. $asset[1] = isset($asset[1]) ? '?' . $asset[1] : null;
  252. $webPath = $request->getAttribute('webroot') . $asset[0];
  253. $file = $asset[0];
  254. if (!empty($this->_View->getTheme())) {
  255. $file = trim($file, '/');
  256. $theme = $this->_inflectThemeName($this->_View->getTheme()) . '/';
  257. if (DIRECTORY_SEPARATOR === '\\') {
  258. $file = str_replace('/', '\\', $file);
  259. }
  260. if (file_exists(Configure::read('App.wwwRoot') . $theme . $file)) {
  261. $webPath = $request->getAttribute('webroot') . $theme . $asset[0];
  262. } else {
  263. $themePath = Plugin::path($this->_View->getTheme());
  264. $path = $themePath . 'webroot/' . $file;
  265. if (file_exists($path)) {
  266. $webPath = $request->getAttribute('webroot') . $theme . $asset[0];
  267. }
  268. }
  269. }
  270. if (strpos($webPath, '//') !== false) {
  271. return str_replace('//', '/', $webPath . $asset[1]);
  272. }
  273. return $webPath . $asset[1];
  274. }
  275. /**
  276. * Inflect the theme name to its underscored version.
  277. *
  278. * @param string $name Name of the theme which should be inflected.
  279. * @return string Inflected name of the theme
  280. */
  281. protected function _inflectThemeName($name)
  282. {
  283. return Inflector::underscore($name);
  284. }
  285. /**
  286. * Event listeners.
  287. *
  288. * @return array
  289. */
  290. public function implementedEvents()
  291. {
  292. return [];
  293. }
  294. }