UrlHelper.php 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (http://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. (http://cakefoundation.org)
  11. * @link http://cakephp.org CakePHP(tm) Project
  12. * @since 3.0.0
  13. * @license http://www.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. * - `full`: 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. 'full' => false,
  45. 'escape' => true,
  46. ];
  47. if (!is_array($options)) {
  48. $options = ['full' => $options];
  49. }
  50. $options += $defaults;
  51. $url = Router::url($url, $options['full']);
  52. if ($options['escape']) {
  53. $url = h($url);
  54. }
  55. return $url;
  56. }
  57. /**
  58. * Generates URL for given image file.
  59. *
  60. * Depending on options passed provides full URL with domain name. Also calls
  61. * `Helper::assetTimestamp()` to add timestamp to local files.
  62. *
  63. * @param string|array $path Path string or URL array
  64. * @param array $options Options array. Possible keys:
  65. * `fullBase` Return full URL with domain name
  66. * `pathPrefix` Path prefix for relative URLs
  67. * `plugin` False value will prevent parsing path as a plugin
  68. * @return string Generated URL
  69. */
  70. public function image($path, array $options = [])
  71. {
  72. $pathPrefix = Configure::read('App.imageBaseUrl');
  73. return $this->assetUrl($path, $options + compact('pathPrefix'));
  74. }
  75. /**
  76. * Generates URL for given CSS file.
  77. *
  78. * Depending on options passed provides full URL with domain name. Also calls
  79. * `Helper::assetTimestamp()` to add timestamp to local files.
  80. *
  81. * @param string|array $path Path string or URL array
  82. * @param array $options Options array. Possible keys:
  83. * `fullBase` Return full URL with domain name
  84. * `pathPrefix` Path prefix for relative URLs
  85. * `ext` Asset extension to append
  86. * `plugin` False value will prevent parsing path as a plugin
  87. * @return string Generated URL
  88. */
  89. public function css($path, array $options = [])
  90. {
  91. $pathPrefix = Configure::read('App.cssBaseUrl');
  92. $ext = '.css';
  93. return $this->assetUrl($path, $options + compact('pathPrefix', 'ext'));
  94. }
  95. /**
  96. * Generates URL for given javascript file.
  97. *
  98. * Depending on options passed provides full URL with domain name. Also calls
  99. * `Helper::assetTimestamp()` to add timestamp to local files.
  100. *
  101. * @param string|array $path Path string or URL array
  102. * @param array $options Options array. Possible keys:
  103. * `fullBase` Return full URL with domain name
  104. * `pathPrefix` Path prefix for relative URLs
  105. * `ext` Asset extension to append
  106. * `plugin` False value will prevent parsing path as a plugin
  107. * @return string Generated URL
  108. */
  109. public function script($path, array $options = [])
  110. {
  111. $pathPrefix = Configure::read('App.jsBaseUrl');
  112. $ext = '.js';
  113. return $this->assetUrl($path, $options + compact('pathPrefix', 'ext'));
  114. }
  115. /**
  116. * Generates URL for given asset file.
  117. *
  118. * Depending on options passed provides full URL with domain name. Also calls
  119. * `Helper::assetTimestamp()` to add timestamp to local files.
  120. *
  121. * @param string|array $path Path string or URL array
  122. * @param array $options Options array. Possible keys:
  123. * `fullBase` Return full URL with domain name
  124. * `pathPrefix` Path prefix for relative URLs
  125. * `ext` Asset extension to append
  126. * `plugin` False value will prevent parsing path as a plugin
  127. * @return string Generated URL
  128. */
  129. public function assetUrl($path, array $options = [])
  130. {
  131. if (is_array($path)) {
  132. return $this->build($path, !empty($options['fullBase']));
  133. }
  134. if (strpos($path, '://') !== false || preg_match('/^[a-z]+:/i', $path)) {
  135. return $path;
  136. }
  137. if (!array_key_exists('plugin', $options) || $options['plugin'] !== false) {
  138. list($plugin, $path) = $this->_View->pluginSplit($path, false);
  139. }
  140. if (!empty($options['pathPrefix']) && $path[0] !== '/') {
  141. $path = $options['pathPrefix'] . $path;
  142. }
  143. if (!empty($options['ext']) &&
  144. strpos($path, '?') === false &&
  145. substr($path, -strlen($options['ext'])) !== $options['ext']
  146. ) {
  147. $path .= $options['ext'];
  148. }
  149. if (preg_match('|^([a-z0-9]+:)?//|', $path)) {
  150. return $path;
  151. }
  152. if (isset($plugin)) {
  153. $path = Inflector::underscore($plugin) . '/' . $path;
  154. }
  155. $path = $this->_encodeUrl($this->assetTimestamp($this->webroot($path)));
  156. if (!empty($options['fullBase'])) {
  157. $path = rtrim(Router::fullBaseUrl(), '/') . '/' . ltrim($path, '/');
  158. }
  159. return $path;
  160. }
  161. /**
  162. * Encodes a URL for use in HTML attributes.
  163. *
  164. * @param string $url The URL to encode.
  165. * @return string The URL encoded for both URL & HTML contexts.
  166. */
  167. protected function _encodeUrl($url)
  168. {
  169. $path = parse_url($url, PHP_URL_PATH);
  170. $parts = array_map('rawurldecode', explode('/', $path));
  171. $parts = array_map('rawurlencode', $parts);
  172. $encoded = implode('/', $parts);
  173. return h(str_replace($path, $encoded, $url));
  174. }
  175. /**
  176. * Adds a timestamp to a file based resource based on the value of `Asset.timestamp` in
  177. * Configure. If Asset.timestamp is true and debug is true, or Asset.timestamp === 'force'
  178. * a timestamp will be added.
  179. *
  180. * @param string $path The file path to timestamp, the path must be inside WWW_ROOT
  181. * @return string Path with a timestamp added, or not.
  182. */
  183. public function assetTimestamp($path)
  184. {
  185. $stamp = Configure::read('Asset.timestamp');
  186. $timestampEnabled = $stamp === 'force' || ($stamp === true && Configure::read('debug'));
  187. if ($timestampEnabled && strpos($path, '?') === false) {
  188. $filepath = preg_replace(
  189. '/^' . preg_quote($this->request->webroot, '/') . '/',
  190. '',
  191. urldecode($path)
  192. );
  193. $webrootPath = WWW_ROOT . str_replace('/', DIRECTORY_SEPARATOR, $filepath);
  194. if (file_exists($webrootPath)) {
  195. //@codingStandardsIgnoreStart
  196. return $path . '?' . @filemtime($webrootPath);
  197. //@codingStandardsIgnoreEnd
  198. }
  199. $segments = explode('/', ltrim($filepath, '/'));
  200. $plugin = Inflector::camelize($segments[0]);
  201. if (Plugin::loaded($plugin)) {
  202. unset($segments[0]);
  203. $pluginPath = Plugin::path($plugin) . 'webroot' . DIRECTORY_SEPARATOR . implode(DIRECTORY_SEPARATOR, $segments);
  204. //@codingStandardsIgnoreStart
  205. return $path . '?' . @filemtime($pluginPath);
  206. //@codingStandardsIgnoreEnd
  207. }
  208. }
  209. return $path;
  210. }
  211. /**
  212. * Checks if a file exists when theme is used, if no file is found default location is returned
  213. *
  214. * @param string $file The file to create a webroot path to.
  215. * @return string Web accessible path to file.
  216. */
  217. public function webroot($file)
  218. {
  219. $asset = explode('?', $file);
  220. $asset[1] = isset($asset[1]) ? '?' . $asset[1] : null;
  221. $webPath = $this->request->webroot . $asset[0];
  222. $file = $asset[0];
  223. if (!empty($this->theme)) {
  224. $file = trim($file, '/');
  225. $theme = $this->_inflectThemeName($this->theme) . '/';
  226. if (DIRECTORY_SEPARATOR === '\\') {
  227. $file = str_replace('/', '\\', $file);
  228. }
  229. if (file_exists(Configure::read('App.wwwRoot') . $theme . $file)) {
  230. $webPath = $this->request->webroot . $theme . $asset[0];
  231. } else {
  232. $themePath = Plugin::path($this->theme);
  233. $path = $themePath . 'webroot/' . $file;
  234. if (file_exists($path)) {
  235. $webPath = $this->request->webroot . $theme . $asset[0];
  236. }
  237. }
  238. }
  239. if (strpos($webPath, '//') !== false) {
  240. return str_replace('//', '/', $webPath . $asset[1]);
  241. }
  242. return $webPath . $asset[1];
  243. }
  244. /**
  245. * Inflect the theme name to its underscored version.
  246. *
  247. * @param string $name Name of the theme which should be inflected.
  248. * @return string Inflected name of the theme
  249. */
  250. protected function _inflectThemeName($name)
  251. {
  252. return Inflector::underscore($name);
  253. }
  254. /**
  255. * Event listeners.
  256. *
  257. * @return array
  258. */
  259. public function implementedEvents()
  260. {
  261. return [];
  262. }
  263. }