HtmlHelper.php 37 KB

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