PageRenderTime 72ms CodeModel.GetById 39ms RepoModel.GetById 1ms app.codeStats 0ms

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

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