HtmlHelper.php 36 KB

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