PageRenderTime 52ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

/cake/libs/view/helpers/js.php

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