PageRenderTime 66ms CodeModel.GetById 29ms RepoModel.GetById 1ms app.codeStats 0ms

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

https://github.com/anfleene/N342
PHP | 1113 lines | 584 code | 57 blank | 472 comment | 91 complexity | 2d929c35622db981cad89b13ca5560e4 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 = '';
  293. if (isset($options['confirm'])) {
  294. $requestString = $this->confirmReturn($options['confirm']);
  295. unset($options['confirm']);
  296. }
  297. $requestString .= $this->request($url, $options);
  298. if (!empty($requestString)) {
  299. $event = $this->event('click', $requestString, $options);
  300. }
  301. if (isset($options['buffer']) && $options['buffer'] == false) {
  302. $opts = array();
  303. if (isset($options['safe'])) {
  304. $opts['safe'] = $options['safe'];
  305. }
  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. * @param string $title The display text of the submit button.
  345. * @param array $options Array of options to use.
  346. * @return string Completed submit button.
  347. * @access public
  348. */
  349. function submit($caption = null, $options = array()) {
  350. if (!isset($options['id'])) {
  351. $options['id'] = 'submit-' . intval(mt_rand());
  352. }
  353. $formOptions = array('div');
  354. list($options, $htmlOptions) = $this->_getHtmlOptions($options, $formOptions);
  355. $out = $this->Form->submit($caption, $htmlOptions);
  356. $this->get('#' . $htmlOptions['id']);
  357. $options['data'] = $this->serializeForm(array('isForm' => false, 'inline' => true));
  358. $requestString = $url = '';
  359. if (isset($options['confirm'])) {
  360. $requestString = $this->confirmReturn($options['confirm']);
  361. unset($options['confirm']);
  362. }
  363. if (isset($options['url'])) {
  364. $url = $options['url'];
  365. unset($options['url']);
  366. }
  367. if (!isset($options['method'])) {
  368. $options['method'] = 'post';
  369. }
  370. $options['dataExpression'] = true;
  371. $requestString .= $this->request($url, $options);
  372. if (!empty($requestString)) {
  373. $event = $this->event('click', $requestString, $options);
  374. }
  375. if (isset($options['buffer']) && $options['buffer'] == false) {
  376. $out .= $this->Html->scriptBlock($event, $options);
  377. }
  378. return $out;
  379. }
  380. /**
  381. * Parse a set of Options and extract the Html options.
  382. * Extracted Html Options are removed from the $options param.
  383. *
  384. * @param array $options Options to filter.
  385. * @param array $additional Array of additional keys to extract and include in the return options array.
  386. * @return array Array of js options and Htmloptions
  387. * @access protected
  388. */
  389. function _getHtmlOptions($options, $additional = array()) {
  390. $htmlKeys = array_merge(array('class', 'id', 'escape', 'onblur', 'onfocus', 'rel', 'title'), $additional);
  391. $htmlOptions = array();
  392. foreach ($htmlKeys as $key) {
  393. if (isset($options[$key])) {
  394. $htmlOptions[$key] = $options[$key];
  395. }
  396. unset($options[$key]);
  397. }
  398. if (isset($options['htmlAttributes'])) {
  399. $htmlOptions = array_merge($htmlOptions, $options['htmlAttributes']);
  400. unset($options['htmlAttributes']);
  401. }
  402. return array($options, $htmlOptions);
  403. }
  404. }
  405. /**
  406. * JsEngineBaseClass
  407. *
  408. * Abstract Base Class for All JsEngines to extend. Provides generic methods.
  409. *
  410. * @package cake.view.helpers
  411. */
  412. class JsBaseEngineHelper extends AppHelper {
  413. /**
  414. * Determines whether native JSON extension is used for encoding. Set by object constructor.
  415. *
  416. * @var boolean
  417. * @access public
  418. */
  419. var $useNative = false;
  420. /**
  421. * The js snippet for the current selection.
  422. *
  423. * @var string
  424. * @access public
  425. */
  426. var $selection;
  427. /**
  428. * Collection of option maps. Option maps allow other helpers to use generic names for engine
  429. * callbacks and options. Allowing uniform code access for all engine types. Their use is optional
  430. * for end user use though.
  431. *
  432. * @var array
  433. * @access protected
  434. */
  435. var $_optionMap = array();
  436. /**
  437. * An array of lowercase method names in the Engine that are buffered unless otherwise disabled.
  438. * This allows specific 'end point' methods to be automatically buffered by the JsHelper.
  439. *
  440. * @var array
  441. * @access public
  442. */
  443. var $bufferedMethods = array('event', 'sortable', 'drag', 'drop', 'slider');
  444. /**
  445. * Contains a list of callback names -> default arguments.
  446. *
  447. * @var array
  448. * @access protected
  449. */
  450. var $_callbackArguments = array();
  451. /**
  452. * Constructor.
  453. *
  454. * @return void
  455. */
  456. function __construct() {
  457. $this->useNative = function_exists('json_encode');
  458. }
  459. /**
  460. * Create an `alert()` message in Javascript
  461. *
  462. * @param string $message Message you want to alter.
  463. * @return string completed alert()
  464. * @access public
  465. */
  466. function alert($message) {
  467. return 'alert("' . $this->escape($message) . '");';
  468. }
  469. /**
  470. * Redirects to a URL. Creates a window.location modification snippet
  471. * that can be used to trigger 'redirects' from Javascript.
  472. *
  473. * @param mixed $url
  474. * @param array $options
  475. * @return string completed redirect in javascript
  476. * @access public
  477. */
  478. function redirect($url = null) {
  479. return 'window.location = "' . Router::url($url) . '";';
  480. }
  481. /**
  482. * Create a `confirm()` message
  483. *
  484. * @param string $message Message you want confirmed.
  485. * @return string completed confirm()
  486. * @access public
  487. */
  488. function confirm($message) {
  489. return 'confirm("' . $this->escape($message) . '");';
  490. }
  491. /**
  492. * Generate a confirm snippet that returns false from the current
  493. * function scope.
  494. *
  495. * @param string $message Message to use in the confirm dialog.
  496. * @return string completed confirm with return script
  497. * @access public
  498. */
  499. function confirmReturn($message) {
  500. $out = 'var _confirm = ' . $this->confirm($message);
  501. $out .= "if (!_confirm) {\n\treturn false;\n}";
  502. return $out;
  503. }
  504. /**
  505. * Create a `prompt()` Javascript function
  506. *
  507. * @param string $message Message you want to prompt.
  508. * @param string $default Default message
  509. * @return string completed prompt()
  510. * @access public
  511. */
  512. 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. * @access public
  528. */
  529. function object($data = array(), $options = array()) {
  530. $defaultOptions = array(
  531. 'prefix' => '', 'postfix' => '',
  532. );
  533. $options = array_merge($defaultOptions, $options);
  534. if (is_object($data)) {
  535. $data = get_object_vars($data);
  536. }
  537. $out = $keys = array();
  538. $numeric = true;
  539. if ($this->useNative && function_exists('json_encode')) {
  540. $rt = json_encode($data);
  541. } else {
  542. if (is_null($data)) {
  543. return 'null';
  544. }
  545. if (is_bool($data)) {
  546. return $data ? 'true' : 'false';
  547. }
  548. if (is_array($data)) {
  549. $keys = array_keys($data);
  550. }
  551. if (!empty($keys)) {
  552. $numeric = (array_values($keys) === array_keys(array_values($keys)));
  553. }
  554. foreach ($data as $key => $val) {
  555. if (is_array($val) || is_object($val)) {
  556. $val = $this->object($val);
  557. } else {
  558. $val = $this->value($val);
  559. }
  560. if (!$numeric) {
  561. $val = '"' . $this->value($key, false) . '":' . $val;
  562. }
  563. $out[] = $val;
  564. }
  565. if (!$numeric) {
  566. $rt = '{' . join(',', $out) . '}';
  567. } else {
  568. $rt = '[' . join(',', $out) . ']';
  569. }
  570. }
  571. $rt = $options['prefix'] . $rt . $options['postfix'];
  572. return $rt;
  573. }
  574. /**
  575. * Converts a PHP-native variable of any type to a JSON-equivalent representation
  576. *
  577. * @param mixed $val A PHP variable to be converted to JSON
  578. * @param boolean $quoteStrings If false, leaves string values unquoted
  579. * @return string a JavaScript-safe/JSON representation of $val
  580. * @access public
  581. */
  582. function value($val, $quoteString = true) {
  583. switch (true) {
  584. case (is_array($val) || is_object($val)):
  585. $val = $this->object($val);
  586. break;
  587. case ($val === null):
  588. $val = 'null';
  589. break;
  590. case (is_bool($val)):
  591. $val = ($val === true) ? 'true' : 'false';
  592. break;
  593. case (is_int($val)):
  594. $val = $val;
  595. break;
  596. case (is_float($val)):
  597. $val = sprintf("%.11f", $val);
  598. break;
  599. default:
  600. $val = $this->escape($val);
  601. if ($quoteString) {
  602. $val = '"' . $val . '"';
  603. }
  604. break;
  605. }
  606. return $val;
  607. }
  608. /**
  609. * Escape a string to be JSON friendly.
  610. *
  611. * List of escaped elements:
  612. *
  613. * - "\r" => '\n'
  614. * - "\n" => '\n'
  615. * - '"' => '\"'
  616. *
  617. * @param string $script String that needs to get escaped.
  618. * @return string Escaped string.
  619. * @access public
  620. */
  621. function escape($string) {
  622. App::import('Core', 'Multibyte');
  623. return $this->_utf8ToHex($string);
  624. }
  625. /**
  626. * Encode a string into JSON. Converts and escapes necessary characters.
  627. *
  628. * @param string $string The string that needs to be utf8->hex encoded
  629. * @return void
  630. * @access protected
  631. */
  632. function _utf8ToHex($string) {
  633. $length = strlen($string);
  634. $return = '';
  635. for ($i = 0; $i < $length; ++$i) {
  636. $ord = ord($string{$i});
  637. switch (true) {
  638. case $ord == 0x08:
  639. $return .= '\b';
  640. break;
  641. case $ord == 0x09:
  642. $return .= '\t';
  643. break;
  644. case $ord == 0x0A:
  645. $return .= '\n';
  646. break;
  647. case $ord == 0x0C:
  648. $return .= '\f';
  649. break;
  650. case $ord == 0x0D:
  651. $return .= '\r';
  652. break;
  653. case $ord == 0x22:
  654. case $ord == 0x2F:
  655. case $ord == 0x5C:
  656. $return .= '\\' . $string{$i};
  657. break;
  658. case (($ord >= 0x20) && ($ord <= 0x7F)):
  659. $return .= $string{$i};
  660. break;
  661. case (($ord & 0xE0) == 0xC0):
  662. if ($i + 1 >= $length) {
  663. $i += 1;
  664. $return .= '?';
  665. break;
  666. }
  667. $charbits = $string{$i} . $string{$i + 1};
  668. $char = Multibyte::utf8($charbits);
  669. $return .= sprintf('\u%04s', dechex($char[0]));
  670. $i += 1;
  671. break;
  672. case (($ord & 0xF0) == 0xE0):
  673. if ($i + 2 >= $length) {
  674. $i += 2;
  675. $return .= '?';
  676. break;
  677. }
  678. $charbits = $string{$i} . $string{$i + 1} . $string{$i + 2};
  679. $char = Multibyte::utf8($charbits);
  680. $return .= sprintf('\u%04s', dechex($char[0]));
  681. $i += 2;
  682. break;
  683. case (($ord & 0xF8) == 0xF0):
  684. if ($i + 3 >= $length) {
  685. $i += 3;
  686. $return .= '?';
  687. break;
  688. }
  689. $charbits = $string{$i} . $string{$i + 1} . $string{$i + 2} . $string{$i + 3};
  690. $char = Multibyte::utf8($charbits);
  691. $return .= sprintf('\u%04s', dechex($char[0]));
  692. $i += 3;
  693. break;
  694. case (($ord & 0xFC) == 0xF8):
  695. if ($i + 4 >= $length) {
  696. $i += 4;
  697. $return .= '?';
  698. break;
  699. }
  700. $charbits = $string{$i} . $string{$i + 1} . $string{$i + 2} . $string{$i + 3} . $string{$i + 4};
  701. $char = Multibyte::utf8($charbits);
  702. $return .= sprintf('\u%04s', dechex($char[0]));
  703. $i += 4;
  704. break;
  705. case (($ord & 0xFE) == 0xFC):
  706. if ($i + 5 >= $length) {
  707. $i += 5;
  708. $return .= '?';
  709. break;
  710. }
  711. $charbits = $string{$i} . $string{$i + 1} . $string{$i + 2} . $string{$i + 3} . $string{$i + 4} . $string{$i + 5};
  712. $char = Multibyte::utf8($charbits);
  713. $return .= sprintf('\u%04s', dechex($char[0]));
  714. $i += 5;
  715. break;
  716. }
  717. }
  718. return $return;
  719. }
  720. /**
  721. * Create javascript selector for a CSS rule
  722. *
  723. * @param string $selector The selector that is targeted
  724. * @return object instance of $this. Allows chained methods.
  725. * @access public
  726. */
  727. function get($selector) {
  728. trigger_error(sprintf(__('%s does not have get() implemented', true), get_class($this)), E_USER_WARNING);
  729. return $this;
  730. }
  731. /**
  732. * Add an event to the script cache. Operates on the currently selected elements.
  733. *
  734. * ### Options
  735. *
  736. * - `wrap` - Whether you want the callback wrapped in an anonymous function. (defaults to true)
  737. * - `stop` - Whether you want the event to stopped. (defaults to true)
  738. *
  739. * @param string $type Type of event to bind to the current dom id
  740. * @param string $callback The Javascript function you wish to trigger or the function literal
  741. * @param array $options Options for the event.
  742. * @return string completed event handler
  743. * @access public
  744. */
  745. function event($type, $callback, $options = array()) {
  746. trigger_error(sprintf(__('%s does not have event() implemented', true), get_class($this)), E_USER_WARNING);
  747. }
  748. /**
  749. * Create a domReady event. This is a special event in many libraries
  750. *
  751. * @param string $functionBody The code to run on domReady
  752. * @return string completed domReady method
  753. * @access public
  754. */
  755. function domReady($functionBody) {
  756. trigger_error(sprintf(__('%s does not have domReady() implemented', true), get_class($this)), E_USER_WARNING);
  757. }
  758. /**
  759. * Create an iteration over the current selection result.
  760. *
  761. * @param string $callback The function body you wish to apply during the iteration.
  762. * @return string completed iteration
  763. */
  764. function each($callback) {
  765. trigger_error(sprintf(__('%s does not have each() implemented', true), get_class($this)), E_USER_WARNING);
  766. }
  767. /**
  768. * Trigger an Effect.
  769. *
  770. * ### Supported Effects
  771. *
  772. * The following effects are supported by all core JsEngines
  773. *
  774. * - `show` - reveal an element.
  775. * - `hide` - hide an element.
  776. * - `fadeIn` - Fade in an element.
  777. * - `fadeOut` - Fade out an element.
  778. * - `slideIn` - Slide an element in.
  779. * - `slideOut` - Slide an element out.
  780. *
  781. * ### Options
  782. *
  783. * - `speed` - Speed at which the animation should occur. Accepted values are 'slow', 'fast'. Not all effects use
  784. * the speed option.
  785. *
  786. * @param string $name The name of the effect to trigger.
  787. * @param array $options Array of options for the effect.
  788. * @return string completed string with effect.
  789. * @access public
  790. */
  791. function effect($name, $options) {
  792. trigger_error(sprintf(__('%s does not have effect() implemented', true), get_class($this)), E_USER_WARNING);
  793. }
  794. /**
  795. * Make an XHR request
  796. *
  797. * ### Event Options
  798. *
  799. * - `complete` - Callback to fire on complete.
  800. * - `success` - Callback to fire on success.
  801. * - `before` - Callback to fire on request initialization.
  802. * - `error` - Callback to fire on request failure.
  803. *
  804. * ### Options
  805. *
  806. * - `method` - The method to make the request with defaults to GET in more libraries
  807. * - `async` - Whether or not you want an asynchronous request.
  808. * - `data` - Additional data to send.
  809. * - `update` - Dom id to update with the content of the request.
  810. * - `type` - Data type for response. 'json' and 'html' are supported. Default is html for most libraries.
  811. * - `evalScripts` - Whether or not <script> tags should be eval'ed.
  812. * - `dataExpression` - Should the `data` key be treated as a callback. Useful for supplying `$options['data']` as
  813. * another Javascript expression.
  814. *
  815. * @param mixed $url Array or String URL to target with the request.
  816. * @param array $options Array of options. See above for cross library supported options
  817. * @return string XHR request.
  818. * @access public
  819. */
  820. function request($url, $options = array()) {
  821. trigger_error(sprintf(__('%s does not have request() implemented', true), get_class($this)), E_USER_WARNING);
  822. }
  823. /**
  824. * Create a draggable element. Works on the currently selected element.
  825. * Additional options may be supported by the library implementation.
  826. *
  827. * ### Options
  828. *
  829. * - `handle` - selector to the handle element.
  830. * - `snapGrid` - The pixel grid that movement snaps to, an array(x, y)
  831. * - `container` - The element that acts as a bounding box for the draggable element.
  832. *
  833. * ### Event Options
  834. *
  835. * - `start` - Event fired when the drag starts
  836. * - `drag` - Event fired on every step of the drag
  837. * - `stop` - Event fired when dragging stops (mouse release)
  838. *
  839. * @param array $options Options array see above.
  840. * @return string Completed drag script
  841. * @access public
  842. */
  843. function drag($options = array()) {
  844. trigger_error(sprintf(__('%s does not have drag() implemented', true), get_class($this)), E_USER_WARNING);
  845. }
  846. /**
  847. * Create a droppable element. Allows for draggable elements to be dropped on it.
  848. * Additional options may be supported by the library implementation.
  849. *
  850. * ### Options
  851. *
  852. * - `accept` - Selector for elements this droppable will accept.
  853. * - `hoverclass` - Class to add to droppable when a draggable is over.
  854. *
  855. * ### Event Options
  856. *
  857. * - `drop` - Event fired when an element is dropped into the drop zone.
  858. * - `hover` - Event fired when a drag enters a drop zone.
  859. * - `leave` - Event fired when a drag is removed from a drop zone without being dropped.
  860. *
  861. * @return string Completed drop script
  862. * @access public
  863. */
  864. function drop($options = array()) {
  865. trigger_error(sprintf(__('%s does not have drop() implemented', true), get_class($this)), E_USER_WARNING);
  866. }
  867. /**
  868. * Create a sortable element.
  869. * Additional options may be supported by the library implementation.
  870. *
  871. * ### Options
  872. *
  873. * - `containment` - Container for move action
  874. * - `handle` - Selector to handle element. Only this element will start sort action.
  875. * - `revert` - Whether or not to use an effect to move sortable into final position.
  876. * - `opacity` - Opacity of the placeholder
  877. * - `distance` - Distance a sortable must be dragged before sorting starts.
  878. *
  879. * ### Event Options
  880. *
  881. * - `start` - Event fired when sorting starts
  882. * - `sort` - Event fired during sorting
  883. * - `complete` - Event fired when sorting completes.
  884. *
  885. * @param array $options Array of options for the sortable. See above.
  886. * @return string Completed sortable script.
  887. * @access public
  888. */
  889. function sortable() {
  890. trigger_error(sprintf(__('%s does not have sortable() implemented', true), get_class($this)), E_USER_WARNING);
  891. }
  892. /**
  893. * Create a slider UI widget. Comprised of a track and knob.
  894. * Additional options may be supported by the library implementation.
  895. *
  896. * ### Options
  897. *
  898. * - `handle` - The id of the element used in sliding.
  899. * - `direction` - The direction of the slider either 'vertical' or 'horizontal'
  900. * - `min` - The min value for the slider.
  901. * - `max` - The max value for the slider.
  902. * - `step` - The number of steps or ticks the slider will have.
  903. * - `value` - The initial offset of the slider.
  904. *
  905. * ### Events
  906. *
  907. * - `change` - Fired when the slider's value is updated
  908. * - `complete` - Fired when the user stops sliding the handle
  909. *
  910. * @return string Completed slider script
  911. * @access public
  912. */
  913. function slider() {
  914. trigger_error(sprintf(__('%s does not have slider() implemented', true), get_class($this)), E_USER_WARNING);
  915. }
  916. /**
  917. * Serialize the form attached to $selector.
  918. * Pass `true` for $isForm if the current selection is a form element.
  919. * Converts the form or the form element attached to the current selection into a string/json object
  920. * (depending on the library implementation) for use with XHR operations.
  921. *
  922. * ### Options
  923. *
  924. * - `isForm` - is the current selection a form, or an input? (defaults to false)
  925. * - `inline` - is the rendered statement going to be used inside another JS statement? (defaults to false)
  926. *
  927. * @param array $options options for serialization generation.
  928. * @return string completed form serialization script
  929. * @access public
  930. */
  931. function serializeForm() {
  932. trigger_error(
  933. sprintf(__('%s does not have serializeForm() implemented', true), get_class($this)), E_USER_WARNING
  934. );
  935. }
  936. /**
  937. * Parse an options assoc array into an Javascript object literal.
  938. * Similar to object() but treats any non-integer value as a string,
  939. * does not include `{ }`
  940. *
  941. * @param array $options Options to be converted
  942. * @param array $safeKeys Keys that should not be escaped.
  943. * @return string Parsed JSON options without enclosing { }.
  944. * @access protected
  945. */
  946. function _parseOptions($options, $safeKeys = array()) {
  947. $out = array();
  948. $safeKeys = array_flip($safeKeys);
  949. foreach ($options as $key => $value) {
  950. if (!is_int($value) && !isset($safeKeys[$key])) {
  951. $value = $this->value($value);
  952. }
  953. $out[] = $key . ':' . $value;
  954. }
  955. sort($out);
  956. return join(', ', $out);
  957. }
  958. /**
  959. * Maps Abstract options to engine specific option names.
  960. * If attributes are missing from the map, they are not changed.
  961. *
  962. * @param string $method Name of method whose options are being worked with.
  963. * @param array $options Array of options to map.
  964. * @return array Array of mapped options.
  965. * @access protected
  966. */
  967. function _mapOptions($method, $options) {
  968. if (!isset($this->_optionMap[$method])) {
  969. return $options;
  970. }
  971. foreach ($this->_optionMap[$method] as $abstract => $concrete) {
  972. if (isset($options[$abstract])) {
  973. $options[$concrete] = $options[$abstract];
  974. unset($options[$abstract]);
  975. }
  976. }
  977. return $options;
  978. }
  979. /**
  980. * Prepare callbacks and wrap them with function ([args]) { } as defined in
  981. * _callbackArgs array.
  982. *
  983. * @param string $method Name of the method you are preparing callbacks for.
  984. * @param array $options Array of options being parsed
  985. * @param string $callbacks Additional Keys that contain callbacks
  986. * @return array Array of options with callbacks added.
  987. * @access protected
  988. */
  989. function _prepareCallbacks($method, $options, $callbacks = array()) {
  990. $wrapCallbacks = true;
  991. if (isset($options['wrapCallbacks'])) {
  992. $wrapCallbacks = $options['wrapCallbacks'];
  993. }
  994. unset($options['wrapCallbacks']);
  995. if (!$wrapCallbacks) {
  996. return $options;
  997. }
  998. $callbackOptions = array();
  999. if (isset($this->_callbackArguments[$method])) {
  1000. $callbackOptions = $this->_callbackArguments[$method];
  1001. }
  1002. $callbacks = array_unique(array_merge(array_keys($callbackOptions), (array)$callbacks));
  1003. foreach ($callbacks as $callback) {
  1004. if (empty($options[$callback])) {
  1005. continue;
  1006. }
  1007. $args = null;
  1008. if (!empty($callbackOptions[$callback])) {
  1009. $args = $callbackOptions[$callback];
  1010. }
  1011. $options[$callback] = 'function (' . $args . ') {' . $options[$callback] . '}';
  1012. }
  1013. return $options;
  1014. }
  1015. /**
  1016. * Conveinence wrapper method for all common option processing steps.
  1017. * Runs _mapOptions, _prepareCallbacks, and _parseOptions in order.
  1018. *
  1019. * @param string $method Name of method processing options for.
  1020. * @param array $options Array of options to process.
  1021. * @return string Parsed options string.
  1022. * @access protected
  1023. */
  1024. function _processOptions($method, $options) {
  1025. $options = $this->_mapOptions($method, $options);
  1026. $options = $this->_prepareCallbacks($method, $options);
  1027. $options = $this->_parseOptions($options, array_keys($this->_callbackArguments[$method]));
  1028. return $options;
  1029. }
  1030. /**
  1031. * Convert an array of data into a query string
  1032. *
  1033. * @param array $parameters Array of parameters to convert to a query string
  1034. * @return string Querystring fragment
  1035. * @access protected
  1036. */
  1037. function _toQuerystring($parameters) {
  1038. $out = '';
  1039. $keys = array_keys($parameters);
  1040. $count = count($parameters);
  1041. for ($i = 0; $i < $count; $i++) {
  1042. $out .= $keys[$i] . '=' . $parameters[$keys[$i]];
  1043. if ($i < $count - 1) {
  1044. $out .= '&';
  1045. }
  1046. }
  1047. return $out;
  1048. }
  1049. }
  1050. ?>