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