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