PageRenderTime 58ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

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

https://bitbucket.org/npitts/easyuat2.0
PHP | 1208 lines | 1030 code | 22 blank | 156 comment | 30 complexity | e73e4bd373cd9ac24f604a4ad416a2ad 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 mixed $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 mixed $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 mixed $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 = h(urldecode($url));
  320. $escapeTitle = false;
  321. }
  322. if (isset($options['escape'])) {
  323. $escapeTitle = $options['escape'];
  324. }
  325. if ($escapeTitle === true) {
  326. $title = h($title);
  327. } elseif (is_string($escapeTitle)) {
  328. $title = htmlentities($title, ENT_QUOTES, $escapeTitle);
  329. }
  330. if (!empty($options['confirm'])) {
  331. $confirmMessage = $options['confirm'];
  332. unset($options['confirm']);
  333. }
  334. if ($confirmMessage) {
  335. $confirmMessage = str_replace("'", "\'", $confirmMessage);
  336. $confirmMessage = str_replace('"', '\"', $confirmMessage);
  337. $options['onclick'] = "return confirm('{$confirmMessage}');";
  338. } elseif (isset($options['default']) && $options['default'] == false) {
  339. if (isset($options['onclick'])) {
  340. $options['onclick'] .= ' event.returnValue = false; return false;';
  341. } else {
  342. $options['onclick'] = 'event.returnValue = false; return false;';
  343. }
  344. unset($options['default']);
  345. }
  346. return sprintf($this->_tags['link'], $url, $this->_parseAttributes($options), $title);
  347. }
  348. /**
  349. * Creates a link element for CSS stylesheets.
  350. *
  351. * ### Usage
  352. *
  353. * Include one CSS file:
  354. *
  355. * `echo $this->Html->css('styles.css');`
  356. *
  357. * Include multiple CSS files:
  358. *
  359. * `echo $this->Html->css(array('one.css', 'two.css'));`
  360. *
  361. * Add the stylesheet to the `$scripts_for_layout` layout var:
  362. *
  363. * `$this->Html->css('styles.css', null, array('inline' => false));`
  364. *
  365. * Add the stylesheet to a custom block:
  366. *
  367. * `$this->Html->css('styles.css', null, array('block' => 'layoutCss'));`
  368. *
  369. * ### Options
  370. *
  371. * - `inline` If set to false, the generated tag will be appended to the 'css' block,
  372. * and included in the `$scripts_for_layout` layout variable. Defaults to true.
  373. * - `block` Set the name of the block link/style tag will be appended to. This overrides the `inline`
  374. * option.
  375. * - `plugin` False value will prevent parsing path as a plugin
  376. *
  377. * @param mixed $path The name of a CSS style sheet or an array containing names of
  378. * CSS stylesheets. If `$path` is prefixed with '/', the path will be relative to the webroot
  379. * of your application. Otherwise, the path will be relative to your CSS path, usually webroot/css.
  380. * @param string $rel Rel attribute. Defaults to "stylesheet". If equal to 'import' the stylesheet will be imported.
  381. * @param array $options Array of HTML attributes.
  382. * @return string CSS <link /> or <style /> tag, depending on the type of link.
  383. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html#HtmlHelper::css
  384. */
  385. public function css($path, $rel = null, $options = array()) {
  386. $options += array('block' => null, 'inline' => true);
  387. if (!$options['inline'] && empty($options['block'])) {
  388. $options['block'] = __FUNCTION__;
  389. }
  390. unset($options['inline']);
  391. if (is_array($path)) {
  392. $out = '';
  393. foreach ($path as $i) {
  394. $out .= "\n\t" . $this->css($i, $rel, $options);
  395. }
  396. if (empty($options['block'])) {
  397. return $out . "\n";
  398. }
  399. return;
  400. }
  401. if (strpos($path, '//') !== false) {
  402. $url = $path;
  403. } else {
  404. $url = $this->assetUrl($path, $options + array('pathPrefix' => CSS_URL, 'ext' => '.css'));
  405. if (Configure::read('Asset.filter.css')) {
  406. $pos = strpos($url, CSS_URL);
  407. if ($pos !== false) {
  408. $url = substr($url, 0, $pos) . 'ccss/' . substr($url, $pos + strlen(CSS_URL));
  409. }
  410. }
  411. }
  412. if ($rel == 'import') {
  413. $out = sprintf($this->_tags['style'], $this->_parseAttributes($options, array('inline', 'block'), '', ' '), '@import url(' . $url . ');');
  414. } else {
  415. if ($rel == null) {
  416. $rel = 'stylesheet';
  417. }
  418. $out = sprintf($this->_tags['css'], $rel, $url, $this->_parseAttributes($options, array('inline', 'block'), '', ' '));
  419. }
  420. if (empty($options['block'])) {
  421. return $out;
  422. } else {
  423. $this->_View->append($options['block'], $out);
  424. }
  425. }
  426. /**
  427. * Returns one or many `<script>` tags depending on the number of scripts given.
  428. *
  429. * If the filename is prefixed with "/", the path will be relative to the base path of your
  430. * application. Otherwise, the path will be relative to your JavaScript path, usually webroot/js.
  431. *
  432. *
  433. * ### Usage
  434. *
  435. * Include one script file:
  436. *
  437. * `echo $this->Html->script('styles.js');`
  438. *
  439. * Include multiple script files:
  440. *
  441. * `echo $this->Html->script(array('one.js', 'two.js'));`
  442. *
  443. * Add the script file to the `$scripts_for_layout` layout var:
  444. *
  445. * `$this->Html->script('styles.js', array('inline' => false));`
  446. *
  447. * Add the script file to a custom block:
  448. *
  449. * `$this->Html->script('styles.js', null, array('block' => 'bodyScript'));`
  450. *
  451. * ### Options
  452. *
  453. * - `inline` Whether script should be output inline or into `$scripts_for_layout`. When set to false,
  454. * the script tag will be appended to the 'script' view block as well as `$scripts_for_layout`.
  455. * - `block` The name of the block you want the script appended to. Leave undefined to output inline.
  456. * Using this option will override the inline option.
  457. * - `once` Whether or not the script should be checked for uniqueness. If true scripts will only be
  458. * included once, use false to allow the same script to be included more than once per request.
  459. * - `plugin` False value will prevent parsing path as a plugin
  460. *
  461. * @param mixed $url String or array of javascript files to include
  462. * @param mixed $options Array of options, and html attributes see above. If boolean sets $options['inline'] = value
  463. * @return mixed String of `<script />` tags or null if $inline is false or if $once is true and the file has been
  464. * included before.
  465. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html#HtmlHelper::script
  466. */
  467. public function script($url, $options = array()) {
  468. if (is_bool($options)) {
  469. list($inline, $options) = array($options, array());
  470. $options['inline'] = $inline;
  471. }
  472. $options = array_merge(array('block' => null, 'inline' => true, 'once' => true), $options);
  473. if (!$options['inline'] && empty($options['block'])) {
  474. $options['block'] = __FUNCTION__;
  475. }
  476. unset($options['inline']);
  477. if (is_array($url)) {
  478. $out = '';
  479. foreach ($url as $i) {
  480. $out .= "\n\t" . $this->script($i, $options);
  481. }
  482. if (empty($options['block'])) {
  483. return $out . "\n";
  484. }
  485. return null;
  486. }
  487. if ($options['once'] && isset($this->_includedScripts[$url])) {
  488. return null;
  489. }
  490. $this->_includedScripts[$url] = true;
  491. if (strpos($url, '//') === false) {
  492. $url = $this->assetUrl($url, $options + array('pathPrefix' => JS_URL, 'ext' => '.js'));
  493. if (Configure::read('Asset.filter.js')) {
  494. $url = str_replace(JS_URL, 'cjs/', $url);
  495. }
  496. }
  497. $attributes = $this->_parseAttributes($options, array('block', 'once'), ' ');
  498. $out = sprintf($this->_tags['javascriptlink'], $url, $attributes);
  499. if (empty($options['block'])) {
  500. return $out;
  501. } else {
  502. $this->_View->append($options['block'], $out);
  503. }
  504. }
  505. /**
  506. * Wrap $script in a script tag.
  507. *
  508. * ### Options
  509. *
  510. * - `safe` (boolean) Whether or not the $script should be wrapped in <![CDATA[ ]]>
  511. * - `inline` (boolean) Whether or not the $script should be added to
  512. * `$scripts_for_layout` / `script` block, or output inline. (Deprecated, use `block` instead)
  513. * - `block` Which block you want this script block appended to.
  514. * Defaults to `script`.
  515. *
  516. * @param string $script The script to wrap
  517. * @param array $options The options to use. Options not listed above will be
  518. * treated as HTML attributes.
  519. * @return mixed string or null depending on the value of `$options['block']`
  520. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html#HtmlHelper::scriptBlock
  521. */
  522. public function scriptBlock($script, $options = array()) {
  523. $options += array('safe' => true, 'inline' => true);
  524. if ($options['safe']) {
  525. $script = "\n" . '//<![CDATA[' . "\n" . $script . "\n" . '//]]>' . "\n";
  526. }
  527. if (!$options['inline'] && empty($options['block'])) {
  528. $options['block'] = 'script';
  529. }
  530. unset($options['inline'], $options['safe']);
  531. $attributes = $this->_parseAttributes($options, array('block'), ' ');
  532. $out = sprintf($this->_tags['javascriptblock'], $attributes, $script);
  533. if (empty($options['block'])) {
  534. return $out;
  535. } else {
  536. $this->_View->append($options['block'], $out);
  537. }
  538. }
  539. /**
  540. * Begin a script block that captures output until HtmlHelper::scriptEnd()
  541. * is called. This capturing block will capture all output between the methods
  542. * and create a scriptBlock from it.
  543. *
  544. * ### Options
  545. *
  546. * - `safe` Whether the code block should contain a CDATA
  547. * - `inline` Should the generated script tag be output inline or in `$scripts_for_layout`
  548. *
  549. * @param array $options Options for the code block.
  550. * @return void
  551. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html#HtmlHelper::scriptStart
  552. */
  553. public function scriptStart($options = array()) {
  554. $options += array('safe' => true, 'inline' => true);
  555. $this->_scriptBlockOptions = $options;
  556. ob_start();
  557. return null;
  558. }
  559. /**
  560. * End a Buffered section of Javascript capturing.
  561. * Generates a script tag inline or in `$scripts_for_layout` depending on the settings
  562. * used when the scriptBlock was started
  563. *
  564. * @return mixed depending on the settings of scriptStart() either a script tag or null
  565. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html#HtmlHelper::scriptEnd
  566. */
  567. public function scriptEnd() {
  568. $buffer = ob_get_clean();
  569. $options = $this->_scriptBlockOptions;
  570. $this->_scriptBlockOptions = array();
  571. return $this->scriptBlock($buffer, $options);
  572. }
  573. /**
  574. * Builds CSS style data from an array of CSS properties
  575. *
  576. * ### Usage:
  577. *
  578. * {{{
  579. * echo $html->style(array('margin' => '10px', 'padding' => '10px'), true);
  580. *
  581. * // creates
  582. * 'margin:10px;padding:10px;'
  583. * }}}
  584. *
  585. * @param array $data Style data array, keys will be used as property names, values as property values.
  586. * @param boolean $oneline Whether or not the style block should be displayed on one line.
  587. * @return string CSS styling data
  588. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html#HtmlHelper::style
  589. */
  590. public function style($data, $oneline = true) {
  591. if (!is_array($data)) {
  592. return $data;
  593. }
  594. $out = array();
  595. foreach ($data as $key => $value) {
  596. $out[] = $key . ':' . $value . ';';
  597. }
  598. if ($oneline) {
  599. return join(' ', $out);
  600. }
  601. return implode("\n", $out);
  602. }
  603. /**
  604. * Returns the breadcrumb trail as a sequence of &raquo;-separated links.
  605. *
  606. * If `$startText` is an array, the accepted keys are:
  607. *
  608. * - `text` Define the text/content for the link.
  609. * - `url` Define the target of the created link.
  610. *
  611. * All other keys will be passed to HtmlHelper::link() as the `$options` parameter.
  612. *
  613. * @param string $separator Text to separate crumbs.
  614. * @param mixed $startText This will be the first crumb, if false it defaults to first crumb in array. Can
  615. * also be an array, see above for details.
  616. * @return string Composed bread crumbs
  617. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html#creating-breadcrumb-trails-with-htmlhelper
  618. */
  619. public function getCrumbs($separator = '&raquo;', $startText = false) {
  620. $crumbs = $this->_prepareCrumbs($startText);
  621. if (!empty($crumbs)) {
  622. $out = array();
  623. foreach ($crumbs as $crumb) {
  624. if (!empty($crumb[1])) {
  625. $out[] = $this->link($crumb[0], $crumb[1], $crumb[2]);
  626. } else {
  627. $out[] = $crumb[0];
  628. }
  629. }
  630. return join($separator, $out);
  631. } else {
  632. return null;
  633. }
  634. }
  635. /**
  636. * Returns breadcrumbs as a (x)html list
  637. *
  638. * This method uses HtmlHelper::tag() to generate list and its elements. Works
  639. * similar to HtmlHelper::getCrumbs(), so it uses options which every
  640. * crumb was added with.
  641. *
  642. * @param array $options Array of html attributes to apply to the generated list elements.
  643. * @param mixed $startText This will be the first crumb, if false it defaults to first crumb in array. Can
  644. * also be an array, see `HtmlHelper::getCrumbs` for details.
  645. * @return string breadcrumbs html list
  646. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html#creating-breadcrumb-trails-with-htmlhelper
  647. */
  648. public function getCrumbList($options = array(), $startText = false) {
  649. $crumbs = $this->_prepareCrumbs($startText);
  650. if (!empty($crumbs)) {
  651. $result = '';
  652. $crumbCount = count($crumbs);
  653. $ulOptions = $options;
  654. foreach ($crumbs as $which => $crumb) {
  655. $options = array();
  656. if (empty($crumb[1])) {
  657. $elementContent = $crumb[0];
  658. } else {
  659. $elementContent = $this->link($crumb[0], $crumb[1], $crumb[2]);
  660. }
  661. if ($which == 0) {
  662. $options['class'] = 'first';
  663. } elseif ($which == $crumbCount - 1) {
  664. $options['class'] = 'last';
  665. }
  666. $result .= $this->tag('li', $elementContent, $options);
  667. }
  668. return $this->tag('ul', $result, $ulOptions);
  669. } else {
  670. return null;
  671. }
  672. }
  673. /**
  674. * Prepends startText to crumbs array if set
  675. *
  676. * @param $startText
  677. * @return array Crumb list including startText (if provided)
  678. */
  679. protected function _prepareCrumbs($startText) {
  680. $crumbs = $this->_crumbs;
  681. if ($startText) {
  682. if (!is_array($startText)) {
  683. $startText = array(
  684. 'url' => '/',
  685. 'text' => $startText
  686. );
  687. }
  688. $startText += array('url' => '/', 'text' => __('Home'));
  689. list($url, $text) = array($startText['url'], $startText['text']);
  690. unset($startText['url'], $startText['text']);
  691. array_unshift($crumbs, array($text, $url, $startText));
  692. }
  693. return $crumbs;
  694. }
  695. /**
  696. * Creates a formatted IMG element.
  697. *
  698. * This method will set an empty alt attribute if one is not supplied.
  699. *
  700. * ### Usage:
  701. *
  702. * Create a regular image:
  703. *
  704. * `echo $html->image('cake_icon.png', array('alt' => 'CakePHP'));`
  705. *
  706. * Create an image link:
  707. *
  708. * `echo $html->image('cake_icon.png', array('alt' => 'CakePHP', 'url' => 'http://cakephp.org'));`
  709. *
  710. * ### Options:
  711. *
  712. * - `url` If provided an image link will be generated and the link will point at
  713. * `$options['url']`.
  714. * - `fullBase` If true the src attribute will get a full address for the image file.
  715. * - `plugin` False value will prevent parsing path as a plugin
  716. *
  717. * @param string $path Path to the image file, relative to the app/webroot/img/ directory.
  718. * @param array $options Array of HTML attributes. See above for special options.
  719. * @return string completed img tag
  720. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html#HtmlHelper::image
  721. */
  722. public function image($path, $options = array()) {
  723. $path = $this->assetUrl($path, $options + array('pathPrefix' => IMAGES_URL));
  724. $options = array_diff_key($options, array('fullBase' => '', 'pathPrefix' => ''));
  725. if (!isset($options['alt'])) {
  726. $options['alt'] = '';
  727. }
  728. $url = false;
  729. if (!empty($options['url'])) {
  730. $url = $options['url'];
  731. unset($options['url']);
  732. }
  733. $image = sprintf($this->_tags['image'], $path, $this->_parseAttributes($options, null, '', ' '));
  734. if ($url) {
  735. return sprintf($this->_tags['link'], $this->url($url), null, $image);
  736. }
  737. return $image;
  738. }
  739. /**
  740. * Returns a row of formatted and named TABLE headers.
  741. *
  742. * @param array $names Array of tablenames.
  743. * @param array $trOptions HTML options for TR elements.
  744. * @param array $thOptions HTML options for TH elements.
  745. * @return string Completed table headers
  746. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html#HtmlHelper::tableHeaders
  747. */
  748. public function tableHeaders($names, $trOptions = null, $thOptions = null) {
  749. $out = array();
  750. foreach ($names as $arg) {
  751. $out[] = sprintf($this->_tags['tableheader'], $this->_parseAttributes($thOptions), $arg);
  752. }
  753. return sprintf($this->_tags['tablerow'], $this->_parseAttributes($trOptions), join(' ', $out));
  754. }
  755. /**
  756. * Returns a formatted string of table rows (TR's with TD's in them).
  757. *
  758. * @param array $data Array of table data
  759. * @param array $oddTrOptions HTML options for odd TR elements if true useCount is used
  760. * @param array $evenTrOptions HTML options for even TR elements
  761. * @param boolean $useCount adds class "column-$i"
  762. * @param boolean $continueOddEven If false, will use a non-static $count variable,
  763. * so that the odd/even count is reset to zero just for that call.
  764. * @return string Formatted HTML
  765. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html#HtmlHelper::tableCells
  766. */
  767. public function tableCells($data, $oddTrOptions = null, $evenTrOptions = null, $useCount = false, $continueOddEven = true) {
  768. if (empty($data[0]) || !is_array($data[0])) {
  769. $data = array($data);
  770. }
  771. if ($oddTrOptions === true) {
  772. $useCount = true;
  773. $oddTrOptions = null;
  774. }
  775. if ($evenTrOptions === false) {
  776. $continueOddEven = false;
  777. $evenTrOptions = null;
  778. }
  779. if ($continueOddEven) {
  780. static $count = 0;
  781. } else {
  782. $count = 0;
  783. }
  784. foreach ($data as $line) {
  785. $count++;
  786. $cellsOut = array();
  787. $i = 0;
  788. foreach ($line as $cell) {
  789. $cellOptions = array();
  790. if (is_array($cell)) {
  791. $cellOptions = $cell[1];
  792. $cell = $cell[0];
  793. } elseif ($useCount) {
  794. $cellOptions['class'] = 'column-' . ++$i;
  795. }
  796. $cellsOut[] = sprintf($this->_tags['tablecell'], $this->_parseAttributes($cellOptions), $cell);
  797. }
  798. $options = $this->_parseAttributes($count % 2 ? $oddTrOptions : $evenTrOptions);
  799. $out[] = sprintf($this->_tags['tablerow'], $options, implode(' ', $cellsOut));
  800. }
  801. return implode("\n", $out);
  802. }
  803. /**
  804. * Returns a formatted block tag, i.e DIV, SPAN, P.
  805. *
  806. * ### Options
  807. *
  808. * - `escape` Whether or not the contents should be html_entity escaped.
  809. *
  810. * @param string $name Tag name.
  811. * @param string $text String content that will appear inside the div element.
  812. * If null, only a start tag will be printed
  813. * @param array $options Additional HTML attributes of the DIV tag, see above.
  814. * @return string The formatted tag element
  815. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html#HtmlHelper::tag
  816. */
  817. public function tag($name, $text = null, $options = array()) {
  818. if (is_array($options) && isset($options['escape']) && $options['escape']) {
  819. $text = h($text);
  820. unset($options['escape']);
  821. }
  822. if (!is_array($options)) {
  823. $options = array('class' => $options);
  824. }
  825. if ($text === null) {
  826. $tag = 'tagstart';
  827. } else {
  828. $tag = 'tag';
  829. }
  830. return sprintf($this->_tags[$tag], $name, $this->_parseAttributes($options, null, ' ', ''), $text, $name);
  831. }
  832. /**
  833. * Returns a formatted existent block of $tags
  834. *
  835. * @param string $tag Tag name
  836. * @return string Formatted block
  837. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html#HtmlHelper::useTag
  838. */
  839. public function useTag($tag) {
  840. if (!isset($this->_tags[$tag])) {
  841. return '';
  842. }
  843. $args = func_get_args();
  844. array_shift($args);
  845. foreach ($args as &$arg) {
  846. if (is_array($arg)) {
  847. $arg = $this->_parseAttributes($arg, null, ' ', '');
  848. }
  849. }
  850. return vsprintf($this->_tags[$tag], $args);
  851. }
  852. /**
  853. * Returns a formatted DIV tag for HTML FORMs.
  854. *
  855. * ### Options
  856. *
  857. * - `escape` Whether or not the contents should be html_entity escaped.
  858. *
  859. * @param string $class CSS class name of the div element.
  860. * @param string $text String content that will appear inside the div element.
  861. * If null, only a start tag will be printed
  862. * @param array $options Additional HTML attributes of the DIV tag
  863. * @return string The formatted DIV element
  864. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html#HtmlHelper::div
  865. */
  866. public function div($class = null, $text = null, $options = array()) {
  867. if (!empty($class)) {
  868. $options['class'] = $class;
  869. }
  870. return $this->tag('div', $text, $options);
  871. }
  872. /**
  873. * Returns a formatted P tag.
  874. *
  875. * ### Options
  876. *
  877. * - `escape` Whether or not the contents should be html_entity escaped.
  878. *
  879. * @param string $class CSS class name of the p element.
  880. * @param string $text String content that will appear inside the p element.
  881. * @param array $options Additional HTML attributes of the P tag
  882. * @return string The formatted P element
  883. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html#HtmlHelper::para
  884. */
  885. public function para($class, $text, $options = array()) {
  886. if (isset($options['escape'])) {
  887. $text = h($text);
  888. }
  889. if ($class != null && !empty($class)) {
  890. $options['class'] = $class;
  891. }
  892. if ($text === null) {
  893. $tag = 'parastart';
  894. } else {
  895. $tag = 'para';
  896. }
  897. return sprintf($this->_tags[$tag], $this->_parseAttributes($options, null, ' ', ''), $text);
  898. }
  899. /**
  900. * Returns an audio/video element
  901. *
  902. * ### Usage
  903. *
  904. * Using an audio file:
  905. *
  906. * `echo $this->Html->media('audio.mp3', array('fullBase' => true));`
  907. *
  908. * Outputs:
  909. *
  910. * `<video src="http://www.somehost.com/files/audio.mp3">Fallback text</video>`
  911. *
  912. * Using a video file:
  913. *
  914. * `echo $this->Html->media('video.mp4', array('text' => 'Fallback text'));`
  915. *
  916. * Outputs:
  917. *
  918. * `<video src="/files/video.mp4">Fallback text</video>`
  919. *
  920. * Using multiple video files:
  921. *
  922. * {{{
  923. * echo $this->Html->media(
  924. * array('video.mp4', array('src' => 'video.ogv', 'type' => "video/ogg; codecs='theora, vorbis'")),
  925. * array('tag' => 'video', 'autoplay')
  926. * );
  927. * }}}
  928. *
  929. * Outputs:
  930. *
  931. * {{{
  932. * <video autoplay="autoplay">
  933. * <source src="/files/video.mp4" type="video/mp4"/>
  934. * <source src="/files/video.ogv" type="video/ogv; codecs='theora, vorbis'"/>
  935. * </video>
  936. * }}}
  937. *
  938. * ### Options
  939. *
  940. * - `tag` Type of media element to generate, either "audio" or "video".
  941. * If tag is not provided it's guessed based on file's mime type.
  942. * - `text` Text to include inside the audio/video tag
  943. * - `pathPrefix` Path prefix to use for relative urls, defaults to 'files/'
  944. * - `fullBase` If provided the src attribute will get a full address including domain name
  945. *
  946. * @param string|array $path Path to the video file, relative to the webroot/{$options['pathPrefix']} directory.
  947. * Or an array where each item itself can be a path string or an associate array containing keys `src` and `type`
  948. * @param array $options Array of HTML attributes, and special options above.
  949. * @return string Generated media element
  950. */
  951. public function media($path, $options = array()) {
  952. $options += array(
  953. 'tag' => null,
  954. 'pathPrefix' => 'files/',
  955. 'text' => ''
  956. );
  957. if (!empty($options['tag'])) {
  958. $tag = $options['tag'];
  959. } else {
  960. $tag = null;
  961. }
  962. if (is_array($path)) {
  963. $sourceTags = '';
  964. foreach ($path as &$source) {
  965. if (is_string($source)) {
  966. $source = array(
  967. 'src' => $source,
  968. );
  969. }
  970. if (!isset($source['type'])) {
  971. $ext = pathinfo($source['src'], PATHINFO_EXTENSION);
  972. $source['type'] = $this->response->getMimeType($ext);
  973. }
  974. $source['src'] = $this->assetUrl($source['src'], $options);
  975. $sourceTags .= $this->useTag('tagselfclosing', 'source', $source);
  976. }
  977. unset($source);
  978. $options['text'] = $sourceTags . $options['text'];
  979. unset($options['fullBase']);
  980. } else {
  981. if (empty($path) && !empty($options['src'])) {
  982. $path = $options['src'];
  983. }
  984. $options['src'] = $this->assetUrl($path, $options);
  985. }
  986. if ($tag === null) {
  987. if (is_array($path)) {
  988. $mimeType = $path[0]['type'];
  989. } else {
  990. $mimeType = $this->response->getMimeType(pathinfo($path, PATHINFO_EXTENSION));
  991. }
  992. if (preg_match('#^video/#', $mimeType)) {
  993. $tag = 'video';
  994. } else {
  995. $tag = 'audio';
  996. }
  997. }
  998. if (isset($options['poster'])) {
  999. $options['poster'] = $this->assetUrl($options['poster'], array('pathPrefix' => IMAGES_URL) + $options);
  1000. }
  1001. $text = $options['text'];
  1002. $options = array_diff_key($options, array(
  1003. 'tag' => '',
  1004. 'fullBase' => '',
  1005. 'pathPrefix' => '',
  1006. 'text' => ''
  1007. ));
  1008. return $this->tag($tag, $text, $options);
  1009. }
  1010. /**
  1011. * Build a nested list (UL/OL) out of an associative array.
  1012. *
  1013. * @param array $list Set of elements to list
  1014. * @param array $options Additional HTML attributes of the list (ol/ul) tag or if ul/ol use that as tag
  1015. * @param array $itemOptions Additional HTML attributes of the list item (LI) tag
  1016. * @param string $tag Type of list tag to use (ol/ul)
  1017. * @return string The nested list
  1018. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html#HtmlHelper::nestedList
  1019. */
  1020. public function nestedList($list, $options = array(), $itemOptions = array(), $tag = 'ul') {
  1021. if (is_string($options)) {
  1022. $tag = $options;
  1023. $options = array();
  1024. }
  1025. $items = $this->_nestedListItem($list, $options, $itemOptions, $tag);
  1026. return sprintf($this->_tags[$tag], $this->_parseAttributes($options, null, ' ', ''), $items);
  1027. }
  1028. /**
  1029. * Internal function to build a nested list (UL/OL) out of an associative array.
  1030. *
  1031. * @param array $items Set of elements to list
  1032. * @param array $options Additional HTML attributes of the list (ol/ul) tag
  1033. * @param array $itemOptions Additional HTML attributes of the list item (LI) tag
  1034. * @param string $tag Type of list tag to use (ol/ul)
  1035. * @return string The nested list element
  1036. * @see HtmlHelper::nestedList()
  1037. */
  1038. protected function _nestedListItem($items, $options, $itemOptions, $tag) {
  1039. $out = '';
  1040. $index = 1;
  1041. foreach ($items as $key => $item) {
  1042. if (is_array($item)) {
  1043. $item = $key . $this->nestedList($item, $options, $itemOptions, $tag);
  1044. }
  1045. if (isset($itemOptions['even']) && $index % 2 == 0) {
  1046. $itemOptions['class'] = $itemOptions['even'];
  1047. } elseif (isset($itemOptions['odd']) && $index % 2 != 0) {
  1048. $itemOptions['class'] = $itemOptions['odd'];
  1049. }
  1050. $out .= sprintf($this->_tags['li'], $this->_parseAttributes($itemOptions, array('even', 'odd'), ' ', ''), $item);
  1051. $index++;
  1052. }
  1053. return $out;
  1054. }
  1055. /**
  1056. * Load Html tag configuration.
  1057. *
  1058. * Loads a file from APP/Config that contains tag data. By default the file is expected
  1059. * to be compatible with PhpReader:
  1060. *
  1061. * `$this->Html->loadConfig('tags.php');`
  1062. *
  1063. * tags.php could look like:
  1064. *
  1065. * {{{
  1066. * $tags = array(
  1067. * 'meta' => '<meta %s>'
  1068. * );
  1069. * }}}
  1070. *
  1071. * If you wish to store tag definitions in another format you can give an array
  1072. * containing the file name, and reader class name:
  1073. *
  1074. * `$this->Html->loadConfig(array('tags.ini', 'ini'));`
  1075. *
  1076. * Its expected that the `tags` index will exist from any configuration file that is read.
  1077. * You can also specify the path to read the configuration file from, if APP/Config is not
  1078. * where the file is.
  1079. *
  1080. * `$this->Html->loadConfig('tags.php', APP . 'Lib' . DS);`
  1081. *
  1082. * Configuration files can define the following sections:
  1083. *
  1084. * - `tags` The tags to replace.
  1085. * - `minimizedAttributes` The attributes that are represented like `disabled="disabled"`
  1086. * - `docTypes` Additional doctypes to use.
  1087. * - `attributeFormat` Format for long attributes e.g. `'%s="%s"'`
  1088. * - `minimizedAttributeFormat` Format for minimized attributes e.g. `'%s="%s"'`
  1089. *
  1090. * @param mixed $configFile String with the config file (load using PhpReader) or an array with file and reader name
  1091. * @param string $path Path with config file
  1092. * @return mixed False to error or loaded configs
  1093. * @throws ConfigureException
  1094. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html#changing-the-tags-output-by-htmlhelper
  1095. */
  1096. public function loadConfig($configFile, $path = null) {
  1097. if (!$path) {
  1098. $path = APP . 'Config' . DS;
  1099. }
  1100. $file = null;
  1101. $reader = 'php';
  1102. if (!is_array($configFile)) {
  1103. $file = $configFile;
  1104. } elseif (isset($configFile[0])) {
  1105. $file = $configFile[0];
  1106. if (isset($configFile[1])) {
  1107. $reader = $configFile[1];
  1108. }
  1109. } else {
  1110. throw new ConfigureException(__d('cake_dev', 'Cannot load the configuration file. Wrong "configFile" configuration.'));
  1111. }
  1112. $readerClass = Inflector::camelize($reader) . 'Reader';
  1113. App::uses($readerClass, 'Configure');
  1114. if (!class_exists($readerClass)) {
  1115. throw new ConfigureException(__d('cake_dev', 'Cannot load the configuration file. Unknown reader.'));
  1116. }
  1117. $readerObj = new $readerClass($path);
  1118. $configs = $readerObj->read($file);
  1119. if (isset($configs['tags']) && is_array($configs['tags'])) {
  1120. $this->_tags = array_merge($this->_tags, $configs['tags']);
  1121. }
  1122. if (isset($configs['minimizedAttributes']) && is_array($configs['minimizedAttributes'])) {
  1123. $this->_minimizedAttributes = array_merge($this->_minimizedAttributes, $configs['minimizedAttributes']);
  1124. }
  1125. if (isset($configs['docTypes']) && is_array($configs['docTypes'])) {
  1126. $this->_docTypes = array_merge($this->_docTypes, $configs['docTypes']);
  1127. }
  1128. if (isset($configs['attributeFormat'])) {
  1129. $this->_attributeFormat = $configs['attributeFormat'];
  1130. }
  1131. if (isset($configs['minimizedAttributeFormat'])) {
  1132. $this->_minimizedAttributeFormat = $configs['minimizedAttributeFormat'];
  1133. }
  1134. return $configs;
  1135. }
  1136. }