JsHelper.php 14 KB

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