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