1: <?php
2: /**
3: * Javascript Generator class file.
4: *
5: * CakePHP : Rapid Development Framework (http://cakephp.org)
6: * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
7: *
8: * Licensed under The MIT License
9: * For full copyright and license information, please see the LICENSE.txt
10: * Redistributions of files must retain the above copyright notice.
11: *
12: * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
13: * @link http://cakephp.org CakePHP(tm) Project
14: * @package Cake.View.Helper
15: * @since CakePHP(tm) v 1.2
16: * @license http://www.opensource.org/licenses/mit-license.php MIT License
17: */
18:
19: App::uses('AppHelper', 'View/Helper');
20: App::uses('JsBaseEngineHelper', 'View/Helper');
21: App::uses('Multibyte', 'I18n');
22:
23: /**
24: * Javascript Generator helper class for easy use of JavaScript.
25: *
26: * JsHelper provides an abstract interface for authoring JavaScript with a
27: * given client-side library.
28: *
29: * @package Cake.View.Helper
30: * @property HtmlHelper $Html
31: * @property FormHelper $Form
32: */
33: class JsHelper extends AppHelper {
34:
35: /**
36: * Whether or not you want scripts to be buffered or output.
37: *
38: * @var boolean
39: */
40: public $bufferScripts = true;
41:
42: /**
43: * Helper dependencies
44: *
45: * @var array
46: */
47: public $helpers = array('Html', 'Form');
48:
49: /**
50: * Variables to pass to Javascript.
51: *
52: * @var array
53: * @see JsHelper::set()
54: */
55: protected $_jsVars = array();
56:
57: /**
58: * Scripts that are queued for output
59: *
60: * @var array
61: * @see JsHelper::buffer()
62: */
63: protected $_bufferedScripts = array();
64:
65: /**
66: * Current Javascript Engine that is being used
67: *
68: * @var string
69: */
70: protected $_engineName;
71:
72: /**
73: * The javascript variable created by set() variables.
74: *
75: * @var string
76: */
77: public $setVariable = 'app';
78:
79: /**
80: * Constructor - determines engine helper
81: *
82: * @param View $View the view object the helper is attached to.
83: * @param string|array $settings Settings array contains name of engine helper.
84: */
85: public function __construct(View $View, $settings = array()) {
86: $className = 'Jquery';
87: if (is_array($settings) && isset($settings[0])) {
88: $className = $settings[0];
89: } elseif (is_string($settings)) {
90: $className = $settings;
91: }
92: $engineName = $className;
93: list(, $className) = pluginSplit($className);
94:
95: $this->_engineName = $className . 'Engine';
96: $engineClass = $engineName . 'Engine';
97: $this->helpers[] = $engineClass;
98: parent::__construct($View, $settings);
99: }
100:
101: /**
102: * call__ Allows for dispatching of methods to the Engine Helper.
103: * methods in the Engines bufferedMethods list will be automatically buffered.
104: * You can control buffering with the buffer param as well. By setting the last parameter to
105: * any engine method to a boolean you can force or disable buffering.
106: *
107: * e.g. `$js->get('#foo')->effect('fadeIn', array('speed' => 'slow'), true);`
108: *
109: * Will force buffering for the effect method. If the method takes an options array you may also add
110: * a 'buffer' param to the options array and control buffering there as well.
111: *
112: * e.g. `$js->get('#foo')->event('click', $functionContents, array('buffer' => true));`
113: *
114: * The buffer parameter will not be passed onto the EngineHelper.
115: *
116: * @param string $method Method to be called
117: * @param array $params Parameters for the method being called.
118: * @return mixed Depends on the return of the dispatched method, or it could be an instance of the EngineHelper
119: */
120: public function __call($method, $params) {
121: if ($this->{$this->_engineName} && method_exists($this->{$this->_engineName}, $method)) {
122: $buffer = false;
123: $engineHelper = $this->{$this->_engineName};
124: if (in_array(strtolower($method), $engineHelper->bufferedMethods)) {
125: $buffer = true;
126: }
127: if (count($params) > 0) {
128: $lastParam = $params[count($params) - 1];
129: $hasBufferParam = (is_bool($lastParam) || is_array($lastParam) && isset($lastParam['buffer']));
130: if ($hasBufferParam && is_bool($lastParam)) {
131: $buffer = $lastParam;
132: unset($params[count($params) - 1]);
133: } elseif ($hasBufferParam && is_array($lastParam)) {
134: $buffer = $lastParam['buffer'];
135: unset($params['buffer']);
136: }
137: }
138:
139: $out = call_user_func_array(array(&$engineHelper, $method), $params);
140: if ($this->bufferScripts && $buffer && is_string($out)) {
141: $this->buffer($out);
142: return null;
143: }
144: if (is_object($out) && $out instanceof JsBaseEngineHelper) {
145: return $this;
146: }
147: return $out;
148: }
149: if (method_exists($this, $method . '_')) {
150: return call_user_func(array(&$this, $method . '_'), $params);
151: }
152: trigger_error(__d('cake_dev', 'JsHelper:: Missing Method %s is undefined', $method), E_USER_WARNING);
153: }
154:
155: /**
156: * Overwrite inherited Helper::value()
157: * See JsBaseEngineHelper::value() for more information on this method.
158: *
159: * @param mixed $val A PHP variable to be converted to JSON
160: * @param boolean $quoteString If false, leaves string values unquoted
161: * @return string a JavaScript-safe/JSON representation of $val
162: * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/js.html#JsHelper::value
163: */
164: public function value($val = array(), $quoteString = null, $key = 'value') {
165: if ($quoteString === null) {
166: $quoteString = true;
167: }
168: return $this->{$this->_engineName}->value($val, $quoteString);
169: }
170:
171: /**
172: * Writes all Javascript generated so far to a code block or
173: * caches them to a file and returns a linked script. If no scripts have been
174: * buffered this method will return null. If the request is an XHR(ajax) request
175: * onDomReady will be set to false. As the dom is already 'ready'.
176: *
177: * ### Options
178: *
179: * - `inline` - Set to true to have scripts output as a script block inline
180: * if `cache` is also true, a script link tag will be generated. (default true)
181: * - `cache` - Set to true to have scripts cached to a file and linked in (default false)
182: * - `clear` - Set to false to prevent script cache from being cleared (default true)
183: * - `onDomReady` - wrap cached scripts in domready event (default true)
184: * - `safe` - if an inline block is generated should it be wrapped in <![CDATA[ ... ]]> (default true)
185: *
186: * @param array $options options for the code block
187: * @return mixed Completed javascript tag if there are scripts, if there are no buffered
188: * scripts null will be returned.
189: * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/js.html#JsHelper::writeBuffer
190: */
191: public function writeBuffer($options = array()) {
192: $domReady = !$this->request->is('ajax');
193: $defaults = array(
194: 'onDomReady' => $domReady, 'inline' => true,
195: 'cache' => false, 'clear' => true, 'safe' => true
196: );
197: $options = array_merge($defaults, $options);
198: $script = implode("\n", $this->getBuffer($options['clear']));
199:
200: if (empty($script)) {
201: return null;
202: }
203:
204: if ($options['onDomReady']) {
205: $script = $this->{$this->_engineName}->domReady($script);
206: }
207: $opts = $options;
208: unset($opts['onDomReady'], $opts['cache'], $opts['clear']);
209:
210: if ($options['cache'] && $options['inline']) {
211: $filename = md5($script);
212: $path = WWW_ROOT . Configure::read('App.jsBaseUrl');
213: if (file_exists($path . $filename . '.js')
214: || cache(str_replace(WWW_ROOT, '', $path) . $filename . '.js', $script, '+999 days', 'public')
215: ) {
216: return $this->Html->script($filename);
217: }
218: }
219:
220: $return = $this->Html->scriptBlock($script, $opts);
221: if ($options['inline']) {
222: return $return;
223: }
224: return null;
225: }
226:
227: /**
228: * Write a script to the buffered scripts.
229: *
230: * @param string $script Script string to add to the buffer.
231: * @param boolean $top If true the script will be added to the top of the
232: * buffered scripts array. If false the bottom.
233: * @return void
234: * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/js.html#JsHelper::buffer
235: */
236: public function buffer($script, $top = false) {
237: if ($top) {
238: array_unshift($this->_bufferedScripts, $script);
239: } else {
240: $this->_bufferedScripts[] = $script;
241: }
242: }
243:
244: /**
245: * Get all the buffered scripts
246: *
247: * @param boolean $clear Whether or not to clear the script caches (default true)
248: * @return array Array of scripts added to the request.
249: * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/js.html#JsHelper::getBuffer
250: */
251: public function getBuffer($clear = true) {
252: $this->_createVars();
253: $scripts = $this->_bufferedScripts;
254: if ($clear) {
255: $this->_bufferedScripts = array();
256: $this->_jsVars = array();
257: }
258: return $scripts;
259: }
260:
261: /**
262: * Generates the object string for variables passed to javascript and adds to buffer
263: *
264: * @return void
265: */
266: protected function _createVars() {
267: if (!empty($this->_jsVars)) {
268: $setVar = (strpos($this->setVariable, '.')) ? $this->setVariable : 'window.' . $this->setVariable;
269: $this->buffer($setVar . ' = ' . $this->object($this->_jsVars) . ';', true);
270: }
271: }
272:
273: /**
274: * Generate an 'Ajax' link. Uses the selected JS engine to create a link
275: * element that is enhanced with Javascript. Options can include
276: * both those for HtmlHelper::link() and JsBaseEngine::request(), JsBaseEngine::event();
277: *
278: * ### Options
279: *
280: * - `confirm` - Generate a confirm() dialog before sending the event.
281: * - `id` - use a custom id.
282: * - `htmlAttributes` - additional non-standard htmlAttributes. Standard attributes are class, id,
283: * rel, title, escape, onblur and onfocus.
284: * - `buffer` - Disable the buffering and return a script tag in addition to the link.
285: *
286: * @param string $title Title for the link.
287: * @param string|array $url Mixed either a string URL or a CakePHP URL array.
288: * @param array $options Options for both the HTML element and Js::request()
289: * @return string Completed link. If buffering is disabled a script tag will be returned as well.
290: * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/js.html#JsHelper::link
291: */
292: public function link($title, $url = null, $options = array()) {
293: if (!isset($options['id'])) {
294: $options['id'] = 'link-' . intval(mt_rand());
295: }
296: list($options, $htmlOptions) = $this->_getHtmlOptions($options);
297: $out = $this->Html->link($title, $url, $htmlOptions);
298: $this->get('#' . $htmlOptions['id']);
299: $requestString = $event = '';
300: if (isset($options['confirm'])) {
301: $requestString = $this->confirmReturn($options['confirm']);
302: unset($options['confirm']);
303: }
304: $buffer = isset($options['buffer']) ? $options['buffer'] : null;
305: $safe = isset($options['safe']) ? $options['safe'] : true;
306: unset($options['buffer'], $options['safe']);
307:
308: $requestString .= $this->request($url, $options);
309:
310: if (!empty($requestString)) {
311: $event = $this->event('click', $requestString, $options + array('buffer' => $buffer));
312: }
313: if (isset($buffer) && !$buffer) {
314: $opts = array('safe' => $safe);
315: $out .= $this->Html->scriptBlock($event, $opts);
316: }
317: return $out;
318: }
319:
320: /**
321: * Pass variables into Javascript. Allows you to set variables that will be
322: * output when the buffer is fetched with `JsHelper::getBuffer()` or `JsHelper::writeBuffer()`
323: * The Javascript variable used to output set variables can be controlled with `JsHelper::$setVariable`
324: *
325: * @param string|array $one Either an array of variables to set, or the name of the variable to set.
326: * @param string|array $two If $one is a string, $two is the value for that key.
327: * @return void
328: * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/js.html#JsHelper::set
329: */
330: public function set($one, $two = null) {
331: $data = null;
332: if (is_array($one)) {
333: if (is_array($two)) {
334: $data = array_combine($one, $two);
335: } else {
336: $data = $one;
337: }
338: } else {
339: $data = array($one => $two);
340: }
341: if (!$data) {
342: return false;
343: }
344: $this->_jsVars = array_merge($this->_jsVars, $data);
345: }
346:
347: /**
348: * Uses the selected JS engine to create a submit input
349: * element that is enhanced with Javascript. Options can include
350: * both those for FormHelper::submit() and JsBaseEngine::request(), JsBaseEngine::event();
351: *
352: * Forms submitting with this method, cannot send files. Files do not transfer over XmlHttpRequest
353: * and require an iframe or flash.
354: *
355: * ### Options
356: *
357: * - `url` The url you wish the XHR request to submit to.
358: * - `confirm` A string to use for a confirm() message prior to submitting the request.
359: * - `method` The method you wish the form to send by, defaults to POST
360: * - `buffer` Whether or not you wish the script code to be buffered, defaults to true.
361: * - Also see options for JsHelper::request() and JsHelper::event()
362: *
363: * @param string $caption The display text of the submit button.
364: * @param array $options Array of options to use. See the options for the above mentioned methods.
365: * @return string Completed submit button.
366: * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/js.html#JsHelper::submit
367: */
368: public function submit($caption = null, $options = array()) {
369: if (!isset($options['id'])) {
370: $options['id'] = 'submit-' . intval(mt_rand());
371: }
372: $formOptions = array('div');
373: list($options, $htmlOptions) = $this->_getHtmlOptions($options, $formOptions);
374: $out = $this->Form->submit($caption, $htmlOptions);
375:
376: $this->get('#' . $htmlOptions['id']);
377:
378: $options['data'] = $this->serializeForm(array('isForm' => false, 'inline' => true));
379: $requestString = $url = '';
380: if (isset($options['confirm'])) {
381: $requestString = $this->confirmReturn($options['confirm']);
382: unset($options['confirm']);
383: }
384: if (isset($options['url'])) {
385: $url = $options['url'];
386: unset($options['url']);
387: }
388: if (!isset($options['method'])) {
389: $options['method'] = 'post';
390: }
391: $options['dataExpression'] = true;
392:
393: $buffer = isset($options['buffer']) ? $options['buffer'] : null;
394: $safe = isset($options['safe']) ? $options['safe'] : true;
395: unset($options['buffer'], $options['safe']);
396:
397: $requestString .= $this->request($url, $options);
398: if (!empty($requestString)) {
399: $event = $this->event('click', $requestString, $options + array('buffer' => $buffer));
400: }
401: if (isset($buffer) && !$buffer) {
402: $opts = array('safe' => $safe);
403: $out .= $this->Html->scriptBlock($event, $opts);
404: }
405: return $out;
406: }
407:
408: /**
409: * Parse a set of Options and extract the Html options.
410: * Extracted Html Options are removed from the $options param.
411: *
412: * @param array $options Options to filter.
413: * @param array $additional Array of additional keys to extract and include in the return options array.
414: * @return array Array of js options and Htmloptions
415: */
416: protected function _getHtmlOptions($options, $additional = array()) {
417: $htmlKeys = array_merge(
418: array('class', 'id', 'escape', 'onblur', 'onfocus', 'rel', 'title', 'style'),
419: $additional
420: );
421: $htmlOptions = array();
422: foreach ($htmlKeys as $key) {
423: if (isset($options[$key])) {
424: $htmlOptions[$key] = $options[$key];
425: }
426: unset($options[$key]);
427: }
428: if (isset($options['htmlAttributes'])) {
429: $htmlOptions = array_merge($htmlOptions, $options['htmlAttributes']);
430: unset($options['htmlAttributes']);
431: }
432: return array($options, $htmlOptions);
433: }
434:
435: }
436: