PageRenderTime 50ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/Cake/View/Helper/HtmlHelper.php

https://bitbucket.org/tlorens/cakefoundation
PHP | 1214 lines | 1036 code | 22 blank | 156 comment | 30 complexity | 960c78043fbc97b0429de9d2f1d19fcd MD5 | raw file
  1. <?php
  2. /**
  3. * Html Helper class file.
  4. *
  5. * Simplifies the construction of HTML elements.
  6. *
  7. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  8. * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
  9. *
  10. * Licensed under The MIT License
  11. * Redistributions of files must retain the above copyright notice.
  12. *
  13. * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
  14. * @link http://cakephp.org CakePHP(tm) Project
  15. * @package Cake.View.Helper
  16. * @since CakePHP(tm) v 0.9.1
  17. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  18. */
  19. App::uses('AppHelper', 'View/Helper');
  20. App::uses('CakeResponse', 'Network');
  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. * @package Cake.View.Helper
  27. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html
  28. */
  29. class HtmlHelper extends AppHelper {
  30. /**
  31. * Reference to the Response object
  32. *
  33. * @var CakeResponse
  34. */
  35. public $response;
  36. /**
  37. * html tags used by this helper.
  38. *
  39. * @var array
  40. */
  41. protected $_tags = array(
  42. 'meta' => '<meta%s/>',
  43. 'metalink' => '<link href="%s"%s/>',
  44. 'link' => '<a href="%s"%s>%s</a>',
  45. 'mailto' => '<a href="mailto:%s" %s>%s</a>',
  46. 'form' => '<form action="%s"%s>',
  47. 'formend' => '</form>',
  48. 'input' => '<input name="%s"%s/>',
  49. 'textarea' => '<textarea name="%s"%s>%s</textarea>',
  50. 'hidden' => '<input type="hidden" name="%s"%s/>',
  51. 'checkbox' => '<input type="checkbox" name="%s" %s/>',
  52. 'checkboxmultiple' => '<input type="checkbox" name="%s[]"%s />',
  53. 'radio' => '<input type="radio" name="%s" id="%s"%s />%s',
  54. 'selectstart' => '<select name="%s"%s>',
  55. 'selectmultiplestart' => '<select name="%s[]"%s>',
  56. 'selectempty' => '<option value=""%s>&nbsp;</option>',
  57. 'selectoption' => '<option value="%s"%s>%s</option>',
  58. 'selectend' => '</select>',
  59. 'optiongroup' => '<optgroup label="%s"%s>',
  60. 'optiongroupend' => '</optgroup>',
  61. 'checkboxmultiplestart' => '',
  62. 'checkboxmultipleend' => '',
  63. 'password' => '<input type="password" name="%s" %s/>',
  64. 'file' => '<input type="file" name="%s" %s/>',
  65. 'file_no_model' => '<input type="file" name="%s" %s/>',
  66. 'submit' => '<input %s/>',
  67. 'submitimage' => '<input type="image" src="%s" %s/>',
  68. 'button' => '<button%s>%s</button>',
  69. 'image' => '<img src="%s" %s/>',
  70. 'tableheader' => '<th%s>%s</th>',
  71. 'tableheaderrow' => '<tr%s>%s</tr>',
  72. 'tablecell' => '<td%s>%s</td>',
  73. 'tablerow' => '<tr%s>%s</tr>',
  74. 'block' => '<div%s>%s</div>',
  75. 'blockstart' => '<div%s>',
  76. 'blockend' => '</div>',
  77. 'tag' => '<%s%s>%s</%s>',
  78. 'tagstart' => '<%s%s>',
  79. 'tagend' => '</%s>',
  80. 'tagselfclosing' => '<%s%s/>',
  81. 'para' => '<p%s>%s</p>',
  82. 'parastart' => '<p%s>',
  83. 'label' => '<label for="%s"%s>%s</label>',
  84. 'fieldset' => '<fieldset%s>%s</fieldset>',
  85. 'fieldsetstart' => '<fieldset><legend>%s</legend>',
  86. 'fieldsetend' => '</fieldset>',
  87. 'legend' => '<legend>%s</legend>',
  88. 'css' => '<link rel="%s" type="text/css" href="%s" %s/>',
  89. 'style' => '<style type="text/css"%s>%s</style>',
  90. 'charset' => '<meta http-equiv="Content-Type" content="text/html; charset=%s" />',
  91. 'ul' => '<ul%s>%s</ul>',
  92. 'ol' => '<ol%s>%s</ol>',
  93. 'li' => '<li%s>%s</li>',
  94. 'error' => '<div%s>%s</div>',
  95. 'javascriptblock' => '<script type="text/javascript"%s>%s</script>',
  96. 'javascriptstart' => '<script type="text/javascript">',
  97. 'javascriptlink' => '<script type="text/javascript" src="%s"%s></script>',
  98. 'javascriptend' => '</script>'
  99. );
  100. /**
  101. * Breadcrumbs.
  102. *
  103. * @var array
  104. */
  105. protected $_crumbs = array();
  106. /**
  107. * Names of script files that have been included once
  108. *
  109. * @var array
  110. */
  111. protected $_includedScripts = array();
  112. /**
  113. * Options for the currently opened script block buffer if any.
  114. *
  115. * @var array
  116. */
  117. protected $_scriptBlockOptions = array();
  118. /**
  119. * Document type definitions
  120. *
  121. * @var array
  122. */
  123. protected $_docTypes = array(
  124. 'html4-strict' => '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">',
  125. 'html4-trans' => '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">',
  126. 'html4-frame' => '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">',
  127. 'html5' => '<!DOCTYPE html>',
  128. 'xhtml-strict' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">',
  129. 'xhtml-trans' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">',
  130. 'xhtml-frame' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">',
  131. 'xhtml11' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">'
  132. );
  133. /**
  134. * Constructor
  135. *
  136. * ### Settings
  137. *
  138. * - `configFile` A file containing an array of tags you wish to redefine.
  139. *
  140. * ### Customizing tag sets
  141. *
  142. * Using the `configFile` option you can redefine the tag HtmlHelper will use.
  143. * The file named should be compatible with HtmlHelper::loadConfig().
  144. *
  145. * @param View $View The View this helper is being attached to.
  146. * @param array $settings Configuration settings for the helper.
  147. */
  148. public function __construct(View $View, $settings = array()) {
  149. parent::__construct($View, $settings);
  150. if (is_object($this->_View->response)) {
  151. $this->response = $this->_View->response;
  152. } else {
  153. $this->response = new CakeResponse(array('charset' => Configure::read('App.encoding')));
  154. }
  155. if (!empty($settings['configFile'])) {
  156. $this->loadConfig($settings['configFile']);
  157. }
  158. }
  159. /**
  160. * Adds a link to the breadcrumbs array.
  161. *
  162. * @param string $name Text for link
  163. * @param string $link URL for link (if empty it won't be a link)
  164. * @param string|array $options Link attributes e.g. array('id' => 'selected')
  165. * @return void
  166. * @see HtmlHelper::link() for details on $options that can be used.
  167. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html#creating-breadcrumb-trails-with-htmlhelper
  168. */
  169. public function addCrumb($name, $link = null, $options = null) {
  170. $this->_crumbs[] = array($name, $link, $options);
  171. }
  172. /**
  173. * Returns a doctype string.
  174. *
  175. * Possible doctypes:
  176. *
  177. * - html4-strict: HTML4 Strict.
  178. * - html4-trans: HTML4 Transitional.
  179. * - html4-frame: HTML4 Frameset.
  180. * - html5: HTML5. Default value.
  181. * - xhtml-strict: XHTML1 Strict.
  182. * - xhtml-trans: XHTML1 Transitional.
  183. * - xhtml-frame: XHTML1 Frameset.
  184. * - xhtml11: XHTML1.1.
  185. *
  186. * @param string $type Doctype to use.
  187. * @return string Doctype string
  188. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html#HtmlHelper::docType
  189. */
  190. public function docType($type = 'html5') {
  191. if (isset($this->_docTypes[$type])) {
  192. return $this->_docTypes[$type];
  193. }
  194. return null;
  195. }
  196. /**
  197. * Creates a link to an external resource and handles basic meta tags
  198. *
  199. * Create a meta tag that is output inline:
  200. *
  201. * `$this->Html->meta('icon', 'favicon.ico');
  202. *
  203. * Append the meta tag to `$scripts_for_layout`:
  204. *
  205. * `$this->Html->meta('description', 'A great page', array('inline' => false));`
  206. *
  207. * Append the meta tag to custom view block:
  208. *
  209. * `$this->Html->meta('description', 'A great page', array('block' => 'metaTags'));`
  210. *
  211. * ### Options
  212. *
  213. * - `inline` Whether or not the link element should be output inline. Set to false to
  214. * have the meta tag included in `$scripts_for_layout`, and appended to the 'meta' view block.
  215. * - `block` Choose a custom block to append the meta tag to. Using this option
  216. * will override the inline option.
  217. *
  218. * @param string $type The title of the external resource
  219. * @param string|array $url The address of the external resource or string for content attribute
  220. * @param array $options Other attributes for the generated tag. If the type attribute is html,
  221. * rss, atom, or icon, the mime-type is returned.
  222. * @return string A completed `<link />` element.
  223. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html#HtmlHelper::meta
  224. */
  225. public function meta($type, $url = null, $options = array()) {
  226. $options += array('inline' => true, 'block' => null);
  227. if (!$options['inline'] && empty($options['block'])) {
  228. $options['block'] = __FUNCTION__;
  229. }
  230. unset($options['inline']);
  231. if (!is_array($type)) {
  232. $types = array(
  233. 'rss' => array('type' => 'application/rss+xml', 'rel' => 'alternate', 'title' => $type, 'link' => $url),
  234. 'atom' => array('type' => 'application/atom+xml', 'title' => $type, 'link' => $url),
  235. 'icon' => array('type' => 'image/x-icon', 'rel' => 'icon', 'link' => $url),
  236. 'keywords' => array('name' => 'keywords', 'content' => $url),
  237. 'description' => array('name' => 'description', 'content' => $url),
  238. );
  239. if ($type === 'icon' && $url === null) {
  240. $types['icon']['link'] = $this->webroot('favicon.ico');
  241. }
  242. if (isset($types[$type])) {
  243. $type = $types[$type];
  244. } elseif (!isset($options['type']) && $url !== null) {
  245. if (is_array($url) && isset($url['ext'])) {
  246. $type = $types[$url['ext']];
  247. } else {
  248. $type = $types['rss'];
  249. }
  250. } elseif (isset($options['type']) && isset($types[$options['type']])) {
  251. $type = $types[$options['type']];
  252. unset($options['type']);
  253. } else {
  254. $type = array();
  255. }
  256. } elseif ($url !== null) {
  257. $inline = $url;
  258. }
  259. $options = array_merge($type, $options);
  260. $out = null;
  261. if (isset($options['link'])) {
  262. if (isset($options['rel']) && $options['rel'] === 'icon') {
  263. $out = sprintf($this->_tags['metalink'], $options['link'], $this->_parseAttributes($options, array('block', 'link'), ' ', ' '));
  264. $options['rel'] = 'shortcut icon';
  265. } else {
  266. $options['link'] = $this->url($options['link'], true);
  267. }
  268. $out .= sprintf($this->_tags['metalink'], $options['link'], $this->_parseAttributes($options, array('block', 'link'), ' ', ' '));
  269. } else {
  270. $out = sprintf($this->_tags['meta'], $this->_parseAttributes($options, array('block', 'type'), ' ', ' '));
  271. }
  272. if (empty($options['block'])) {
  273. return $out;
  274. } else {
  275. $this->_View->append($options['block'], $out);
  276. }
  277. }
  278. /**
  279. * Returns a charset META-tag.
  280. *
  281. * @param string $charset The character set to be used in the meta tag. If empty,
  282. * The App.encoding value will be used. Example: "utf-8".
  283. * @return string A meta tag containing the specified character set.
  284. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html#HtmlHelper::charset
  285. */
  286. public function charset($charset = null) {
  287. if (empty($charset)) {
  288. $charset = strtolower(Configure::read('App.encoding'));
  289. }
  290. return sprintf($this->_tags['charset'], (!empty($charset) ? $charset : 'utf-8'));
  291. }
  292. /**
  293. * Creates an HTML link.
  294. *
  295. * If $url starts with "http://" this is treated as an external link. Else,
  296. * it is treated as a path to controller/action and parsed with the
  297. * HtmlHelper::url() method.
  298. *
  299. * If the $url is empty, $title is used instead.
  300. *
  301. * ### Options
  302. *
  303. * - `escape` Set to false to disable escaping of title and attributes.
  304. * - `confirm` JavaScript confirmation message.
  305. *
  306. * @param string $title The content to be wrapped by <a> tags.
  307. * @param string|array $url Cake-relative URL or array of URL parameters, or external URL (starts with http://)
  308. * @param array $options Array of HTML attributes.
  309. * @param string $confirmMessage JavaScript confirmation message.
  310. * @return string An `<a />` element.
  311. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html#HtmlHelper::link
  312. */
  313. public function link($title, $url = null, $options = array(), $confirmMessage = false) {
  314. $escapeTitle = true;
  315. if ($url !== null) {
  316. $url = $this->url($url);
  317. } else {
  318. $url = $this->url($title);
  319. $title = htmlspecialchars_decode($url, ENT_QUOTES);
  320. $title = h(urldecode($title));
  321. $escapeTitle = false;
  322. }
  323. if (isset($options['escape'])) {
  324. $escapeTitle = $options['escape'];
  325. }
  326. if ($escapeTitle === true) {
  327. $title = h($title);
  328. } elseif (is_string($escapeTitle)) {
  329. $title = htmlentities($title, ENT_QUOTES, $escapeTitle);
  330. }
  331. if (!empty($options['confirm'])) {
  332. $confirmMessage = $options['confirm'];
  333. unset($options['confirm']);
  334. }
  335. if ($confirmMessage) {
  336. $confirmMessage = str_replace("'", "\'", $confirmMessage);
  337. $confirmMessage = str_replace('"', '\"', $confirmMessage);
  338. $options['onclick'] = "return confirm('{$confirmMessage}');";
  339. } elseif (isset($options['default']) && $options['default'] == false) {
  340. if (isset($options['onclick'])) {
  341. $options['onclick'] .= ' event.returnValue = false; return false;';
  342. } else {
  343. $options['onclick'] = 'event.returnValue = false; return false;';
  344. }
  345. unset($options['default']);
  346. }
  347. return sprintf($this->_tags['link'], $url, $this->_parseAttributes($options), $title);
  348. }
  349. /**
  350. * Creates a link element for CSS stylesheets.
  351. *
  352. * ### Usage
  353. *
  354. * Include one CSS file:
  355. *
  356. * `echo $this->Html->css('styles.css');`
  357. *
  358. * Include multiple CSS files:
  359. *
  360. * `echo $this->Html->css(array('one.css', 'two.css'));`
  361. *
  362. * Add the stylesheet to the `$scripts_for_layout` layout var:
  363. *
  364. * `$this->Html->css('styles.css', null, array('inline' => false));`
  365. *
  366. * Add the stylesheet to a custom block:
  367. *
  368. * `$this->Html->css('styles.css', null, array('block' => 'layoutCss'));`
  369. *
  370. * ### Options
  371. *
  372. * - `inline` If set to false, the generated tag will be appended to the 'css' block,
  373. * and included in the `$scripts_for_layout` layout variable. Defaults to true.
  374. * - `block` Set the name of the block link/style tag will be appended to. This overrides the `inline`
  375. * option.
  376. * - `plugin` False value will prevent parsing path as a plugin
  377. *
  378. * @param string|array $path The name of a CSS style sheet or an array containing names of
  379. * CSS stylesheets. If `$path` is prefixed with '/', the path will be relative to the webroot
  380. * of your application. Otherwise, the path will be relative to your CSS path, usually webroot/css.
  381. * @param string $rel Rel attribute. Defaults to "stylesheet". If equal to 'import' the stylesheet will be imported.
  382. * @param array $options Array of HTML attributes.
  383. * @return string CSS <link /> or <style /> tag, depending on the type of link.
  384. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html#HtmlHelper::css
  385. */
  386. public function css($path, $rel = null, $options = array()) {
  387. $options += array('block' => null, 'inline' => true);
  388. if (!$options['inline'] && empty($options['block'])) {
  389. $options['block'] = __FUNCTION__;
  390. }
  391. unset($options['inline']);
  392. if (is_array($path)) {
  393. $out = '';
  394. foreach ($path as $i) {
  395. $out .= "\n\t" . $this->css($i, $rel, $options);
  396. }
  397. if (empty($options['block'])) {
  398. return $out . "\n";
  399. }
  400. return;
  401. }
  402. if (strpos($path, '//') !== false) {
  403. $url = $path;
  404. } else {
  405. $url = $this->assetUrl($path, $options + array('pathPrefix' => CSS_URL, 'ext' => '.css'));
  406. if (Configure::read('Asset.filter.css')) {
  407. $pos = strpos($url, CSS_URL);
  408. if ($pos !== false) {
  409. $url = substr($url, 0, $pos) . 'ccss/' . substr($url, $pos + strlen(CSS_URL));
  410. }
  411. }
  412. }
  413. if ($rel == 'import') {
  414. $out = sprintf($this->_tags['style'], $this->_parseAttributes($options, array('inline', 'block'), '', ' '), '@import url(' . $url . ');');
  415. } else {
  416. if ($rel == null) {
  417. $rel = 'stylesheet';
  418. }
  419. $out = sprintf($this->_tags['css'], $rel, $url, $this->_parseAttributes($options, array('inline', 'block'), '', ' '));
  420. }
  421. if (empty($options['block'])) {
  422. return $out;
  423. } else {
  424. $this->_View->append($options['block'], $out);
  425. }
  426. }
  427. /**
  428. * Returns one or many `<script>` tags depending on the number of scripts given.
  429. *
  430. * If the filename is prefixed with "/", the path will be relative to the base path of your
  431. * application. Otherwise, the path will be relative to your JavaScript path, usually webroot/js.
  432. *
  433. *
  434. * ### Usage
  435. *
  436. * Include one script file:
  437. *
  438. * `echo $this->Html->script('styles.js');`
  439. *
  440. * Include multiple script files:
  441. *
  442. * `echo $this->Html->script(array('one.js', 'two.js'));`
  443. *
  444. * Add the script file to the `$scripts_for_layout` layout var:
  445. *
  446. * `$this->Html->script('styles.js', array('inline' => false));`
  447. *
  448. * Add the script file to a custom block:
  449. *
  450. * `$this->Html->script('styles.js', null, array('block' => 'bodyScript'));`
  451. *
  452. * ### Options
  453. *
  454. * - `inline` Whether script should be output inline or into `$scripts_for_layout`. When set to false,
  455. * the script tag will be appended to the 'script' view block as well as `$scripts_for_layout`.
  456. * - `block` The name of the block you want the script appended to. Leave undefined to output inline.
  457. * Using this option will override the inline option.
  458. * - `once` Whether or not the script should be checked for uniqueness. If true scripts will only be
  459. * included once, use false to allow the same script to be included more than once per request.
  460. * - `plugin` False value will prevent parsing path as a plugin
  461. *
  462. * @param string|array $url String or array of javascript files to include
  463. * @param array|boolean $options Array of options, and html attributes see above. If boolean sets $options['inline'] = value
  464. * @return mixed String of `<script />` tags or null if $inline is false or if $once is true and the file has been
  465. * included before.
  466. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html#HtmlHelper::script
  467. */
  468. public function script($url, $options = array()) {
  469. if (is_bool($options)) {
  470. list($inline, $options) = array($options, array());
  471. $options['inline'] = $inline;
  472. }
  473. $options = array_merge(array('block' => null, 'inline' => true, 'once' => true), $options);
  474. if (!$options['inline'] && empty($options['block'])) {
  475. $options['block'] = __FUNCTION__;
  476. }
  477. unset($options['inline']);
  478. if (is_array($url)) {
  479. $out = '';
  480. foreach ($url as $i) {
  481. $out .= "\n\t" . $this->script($i, $options);
  482. }
  483. if (empty($options['block'])) {
  484. return $out . "\n";
  485. }
  486. return null;
  487. }
  488. if ($options['once'] && isset($this->_includedScripts[$url])) {
  489. return null;
  490. }
  491. $this->_includedScripts[$url] = true;
  492. if (strpos($url, '//') === false) {
  493. $url = $this->assetUrl($url, $options + array('pathPrefix' => JS_URL, 'ext' => '.js'));
  494. if (Configure::read('Asset.filter.js')) {
  495. $url = str_replace(JS_URL, 'cjs/', $url);
  496. }
  497. }
  498. $attributes = $this->_parseAttributes($options, array('block', 'once'), ' ');
  499. $out = sprintf($this->_tags['javascriptlink'], $url, $attributes);
  500. if (empty($options['block'])) {
  501. return $out;
  502. } else {
  503. $this->_View->append($options['block'], $out);
  504. }
  505. }
  506. /**
  507. * Wrap $script in a script tag.
  508. *
  509. * ### Options
  510. *
  511. * - `safe` (boolean) Whether or not the $script should be wrapped in <![CDATA[ ]]>
  512. * - `inline` (boolean) Whether or not the $script should be added to
  513. * `$scripts_for_layout` / `script` block, or output inline. (Deprecated, use `block` instead)
  514. * - `block` Which block you want this script block appended to.
  515. * Defaults to `script`.
  516. *
  517. * @param string $script The script to wrap
  518. * @param array $options The options to use. Options not listed above will be
  519. * treated as HTML attributes.
  520. * @return mixed string or null depending on the value of `$options['block']`
  521. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html#HtmlHelper::scriptBlock
  522. */
  523. public function scriptBlock($script, $options = array()) {
  524. $options += array('safe' => true, 'inline' => true);
  525. if ($options['safe']) {
  526. $script = "\n" . '//<![CDATA[' . "\n" . $script . "\n" . '//]]>' . "\n";
  527. }
  528. if (!$options['inline'] && empty($options['block'])) {
  529. $options['block'] = 'script';
  530. }
  531. unset($options['inline'], $options['safe']);
  532. $attributes = $this->_parseAttributes($options, array('block'), ' ');
  533. $out = sprintf($this->_tags['javascriptblock'], $attributes, $script);
  534. if (empty($options['block'])) {
  535. return $out;
  536. } else {
  537. $this->_View->append($options['block'], $out);
  538. }
  539. }
  540. /**
  541. * Begin a script block that captures output until HtmlHelper::scriptEnd()
  542. * is called. This capturing block will capture all output between the methods
  543. * and create a scriptBlock from it.
  544. *
  545. * ### Options
  546. *
  547. * - `safe` Whether the code block should contain a CDATA
  548. * - `inline` Should the generated script tag be output inline or in `$scripts_for_layout`
  549. *
  550. * @param array $options Options for the code block.
  551. * @return void
  552. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html#HtmlHelper::scriptStart
  553. */
  554. public function scriptStart($options = array()) {
  555. $options += array('safe' => true, 'inline' => true);
  556. $this->_scriptBlockOptions = $options;
  557. ob_start();
  558. return null;
  559. }
  560. /**
  561. * End a Buffered section of Javascript capturing.
  562. * Generates a script tag inline or in `$scripts_for_layout` depending on the settings
  563. * used when the scriptBlock was started
  564. *
  565. * @return mixed depending on the settings of scriptStart() either a script tag or null
  566. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html#HtmlHelper::scriptEnd
  567. */
  568. public function scriptEnd() {
  569. $buffer = ob_get_clean();
  570. $options = $this->_scriptBlockOptions;
  571. $this->_scriptBlockOptions = array();
  572. return $this->scriptBlock($buffer, $options);
  573. }
  574. /**
  575. * Builds CSS style data from an array of CSS properties
  576. *
  577. * ### Usage:
  578. *
  579. * {{{
  580. * echo $html->style(array('margin' => '10px', 'padding' => '10px'), true);
  581. *
  582. * // creates
  583. * 'margin:10px;padding:10px;'
  584. * }}}
  585. *
  586. * @param array $data Style data array, keys will be used as property names, values as property values.
  587. * @param boolean $oneline Whether or not the style block should be displayed on one line.
  588. * @return string CSS styling data
  589. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html#HtmlHelper::style
  590. */
  591. public function style($data, $oneline = true) {
  592. if (!is_array($data)) {
  593. return $data;
  594. }
  595. $out = array();
  596. foreach ($data as $key => $value) {
  597. $out[] = $key . ':' . $value . ';';
  598. }
  599. if ($oneline) {
  600. return join(' ', $out);
  601. }
  602. return implode("\n", $out);
  603. }
  604. /**
  605. * Returns the breadcrumb trail as a sequence of &raquo;-separated links.
  606. *
  607. * If `$startText` is an array, the accepted keys are:
  608. *
  609. * - `text` Define the text/content for the link.
  610. * - `url` Define the target of the created link.
  611. *
  612. * All other keys will be passed to HtmlHelper::link() as the `$options` parameter.
  613. *
  614. * @param string $separator Text to separate crumbs.
  615. * @param string|array|boolean $startText This will be the first crumb, if false it defaults to first crumb in array. Can
  616. * also be an array, see above for details.
  617. * @return string Composed bread crumbs
  618. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html#creating-breadcrumb-trails-with-htmlhelper
  619. */
  620. public function getCrumbs($separator = '&raquo;', $startText = false) {
  621. $crumbs = $this->_prepareCrumbs($startText);
  622. if (!empty($crumbs)) {
  623. $out = array();
  624. foreach ($crumbs as $crumb) {
  625. if (!empty($crumb[1])) {
  626. $out[] = $this->link($crumb[0], $crumb[1], $crumb[2]);
  627. } else {
  628. $out[] = $crumb[0];
  629. }
  630. }
  631. return join($separator, $out);
  632. } else {
  633. return null;
  634. }
  635. }
  636. /**
  637. * Returns breadcrumbs as a (x)html list
  638. *
  639. * This method uses HtmlHelper::tag() to generate list and its elements. Works
  640. * similar to HtmlHelper::getCrumbs(), so it uses options which every
  641. * crumb was added with.
  642. *
  643. * @param array $options Array of html attributes to apply to the generated list elements.
  644. * @param string|array|boolean $startText This will be the first crumb, if false it defaults to first crumb in array. Can
  645. * also be an array, see `HtmlHelper::getCrumbs` for details.
  646. * @return string breadcrumbs html list
  647. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html#creating-breadcrumb-trails-with-htmlhelper
  648. */
  649. public function getCrumbList($options = array(), $startText = false) {
  650. $crumbs = $this->_prepareCrumbs($startText);
  651. if (!empty($crumbs)) {
  652. $result = '';
  653. $crumbCount = count($crumbs);
  654. $ulOptions = $options;
  655. foreach ($crumbs as $which => $crumb) {
  656. $options = array();
  657. if (empty($crumb[1])) {
  658. $elementContent = $crumb[0];
  659. } else {
  660. $elementContent = $this->link($crumb[0], $crumb[1], $crumb[2]);
  661. }
  662. if ($which == 0) {
  663. $options['class'] = 'first';
  664. } elseif ($which == $crumbCount - 1) {
  665. $options['class'] = 'last';
  666. }
  667. $result .= $this->tag('li', $elementContent, $options);
  668. }
  669. return $this->tag('ul', $result, $ulOptions);
  670. } else {
  671. return null;
  672. }
  673. }
  674. /**
  675. * Prepends startText to crumbs array if set
  676. *
  677. * @param $startText
  678. * @return array Crumb list including startText (if provided)
  679. */
  680. protected function _prepareCrumbs($startText) {
  681. $crumbs = $this->_crumbs;
  682. if ($startText) {
  683. if (!is_array($startText)) {
  684. $startText = array(
  685. 'url' => '/',
  686. 'text' => $startText
  687. );
  688. }
  689. $startText += array('url' => '/', 'text' => __('Home'));
  690. list($url, $text) = array($startText['url'], $startText['text']);
  691. unset($startText['url'], $startText['text']);
  692. array_unshift($crumbs, array($text, $url, $startText));
  693. }
  694. return $crumbs;
  695. }
  696. /**
  697. * Creates a formatted IMG element.
  698. *
  699. * This method will set an empty alt attribute if one is not supplied.
  700. *
  701. * ### Usage:
  702. *
  703. * Create a regular image:
  704. *
  705. * `echo $html->image('cake_icon.png', array('alt' => 'CakePHP'));`
  706. *
  707. * Create an image link:
  708. *
  709. * `echo $html->image('cake_icon.png', array('alt' => 'CakePHP', 'url' => 'http://cakephp.org'));`
  710. *
  711. * ### Options:
  712. *
  713. * - `url` If provided an image link will be generated and the link will point at
  714. * `$options['url']`.
  715. * - `fullBase` If true the src attribute will get a full address for the image file.
  716. * - `plugin` False value will prevent parsing path as a plugin
  717. *
  718. * @param string $path Path to the image file, relative to the app/webroot/img/ directory.
  719. * @param array $options Array of HTML attributes. See above for special options.
  720. * @return string completed img tag
  721. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html#HtmlHelper::image
  722. */
  723. public function image($path, $options = array()) {
  724. $path = $this->assetUrl($path, $options + array('pathPrefix' => IMAGES_URL));
  725. $options = array_diff_key($options, array('fullBase' => '', 'pathPrefix' => ''));
  726. if (!isset($options['alt'])) {
  727. $options['alt'] = '';
  728. }
  729. $url = false;
  730. if (!empty($options['url'])) {
  731. $url = $options['url'];
  732. unset($options['url']);
  733. }
  734. $image = sprintf($this->_tags['image'], $path, $this->_parseAttributes($options, null, '', ' '));
  735. if ($url) {
  736. return sprintf($this->_tags['link'], $this->url($url), null, $image);
  737. }
  738. return $image;
  739. }
  740. /**
  741. * Returns a row of formatted and named TABLE headers.
  742. *
  743. * @param array $names Array of tablenames. Each tablename also can be a key that points to an array with a set
  744. * of attributes to its specific tag
  745. * @param array $trOptions HTML options for TR elements.
  746. * @param array $thOptions HTML options for TH elements.
  747. * @return string Completed table headers
  748. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html#HtmlHelper::tableHeaders
  749. */
  750. public function tableHeaders($names, $trOptions = null, $thOptions = null) {
  751. $out = array();
  752. foreach ($names as $arg) {
  753. if (!is_array($arg)) {
  754. $out[] = sprintf($this->_tags['tableheader'], $this->_parseAttributes($thOptions), $arg);
  755. } else {
  756. $out[] = sprintf($this->_tags['tableheader'], $this->_parseAttributes(current($arg)), key($arg));
  757. }
  758. }
  759. return sprintf($this->_tags['tablerow'], $this->_parseAttributes($trOptions), join(' ', $out));
  760. }
  761. /**
  762. * Returns a formatted string of table rows (TR's with TD's in them).
  763. *
  764. * @param array $data Array of table data
  765. * @param array $oddTrOptions HTML options for odd TR elements if true useCount is used
  766. * @param array $evenTrOptions HTML options for even TR elements
  767. * @param boolean $useCount adds class "column-$i"
  768. * @param boolean $continueOddEven If false, will use a non-static $count variable,
  769. * so that the odd/even count is reset to zero just for that call.
  770. * @return string Formatted HTML
  771. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html#HtmlHelper::tableCells
  772. */
  773. public function tableCells($data, $oddTrOptions = null, $evenTrOptions = null, $useCount = false, $continueOddEven = true) {
  774. if (empty($data[0]) || !is_array($data[0])) {
  775. $data = array($data);
  776. }
  777. if ($oddTrOptions === true) {
  778. $useCount = true;
  779. $oddTrOptions = null;
  780. }
  781. if ($evenTrOptions === false) {
  782. $continueOddEven = false;
  783. $evenTrOptions = null;
  784. }
  785. if ($continueOddEven) {
  786. static $count = 0;
  787. } else {
  788. $count = 0;
  789. }
  790. foreach ($data as $line) {
  791. $count++;
  792. $cellsOut = array();
  793. $i = 0;
  794. foreach ($line as $cell) {
  795. $cellOptions = array();
  796. if (is_array($cell)) {
  797. $cellOptions = $cell[1];
  798. $cell = $cell[0];
  799. } elseif ($useCount) {
  800. $cellOptions['class'] = 'column-' . ++$i;
  801. }
  802. $cellsOut[] = sprintf($this->_tags['tablecell'], $this->_parseAttributes($cellOptions), $cell);
  803. }
  804. $options = $this->_parseAttributes($count % 2 ? $oddTrOptions : $evenTrOptions);
  805. $out[] = sprintf($this->_tags['tablerow'], $options, implode(' ', $cellsOut));
  806. }
  807. return implode("\n", $out);
  808. }
  809. /**
  810. * Returns a formatted block tag, i.e DIV, SPAN, P.
  811. *
  812. * ### Options
  813. *
  814. * - `escape` Whether or not the contents should be html_entity escaped.
  815. *
  816. * @param string $name Tag name.
  817. * @param string $text String content that will appear inside the div element.
  818. * If null, only a start tag will be printed
  819. * @param array $options Additional HTML attributes of the DIV tag, see above.
  820. * @return string The formatted tag element
  821. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html#HtmlHelper::tag
  822. */
  823. public function tag($name, $text = null, $options = array()) {
  824. if (is_array($options) && isset($options['escape']) && $options['escape']) {
  825. $text = h($text);
  826. unset($options['escape']);
  827. }
  828. if (!is_array($options)) {
  829. $options = array('class' => $options);
  830. }
  831. if ($text === null) {
  832. $tag = 'tagstart';
  833. } else {
  834. $tag = 'tag';
  835. }
  836. return sprintf($this->_tags[$tag], $name, $this->_parseAttributes($options, null, ' ', ''), $text, $name);
  837. }
  838. /**
  839. * Returns a formatted existent block of $tags
  840. *
  841. * @param string $tag Tag name
  842. * @return string Formatted block
  843. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html#HtmlHelper::useTag
  844. */
  845. public function useTag($tag) {
  846. if (!isset($this->_tags[$tag])) {
  847. return '';
  848. }
  849. $args = func_get_args();
  850. array_shift($args);
  851. foreach ($args as &$arg) {
  852. if (is_array($arg)) {
  853. $arg = $this->_parseAttributes($arg, null, ' ', '');
  854. }
  855. }
  856. return vsprintf($this->_tags[$tag], $args);
  857. }
  858. /**
  859. * Returns a formatted DIV tag for HTML FORMs.
  860. *
  861. * ### Options
  862. *
  863. * - `escape` Whether or not the contents should be html_entity escaped.
  864. *
  865. * @param string $class CSS class name of the div element.
  866. * @param string $text String content that will appear inside the div element.
  867. * If null, only a start tag will be printed
  868. * @param array $options Additional HTML attributes of the DIV tag
  869. * @return string The formatted DIV element
  870. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html#HtmlHelper::div
  871. */
  872. public function div($class = null, $text = null, $options = array()) {
  873. if (!empty($class)) {
  874. $options['class'] = $class;
  875. }
  876. return $this->tag('div', $text, $options);
  877. }
  878. /**
  879. * Returns a formatted P tag.
  880. *
  881. * ### Options
  882. *
  883. * - `escape` Whether or not the contents should be html_entity escaped.
  884. *
  885. * @param string $class CSS class name of the p element.
  886. * @param string $text String content that will appear inside the p element.
  887. * @param array $options Additional HTML attributes of the P tag
  888. * @return string The formatted P element
  889. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html#HtmlHelper::para
  890. */
  891. public function para($class, $text, $options = array()) {
  892. if (isset($options['escape'])) {
  893. $text = h($text);
  894. }
  895. if ($class != null && !empty($class)) {
  896. $options['class'] = $class;
  897. }
  898. if ($text === null) {
  899. $tag = 'parastart';
  900. } else {
  901. $tag = 'para';
  902. }
  903. return sprintf($this->_tags[$tag], $this->_parseAttributes($options, null, ' ', ''), $text);
  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, $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->useTag('tagselfclosing', 'source', $source);
  982. }
  983. unset($source);
  984. $options['text'] = $sourceTags . $options['text'];
  985. unset($options['fullBase']);
  986. } else {
  987. if (empty($path) && !empty($options['src'])) {
  988. $path = $options['src'];
  989. }
  990. $options['src'] = $this->assetUrl($path, $options);
  991. }
  992. if ($tag === null) {
  993. if (is_array($path)) {
  994. $mimeType = $path[0]['type'];
  995. } else {
  996. $mimeType = $this->response->getMimeType(pathinfo($path, PATHINFO_EXTENSION));
  997. }
  998. if (preg_match('#^video/#', $mimeType)) {
  999. $tag = 'video';
  1000. } else {
  1001. $tag = 'audio';
  1002. }
  1003. }
  1004. if (isset($options['poster'])) {
  1005. $options['poster'] = $this->assetUrl($options['poster'], array('pathPrefix' => IMAGES_URL) + $options);
  1006. }
  1007. $text = $options['text'];
  1008. $options = array_diff_key($options, array(
  1009. 'tag' => '',
  1010. 'fullBase' => '',
  1011. 'pathPrefix' => '',
  1012. 'text' => ''
  1013. ));
  1014. return $this->tag($tag, $text, $options);
  1015. }
  1016. /**
  1017. * Build a nested list (UL/OL) out of an associative array.
  1018. *
  1019. * @param array $list Set of elements to list
  1020. * @param array $options Additional HTML attributes of the list (ol/ul) tag or if ul/ol use that as tag
  1021. * @param array $itemOptions Additional HTML attributes of the list item (LI) tag
  1022. * @param string $tag Type of list tag to use (ol/ul)
  1023. * @return string The nested list
  1024. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html#HtmlHelper::nestedList
  1025. */
  1026. public function nestedList($list, $options = array(), $itemOptions = array(), $tag = 'ul') {
  1027. if (is_string($options)) {
  1028. $tag = $options;
  1029. $options = array();
  1030. }
  1031. $items = $this->_nestedListItem($list, $options, $itemOptions, $tag);
  1032. return sprintf($this->_tags[$tag], $this->_parseAttributes($options, null, ' ', ''), $items);
  1033. }
  1034. /**
  1035. * Internal function to build a nested list (UL/OL) out of an associative array.
  1036. *
  1037. * @param array $items Set of elements to list
  1038. * @param array $options Additional HTML attributes of the list (ol/ul) tag
  1039. * @param array $itemOptions Additional HTML attributes of the list item (LI) tag
  1040. * @param string $tag Type of list tag to use (ol/ul)
  1041. * @return string The nested list element
  1042. * @see HtmlHelper::nestedList()
  1043. */
  1044. protected function _nestedListItem($items, $options, $itemOptions, $tag) {
  1045. $out = '';
  1046. $index = 1;
  1047. foreach ($items as $key => $item) {
  1048. if (is_array($item)) {
  1049. $item = $key . $this->nestedList($item, $options, $itemOptions, $tag);
  1050. }
  1051. if (isset($itemOptions['even']) && $index % 2 == 0) {
  1052. $itemOptions['class'] = $itemOptions['even'];
  1053. } elseif (isset($itemOptions['odd']) && $index % 2 != 0) {
  1054. $itemOptions['class'] = $itemOptions['odd'];
  1055. }
  1056. $out .= sprintf($this->_tags['li'], $this->_parseAttributes($itemOptions, array('even', 'odd'), ' ', ''), $item);
  1057. $index++;
  1058. }
  1059. return $out;
  1060. }
  1061. /**
  1062. * Load Html tag configuration.
  1063. *
  1064. * Loads a file from APP/Config that contains tag data. By default the file is expected
  1065. * to be compatible with PhpReader:
  1066. *
  1067. * `$this->Html->loadConfig('tags.php');`
  1068. *
  1069. * tags.php could look like:
  1070. *
  1071. * {{{
  1072. * $tags = array(
  1073. * 'meta' => '<meta %s>'
  1074. * );
  1075. * }}}
  1076. *
  1077. * If you wish to store tag definitions in another format you can give an array
  1078. * containing the file name, and reader class name:
  1079. *
  1080. * `$this->Html->loadConfig(array('tags.ini', 'ini'));`
  1081. *
  1082. * Its expected that the `tags` index will exist from any configuration file that is read.
  1083. * You can also specify the path to read the configuration file from, if APP/Config is not
  1084. * where the file is.
  1085. *
  1086. * `$this->Html->loadConfig('tags.php', APP . 'Lib' . DS);`
  1087. *
  1088. * Configuration files can define the following sections:
  1089. *
  1090. * - `tags` The tags to replace.
  1091. * - `minimizedAttributes` The attributes that are represented like `disabled="disabled"`
  1092. * - `docTypes` Additional doctypes to use.
  1093. * - `attributeFormat` Format for long attributes e.g. `'%s="%s"'`
  1094. * - `minimizedAttributeFormat` Format for minimized attributes e.g. `'%s="%s"'`
  1095. *
  1096. * @param string|array $configFile String with the config file (load using PhpReader) or an array with file and reader name
  1097. * @param string $path Path with config file
  1098. * @return mixed False to error or loaded configs
  1099. * @throws ConfigureException
  1100. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html#changing-the-tags-output-by-htmlhelper
  1101. */
  1102. public function loadConfig($configFile, $path = null) {
  1103. if (!$path) {
  1104. $path = APP . 'Config' . DS;
  1105. }
  1106. $file = null;
  1107. $reader = 'php';
  1108. if (!is_array($configFile)) {
  1109. $file = $configFile;
  1110. } elseif (isset($configFile[0])) {
  1111. $file = $configFile[0];
  1112. if (isset($configFile[1])) {
  1113. $reader = $configFile[1];
  1114. }
  1115. } else {
  1116. throw new ConfigureException(__d('cake_dev', 'Cannot load the configuration file. Wrong "configFile" configuration.'));
  1117. }
  1118. $readerClass = Inflector::camelize($reader) . 'Reader';
  1119. App::uses($readerClass, 'Configure');
  1120. if (!class_exists($readerClass)) {
  1121. throw new ConfigureException(__d('cake_dev', 'Cannot load the configuration file. Unknown reader.'));
  1122. }
  1123. $readerObj = new $readerClass($path);
  1124. $configs = $readerObj->read($file);
  1125. if (isset($configs['tags']) && is_array($configs['tags'])) {
  1126. $this->_tags = array_merge($this->_tags, $configs['tags']);
  1127. }
  1128. if (isset($configs['minimizedAttributes']) && is_array($configs['minimizedAttributes'])) {
  1129. $this->_minimizedAttributes = array_merge($this->_minimizedAttributes, $configs['minimizedAttributes']);
  1130. }
  1131. if (isset($configs['docTypes']) && is_array($configs['docTypes'])) {
  1132. $this->_docTypes = array_merge($this->_docTypes, $configs['docTypes']);
  1133. }
  1134. if (isset($configs['attributeFormat'])) {
  1135. $this->_attributeFormat = $configs['attributeFormat'];
  1136. }
  1137. if (isset($configs['minimizedAttributeFormat'])) {
  1138. $this->_minimizedAttributeFormat = $configs['minimizedAttributeFormat'];
  1139. }
  1140. return $configs;
  1141. }
  1142. }