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) && $out instanceof 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: $filename = md5($script);
213: if (file_exists(JS . $filename . '.js')
214: || cache(str_replace(WWW_ROOT, '', JS) . $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.
263: *
264: * @return string Generated JSON object of all set vars
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 an cake 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 == null) {
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: