UrlHelper.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  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. if (strpos($path, '://') !== false || preg_match('/^[a-z]+:/i', $path)) {
  153. return ltrim($this->build($path), '/');
  154. }
  155. if (!array_key_exists('plugin', $options) || $options['plugin'] !== false) {
  156. list($plugin, $path) = $this->_View->pluginSplit($path, false);
  157. }
  158. if (!empty($options['pathPrefix']) && $path[0] !== '/') {
  159. $path = $options['pathPrefix'] . $path;
  160. }
  161. if (!empty($options['ext']) &&
  162. strpos($path, '?') === false &&
  163. substr($path, -strlen($options['ext'])) !== $options['ext']
  164. ) {
  165. $path .= $options['ext'];
  166. }
  167. if (preg_match('|^([a-z0-9]+:)?//|', $path)) {
  168. return $this->build($path);
  169. }
  170. if (isset($plugin)) {
  171. $path = Inflector::underscore($plugin) . '/' . $path;
  172. }
  173. $optionTimestamp = null;
  174. if (array_key_exists('timestamp', $options)) {
  175. $optionTimestamp = $options['timestamp'];
  176. }
  177. $webPath = $this->assetTimestamp($this->webroot($path), $optionTimestamp);
  178. $path = $this->_encodeUrl($webPath);
  179. if (!empty($options['fullBase'])) {
  180. $path = rtrim(Router::fullBaseUrl(), '/') . '/' . ltrim($path, '/');
  181. }
  182. return $path;
  183. }
  184. /**
  185. * Encodes a URL for use in HTML attributes.
  186. *
  187. * @param string $url The URL to encode.
  188. * @return string The URL encoded for both URL & HTML contexts.
  189. */
  190. protected function _encodeUrl($url)
  191. {
  192. $path = parse_url($url, PHP_URL_PATH);
  193. $parts = array_map('rawurldecode', explode('/', $path));
  194. $parts = array_map('rawurlencode', $parts);
  195. $encoded = implode('/', $parts);
  196. /** @var string $url */
  197. $url = h(str_replace($path, $encoded, $url));
  198. return $url;
  199. }
  200. /**
  201. * Adds a timestamp to a file based resource based on the value of `Asset.timestamp` in
  202. * Configure. If Asset.timestamp is true and debug is true, or Asset.timestamp === 'force'
  203. * a timestamp will be added.
  204. *
  205. * @param string $path The file path to timestamp, the path must be inside WWW_ROOT
  206. * @param bool|string $timestamp If set will overrule the value of `Asset.timestamp` in Configure.
  207. * @return string Path with a timestamp added, or not.
  208. */
  209. public function assetTimestamp($path, $timestamp = null)
  210. {
  211. if ($timestamp === null) {
  212. $timestamp = Configure::read('Asset.timestamp');
  213. }
  214. $timestampEnabled = $timestamp === 'force' || ($timestamp === true && Configure::read('debug'));
  215. if ($timestampEnabled && strpos($path, '?') === false) {
  216. $filepath = preg_replace(
  217. '/^' . preg_quote($this->request->getAttribute('webroot'), '/') . '/',
  218. '',
  219. urldecode($path)
  220. );
  221. $webrootPath = WWW_ROOT . str_replace('/', DIRECTORY_SEPARATOR, $filepath);
  222. if (file_exists($webrootPath)) {
  223. return $path . '?' . filemtime($webrootPath);
  224. }
  225. $segments = explode('/', ltrim($filepath, '/'));
  226. $plugin = Inflector::camelize($segments[0]);
  227. if (Plugin::loaded($plugin)) {
  228. unset($segments[0]);
  229. $pluginPath = Plugin::path($plugin) . 'webroot' . DIRECTORY_SEPARATOR . implode(DIRECTORY_SEPARATOR, $segments);
  230. if (file_exists($pluginPath)) {
  231. return $path . '?' . filemtime($pluginPath);
  232. }
  233. }
  234. }
  235. return $path;
  236. }
  237. /**
  238. * Checks if a file exists when theme is used, if no file is found default location is returned
  239. *
  240. * @param string $file The file to create a webroot path to.
  241. * @return string Web accessible path to file.
  242. */
  243. public function webroot($file)
  244. {
  245. $asset = explode('?', $file);
  246. $asset[1] = isset($asset[1]) ? '?' . $asset[1] : null;
  247. $webPath = $this->request->getAttribute('webroot') . $asset[0];
  248. $file = $asset[0];
  249. if (!empty($this->theme)) {
  250. $file = trim($file, '/');
  251. $theme = $this->_inflectThemeName($this->theme) . '/';
  252. if (DIRECTORY_SEPARATOR === '\\') {
  253. $file = str_replace('/', '\\', $file);
  254. }
  255. if (file_exists(Configure::read('App.wwwRoot') . $theme . $file)) {
  256. $webPath = $this->request->getAttribute('webroot') . $theme . $asset[0];
  257. } else {
  258. $themePath = Plugin::path($this->theme);
  259. $path = $themePath . 'webroot/' . $file;
  260. if (file_exists($path)) {
  261. $webPath = $this->request->getAttribute('webroot') . $theme . $asset[0];
  262. }
  263. }
  264. }
  265. if (strpos($webPath, '//') !== false) {
  266. return str_replace('//', '/', $webPath . $asset[1]);
  267. }
  268. return $webPath . $asset[1];
  269. }
  270. /**
  271. * Inflect the theme name to its underscored version.
  272. *
  273. * @param string $name Name of the theme which should be inflected.
  274. * @return string Inflected name of the theme
  275. */
  276. protected function _inflectThemeName($name)
  277. {
  278. return Inflector::underscore($name);
  279. }
  280. /**
  281. * Event listeners.
  282. *
  283. * @return array
  284. */
  285. public function implementedEvents()
  286. {
  287. return [];
  288. }
  289. }