JsHelper.php 14 KB

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