PageRenderTime 60ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

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

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