HtmlHelper.php 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279
  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 0.9.1
  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\Network\Response;
  18. use Cake\View\Helper;
  19. use Cake\View\StringTemplateTrait;
  20. use Cake\View\View;
  21. /**
  22. * Html Helper class for easy use of HTML widgets.
  23. *
  24. * HtmlHelper encloses all methods needed while working with HTML pages.
  25. *
  26. * @property UrlHelper $Url
  27. * @link http://book.cakephp.org/3.0/en/views/helpers/html.html
  28. */
  29. class HtmlHelper extends Helper
  30. {
  31. use StringTemplateTrait;
  32. /**
  33. * List of helpers used by this helper
  34. *
  35. * @var array
  36. */
  37. public $helpers = ['Url'];
  38. /**
  39. * Reference to the Response object
  40. *
  41. * @var \Cake\Network\Response
  42. */
  43. public $response;
  44. /**
  45. * Default config for this class
  46. *
  47. * @var array
  48. */
  49. protected $_defaultConfig = [
  50. 'templates' => [
  51. 'meta' => '<meta{{attrs}}/>',
  52. 'metalink' => '<link href="{{url}}"{{attrs}}/>',
  53. 'link' => '<a href="{{url}}"{{attrs}}>{{content}}</a>',
  54. 'mailto' => '<a href="mailto:{{url}}"{{attrs}}>{{content}}</a>',
  55. 'image' => '<img src="{{url}}"{{attrs}}/>',
  56. 'tableheader' => '<th{{attrs}}>{{content}}</th>',
  57. 'tableheaderrow' => '<tr{{attrs}}>{{content}}</tr>',
  58. 'tablecell' => '<td{{attrs}}>{{content}}</td>',
  59. 'tablerow' => '<tr{{attrs}}>{{content}}</tr>',
  60. 'block' => '<div{{attrs}}>{{content}}</div>',
  61. 'blockstart' => '<div{{attrs}}>',
  62. 'blockend' => '</div>',
  63. 'tag' => '<{{tag}}{{attrs}}>{{content}}</{{tag}}>',
  64. 'tagstart' => '<{{tag}}{{attrs}}>',
  65. 'tagend' => '</{{tag}}>',
  66. 'tagselfclosing' => '<{{tag}}{{attrs}}/>',
  67. 'para' => '<p{{attrs}}>{{content}}</p>',
  68. 'parastart' => '<p{{attrs}}>',
  69. 'css' => '<link rel="{{rel}}" href="{{url}}"{{attrs}}/>',
  70. 'style' => '<style{{attrs}}>{{content}}</style>',
  71. 'charset' => '<meta charset="{{charset}}"/>',
  72. 'ul' => '<ul{{attrs}}>{{content}}</ul>',
  73. 'ol' => '<ol{{attrs}}>{{content}}</ol>',
  74. 'li' => '<li{{attrs}}>{{content}}</li>',
  75. 'javascriptblock' => '<script{{attrs}}>{{content}}</script>',
  76. 'javascriptstart' => '<script>',
  77. 'javascriptlink' => '<script src="{{url}}"{{attrs}}></script>',
  78. 'javascriptend' => '</script>'
  79. ]
  80. ];
  81. /**
  82. * Breadcrumbs.
  83. *
  84. * @var array
  85. */
  86. protected $_crumbs = [];
  87. /**
  88. * Names of script & css files that have been included once
  89. *
  90. * @var array
  91. */
  92. protected $_includedAssets = [];
  93. /**
  94. * Options for the currently opened script block buffer if any.
  95. *
  96. * @var array
  97. */
  98. protected $_scriptBlockOptions = [];
  99. /**
  100. * Document type definitions
  101. *
  102. * @var array
  103. */
  104. protected $_docTypes = [
  105. 'html4-strict' => '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">',
  106. 'html4-trans' => '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">',
  107. 'html4-frame' => '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">',
  108. 'html5' => '<!DOCTYPE html>',
  109. 'xhtml-strict' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">',
  110. 'xhtml-trans' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">',
  111. 'xhtml-frame' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">',
  112. 'xhtml11' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">'
  113. ];
  114. /**
  115. * Constructor
  116. *
  117. * ### Settings
  118. *
  119. * - `templates` Either a filename to a config containing templates.
  120. * Or an array of templates to load. See Cake\View\StringTemplate for
  121. * template formatting.
  122. *
  123. * ### Customizing tag sets
  124. *
  125. * Using the `templates` option you can redefine the tag HtmlHelper will use.
  126. *
  127. * @param \Cake\View\View $View The View this helper is being attached to.
  128. * @param array $config Configuration settings for the helper.
  129. */
  130. public function __construct(View $View, array $config = [])
  131. {
  132. parent::__construct($View, $config);
  133. $this->response = $this->_View->response ?: new Response();
  134. }
  135. /**
  136. * Adds a link to the breadcrumbs array.
  137. *
  138. * @param string $name Text for link
  139. * @param string|array|null $link URL for link (if empty it won't be a link)
  140. * @param string|array $options Link attributes e.g. ['id' => 'selected']
  141. * @return $this
  142. * @see \Cake\View\Helper\HtmlHelper::link() for details on $options that can be used.
  143. * @link http://book.cakephp.org/3.0/en/views/helpers/html.html#creating-breadcrumb-trails-with-htmlhelper
  144. */
  145. public function addCrumb($name, $link = null, array $options = [])
  146. {
  147. $this->_crumbs[] = [$name, $link, $options];
  148. return $this;
  149. }
  150. /**
  151. * Returns a doctype string.
  152. *
  153. * Possible doctypes:
  154. *
  155. * - html4-strict: HTML4 Strict.
  156. * - html4-trans: HTML4 Transitional.
  157. * - html4-frame: HTML4 Frameset.
  158. * - html5: HTML5. Default value.
  159. * - xhtml-strict: XHTML1 Strict.
  160. * - xhtml-trans: XHTML1 Transitional.
  161. * - xhtml-frame: XHTML1 Frameset.
  162. * - xhtml11: XHTML1.1.
  163. *
  164. * @param string $type Doctype to use.
  165. * @return string|null Doctype string
  166. * @link http://book.cakephp.org/3.0/en/views/helpers/html.html#creating-doctype-tags
  167. */
  168. public function docType($type = 'html5')
  169. {
  170. if (isset($this->_docTypes[$type])) {
  171. return $this->_docTypes[$type];
  172. }
  173. return null;
  174. }
  175. /**
  176. * Creates a link to an external resource and handles basic meta tags
  177. *
  178. * Create a meta tag that is output inline:
  179. *
  180. * `$this->Html->meta('icon', 'favicon.ico');
  181. *
  182. * Append the meta tag to custom view block "meta":
  183. *
  184. * ```
  185. * $this->Html->meta('description', 'A great page', ['block' => true]);
  186. * ```
  187. *
  188. * Append the meta tag to custom view block:
  189. *
  190. * ```
  191. * $this->Html->meta('description', 'A great page', ['block' => 'metaTags']);
  192. * ```
  193. *
  194. * Create a custom meta tag:
  195. *
  196. * ```
  197. * $this->Html->meta(['property' => 'og:site_name', 'content' => 'CakePHP']);
  198. * ```
  199. *
  200. * ### Options
  201. *
  202. * - `block` - Set to true to append output to view block "meta" or provide
  203. * custom block name.
  204. *
  205. * @param string|array $type The title of the external resource
  206. * @param string|array|null $content The address of the external resource or string for content attribute
  207. * @param array $options Other attributes for the generated tag. If the type attribute is html,
  208. * rss, atom, or icon, the mime-type is returned.
  209. * @return string A completed `<link />` element.
  210. * @link http://book.cakephp.org/3.0/en/views/helpers/html.html#creating-meta-tags
  211. */
  212. public function meta($type, $content = null, array $options = [])
  213. {
  214. $options += ['block' => null];
  215. if (!is_array($type)) {
  216. $types = [
  217. 'rss' => ['type' => 'application/rss+xml', 'rel' => 'alternate', 'title' => $type, 'link' => $content],
  218. 'atom' => ['type' => 'application/atom+xml', 'title' => $type, 'link' => $content],
  219. 'icon' => ['type' => 'image/x-icon', 'rel' => 'icon', 'link' => $content],
  220. 'keywords' => ['name' => 'keywords', 'content' => $content],
  221. 'description' => ['name' => 'description', 'content' => $content],
  222. 'robots' => ['name' => 'robots', 'content' => $content],
  223. 'viewport' => ['name' => 'viewport', 'content' => $content],
  224. 'canonical' => ['rel' => 'canonical', 'link' => $content]
  225. ];
  226. if ($type === 'icon' && $content === null) {
  227. $types['icon']['link'] = 'favicon.ico';
  228. }
  229. if (isset($types[$type])) {
  230. $type = $types[$type];
  231. } elseif (!isset($options['type']) && $content !== null) {
  232. if (is_array($content) && isset($content['_ext'])) {
  233. $type = $types[$content['_ext']];
  234. } else {
  235. $type = ['name' => $type, 'content' => $content];
  236. }
  237. } elseif (isset($options['type'], $types[$options['type']])) {
  238. $type = $types[$options['type']];
  239. unset($options['type']);
  240. } else {
  241. $type = [];
  242. }
  243. }
  244. $options += $type;
  245. $out = null;
  246. if (isset($options['link'])) {
  247. $options['link'] = $this->Url->assetUrl($options['link']);
  248. if (isset($options['rel']) && $options['rel'] === 'icon') {
  249. $out = $this->formatTemplate('metalink', [
  250. 'url' => $options['link'],
  251. 'attrs' => $this->templater()->formatAttributes($options, ['block', 'link'])
  252. ]);
  253. $options['rel'] = 'shortcut icon';
  254. }
  255. $out .= $this->formatTemplate('metalink', [
  256. 'url' => $options['link'],
  257. 'attrs' => $this->templater()->formatAttributes($options, ['block', 'link'])
  258. ]);
  259. } else {
  260. $out = $this->formatTemplate('meta', [
  261. 'attrs' => $this->templater()->formatAttributes($options, ['block', 'type'])
  262. ]);
  263. }
  264. if (empty($options['block'])) {
  265. return $out;
  266. }
  267. if ($options['block'] === true) {
  268. $options['block'] = __FUNCTION__;
  269. }
  270. $this->_View->append($options['block'], $out);
  271. }
  272. /**
  273. * Returns a charset META-tag.
  274. *
  275. * @param string|null $charset The character set to be used in the meta tag. If empty,
  276. * The App.encoding value will be used. Example: "utf-8".
  277. * @return string A meta tag containing the specified character set.
  278. * @link http://book.cakephp.org/3.0/en/views/helpers/html.html#creating-charset-tags
  279. */
  280. public function charset($charset = null)
  281. {
  282. if (empty($charset)) {
  283. $charset = strtolower(Configure::read('App.encoding'));
  284. }
  285. return $this->formatTemplate('charset', [
  286. 'charset' => (!empty($charset) ? $charset : 'utf-8')
  287. ]);
  288. }
  289. /**
  290. * Creates an HTML link.
  291. *
  292. * If $url starts with "http://" this is treated as an external link. Else,
  293. * it is treated as a path to controller/action and parsed with the
  294. * UrlHelper::build() method.
  295. *
  296. * If the $url is empty, $title is used instead.
  297. *
  298. * ### Options
  299. *
  300. * - `escape` Set to false to disable escaping of title and attributes.
  301. * - `escapeTitle` Set to false to disable escaping of title. Takes precedence
  302. * over value of `escape`)
  303. * - `confirm` JavaScript confirmation message.
  304. *
  305. * @param string $title The content to be wrapped by `<a>` tags.
  306. * @param string|array|null $url Cake-relative URL or array of URL parameters, or
  307. * external URL (starts with http://)
  308. * @param array $options Array of options and HTML attributes.
  309. * @return string An `<a />` element.
  310. * @link http://book.cakephp.org/3.0/en/views/helpers/html.html#creating-links
  311. */
  312. public function link($title, $url = null, array $options = [])
  313. {
  314. $escapeTitle = true;
  315. if ($url !== null) {
  316. $url = $this->Url->build($url);
  317. } else {
  318. $url = $this->Url->build($title);
  319. $title = htmlspecialchars_decode($url, ENT_QUOTES);
  320. $title = h(urldecode($title));
  321. $escapeTitle = false;
  322. }
  323. if (isset($options['escapeTitle'])) {
  324. $escapeTitle = $options['escapeTitle'];
  325. unset($options['escapeTitle']);
  326. } elseif (isset($options['escape'])) {
  327. $escapeTitle = $options['escape'];
  328. }
  329. if ($escapeTitle === true) {
  330. $title = h($title);
  331. } elseif (is_string($escapeTitle)) {
  332. $title = htmlentities($title, ENT_QUOTES, $escapeTitle);
  333. }
  334. $confirmMessage = null;
  335. if (isset($options['confirm'])) {
  336. $confirmMessage = $options['confirm'];
  337. unset($options['confirm']);
  338. }
  339. if ($confirmMessage) {
  340. $options['onclick'] = $this->_confirm($confirmMessage, 'return true;', 'return false;', $options);
  341. }
  342. $templater = $this->templater();
  343. return $templater->format('link', [
  344. 'url' => $url,
  345. 'attrs' => $templater->formatAttributes($options),
  346. 'content' => $title
  347. ]);
  348. }
  349. /**
  350. * Creates a link element for CSS stylesheets.
  351. *
  352. * ### Usage
  353. *
  354. * Include one CSS file:
  355. *
  356. * ```
  357. * echo $this->Html->css('styles.css');
  358. * ```
  359. *
  360. * Include multiple CSS files:
  361. *
  362. * ```
  363. * echo $this->Html->css(['one.css', 'two.css']);
  364. * ```
  365. *
  366. * Add the stylesheet to view block "css":
  367. *
  368. * ```
  369. * $this->Html->css('styles.css', ['block' => true]);
  370. * ```
  371. *
  372. * Add the stylesheet to a custom block:
  373. *
  374. * ```
  375. * $this->Html->css('styles.css', ['block' => 'layoutCss']);
  376. * ```
  377. *
  378. * ### Options
  379. *
  380. * - `block` Set to true to append output to view block "css" or provide
  381. * custom block name.
  382. * - `once` Whether or not the css file should be checked for uniqueness. If true css
  383. * files will only be included once, use false to allow the same
  384. * css to be included more than once per request.
  385. * - `plugin` False value will prevent parsing path as a plugin
  386. * - `rel` Defaults to 'stylesheet'. If equal to 'import' the stylesheet will be imported.
  387. * - `fullBase` If true the URL will get a full address for the css file.
  388. *
  389. * @param string|array $path The name of a CSS style sheet or an array containing names of
  390. * CSS stylesheets. If `$path` is prefixed with '/', the path will be relative to the webroot
  391. * of your application. Otherwise, the path will be relative to your CSS path, usually webroot/css.
  392. * @param array $options Array of options and HTML arguments.
  393. * @return string|null CSS `<link />` or `<style />` tag, depending on the type of link.
  394. * @link http://book.cakephp.org/3.0/en/views/helpers/html.html#linking-to-css-files
  395. */
  396. public function css($path, array $options = [])
  397. {
  398. $options += ['once' => true, 'block' => null, 'rel' => 'stylesheet'];
  399. if (is_array($path)) {
  400. $out = '';
  401. foreach ($path as $i) {
  402. $out .= "\n\t" . $this->css($i, $options);
  403. }
  404. if (empty($options['block'])) {
  405. return $out . "\n";
  406. }
  407. return null;
  408. }
  409. if (strpos($path, '//') !== false) {
  410. $url = $path;
  411. } else {
  412. $url = $this->Url->css($path, $options);
  413. $options = array_diff_key($options, ['fullBase' => null, 'pathPrefix' => null]);
  414. }
  415. if ($options['once'] && isset($this->_includedAssets[__METHOD__][$path])) {
  416. return null;
  417. }
  418. unset($options['once']);
  419. $this->_includedAssets[__METHOD__][$path] = true;
  420. $templater = $this->templater();
  421. if ($options['rel'] === 'import') {
  422. $out = $templater->format('style', [
  423. 'attrs' => $templater->formatAttributes($options, ['rel', 'block']),
  424. 'content' => '@import url(' . $url . ');',
  425. ]);
  426. } else {
  427. $out = $templater->format('css', [
  428. 'rel' => $options['rel'],
  429. 'url' => $url,
  430. 'attrs' => $templater->formatAttributes($options, ['rel', 'block']),
  431. ]);
  432. }
  433. if (empty($options['block'])) {
  434. return $out;
  435. }
  436. if ($options['block'] === true) {
  437. $options['block'] = __FUNCTION__;
  438. }
  439. $this->_View->append($options['block'], $out);
  440. }
  441. /**
  442. * Returns one or many `<script>` tags depending on the number of scripts given.
  443. *
  444. * If the filename is prefixed with "/", the path will be relative to the base path of your
  445. * application. Otherwise, the path will be relative to your JavaScript path, usually webroot/js.
  446. *
  447. * ### Usage
  448. *
  449. * Include one script file:
  450. *
  451. * ```
  452. * echo $this->Html->script('styles.js');
  453. * ```
  454. *
  455. * Include multiple script files:
  456. *
  457. * ```
  458. * echo $this->Html->script(['one.js', 'two.js']);
  459. * ```
  460. *
  461. * Add the script file to a custom block:
  462. *
  463. * ```
  464. * $this->Html->script('styles.js', ['block' => 'bodyScript']);
  465. * ```
  466. *
  467. * ### Options
  468. *
  469. * - `block` Set to true to append output to view block "script" or provide
  470. * custom block name.
  471. * - `once` Whether or not the script should be checked for uniqueness. If true scripts will only be
  472. * included once, use false to allow the same script to be included more than once per request.
  473. * - `plugin` False value will prevent parsing path as a plugin
  474. * - `fullBase` If true the url will get a full address for the script file.
  475. *
  476. * @param string|array $url String or array of javascript files to include
  477. * @param array $options Array of options, and html attributes see above.
  478. * @return string|null String of `<script />` tags or null if block is specified in options
  479. * or if $once is true and the file has been included before.
  480. * @link http://book.cakephp.org/3.0/en/views/helpers/html.html#linking-to-javascript-files
  481. */
  482. public function script($url, array $options = [])
  483. {
  484. $defaults = ['block' => null, 'once' => true];
  485. $options += $defaults;
  486. if (is_array($url)) {
  487. $out = '';
  488. foreach ($url as $i) {
  489. $out .= "\n\t" . $this->script($i, $options);
  490. }
  491. if (empty($options['block'])) {
  492. return $out . "\n";
  493. }
  494. return null;
  495. }
  496. if (strpos($url, '//') === false) {
  497. $url = $this->Url->script($url, $options);
  498. $options = array_diff_key($options, ['fullBase' => null, 'pathPrefix' => null]);
  499. }
  500. if ($options['once'] && isset($this->_includedAssets[__METHOD__][$url])) {
  501. return null;
  502. }
  503. $this->_includedAssets[__METHOD__][$url] = true;
  504. $out = $this->formatTemplate('javascriptlink', [
  505. 'url' => $url,
  506. 'attrs' => $this->templater()->formatAttributes($options, ['block', 'once']),
  507. ]);
  508. if (empty($options['block'])) {
  509. return $out;
  510. }
  511. if ($options['block'] === true) {
  512. $options['block'] = __FUNCTION__;
  513. }
  514. $this->_View->append($options['block'], $out);
  515. }
  516. /**
  517. * Wrap $script in a script tag.
  518. *
  519. * ### Options
  520. *
  521. * - `safe` (boolean) Whether or not the $script should be wrapped in `<![CDATA[ ]]>`
  522. * - `block` Set to true to append output to view block "script" or provide
  523. * custom block name.
  524. *
  525. * @param string $script The script to wrap
  526. * @param array $options The options to use. Options not listed above will be
  527. * treated as HTML attributes.
  528. * @return string|null String or null depending on the value of `$options['block']`
  529. * @link http://book.cakephp.org/3.0/en/views/helpers/html.html#creating-inline-javascript-blocks
  530. */
  531. public function scriptBlock($script, array $options = [])
  532. {
  533. $options += ['safe' => true, 'block' => null];
  534. if ($options['safe']) {
  535. $script = "\n" . '//<![CDATA[' . "\n" . $script . "\n" . '//]]>' . "\n";
  536. }
  537. unset($options['safe']);
  538. $out = $this->formatTemplate('javascriptblock', [
  539. 'attrs' => $this->templater()->formatAttributes($options, ['block']),
  540. 'content' => $script
  541. ]);
  542. if (empty($options['block'])) {
  543. return $out;
  544. }
  545. if ($options['block'] === true) {
  546. $options['block'] = 'script';
  547. }
  548. $this->_View->append($options['block'], $out);
  549. }
  550. /**
  551. * Begin a script block that captures output until HtmlHelper::scriptEnd()
  552. * is called. This capturing block will capture all output between the methods
  553. * and create a scriptBlock from it.
  554. *
  555. * ### Options
  556. *
  557. * - `safe` Whether the code block should contain a CDATA
  558. * - `block` Set to true to append output to view block "script" or provide
  559. * custom block name.
  560. *
  561. * @param array $options Options for the code block.
  562. * @return void
  563. * @link http://book.cakephp.org/3.0/en/views/helpers/html.html#creating-javascript-blocks
  564. */
  565. public function scriptStart(array $options = [])
  566. {
  567. $options += ['safe' => true, 'block' => null];
  568. $this->_scriptBlockOptions = $options;
  569. ob_start();
  570. }
  571. /**
  572. * End a Buffered section of JavaScript capturing.
  573. * Generates a script tag inline or appends to specified view block depending on
  574. * the settings used when the scriptBlock was started
  575. *
  576. * @return string|null Depending on the settings of scriptStart() either a script tag or null
  577. * @link http://book.cakephp.org/3.0/en/views/helpers/html.html#creating-javascript-blocks
  578. */
  579. public function scriptEnd()
  580. {
  581. $buffer = ob_get_clean();
  582. $options = $this->_scriptBlockOptions;
  583. $this->_scriptBlockOptions = [];
  584. return $this->scriptBlock($buffer, $options);
  585. }
  586. /**
  587. * Builds CSS style data from an array of CSS properties
  588. *
  589. * ### Usage:
  590. *
  591. * ```
  592. * echo $this->Html->style(['margin' => '10px', 'padding' => '10px'], true);
  593. *
  594. * // creates
  595. * 'margin:10px;padding:10px;'
  596. * ```
  597. *
  598. * @param array $data Style data array, keys will be used as property names, values as property values.
  599. * @param bool $oneLine Whether or not the style block should be displayed on one line.
  600. * @return string CSS styling data
  601. * @link http://book.cakephp.org/3.0/en/views/helpers/html.html#creating-css-programatically
  602. */
  603. public function style(array $data, $oneLine = true)
  604. {
  605. $out = [];
  606. foreach ($data as $key => $value) {
  607. $out[] = $key . ':' . $value . ';';
  608. }
  609. if ($oneLine) {
  610. return implode(' ', $out);
  611. }
  612. return implode("\n", $out);
  613. }
  614. /**
  615. * Returns the breadcrumb trail as a sequence of &raquo;-separated links.
  616. *
  617. * If `$startText` is an array, the accepted keys are:
  618. *
  619. * - `text` Define the text/content for the link.
  620. * - `url` Define the target of the created link.
  621. *
  622. * All other keys will be passed to HtmlHelper::link() as the `$options` parameter.
  623. *
  624. * @param string $separator Text to separate crumbs.
  625. * @param string|array|bool $startText This will be the first crumb, if false it defaults to first crumb in array. Can
  626. * also be an array, see above for details.
  627. * @return string|null Composed bread crumbs
  628. * @link http://book.cakephp.org/3.0/en/views/helpers/html.html#creating-breadcrumb-trails-with-htmlhelper
  629. */
  630. public function getCrumbs($separator = '&raquo;', $startText = false)
  631. {
  632. $crumbs = $this->_prepareCrumbs($startText);
  633. if (!empty($crumbs)) {
  634. $out = [];
  635. foreach ($crumbs as $crumb) {
  636. if (!empty($crumb[1])) {
  637. $out[] = $this->link($crumb[0], $crumb[1], $crumb[2]);
  638. } else {
  639. $out[] = $crumb[0];
  640. }
  641. }
  642. return implode($separator, $out);
  643. }
  644. return null;
  645. }
  646. /**
  647. * Returns breadcrumbs as a (x)html list
  648. *
  649. * This method uses HtmlHelper::tag() to generate list and its elements. Works
  650. * similar to HtmlHelper::getCrumbs(), so it uses options which every
  651. * crumb was added with.
  652. *
  653. * ### Options
  654. *
  655. * - `separator` Separator content to insert in between breadcrumbs, defaults to ''
  656. * - `firstClass` Class for wrapper tag on the first breadcrumb, defaults to 'first'
  657. * - `lastClass` Class for wrapper tag on current active page, defaults to 'last'
  658. *
  659. * @param array $options Array of HTML attributes to apply to the generated list elements.
  660. * @param string|array|bool $startText This will be the first crumb, if false it defaults to first crumb in array. Can
  661. * also be an array, see `HtmlHelper::getCrumbs` for details.
  662. * @return string|null Breadcrumbs HTML list.
  663. * @link http://book.cakephp.org/3.0/en/views/helpers/html.html#creating-breadcrumb-trails-with-htmlhelper
  664. */
  665. public function getCrumbList(array $options = [], $startText = false)
  666. {
  667. $defaults = ['firstClass' => 'first', 'lastClass' => 'last', 'separator' => '', 'escape' => true];
  668. $options += $defaults;
  669. $firstClass = $options['firstClass'];
  670. $lastClass = $options['lastClass'];
  671. $separator = $options['separator'];
  672. $escape = $options['escape'];
  673. unset($options['firstClass'], $options['lastClass'], $options['separator'], $options['escape']);
  674. $crumbs = $this->_prepareCrumbs($startText, $escape);
  675. if (empty($crumbs)) {
  676. return null;
  677. }
  678. $result = '';
  679. $crumbCount = count($crumbs);
  680. $ulOptions = $options;
  681. foreach ($crumbs as $which => $crumb) {
  682. $options = [];
  683. if (empty($crumb[1])) {
  684. $elementContent = $crumb[0];
  685. } else {
  686. $elementContent = $this->link($crumb[0], $crumb[1], $crumb[2]);
  687. }
  688. if (!$which && $firstClass !== false) {
  689. $options['class'] = $firstClass;
  690. } elseif ($which == $crumbCount - 1 && $lastClass !== false) {
  691. $options['class'] = $lastClass;
  692. }
  693. if (!empty($separator) && ($crumbCount - $which >= 2)) {
  694. $elementContent .= $separator;
  695. }
  696. $result .= $this->formatTemplate('li', [
  697. 'content' => $elementContent,
  698. 'attrs' => $this->templater()->formatAttributes($options)
  699. ]);
  700. }
  701. return $this->formatTemplate('ul', [
  702. 'content' => $result,
  703. 'attrs' => $this->templater()->formatAttributes($ulOptions)
  704. ]);
  705. }
  706. /**
  707. * Prepends startText to crumbs array if set
  708. *
  709. * @param string|array|bool $startText Text to prepend
  710. * @param bool $escape If the output should be escaped or not
  711. * @return array Crumb list including startText (if provided)
  712. */
  713. protected function _prepareCrumbs($startText, $escape = true)
  714. {
  715. $crumbs = $this->_crumbs;
  716. if ($startText) {
  717. if (!is_array($startText)) {
  718. $startText = [
  719. 'url' => '/',
  720. 'text' => $startText
  721. ];
  722. }
  723. $startText += ['url' => '/', 'text' => __d('cake', 'Home')];
  724. list($url, $text) = [$startText['url'], $startText['text']];
  725. unset($startText['url'], $startText['text']);
  726. array_unshift($crumbs, [$text, $url, $startText + ['escape' => $escape]]);
  727. }
  728. return $crumbs;
  729. }
  730. /**
  731. * Creates a formatted IMG element.
  732. *
  733. * This method will set an empty alt attribute if one is not supplied.
  734. *
  735. * ### Usage:
  736. *
  737. * Create a regular image:
  738. *
  739. * ```
  740. * echo $this->Html->image('cake_icon.png', ['alt' => 'CakePHP']);
  741. * ```
  742. *
  743. * Create an image link:
  744. *
  745. * ```
  746. * echo $this->Html->image('cake_icon.png', ['alt' => 'CakePHP', 'url' => 'http://cakephp.org']);
  747. * ```
  748. *
  749. * ### Options:
  750. *
  751. * - `url` If provided an image link will be generated and the link will point at
  752. * `$options['url']`.
  753. * - `fullBase` If true the src attribute will get a full address for the image file.
  754. * - `plugin` False value will prevent parsing path as a plugin
  755. *
  756. * @param string $path Path to the image file, relative to the app/webroot/img/ directory.
  757. * @param array $options Array of HTML attributes. See above for special options.
  758. * @return string completed img tag
  759. * @link http://book.cakephp.org/3.0/en/views/helpers/html.html#linking-to-images
  760. */
  761. public function image($path, array $options = [])
  762. {
  763. $path = $this->Url->image($path, $options);
  764. $options = array_diff_key($options, ['fullBase' => null, 'pathPrefix' => null]);
  765. if (!isset($options['alt'])) {
  766. $options['alt'] = '';
  767. }
  768. $url = false;
  769. if (!empty($options['url'])) {
  770. $url = $options['url'];
  771. unset($options['url']);
  772. }
  773. $templater = $this->templater();
  774. $image = $templater->format('image', [
  775. 'url' => $path,
  776. 'attrs' => $templater->formatAttributes($options),
  777. ]);
  778. if ($url) {
  779. return $templater->format('link', [
  780. 'url' => $this->Url->build($url),
  781. 'attrs' => null,
  782. 'content' => $image
  783. ]);
  784. }
  785. return $image;
  786. }
  787. /**
  788. * Returns a row of formatted and named TABLE headers.
  789. *
  790. * @param array $names Array of tablenames. Each tablename also can be a key that points to an array with a set
  791. * of attributes to its specific tag
  792. * @param array|null $trOptions HTML options for TR elements.
  793. * @param array|null $thOptions HTML options for TH elements.
  794. * @return string Completed table headers
  795. * @link http://book.cakephp.org/3.0/en/views/helpers/html.html#creating-table-headings
  796. */
  797. public function tableHeaders(array $names, array $trOptions = null, array $thOptions = null)
  798. {
  799. $out = [];
  800. foreach ($names as $arg) {
  801. if (!is_array($arg)) {
  802. $out[] = $this->formatTemplate('tableheader', [
  803. 'attrs' => $this->templater()->formatAttributes($thOptions),
  804. 'content' => $arg
  805. ]);
  806. } else {
  807. $out[] = $this->formatTemplate('tableheader', [
  808. 'attrs' => $this->templater()->formatAttributes(current($arg)),
  809. 'content' => key($arg)
  810. ]);
  811. }
  812. }
  813. return $this->tableRow(implode(' ', $out), (array)$trOptions);
  814. }
  815. /**
  816. * Returns a formatted string of table rows (TR's with TD's in them).
  817. *
  818. * @param array|string $data Array of table data
  819. * @param array|bool|null $oddTrOptions HTML options for odd TR elements if true useCount is used
  820. * @param array|bool|null $evenTrOptions HTML options for even TR elements
  821. * @param bool $useCount adds class "column-$i"
  822. * @param bool $continueOddEven If false, will use a non-static $count variable,
  823. * so that the odd/even count is reset to zero just for that call.
  824. * @return string Formatted HTML
  825. * @link http://book.cakephp.org/3.0/en/views/helpers/html.html#creating-table-cells
  826. */
  827. public function tableCells($data, $oddTrOptions = null, $evenTrOptions = null, $useCount = false, $continueOddEven = true)
  828. {
  829. if (empty($data[0]) || !is_array($data[0])) {
  830. $data = [$data];
  831. }
  832. if ($oddTrOptions === true) {
  833. $useCount = true;
  834. $oddTrOptions = null;
  835. }
  836. if ($evenTrOptions === false) {
  837. $continueOddEven = false;
  838. $evenTrOptions = null;
  839. }
  840. if ($continueOddEven) {
  841. static $count = 0;
  842. } else {
  843. $count = 0;
  844. }
  845. foreach ($data as $line) {
  846. $count++;
  847. $cellsOut = $this->_renderCells($line, $useCount);
  848. $opts = $count % 2 ? $oddTrOptions : $evenTrOptions;
  849. $out[] = $this->tableRow(implode(' ', $cellsOut), (array)$opts);
  850. }
  851. return implode("\n", $out);
  852. }
  853. /**
  854. * Renders cells for a row of a table.
  855. *
  856. * This is a helper method for tableCells(). Overload this method as you
  857. * need to change the behavior of the cell rendering.
  858. *
  859. * @param array $line Line data to render.
  860. * @param bool $useCount Renders the count into the row. Default is false.
  861. * @return string
  862. */
  863. protected function _renderCells($line, $useCount = false)
  864. {
  865. $i = 0;
  866. $cellsOut = [];
  867. foreach ($line as $cell) {
  868. $cellOptions = [];
  869. if (is_array($cell)) {
  870. $cellOptions = $cell[1];
  871. $cell = $cell[0];
  872. }
  873. if ($useCount) {
  874. if (isset($cellOptions['class'])) {
  875. $cellOptions['class'] .= ' column-' . ++$i;
  876. } else {
  877. $cellOptions['class'] = 'column-' . ++$i;
  878. }
  879. }
  880. $cellsOut[] = $this->tableCell($cell, $cellOptions);
  881. }
  882. return $cellsOut;
  883. }
  884. /**
  885. * Renders a single table row (A TR with attributes).
  886. *
  887. * @param string $content The content of the row.
  888. * @param array $options HTML attributes.
  889. * @return string
  890. */
  891. public function tableRow($content, array $options = [])
  892. {
  893. return $this->formatTemplate('tablerow', [
  894. 'attrs' => $this->templater()->formatAttributes($options),
  895. 'content' => $content
  896. ]);
  897. }
  898. /**
  899. * Renders a single table cell (A TD with attributes).
  900. *
  901. * @param string $content The content of the cell.
  902. * @param array $options HTML attributes.
  903. * @return string
  904. */
  905. public function tableCell($content, array $options = [])
  906. {
  907. return $this->formatTemplate('tablecell', [
  908. 'attrs' => $this->templater()->formatAttributes($options),
  909. 'content' => $content
  910. ]);
  911. }
  912. /**
  913. * Returns a formatted block tag, i.e DIV, SPAN, P.
  914. *
  915. * ### Options
  916. *
  917. * - `escape` Whether or not the contents should be html_entity escaped.
  918. *
  919. * @param string $name Tag name.
  920. * @param string|null $text String content that will appear inside the div element.
  921. * If null, only a start tag will be printed
  922. * @param array $options Additional HTML attributes of the DIV tag, see above.
  923. * @return string The formatted tag element
  924. */
  925. public function tag($name, $text = null, array $options = [])
  926. {
  927. if (empty($name)) {
  928. return $text;
  929. }
  930. if (isset($options['escape']) && $options['escape']) {
  931. $text = h($text);
  932. unset($options['escape']);
  933. }
  934. if ($text === null) {
  935. $tag = 'tagstart';
  936. } else {
  937. $tag = 'tag';
  938. }
  939. return $this->formatTemplate($tag, [
  940. 'attrs' => $this->templater()->formatAttributes($options),
  941. 'tag' => $name,
  942. 'content' => $text,
  943. ]);
  944. }
  945. /**
  946. * Returns a formatted DIV tag for HTML FORMs.
  947. *
  948. * ### Options
  949. *
  950. * - `escape` Whether or not the contents should be html_entity escaped.
  951. *
  952. * @param string|null $class CSS class name of the div element.
  953. * @param string|null $text String content that will appear inside the div element.
  954. * If null, only a start tag will be printed
  955. * @param array $options Additional HTML attributes of the DIV tag
  956. * @return string The formatted DIV element
  957. */
  958. public function div($class = null, $text = null, array $options = [])
  959. {
  960. if (!empty($class)) {
  961. $options['class'] = $class;
  962. }
  963. return $this->tag('div', $text, $options);
  964. }
  965. /**
  966. * Returns a formatted P tag.
  967. *
  968. * ### Options
  969. *
  970. * - `escape` Whether or not the contents should be html_entity escaped.
  971. *
  972. * @param string $class CSS class name of the p element.
  973. * @param string $text String content that will appear inside the p element.
  974. * @param array $options Additional HTML attributes of the P tag
  975. * @return string The formatted P element
  976. */
  977. public function para($class, $text, array $options = [])
  978. {
  979. if (isset($options['escape'])) {
  980. $text = h($text);
  981. }
  982. if ($class && !empty($class)) {
  983. $options['class'] = $class;
  984. }
  985. $tag = 'para';
  986. if ($text === null) {
  987. $tag = 'parastart';
  988. }
  989. return $this->formatTemplate($tag, [
  990. 'attrs' => $this->templater()->formatAttributes($options),
  991. 'content' => $text,
  992. ]);
  993. }
  994. /**
  995. * Returns an audio/video element
  996. *
  997. * ### Usage
  998. *
  999. * Using an audio file:
  1000. *
  1001. * ```
  1002. * echo $this->Html->media('audio.mp3', ['fullBase' => true]);
  1003. * ```
  1004. *
  1005. * Outputs:
  1006. *
  1007. * `<video src="http://www.somehost.com/files/audio.mp3">Fallback text</video>`
  1008. *
  1009. * Using a video file:
  1010. *
  1011. * ```
  1012. * echo $this->Html->media('video.mp4', ['text' => 'Fallback text']);
  1013. * ```
  1014. *
  1015. * Outputs:
  1016. *
  1017. * `<video src="/files/video.mp4">Fallback text</video>`
  1018. *
  1019. * Using multiple video files:
  1020. *
  1021. * ```
  1022. * echo $this->Html->media(
  1023. * ['video.mp4', ['src' => 'video.ogv', 'type' => "video/ogg; codecs='theora, vorbis'"]],
  1024. * ['tag' => 'video', 'autoplay']
  1025. * );
  1026. * ```
  1027. *
  1028. * Outputs:
  1029. *
  1030. * ```
  1031. * <video autoplay="autoplay">
  1032. * <source src="/files/video.mp4" type="video/mp4"/>
  1033. * <source src="/files/video.ogv" type="video/ogv; codecs='theora, vorbis'"/>
  1034. * </video>
  1035. * ```
  1036. *
  1037. * ### Options
  1038. *
  1039. * - `tag` Type of media element to generate, either "audio" or "video".
  1040. * If tag is not provided it's guessed based on file's mime type.
  1041. * - `text` Text to include inside the audio/video tag
  1042. * - `pathPrefix` Path prefix to use for relative URLs, defaults to 'files/'
  1043. * - `fullBase` If provided the src attribute will get a full address including domain name
  1044. *
  1045. * @param string|array $path Path to the video file, relative to the webroot/{$options['pathPrefix']} directory.
  1046. * Or an array where each item itself can be a path string or an associate array containing keys `src` and `type`
  1047. * @param array $options Array of HTML attributes, and special options above.
  1048. * @return string Generated media element
  1049. */
  1050. public function media($path, array $options = [])
  1051. {
  1052. $options += [
  1053. 'tag' => null,
  1054. 'pathPrefix' => 'files/',
  1055. 'text' => ''
  1056. ];
  1057. if (!empty($options['tag'])) {
  1058. $tag = $options['tag'];
  1059. } else {
  1060. $tag = null;
  1061. }
  1062. if (is_array($path)) {
  1063. $sourceTags = '';
  1064. foreach ($path as &$source) {
  1065. if (is_string($source)) {
  1066. $source = [
  1067. 'src' => $source,
  1068. ];
  1069. }
  1070. if (!isset($source['type'])) {
  1071. $ext = pathinfo($source['src'], PATHINFO_EXTENSION);
  1072. $source['type'] = $this->response->getMimeType($ext);
  1073. }
  1074. $source['src'] = $this->Url->assetUrl($source['src'], $options);
  1075. $sourceTags .= $this->formatTemplate('tagselfclosing', [
  1076. 'tag' => 'source',
  1077. 'attrs' => $this->templater()->formatAttributes($source)
  1078. ]);
  1079. }
  1080. unset($source);
  1081. $options['text'] = $sourceTags . $options['text'];
  1082. unset($options['fullBase']);
  1083. } else {
  1084. if (empty($path) && !empty($options['src'])) {
  1085. $path = $options['src'];
  1086. }
  1087. $options['src'] = $this->Url->assetUrl($path, $options);
  1088. }
  1089. if ($tag === null) {
  1090. if (is_array($path)) {
  1091. $mimeType = $path[0]['type'];
  1092. } else {
  1093. $mimeType = $this->response->getMimeType(pathinfo($path, PATHINFO_EXTENSION));
  1094. }
  1095. if (preg_match('#^video/#', $mimeType)) {
  1096. $tag = 'video';
  1097. } else {
  1098. $tag = 'audio';
  1099. }
  1100. }
  1101. if (isset($options['poster'])) {
  1102. $options['poster'] = $this->Url->assetUrl($options['poster'], ['pathPrefix' => Configure::read('App.imageBaseUrl')] + $options);
  1103. }
  1104. $text = $options['text'];
  1105. $options = array_diff_key($options, [
  1106. 'tag' => null,
  1107. 'fullBase' => null,
  1108. 'pathPrefix' => null,
  1109. 'text' => null
  1110. ]);
  1111. return $this->tag($tag, $text, $options);
  1112. }
  1113. /**
  1114. * Build a nested list (UL/OL) out of an associative array.
  1115. *
  1116. * Options for $options:
  1117. *
  1118. * - `tag` - Type of list tag to use (ol/ul)
  1119. *
  1120. * Options for $itemOptions:
  1121. *
  1122. * - `even` - Class to use for even rows.
  1123. * - `odd` - Class to use for odd rows.
  1124. *
  1125. * @param array $list Set of elements to list
  1126. * @param array $options Options and additional HTML attributes of the list (ol/ul) tag.
  1127. * @param array $itemOptions Options and additional HTML attributes of the list item (LI) tag.
  1128. * @return string The nested list
  1129. * @link http://book.cakephp.org/3.0/en/views/helpers/html.html#creating-nested-lists
  1130. */
  1131. public function nestedList(array $list, array $options = [], array $itemOptions = [])
  1132. {
  1133. $options += ['tag' => 'ul'];
  1134. $items = $this->_nestedListItem($list, $options, $itemOptions);
  1135. return $this->formatTemplate($options['tag'], [
  1136. 'attrs' => $this->templater()->formatAttributes($options, ['tag']),
  1137. 'content' => $items
  1138. ]);
  1139. }
  1140. /**
  1141. * Internal function to build a nested list (UL/OL) out of an associative array.
  1142. *
  1143. * @param array $items Set of elements to list.
  1144. * @param array $options Additional HTML attributes of the list (ol/ul) tag.
  1145. * @param array $itemOptions Options and additional HTML attributes of the list item (LI) tag.
  1146. * @return string The nested list element
  1147. * @see \Cake\View\Helper\HtmlHelper::nestedList()
  1148. */
  1149. protected function _nestedListItem($items, $options, $itemOptions)
  1150. {
  1151. $out = '';
  1152. $index = 1;
  1153. foreach ($items as $key => $item) {
  1154. if (is_array($item)) {
  1155. $item = $key . $this->nestedList($item, $options, $itemOptions);
  1156. }
  1157. if (isset($itemOptions['even']) && $index % 2 === 0) {
  1158. $itemOptions['class'] = $itemOptions['even'];
  1159. } elseif (isset($itemOptions['odd']) && $index % 2 !== 0) {
  1160. $itemOptions['class'] = $itemOptions['odd'];
  1161. }
  1162. $out .= $this->formatTemplate('li', [
  1163. 'attrs' => $this->templater()->formatAttributes($itemOptions, ['even', 'odd']),
  1164. 'content' => $item
  1165. ]);
  1166. $index++;
  1167. }
  1168. return $out;
  1169. }
  1170. /**
  1171. * Event listeners.
  1172. *
  1173. * @return array
  1174. */
  1175. public function implementedEvents()
  1176. {
  1177. return [];
  1178. }
  1179. }