PageRenderTime 45ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/Cake/View/Helper/JsHelper.php

https://bitbucket.org/udeshika/fake_twitter
PHP | 433 lines | 210 code | 31 blank | 192 comment | 49 complexity | ff86e3b69c76ee788eec689e62f782d7 MD5 | raw file
  1. <?php
  2. /**
  3. * Javascript Generator class file.
  4. *
  5. * PHP 5
  6. *
  7. * CakePHP : Rapid Development Framework (http://cakephp.org)
  8. * Copyright 2005-2011, 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-2011, 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($plugin, $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) && is_a($out, '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. return $this->Html->scriptBlock($script, $opts);
  196. }
  197. if ($options['cache'] && $options['inline']) {
  198. $filename = md5($script);
  199. if (!file_exists(JS . $filename . '.js')) {
  200. cache(str_replace(WWW_ROOT, '', JS) . $filename . '.js', $script, '+999 days', 'public');
  201. }
  202. return $this->Html->script($filename);
  203. }
  204. $this->Html->scriptBlock($script, $opts);
  205. return null;
  206. }
  207. /**
  208. * Write a script to the buffered scripts.
  209. *
  210. * @param string $script Script string to add to the buffer.
  211. * @param boolean $top If true the script will be added to the top of the
  212. * buffered scripts array. If false the bottom.
  213. * @return void
  214. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/js.html#JsHelper::buffer
  215. */
  216. public function buffer($script, $top = false) {
  217. if ($top) {
  218. array_unshift($this->_bufferedScripts, $script);
  219. } else {
  220. $this->_bufferedScripts[] = $script;
  221. }
  222. }
  223. /**
  224. * Get all the buffered scripts
  225. *
  226. * @param boolean $clear Whether or not to clear the script caches (default true)
  227. * @return array Array of scripts added to the request.
  228. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/js.html#JsHelper::getBuffer
  229. */
  230. public function getBuffer($clear = true) {
  231. $this->_createVars();
  232. $scripts = $this->_bufferedScripts;
  233. if ($clear) {
  234. $this->_bufferedScripts = array();
  235. $this->_jsVars = array();
  236. }
  237. return $scripts;
  238. }
  239. /**
  240. * Generates the object string for variables passed to javascript.
  241. *
  242. * @return string Generated JSON object of all set vars
  243. */
  244. protected function _createVars() {
  245. if (!empty($this->_jsVars)) {
  246. $setVar = (strpos($this->setVariable, '.')) ? $this->setVariable : 'window.' . $this->setVariable;
  247. $this->buffer($setVar . ' = ' . $this->object($this->_jsVars) . ';', true);
  248. }
  249. }
  250. /**
  251. * Generate an 'Ajax' link. Uses the selected JS engine to create a link
  252. * element that is enhanced with Javascript. Options can include
  253. * both those for HtmlHelper::link() and JsBaseEngine::request(), JsBaseEngine::event();
  254. *
  255. * ### Options
  256. *
  257. * - `confirm` - Generate a confirm() dialog before sending the event.
  258. * - `id` - use a custom id.
  259. * - `htmlAttributes` - additional non-standard htmlAttributes. Standard attributes are class, id,
  260. * rel, title, escape, onblur and onfocus.
  261. * - `buffer` - Disable the buffering and return a script tag in addition to the link.
  262. *
  263. * @param string $title Title for the link.
  264. * @param mixed $url Mixed either a string URL or an cake url array.
  265. * @param array $options Options for both the HTML element and Js::request()
  266. * @return string Completed link. If buffering is disabled a script tag will be returned as well.
  267. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/js.html#JsHelper::link
  268. */
  269. public function link($title, $url = null, $options = array()) {
  270. if (!isset($options['id'])) {
  271. $options['id'] = 'link-' . intval(mt_rand());
  272. }
  273. list($options, $htmlOptions) = $this->_getHtmlOptions($options);
  274. $out = $this->Html->link($title, $url, $htmlOptions);
  275. $this->get('#' . $htmlOptions['id']);
  276. $requestString = $event = '';
  277. if (isset($options['confirm'])) {
  278. $requestString = $this->confirmReturn($options['confirm']);
  279. unset($options['confirm']);
  280. }
  281. $buffer = isset($options['buffer']) ? $options['buffer'] : null;
  282. $safe = isset($options['safe']) ? $options['safe'] : true;
  283. unset($options['buffer'], $options['safe']);
  284. $requestString .= $this->request($url, $options);
  285. if (!empty($requestString)) {
  286. $event = $this->event('click', $requestString, $options + array('buffer' => $buffer));
  287. }
  288. if (isset($buffer) && !$buffer) {
  289. $opts = array('safe' => $safe);
  290. $out .= $this->Html->scriptBlock($event, $opts);
  291. }
  292. return $out;
  293. }
  294. /**
  295. * Pass variables into Javascript. Allows you to set variables that will be
  296. * output when the buffer is fetched with `JsHelper::getBuffer()` or `JsHelper::writeBuffer()`
  297. * The Javascript variable used to output set variables can be controlled with `JsHelper::$setVariable`
  298. *
  299. * @param mixed $one Either an array of variables to set, or the name of the variable to set.
  300. * @param mixed $two If $one is a string, $two is the value for that key.
  301. * @return void
  302. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/js.html#JsHelper::set
  303. */
  304. public function set($one, $two = null) {
  305. $data = null;
  306. if (is_array($one)) {
  307. if (is_array($two)) {
  308. $data = array_combine($one, $two);
  309. } else {
  310. $data = $one;
  311. }
  312. } else {
  313. $data = array($one => $two);
  314. }
  315. if ($data == null) {
  316. return false;
  317. }
  318. $this->_jsVars = array_merge($this->_jsVars, $data);
  319. }
  320. /**
  321. * Uses the selected JS engine to create a submit input
  322. * element that is enhanced with Javascript. Options can include
  323. * both those for FormHelper::submit() and JsBaseEngine::request(), JsBaseEngine::event();
  324. *
  325. * Forms submitting with this method, cannot send files. Files do not transfer over XmlHttpRequest
  326. * and require an iframe or flash.
  327. *
  328. * ### Options
  329. *
  330. * - `url` The url you wish the XHR request to submit to.
  331. * - `confirm` A string to use for a confirm() message prior to submitting the request.
  332. * - `method` The method you wish the form to send by, defaults to POST
  333. * - `buffer` Whether or not you wish the script code to be buffered, defaults to true.
  334. * - Also see options for JsHelper::request() and JsHelper::event()
  335. *
  336. * @param string $caption The display text of the submit button.
  337. * @param array $options Array of options to use. See the options for the above mentioned methods.
  338. * @return string Completed submit button.
  339. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/js.html#JsHelper::submit
  340. */
  341. public function submit($caption = null, $options = array()) {
  342. if (!isset($options['id'])) {
  343. $options['id'] = 'submit-' . intval(mt_rand());
  344. }
  345. $formOptions = array('div');
  346. list($options, $htmlOptions) = $this->_getHtmlOptions($options, $formOptions);
  347. $out = $this->Form->submit($caption, $htmlOptions);
  348. $this->get('#' . $htmlOptions['id']);
  349. $options['data'] = $this->serializeForm(array('isForm' => false, 'inline' => true));
  350. $requestString = $url = '';
  351. if (isset($options['confirm'])) {
  352. $requestString = $this->confirmReturn($options['confirm']);
  353. unset($options['confirm']);
  354. }
  355. if (isset($options['url'])) {
  356. $url = $options['url'];
  357. unset($options['url']);
  358. }
  359. if (!isset($options['method'])) {
  360. $options['method'] = 'post';
  361. }
  362. $options['dataExpression'] = true;
  363. $buffer = isset($options['buffer']) ? $options['buffer'] : null;
  364. $safe = isset($options['safe']) ? $options['safe'] : true;
  365. unset($options['buffer'], $options['safe']);
  366. $requestString .= $this->request($url, $options);
  367. if (!empty($requestString)) {
  368. $event = $this->event('click', $requestString, $options + array('buffer' => $buffer));
  369. }
  370. if (isset($buffer) && !$buffer) {
  371. $opts = array('safe' => $safe);
  372. $out .= $this->Html->scriptBlock($event, $opts);
  373. }
  374. return $out;
  375. }
  376. /**
  377. * Parse a set of Options and extract the Html options.
  378. * Extracted Html Options are removed from the $options param.
  379. *
  380. * @param array $options Options to filter.
  381. * @param array $additional Array of additional keys to extract and include in the return options array.
  382. * @return array Array of js options and Htmloptions
  383. */
  384. protected function _getHtmlOptions($options, $additional = array()) {
  385. $htmlKeys = array_merge(
  386. array('class', 'id', 'escape', 'onblur', 'onfocus', 'rel', 'title', 'style'),
  387. $additional
  388. );
  389. $htmlOptions = array();
  390. foreach ($htmlKeys as $key) {
  391. if (isset($options[$key])) {
  392. $htmlOptions[$key] = $options[$key];
  393. }
  394. unset($options[$key]);
  395. }
  396. if (isset($options['htmlAttributes'])) {
  397. $htmlOptions = array_merge($htmlOptions, $options['htmlAttributes']);
  398. unset($options['htmlAttributes']);
  399. }
  400. return array($options, $htmlOptions);
  401. }
  402. }