PageRenderTime 48ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

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

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