JsHelper.php 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072
  1. <?php
  2. /**
  3. * Javascript Generator class file.
  4. *
  5. * PHP 5
  6. *
  7. * CakePHP : Rapid Development Framework (http://cakephp.org)
  8. * Copyright 2006-2010, 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 2006-2010, Cake Software Foundation, Inc.
  14. * @link http://cakephp.org CakePHP Project
  15. * @package cake
  16. * @subpackage cake.cake.libs.view.helpers
  17. * @since CakePHP v 1.2
  18. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  19. */
  20. App::uses('Multibyte', 'Core');
  21. /**
  22. * Javascript Generator helper class for easy use of JavaScript.
  23. *
  24. * JsHelper provides an abstract interface for authoring JavaScript with a
  25. * given client-side library.
  26. *
  27. * @package cake
  28. * @subpackage cake.cake.libs.view.helpers
  29. */
  30. class JsHelper extends AppHelper {
  31. /**
  32. * Whether or not you want scripts to be buffered or output.
  33. *
  34. * @var boolean
  35. * @access public
  36. */
  37. public $bufferScripts = true;
  38. /**
  39. * helpers
  40. *
  41. * @var array
  42. * @access public
  43. */
  44. public $helpers = array('Html', 'Form');
  45. /**
  46. * Variables to pass to Javascript.
  47. *
  48. * @var array
  49. * @see JsHelper::set()
  50. * @access private
  51. */
  52. private $__jsVars = array();
  53. /**
  54. * Scripts that are queued for output
  55. *
  56. * @var array
  57. * @see JsHelper::buffer()
  58. * @access private
  59. */
  60. private $__bufferedScripts = array();
  61. /**
  62. * Current Javascript Engine that is being used
  63. *
  64. * @var string
  65. * @access private
  66. */
  67. private $__engineName;
  68. /**
  69. * The javascript variable created by set() variables.
  70. *
  71. * @var string
  72. * @access public
  73. */
  74. public $setVariable = APP_DIR;
  75. /**
  76. * Constructor - determines engine helper
  77. *
  78. * @param View $View the view object the helper is attached to.
  79. * @param array $settings Settings array contains name of engine helper.
  80. * @return void
  81. */
  82. public function __construct(View $View, $settings = array()) {
  83. $className = 'Jquery';
  84. if (is_array($settings) && isset($settings[0])) {
  85. $className = $settings[0];
  86. } elseif (is_string($settings)) {
  87. $className = $settings;
  88. }
  89. $engineName = $className;
  90. list($plugin, $className) = pluginSplit($className);
  91. $this->__engineName = $className . 'Engine';
  92. $engineClass = $engineName . 'Engine';
  93. $this->helpers[] = $engineClass;
  94. parent::__construct($View, $settings);
  95. }
  96. /**
  97. * call__ Allows for dispatching of methods to the Engine Helper.
  98. * methods in the Engines bufferedMethods list will be automatically buffered.
  99. * You can control buffering with the buffer param as well. By setting the last parameter to
  100. * any engine method to a boolean you can force or disable buffering.
  101. *
  102. * e.g. `$js->get('#foo')->effect('fadeIn', array('speed' => 'slow'), true);`
  103. *
  104. * Will force buffering for the effect method. If the method takes an options array you may also add
  105. * a 'buffer' param to the options array and control buffering there as well.
  106. *
  107. * e.g. `$js->get('#foo')->event('click', $functionContents, array('buffer' => true));`
  108. *
  109. * The buffer parameter will not be passed onto the EngineHelper.
  110. *
  111. * @param string $method Method to be called
  112. * @param array $params Parameters for the method being called.
  113. * @return mixed Depends on the return of the dispatched method, or it could be an instance of the EngineHelper
  114. */
  115. public function __call($method, $params) {
  116. if ($this->{$this->__engineName} && method_exists($this->{$this->__engineName}, $method)) {
  117. $buffer = false;
  118. $engineHelper = $this->{$this->__engineName};
  119. if (in_array(strtolower($method), $engineHelper->bufferedMethods)) {
  120. $buffer = true;
  121. }
  122. if (count($params) > 0) {
  123. $lastParam = $params[count($params) - 1];
  124. $hasBufferParam = (is_bool($lastParam) || is_array($lastParam) && isset($lastParam['buffer']));
  125. if ($hasBufferParam && is_bool($lastParam)) {
  126. $buffer = $lastParam;
  127. unset($params[count($params) - 1]);
  128. } elseif ($hasBufferParam && is_array($lastParam)) {
  129. $buffer = $lastParam['buffer'];
  130. unset($params['buffer']);
  131. }
  132. }
  133. $out = call_user_func_array(array(&$engineHelper, $method), $params);
  134. if ($this->bufferScripts && $buffer && is_string($out)) {
  135. $this->buffer($out);
  136. return null;
  137. }
  138. if (is_object($out) && is_a($out, 'JsBaseEngineHelper')) {
  139. return $this;
  140. }
  141. return $out;
  142. }
  143. if (method_exists($this, $method . '_')) {
  144. return call_user_func(array(&$this, $method . '_'), $params);
  145. }
  146. trigger_error(sprintf(__('JsHelper:: Missing Method %s is undefined'), $method), E_USER_WARNING);
  147. }
  148. /**
  149. * Workaround for Object::Object() existing. Since Object::object exists, it does not
  150. * fall into call__ and is not passed onto the engine helper. See JsBaseEngineHelper::object() for
  151. * more information on this method.
  152. *
  153. * @param mixed $data Data to convert into JSON
  154. * @param array $options Options to use for encoding JSON. See JsBaseEngineHelper::object() for more details.
  155. * @return string encoded JSON
  156. * @deprecated Remove when support for PHP4 and Object::object are removed.
  157. */
  158. public function object($data = array(), $options = array()) {
  159. return $this->{$this->__engineName}->object($data, $options);
  160. }
  161. /**
  162. * Overwrite inherited Helper::value()
  163. * See JsBaseEngineHelper::value() for more information on this method.
  164. *
  165. * @param mixed $val A PHP variable to be converted to JSON
  166. * @param boolean $quoteStrings If false, leaves string values unquoted
  167. * @return string a JavaScript-safe/JSON representation of $val
  168. * @access public
  169. **/
  170. function value($val, $quoteString = true) {
  171. return $this->{$this->__engineName}->value($val, $quoteString);
  172. }
  173. /**
  174. * Writes all Javascript generated so far to a code block or
  175. * caches them to a file and returns a linked script. If no scripts have been
  176. * buffered this method will return null. If the request is an XHR(ajax) request
  177. * onDomReady will be set to false. As the dom is already 'ready'.
  178. *
  179. * ### Options
  180. *
  181. * - `inline` - Set to true to have scripts output as a script block inline
  182. * if `cache` is also true, a script link tag will be generated. (default true)
  183. * - `cache` - Set to true to have scripts cached to a file and linked in (default false)
  184. * - `clear` - Set to false to prevent script cache from being cleared (default true)
  185. * - `onDomReady` - wrap cached scripts in domready event (default true)
  186. * - `safe` - if an inline block is generated should it be wrapped in <![CDATA[ ... ]]> (default true)
  187. *
  188. * @param array $options options for the code block
  189. * @return mixed Completed javascript tag if there are scripts, if there are no buffered
  190. * scripts null will be returned.
  191. */
  192. public function writeBuffer($options = array()) {
  193. $domReady = $this->request->is('ajax');
  194. // $domReady = isset($this->params['isAjax']) ? !$this->params['isAjax'] : true;
  195. $defaults = array(
  196. 'onDomReady' => $domReady, 'inline' => true,
  197. 'cache' => false, 'clear' => true, 'safe' => true
  198. );
  199. $options = array_merge($defaults, $options);
  200. $script = implode("\n", $this->getBuffer($options['clear']));
  201. if (empty($script)) {
  202. return null;
  203. }
  204. if ($options['onDomReady']) {
  205. $script = $this->{$this->__engineName}->domReady($script);
  206. }
  207. $opts = $options;
  208. unset($opts['onDomReady'], $opts['cache'], $opts['clear']);
  209. if (!$options['cache'] && $options['inline']) {
  210. return $this->Html->scriptBlock($script, $opts);
  211. }
  212. if ($options['cache'] && $options['inline']) {
  213. $filename = md5($script);
  214. if (!file_exists(JS . $filename . '.js')) {
  215. cache(str_replace(WWW_ROOT, '', JS) . $filename . '.js', $script, '+999 days', 'public');
  216. }
  217. return $this->Html->script($filename);
  218. }
  219. $this->Html->scriptBlock($script, $opts);
  220. return null;
  221. }
  222. /**
  223. * Write a script to the buffered scripts.
  224. *
  225. * @param string $script Script string to add to the buffer.
  226. * @param boolean $top If true the script will be added to the top of the
  227. * buffered scripts array. If false the bottom.
  228. * @return void
  229. */
  230. public function buffer($script, $top = false) {
  231. if ($top) {
  232. array_unshift($this->__bufferedScripts, $script);
  233. } else {
  234. $this->__bufferedScripts[] = $script;
  235. }
  236. }
  237. /**
  238. * Get all the buffered scripts
  239. *
  240. * @param boolean $clear Whether or not to clear the script caches (default true)
  241. * @return array Array of scripts added to the request.
  242. */
  243. public function getBuffer($clear = true) {
  244. $this->_createVars();
  245. $scripts = $this->__bufferedScripts;
  246. if ($clear) {
  247. $this->__bufferedScripts = array();
  248. $this->__jsVars = array();
  249. }
  250. return $scripts;
  251. }
  252. /**
  253. * Generates the object string for variables passed to javascript.
  254. *
  255. * @return string Generated JSON object of all set vars
  256. */
  257. protected function _createVars() {
  258. if (!empty($this->__jsVars)) {
  259. $setVar = (strpos($this->setVariable, '.')) ? $this->setVariable : 'window.' . $this->setVariable;
  260. $this->buffer($setVar . ' = ' . $this->object($this->__jsVars) . ';', true);
  261. }
  262. }
  263. /**
  264. * Generate an 'Ajax' link. Uses the selected JS engine to create a link
  265. * element that is enhanced with Javascript. Options can include
  266. * both those for HtmlHelper::link() and JsBaseEngine::request(), JsBaseEngine::event();
  267. *
  268. * ### Options
  269. *
  270. * - `confirm` - Generate a confirm() dialog before sending the event.
  271. * - `id` - use a custom id.
  272. * - `htmlAttributes` - additional non-standard htmlAttributes. Standard attributes are class, id,
  273. * rel, title, escape, onblur and onfocus.
  274. * - `buffer` - Disable the buffering and return a script tag in addition to the link.
  275. *
  276. * @param string $title Title for the link.
  277. * @param mixed $url Mixed either a string URL or an cake url array.
  278. * @param array $options Options for both the HTML element and Js::request()
  279. * @return string Completed link. If buffering is disabled a script tag will be returned as well.
  280. */
  281. public function link($title, $url = null, $options = array()) {
  282. if (!isset($options['id'])) {
  283. $options['id'] = 'link-' . intval(mt_rand());
  284. }
  285. list($options, $htmlOptions) = $this->_getHtmlOptions($options);
  286. $out = $this->Html->link($title, $url, $htmlOptions);
  287. $this->get('#' . $htmlOptions['id']);
  288. $requestString = $event = '';
  289. if (isset($options['confirm'])) {
  290. $requestString = $this->confirmReturn($options['confirm']);
  291. unset($options['confirm']);
  292. }
  293. $buffer = isset($options['buffer']) ? $options['buffer'] : null;
  294. $safe = isset($options['safe']) ? $options['safe'] : true;
  295. unset($options['buffer'], $options['safe']);
  296. $requestString .= $this->request($url, $options);
  297. if (!empty($requestString)) {
  298. $event = $this->event('click', $requestString, $options + array('buffer' => $buffer));
  299. }
  300. if (isset($buffer) && !$buffer) {
  301. $opts = array('safe' => $safe);
  302. $out .= $this->Html->scriptBlock($event, $opts);
  303. }
  304. return $out;
  305. }
  306. /**
  307. * Pass variables into Javascript. Allows you to set variables that will be
  308. * output when the buffer is fetched with `JsHelper::getBuffer()` or `JsHelper::writeBuffer()`
  309. * The Javascript variable used to output set variables can be controlled with `JsHelper::$setVariable`
  310. *
  311. * @param mixed $one Either an array of variables to set, or the name of the variable to set.
  312. * @param mixed $two If $one is a string, $two is the value for that key.
  313. * @return void
  314. */
  315. public function set($one, $two = null) {
  316. $data = null;
  317. if (is_array($one)) {
  318. if (is_array($two)) {
  319. $data = array_combine($one, $two);
  320. } else {
  321. $data = $one;
  322. }
  323. } else {
  324. $data = array($one => $two);
  325. }
  326. if ($data == null) {
  327. return false;
  328. }
  329. $this->__jsVars = array_merge($this->__jsVars, $data);
  330. }
  331. /**
  332. * Uses the selected JS engine to create a submit input
  333. * element that is enhanced with Javascript. Options can include
  334. * both those for FormHelper::submit() and JsBaseEngine::request(), JsBaseEngine::event();
  335. *
  336. * Forms submitting with this method, cannot send files. Files do not transfer over XmlHttpRequest
  337. * and require an iframe or flash.
  338. *
  339. * ### Options
  340. *
  341. * - `url` The url you wish the XHR request to submit to.
  342. * - `confirm` A string to use for a confirm() message prior to submitting the request.
  343. * - `method` The method you wish the form to send by, defaults to POST
  344. * - `buffer` Whether or not you wish the script code to be buffered, defaults to true.
  345. * - Also see options for JsHelper::request() and JsHelper::event()
  346. *
  347. * @param string $title The display text of the submit button.
  348. * @param array $options Array of options to use. See the options for the above mentioned methods.
  349. * @return string Completed submit button.
  350. */
  351. public function submit($caption = null, $options = array()) {
  352. if (!isset($options['id'])) {
  353. $options['id'] = 'submit-' . intval(mt_rand());
  354. }
  355. $formOptions = array('div');
  356. list($options, $htmlOptions) = $this->_getHtmlOptions($options, $formOptions);
  357. $out = $this->Form->submit($caption, $htmlOptions);
  358. $this->get('#' . $htmlOptions['id']);
  359. $options['data'] = $this->serializeForm(array('isForm' => false, 'inline' => true));
  360. $requestString = $url = '';
  361. if (isset($options['confirm'])) {
  362. $requestString = $this->confirmReturn($options['confirm']);
  363. unset($options['confirm']);
  364. }
  365. if (isset($options['url'])) {
  366. $url = $options['url'];
  367. unset($options['url']);
  368. }
  369. if (!isset($options['method'])) {
  370. $options['method'] = 'post';
  371. }
  372. $options['dataExpression'] = true;
  373. $buffer = isset($options['buffer']) ? $options['buffer'] : null;
  374. $safe = isset($options['safe']) ? $options['safe'] : true;
  375. unset($options['buffer'], $options['safe']);
  376. $requestString .= $this->request($url, $options);
  377. if (!empty($requestString)) {
  378. $event = $this->event('click', $requestString, $options + array('buffer' => $buffer));
  379. }
  380. if (isset($buffer) && !$buffer) {
  381. $opts = array('safe' => $safe);
  382. $out .= $this->Html->scriptBlock($event, $opts);
  383. }
  384. return $out;
  385. }
  386. /**
  387. * Parse a set of Options and extract the Html options.
  388. * Extracted Html Options are removed from the $options param.
  389. *
  390. * @param array $options Options to filter.
  391. * @param array $additional Array of additional keys to extract and include in the return options array.
  392. * @return array Array of js options and Htmloptions
  393. */
  394. protected function _getHtmlOptions($options, $additional = array()) {
  395. $htmlKeys = array_merge(array('class', 'id', 'escape', 'onblur', 'onfocus', 'rel', 'title'), $additional);
  396. $htmlOptions = array();
  397. foreach ($htmlKeys as $key) {
  398. if (isset($options[$key])) {
  399. $htmlOptions[$key] = $options[$key];
  400. }
  401. unset($options[$key]);
  402. }
  403. if (isset($options['htmlAttributes'])) {
  404. $htmlOptions = array_merge($htmlOptions, $options['htmlAttributes']);
  405. unset($options['htmlAttributes']);
  406. }
  407. return array($options, $htmlOptions);
  408. }
  409. }
  410. /**
  411. * JsEngineBaseClass
  412. *
  413. * Abstract Base Class for All JsEngines to extend. Provides generic methods.
  414. *
  415. * @package cake.view.helpers
  416. */
  417. abstract class JsBaseEngineHelper extends AppHelper {
  418. /**
  419. * Determines whether native JSON extension is used for encoding. Set by object constructor.
  420. *
  421. * @var boolean
  422. * @access public
  423. */
  424. public $useNative = false;
  425. /**
  426. * The js snippet for the current selection.
  427. *
  428. * @var string
  429. * @access public
  430. */
  431. public $selection;
  432. /**
  433. * Collection of option maps. Option maps allow other helpers to use generic names for engine
  434. * callbacks and options. Allowing uniform code access for all engine types. Their use is optional
  435. * for end user use though.
  436. *
  437. * @var array
  438. * @access protected
  439. */
  440. protected $_optionMap = array();
  441. /**
  442. * An array of lowercase method names in the Engine that are buffered unless otherwise disabled.
  443. * This allows specific 'end point' methods to be automatically buffered by the JsHelper.
  444. *
  445. * @var array
  446. * @access public
  447. */
  448. public $bufferedMethods = array('event', 'sortable', 'drag', 'drop', 'slider');
  449. /**
  450. * Contains a list of callback names -> default arguments.
  451. *
  452. * @var array
  453. * @access protected
  454. */
  455. protected $_callbackArguments = array();
  456. /**
  457. * Constructor.
  458. *
  459. * @return void
  460. */
  461. function __construct() {
  462. $this->useNative = function_exists('json_encode');
  463. }
  464. /**
  465. * Create an `alert()` message in Javascript
  466. *
  467. * @param string $message Message you want to alter.
  468. * @return string completed alert()
  469. */
  470. public function alert($message) {
  471. return 'alert("' . $this->escape($message) . '");';
  472. }
  473. /**
  474. * Redirects to a URL. Creates a window.location modification snippet
  475. * that can be used to trigger 'redirects' from Javascript.
  476. *
  477. * @param mixed $url
  478. * @param array $options
  479. * @return string completed redirect in javascript
  480. */
  481. public function redirect($url = null) {
  482. return 'window.location = "' . Router::url($url) . '";';
  483. }
  484. /**
  485. * Create a `confirm()` message
  486. *
  487. * @param string $message Message you want confirmed.
  488. * @return string completed confirm()
  489. */
  490. public function confirm($message) {
  491. return 'confirm("' . $this->escape($message) . '");';
  492. }
  493. /**
  494. * Generate a confirm snippet that returns false from the current
  495. * function scope.
  496. *
  497. * @param string $message Message to use in the confirm dialog.
  498. * @return string completed confirm with return script
  499. */
  500. public function confirmReturn($message) {
  501. $out = 'var _confirm = ' . $this->confirm($message);
  502. $out .= "if (!_confirm) {\n\treturn false;\n}";
  503. return $out;
  504. }
  505. /**
  506. * Create a `prompt()` Javascript function
  507. *
  508. * @param string $message Message you want to prompt.
  509. * @param string $default Default message
  510. * @return string completed prompt()
  511. */
  512. public function prompt($message, $default = '') {
  513. return 'prompt("' . $this->escape($message) . '", "' . $this->escape($default) . '");';
  514. }
  515. /**
  516. * Generates a JavaScript object in JavaScript Object Notation (JSON)
  517. * from an array. Will use native JSON encode method if available, and $useNative == true
  518. *
  519. * ### Options:
  520. *
  521. * - `prefix` - String prepended to the returned data.
  522. * - `postfix` - String appended to the returned data.
  523. *
  524. * @param array $data Data to be converted.
  525. * @param array $options Set of options, see above.
  526. * @return string A JSON code block
  527. */
  528. public function object($data = array(), $options = array()) {
  529. $defaultOptions = array(
  530. 'prefix' => '', 'postfix' => '',
  531. );
  532. $options = array_merge($defaultOptions, $options);
  533. if (is_object($data)) {
  534. $data = get_object_vars($data);
  535. }
  536. $out = $keys = array();
  537. $numeric = true;
  538. if ($this->useNative && function_exists('json_encode')) {
  539. $rt = json_encode($data);
  540. } else {
  541. if (is_null($data)) {
  542. return 'null';
  543. }
  544. if (is_bool($data)) {
  545. return $data ? 'true' : 'false';
  546. }
  547. if (is_array($data)) {
  548. $keys = array_keys($data);
  549. }
  550. if (!empty($keys)) {
  551. $numeric = (array_values($keys) === array_keys(array_values($keys)));
  552. }
  553. foreach ($data as $key => $val) {
  554. if (is_array($val) || is_object($val)) {
  555. $val = $this->object($val);
  556. } else {
  557. $val = $this->value($val);
  558. }
  559. if (!$numeric) {
  560. $val = '"' . $this->value($key, false) . '":' . $val;
  561. }
  562. $out[] = $val;
  563. }
  564. if (!$numeric) {
  565. $rt = '{' . join(',', $out) . '}';
  566. } else {
  567. $rt = '[' . join(',', $out) . ']';
  568. }
  569. }
  570. $rt = $options['prefix'] . $rt . $options['postfix'];
  571. return $rt;
  572. }
  573. /**
  574. * Converts a PHP-native variable of any type to a JSON-equivalent representation
  575. *
  576. * @param mixed $val A PHP variable to be converted to JSON
  577. * @param boolean $quoteStrings If false, leaves string values unquoted
  578. * @return string a JavaScript-safe/JSON representation of $val
  579. */
  580. public function value($val, $quoteString = true) {
  581. switch (true) {
  582. case (is_array($val) || is_object($val)):
  583. $val = $this->object($val);
  584. break;
  585. case ($val === null):
  586. $val = 'null';
  587. break;
  588. case (is_bool($val)):
  589. $val = ($val === true) ? 'true' : 'false';
  590. break;
  591. case (is_int($val)):
  592. $val = $val;
  593. break;
  594. case (is_float($val)):
  595. $val = sprintf("%.11f", $val);
  596. break;
  597. default:
  598. $val = $this->escape($val);
  599. if ($quoteString) {
  600. $val = '"' . $val . '"';
  601. }
  602. break;
  603. }
  604. return $val;
  605. }
  606. /**
  607. * Escape a string to be JSON friendly.
  608. *
  609. * List of escaped elements:
  610. *
  611. * - "\r" => '\n'
  612. * - "\n" => '\n'
  613. * - '"' => '\"'
  614. *
  615. * @param string $script String that needs to get escaped.
  616. * @return string Escaped string.
  617. */
  618. public function escape($string) {
  619. return $this->_utf8ToHex($string);
  620. }
  621. /**
  622. * Encode a string into JSON. Converts and escapes necessary characters.
  623. *
  624. * @param string $string The string that needs to be utf8->hex encoded
  625. * @return void
  626. */
  627. protected function _utf8ToHex($string) {
  628. $length = strlen($string);
  629. $return = '';
  630. for ($i = 0; $i < $length; ++$i) {
  631. $ord = ord($string{$i});
  632. switch (true) {
  633. case $ord == 0x08:
  634. $return .= '\b';
  635. break;
  636. case $ord == 0x09:
  637. $return .= '\t';
  638. break;
  639. case $ord == 0x0A:
  640. $return .= '\n';
  641. break;
  642. case $ord == 0x0C:
  643. $return .= '\f';
  644. break;
  645. case $ord == 0x0D:
  646. $return .= '\r';
  647. break;
  648. case $ord == 0x22:
  649. case $ord == 0x2F:
  650. case $ord == 0x5C:
  651. $return .= '\\' . $string{$i};
  652. break;
  653. case (($ord >= 0x20) && ($ord <= 0x7F)):
  654. $return .= $string{$i};
  655. break;
  656. case (($ord & 0xE0) == 0xC0):
  657. if ($i + 1 >= $length) {
  658. $i += 1;
  659. $return .= '?';
  660. break;
  661. }
  662. $charbits = $string{$i} . $string{$i + 1};
  663. $char = Multibyte::utf8($charbits);
  664. $return .= sprintf('\u%04s', dechex($char[0]));
  665. $i += 1;
  666. break;
  667. case (($ord & 0xF0) == 0xE0):
  668. if ($i + 2 >= $length) {
  669. $i += 2;
  670. $return .= '?';
  671. break;
  672. }
  673. $charbits = $string{$i} . $string{$i + 1} . $string{$i + 2};
  674. $char = Multibyte::utf8($charbits);
  675. $return .= sprintf('\u%04s', dechex($char[0]));
  676. $i += 2;
  677. break;
  678. case (($ord & 0xF8) == 0xF0):
  679. if ($i + 3 >= $length) {
  680. $i += 3;
  681. $return .= '?';
  682. break;
  683. }
  684. $charbits = $string{$i} . $string{$i + 1} . $string{$i + 2} . $string{$i + 3};
  685. $char = Multibyte::utf8($charbits);
  686. $return .= sprintf('\u%04s', dechex($char[0]));
  687. $i += 3;
  688. break;
  689. case (($ord & 0xFC) == 0xF8):
  690. if ($i + 4 >= $length) {
  691. $i += 4;
  692. $return .= '?';
  693. break;
  694. }
  695. $charbits = $string{$i} . $string{$i + 1} . $string{$i + 2} . $string{$i + 3} . $string{$i + 4};
  696. $char = Multibyte::utf8($charbits);
  697. $return .= sprintf('\u%04s', dechex($char[0]));
  698. $i += 4;
  699. break;
  700. case (($ord & 0xFE) == 0xFC):
  701. if ($i + 5 >= $length) {
  702. $i += 5;
  703. $return .= '?';
  704. break;
  705. }
  706. $charbits = $string{$i} . $string{$i + 1} . $string{$i + 2} . $string{$i + 3} . $string{$i + 4} . $string{$i + 5};
  707. $char = Multibyte::utf8($charbits);
  708. $return .= sprintf('\u%04s', dechex($char[0]));
  709. $i += 5;
  710. break;
  711. }
  712. }
  713. return $return;
  714. }
  715. /**
  716. * Create javascript selector for a CSS rule
  717. *
  718. * @param string $selector The selector that is targeted
  719. * @return object instance of $this. Allows chained methods.
  720. */
  721. abstract public function get($selector);
  722. /**
  723. * Add an event to the script cache. Operates on the currently selected elements.
  724. *
  725. * ### Options
  726. *
  727. * - `wrap` - Whether you want the callback wrapped in an anonymous function. (defaults to true)
  728. * - `stop` - Whether you want the event to stopped. (defaults to true)
  729. *
  730. * @param string $type Type of event to bind to the current dom id
  731. * @param string $callback The Javascript function you wish to trigger or the function literal
  732. * @param array $options Options for the event.
  733. * @return string completed event handler
  734. */
  735. abstract public function event($type, $callback, $options = array());
  736. /**
  737. * Create a domReady event. This is a special event in many libraries
  738. *
  739. * @param string $functionBody The code to run on domReady
  740. * @return string completed domReady method
  741. */
  742. abstract public function domReady($functionBody);
  743. /**
  744. * Create an iteration over the current selection result.
  745. *
  746. * @param string $callback The function body you wish to apply during the iteration.
  747. * @return string completed iteration
  748. */
  749. abstract public function each($callback);
  750. /**
  751. * Trigger an Effect.
  752. *
  753. * ### Supported Effects
  754. *
  755. * The following effects are supported by all core JsEngines
  756. *
  757. * - `show` - reveal an element.
  758. * - `hide` - hide an element.
  759. * - `fadeIn` - Fade in an element.
  760. * - `fadeOut` - Fade out an element.
  761. * - `slideIn` - Slide an element in.
  762. * - `slideOut` - Slide an element out.
  763. *
  764. * ### Options
  765. *
  766. * - `speed` - Speed at which the animation should occur. Accepted values are 'slow', 'fast'. Not all effects use
  767. * the speed option.
  768. *
  769. * @param string $name The name of the effect to trigger.
  770. * @param array $options Array of options for the effect.
  771. * @return string completed string with effect.
  772. */
  773. abstract public function effect($name, $options = array());
  774. /**
  775. * Make an XHR request
  776. *
  777. * ### Event Options
  778. *
  779. * - `complete` - Callback to fire on complete.
  780. * - `success` - Callback to fire on success.
  781. * - `before` - Callback to fire on request initialization.
  782. * - `error` - Callback to fire on request failure.
  783. *
  784. * ### Options
  785. *
  786. * - `method` - The method to make the request with defaults to GET in more libraries
  787. * - `async` - Whether or not you want an asynchronous request.
  788. * - `data` - Additional data to send.
  789. * - `update` - Dom id to update with the content of the request.
  790. * - `type` - Data type for response. 'json' and 'html' are supported. Default is html for most libraries.
  791. * - `evalScripts` - Whether or not <script> tags should be eval'ed.
  792. * - `dataExpression` - Should the `data` key be treated as a callback. Useful for supplying `$options['data']` as
  793. * another Javascript expression.
  794. *
  795. * @param mixed $url Array or String URL to target with the request.
  796. * @param array $options Array of options. See above for cross library supported options
  797. * @return string XHR request.
  798. */
  799. abstract public function request($url, $options = array());
  800. /**
  801. * Create a draggable element. Works on the currently selected element.
  802. * Additional options may be supported by the library implementation.
  803. *
  804. * ### Options
  805. *
  806. * - `handle` - selector to the handle element.
  807. * - `snapGrid` - The pixel grid that movement snaps to, an array(x, y)
  808. * - `container` - The element that acts as a bounding box for the draggable element.
  809. *
  810. * ### Event Options
  811. *
  812. * - `start` - Event fired when the drag starts
  813. * - `drag` - Event fired on every step of the drag
  814. * - `stop` - Event fired when dragging stops (mouse release)
  815. *
  816. * @param array $options Options array see above.
  817. * @return string Completed drag script
  818. */
  819. abstract public function drag($options = array());
  820. /**
  821. * Create a droppable element. Allows for draggable elements to be dropped on it.
  822. * Additional options may be supported by the library implementation.
  823. *
  824. * ### Options
  825. *
  826. * - `accept` - Selector for elements this droppable will accept.
  827. * - `hoverclass` - Class to add to droppable when a draggable is over.
  828. *
  829. * ### Event Options
  830. *
  831. * - `drop` - Event fired when an element is dropped into the drop zone.
  832. * - `hover` - Event fired when a drag enters a drop zone.
  833. * - `leave` - Event fired when a drag is removed from a drop zone without being dropped.
  834. *
  835. * @return string Completed drop script
  836. */
  837. abstract public function drop($options = array());
  838. /**
  839. * Create a sortable element.
  840. * Additional options may be supported by the library implementation.
  841. *
  842. * ### Options
  843. *
  844. * - `containment` - Container for move action
  845. * - `handle` - Selector to handle element. Only this element will start sort action.
  846. * - `revert` - Whether or not to use an effect to move sortable into final position.
  847. * - `opacity` - Opacity of the placeholder
  848. * - `distance` - Distance a sortable must be dragged before sorting starts.
  849. *
  850. * ### Event Options
  851. *
  852. * - `start` - Event fired when sorting starts
  853. * - `sort` - Event fired during sorting
  854. * - `complete` - Event fired when sorting completes.
  855. *
  856. * @param array $options Array of options for the sortable. See above.
  857. * @return string Completed sortable script.
  858. */
  859. abstract public function sortable($options = array());
  860. /**
  861. * Create a slider UI widget. Comprised of a track and knob.
  862. * Additional options may be supported by the library implementation.
  863. *
  864. * ### Options
  865. *
  866. * - `handle` - The id of the element used in sliding.
  867. * - `direction` - The direction of the slider either 'vertical' or 'horizontal'
  868. * - `min` - The min value for the slider.
  869. * - `max` - The max value for the slider.
  870. * - `step` - The number of steps or ticks the slider will have.
  871. * - `value` - The initial offset of the slider.
  872. *
  873. * ### Events
  874. *
  875. * - `change` - Fired when the slider's value is updated
  876. * - `complete` - Fired when the user stops sliding the handle
  877. *
  878. * @return string Completed slider script
  879. */
  880. abstract public function slider($options = array());
  881. /**
  882. * Serialize the form attached to $selector.
  883. * Pass `true` for $isForm if the current selection is a form element.
  884. * Converts the form or the form element attached to the current selection into a string/json object
  885. * (depending on the library implementation) for use with XHR operations.
  886. *
  887. * ### Options
  888. *
  889. * - `isForm` - is the current selection a form, or an input? (defaults to false)
  890. * - `inline` - is the rendered statement going to be used inside another JS statement? (defaults to false)
  891. *
  892. * @param array $options options for serialization generation.
  893. * @return string completed form serialization script
  894. */
  895. abstract public function serializeForm($options = array());
  896. /**
  897. * Parse an options assoc array into an Javascript object literal.
  898. * Similar to object() but treats any non-integer value as a string,
  899. * does not include `{ }`
  900. *
  901. * @param array $options Options to be converted
  902. * @param array $safeKeys Keys that should not be escaped.
  903. * @return string Parsed JSON options without enclosing { }.
  904. */
  905. protected function _parseOptions($options, $safeKeys = array()) {
  906. $out = array();
  907. $safeKeys = array_flip($safeKeys);
  908. foreach ($options as $key => $value) {
  909. if (!is_int($value) && !isset($safeKeys[$key])) {
  910. $value = $this->value($value);
  911. }
  912. $out[] = $key . ':' . $value;
  913. }
  914. sort($out);
  915. return join(', ', $out);
  916. }
  917. /**
  918. * Maps Abstract options to engine specific option names.
  919. * If attributes are missing from the map, they are not changed.
  920. *
  921. * @param string $method Name of method whose options are being worked with.
  922. * @param array $options Array of options to map.
  923. * @return array Array of mapped options.
  924. */
  925. protected function _mapOptions($method, $options) {
  926. if (!isset($this->_optionMap[$method])) {
  927. return $options;
  928. }
  929. foreach ($this->_optionMap[$method] as $abstract => $concrete) {
  930. if (isset($options[$abstract])) {
  931. $options[$concrete] = $options[$abstract];
  932. unset($options[$abstract]);
  933. }
  934. }
  935. return $options;
  936. }
  937. /**
  938. * Prepare callbacks and wrap them with function ([args]) { } as defined in
  939. * _callbackArgs array.
  940. *
  941. * @param string $method Name of the method you are preparing callbacks for.
  942. * @param array $options Array of options being parsed
  943. * @param string $callbacks Additional Keys that contain callbacks
  944. * @return array Array of options with callbacks added.
  945. */
  946. protected function _prepareCallbacks($method, $options, $callbacks = array()) {
  947. $wrapCallbacks = true;
  948. if (isset($options['wrapCallbacks'])) {
  949. $wrapCallbacks = $options['wrapCallbacks'];
  950. }
  951. unset($options['wrapCallbacks']);
  952. if (!$wrapCallbacks) {
  953. return $options;
  954. }
  955. $callbackOptions = array();
  956. if (isset($this->_callbackArguments[$method])) {
  957. $callbackOptions = $this->_callbackArguments[$method];
  958. }
  959. $callbacks = array_unique(array_merge(array_keys($callbackOptions), (array)$callbacks));
  960. foreach ($callbacks as $callback) {
  961. if (empty($options[$callback])) {
  962. continue;
  963. }
  964. $args = null;
  965. if (!empty($callbackOptions[$callback])) {
  966. $args = $callbackOptions[$callback];
  967. }
  968. $options[$callback] = 'function (' . $args . ') {' . $options[$callback] . '}';
  969. }
  970. return $options;
  971. }
  972. /**
  973. * Conveinence wrapper method for all common option processing steps.
  974. * Runs _mapOptions, _prepareCallbacks, and _parseOptions in order.
  975. *
  976. * @param string $method Name of method processing options for.
  977. * @param array $options Array of options to process.
  978. * @return string Parsed options string.
  979. */
  980. protected function _processOptions($method, $options) {
  981. $options = $this->_mapOptions($method, $options);
  982. $options = $this->_prepareCallbacks($method, $options);
  983. $options = $this->_parseOptions($options, array_keys($this->_callbackArguments[$method]));
  984. return $options;
  985. }
  986. /**
  987. * Convert an array of data into a query string
  988. *
  989. * @param array $parameters Array of parameters to convert to a query string
  990. * @return string Querystring fragment
  991. */
  992. protected function _toQuerystring($parameters) {
  993. $out = '';
  994. $keys = array_keys($parameters);
  995. $count = count($parameters);
  996. for ($i = 0; $i < $count; $i++) {
  997. $out .= $keys[$i] . '=' . $parameters[$keys[$i]];
  998. if ($i < $count - 1) {
  999. $out .= '&';
  1000. }
  1001. }
  1002. return $out;
  1003. }
  1004. }