-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathexamples.php
More file actions
2851 lines (2837 loc) · 131 KB
/
examples.php
File metadata and controls
2851 lines (2837 loc) · 131 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php // -*- mode: web -*-
header("X-Powered-By: ");
require('utils.php');
$version = version();
?><!DOCTYPE HTML>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<meta charset="utf-8" />
<title>Examples for jQuery Terminal, Web Based Terminal</title>
<link rel="canonical" href="https://terminal.jcubic.pl/examples.php"/>
<meta name="author" content="Jakub T. Jankiewicz - jcubic@onet.pl"/>
<meta name="Description" content="This is a bunch of useful things that you can do with jQuery Terminal Emulator plugin. Live demos and source code likewise."/>
<meta name="keywords" content="jquery,terminal,interpreter,console,bash,history,authentication,ajax,server,client"/>
<link rel="shortcut icon" href="favicon.ico"/>
<link rel="alternate" type="application/rss+xml" title="Notification RSS" href="https://terminal.jcubic.pl/notification.rss"/>
<link href="https://fonts.googleapis.com/css?family=Droid+Sans+Mono&display=swap"
rel="stylesheet" type="text/css" media="print"
onload="this.media='all'" />
<script>if (typeof module === 'object') {window.module = module; module = undefined;}</script>
<script src="js/biwascheme.js"></script>
<!-- Other files -->
<link href="css/jquery-ui-1.8.7.custom.css" rel="stylesheet"/>
<script src="js/jquery-ui-1.8.7.custom.min.js"></script>
<script src="js/code.js"></script>
<script src="js/star_wars.js"></script>
<!-- Terminal Files -->
<script src="https://cdn.jsdelivr.net/gh/jcubic/static/js/wcwidth.js"></script>
<script src="js/jquery.terminal.js?<?= md5(file_get_contents('js/jquery.terminal.js')) ?>"></script>
<link href="css/jquery.terminal.min.css?<?= md5(file_get_contents('css/jquery.terminal.min.css')) ?>" rel="stylesheet"/>
<link rel="stylesheet" href="css/style.css?<?= md5(file_get_contents('css/style.css')) ?>"/>
<script src="js/dterm.js?<?= md5(file_get_contents('js/dterm.js')) ?>"></script>
<script>var Interpreter = BiwaScheme.Interpreter;</script>
<script src="js/biwascheme.func.js"></script>
<script src="js/jqbiwa.js"></script>
<script src="https://cdn.jsdelivr.net/npm/js-polyfills/keyboard.js"></script>
<script>if (window.module) module = window.module;</script>
<!--[if IE]>
<script src="https://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<meta property="og:locale" content="en_US"/>
<meta property="og:type" content="website"/>
<meta property="og:title" content="Examples for jQuery Terminal plugin"/>
<meta property="og:description" content="jQuery plugin for Command Line applications. Automatic JSON-RPC, custom object or a function. History, Authentication, Bash Shortcuts. Tab completion."/>
<meta property="og:url" content="https://terminal.jcubic.pl/examples.php"/>
<meta property="og:site_name" content="JQuery Terminal Emulator Plugin"/>
<meta property="og:image" content="https://terminal.jcubic.pl/signature.png"/>
<meta name="twitter:image" content="https://terminal.jcubic.pl/signature.png"/>
<meta name="twitter:image:alt" content="Main ASCII Art for jQuery Terminal"/>
<meta name="twitter:title" content="Examples for jQuery Terminal plugin"/>
<meta name="twitter:description" content="jQuery plugin for Command Line applications. Automatic JSON-RPC, custom object or a function. History, Authentication, Bash Shortcuts. Tab completion."/>
<meta name="twitter:card" content="summary_large_image"/>
<meta name="twitter:site" content="@jcubic"/>
<meta name="twitter:creator" content="@jcubic"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
</head>
<body>
<header id="main" role="presentation" aria-hidden="true"x><h1>jQuery Terminal Emulator Plugin</h1>
<a href="/"><pre id="sig">
<div class="big">
__ _____ ________ __
/ // _ /__ __ _____ ___ __ _/__ ___/__ ___ ______ __ __ __ ___ / /
__ / // // // // // _ // _// // / / // _ // _// // // \/ // _ \/ /
/ / // // // // // ___// / / // / / // ___// / / / / // // /\ // // / /__
\___//____ \\___//____//_/ _\_ / /_//____//_/ /_/ /_//_//_/ /_/ \__\_\___/
\/ /____/ <?=$version?>
</div>
<div class="medium">
__ ____ ________ __
/ // _ /__ ___/__ ___ ______ __ __ __ ___ / /
__ / // // / / // _ // _// // // \/ // _ \/ /
/ / // // / / // ___// / / / / // // /\ // // / /__
\___//____ \ /_//____//_/ /_/ /_//_//_/ /_/ \__\_\___/
\/ <?=$version?>
</div>
<div class="small">
__ ____ ________
/ // _ /__ ___/__ ___ ______
__ / // // / / // _ // _// /
/ / // // / / // ___// / / / / /
\___//____ \ /_//____//_/ /_/ /_/
\/ <?=$version?>
</div>
</pre><img src="signature.png"/><!-- for FB bigger then gihub ribbon --></a>
<pre class="separator">---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------</pre>
</header>
<nav>
<ul>
<li><a href="/#demo">Demo</a></li>
<li><a href="/documentation.php">Documentation</a></li>
<li><a href="/examples.php">Examples</a></li>
<li><a href="https://stackoverflow.com/questions/tagged/jquery-terminal">Q&A</a></li>
<li><a href="/#download">Download</a></li>
<li><a href="/#comments">Comments</a></li>
<li><a class="chat" href="https://gitter.im/jcubic/jquery.terminal">Chat</a></li>
<li><a href="https://github.com/sponsors/jcubic">Donate</a></li>
</ul>
</nav>
<a class="support-ribbon" href="https://support.jcubic.pl/"
style="position: fixed; top: 0; right: 0; z-index:1000">
<img style="border: 0;" src="https://terminal.jcubic.pl/support.svg"
alt="Get Paid Support">
</a>
<a href="https://github.com/jcubic/jquery.terminal" class="github-corner" aria-label="View source on GitHub"><svg width="80" height="80" viewBox="0 0 250 250" style="fill:#151513; color:#fff; position: fixed; top: 0; border: 0; left: 0; transform: scale(-1, 1);" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style></a>
<?php include('banner.php'); ?>
<section>
<article>
<header id="examples"><h1>Examples</h1></header>
<ul>
<li><a href="#json_rpc_demo">JSON-RPC with Simple authentication</a></li>
<li><a href="#jwt">JSON-RPC with JWT authentication</a></li>
<li><a href="#simple_ajax">Simple AJAX example</a></li>
<li><a href="#autocomplete">Autocomplete</a></li>
<li><a href="#csrf"><abbr title="Cross-Site Request Forgery">CSRF</abbr></a></li>
<li><a href="#syntax_highlight">SQL Syntax highlighter</a></li>
<li><a href="#tilda">Quake like terminal</a></li>
<li><a href="#dterm">Terminal in jQuery UI Dialog</a></li>
<li><a href="#multiple-interpreters">Multiple interpreters</a></li>
<li><a href="#starwars">Star Wars Animation</a></li>
<li><a href="#ask">Ask before executing a command</a></li>
<li><a href="#user-typing">Animation that emulate user typing</a></li>
<li><a href="#progress-bar">Progress bar animation</a></li>
<li><a href="#spinners">Spinners animation</a></li>
<li><a href="#less">Less bash command</a></li>
<li><a href="#pipe">Pipe operator</a></li>
<li><a href="#bash-history">Bash history commands</a></li>
<li><a href="#css-cursor">Smooth CSS3 cursor animation</a></li>
<li><a href="#virtual">Virtual Keyboard with Terminal</a></li>
<li><a href="#history">History API for commands</a></li>
<li><a href="#shell">Shell</a></li>
<li><a href="#different_look">Vintage, OS Like Terminals and 3D effects</a></li>
<li><a href="#404">404 Error Page</a></li>
<li><a href="#emoji">Emoji</a></li>
<li><a href="#questions">Create Settings object from questions (form)</a></li>
<li><a href="#terminal-widget">Terminal Widget</a></li>
<li><a href="#reactjs-terminal">ReactJS Terminal</a></li>
<li><a href="#electron-terminal">Electron Terminal</a></li>
<li><a href="#parenthesis">Balancing parenthesis</a></li>
<li><a href="#multiline">Multiline input</a></li>
<li><a href="#rouge">Rouge like game</a></li>
<li><a href="#confirm">Browser confirm replacement</a></li>
<li><a href="#newline">Echo without newline</a></li>
<li><a href="#ansi">ANSI artwork</a></li>
<li><a href="#figlet">Figlet ASCII art fonts</a></li>
<li><a href="#fontawesome">FontAwesome Icons</a></li>
<li><a href="#mobile">Mobile demos</a></li>
<li><a href="#codepen">Codepen Demos</a></li>
<li><a href="#wild">In the wild</a></li>
</ul>
</article>
<article id="json_rpc_demo">
<header><h2>JSON-RPC with Simple Authentication</h2></header>
<p>See <a title="JSON-RPC demo" href="rpc-demo.html">demo in action</a>. (If you want to copy code from examples click “toogle highlight” first)</p>
<p>Javascript code:</p>
<pre class="javascript">jQuery(function($) {
$('#term').terminal("json-rpc-service-demo.php", {
login: true,
greetings: "You are authenticated"});
});</pre>
<p>PHP code (in rpc_demo.php):</p>
<pre class="php"><?php
require('json_rpc.php');
class Demo {
static $login_documentation = "return auth token";
public function login($user, $passwd) {
if (strcmp($user, 'demo') == 0 &&
strcmp($passwd, 'demo') == 0) {
// If you need to handle more than one user you can
// create new token and save it in database
return md5($user . ":" . $passwd);
} else {
throw new Exception("Wrong Password");
}
}
static $ls_documentation = "list directory if token is" .
" valid";
public function ls($token, $path) {
if (strcmp(md5("demo:demo"), $token) == 0) {
if (preg_match("/\.\./", $path)) {
throw new Exception("No directory traversal Dude");
}
$base = preg_replace("/(.*\/).*/", "$1",
$_SERVER["SCRIPT_FILENAME"]);
$path = $base . ($path[0] != '/' ? "/" : "") . $path;
$dir = opendir($path);
while($name = readdir($dir)) {
$fname = $path."/".$name;
if (!is_dir($name) && !is_dir($fname)) {
$list[] = $name;
}
}
closedir($dir);
return $list;
} else {
throw new Exception("Access Denied");
}
}
static $whoami_documentation = "return user information";
public function whoami() {
return array(
"user-agent" => $_SERVER["HTTP_USER_AGENT"],
"your ip" => $_SERVER['REMOTE_ADDR'],
"referer" => $_SERVER["HTTP_REFERER"],
"request uri" => $_SERVER["REQUEST_URI"]);
}
}
handle_json_rpc(new Demo());
?></pre>
<p><strong>NOTE:</strong> If you use json_rpc.php file (which handle json-rpc) from the <a href="/#download">package</a> you have always help function which display all methods or documentation strings if you provide them.</p>
<p>If you want secure login you should generate random token in login JSON-RPC function, and store it in database or session.<br/>For example: md5(time()). You can also use <a href="https://en.wikipedia.org/wiki/Secure_Sockets_Layer">SSL</a> to make it more secured.</p>
<p>See <a title="JSON-RPC demo" href="rpc-demo.html">demo in action</a>. login is "demo" and password is "demo". Available command are "ls", "whoami", "help" and "help [rpc-method]"</p>
</article>
<article id="jwt">
<header><h2>JSON-RPC with JWT authentication</h2></header>
<p>See <a title="JWT Auth Demo" href="https://terminal.jcubic.pl/jwt/">demo in action</a>.</p>
<p>The full code is available on <a href="https://github.com/jcubic/php-terminal-jwt">GitHub</a></p>
<p>Javascript code:</p>
<pre class="javascript">function interceptor(req, res) {
if (res.error && res.error.message === 'Access token expired') {
// TODO: remove this echo
this.echo('Token expired: refreshing ...');
this.pause();
return new Promise(resolve => {
$.jrpc('service.php', 'refresh', [], data => {
const re = /Refresh token expired/;
if (data.error && data.error.message.match(re)) {
this.logout();
return resolve({...res, error: data.error});
}
const token = data.result;
this.set_token(token);
req.params[0] = token;
const { method, params } = req;
$.jrpc('service.php', method, params, message => {
this.resume();
resolve(message);
});
});
});
}
}
let term;
$(function() {
term = $('#term').terminal(['service.php', {
refresh() {
// this command will manually referesh the token
// you don't need this command, it's only for demo purpose
return new Promise(resolve => {
$.jrpc('service.php', 'refresh', [], (message) => {
this.set_token(message.result);
resolve();
});
});
}
}], {
login: true,
completion: true,
describe: false,
greetings: 'Welcome to JWT demo',
rpc: interceptor
});
});</pre>
<p>see <a href="https://github.com/jcubic/php-terminal-jwt/blob/master/service.php">PHP Code</a></p>
</article>
<article id="simple_ajax">
<header><h2>Simple AJAX example</h2></header>
<p>If you for some reason don't want to use JSON-RPC you can create interpreter that will echo ajax responses and simple php script.</p>
<pre class="javascript">$(function() {
$('body').terminal(function(command, term) {
term.pause();
$.post('script.php', {command: command}).then(function(response) {
term.echo(response).resume();
});
}, {
greetings: 'Simple php example'
});
});</pre>
<p>From version 1.0.0 you can simplify that code using:</p>
<pre class="javascript">$(function() {
$('body').terminal(function(command, term) {
return $.post('script.php', {command: command});
}, {
greetings: 'Simple php example'
});
});</pre>
<p><strong>NOTE:</strong> if you return a promise from interpreter it will call pause, wait for the response, then echo the response when it arrive and call resume.</p>
<pre class="php"><?php
if (isset($_POST['command'])) {
echo "you typed '" . $_POST['command'] . "'.";
}</pre>
<p>You can use different server side language instead of php.</p>
</article>
<article id="autocomplete">
<header><h2>Autocomplete</h2></header>
<p>Adding autocomplete to terminal is simple use complete option with array or function as in <a href="api_reference.php#completion">api documentation</a> or true value if you use JSON-RPC with <code>system.describe</code> or object as interpreter.</p>
<p>You can also create custom completion, for instance add, menu with items that you can click on that's added on keypress, From version 0.12.0 of the terminal there are two new api methods <code><a href="api_reference.php#complete">complete</a></code> and <code><a href="api_reference.php#before_cursor">before_cursor</a></code> that simplify the code.</p>
<p>From version 2.8.0 repo now includes the file that will add <strong>menu autocomplete automatically</strong>.</p>
<pre class="html">
<script src="https://unpkg.com/jquery.terminal/js/autocomplete_menu.js"></script>
</pre>
<p>The file will monkey patch the terminal and create new option for terminal. To use menu autocomplete you just need this:</p>
<pre class="javascript">$('body').terminal(function(command) {
}, {
autocompleteMenu: true,
completion: ['foo', 'bar', 'baz']
});</pre>
<p>The complition options is the same, it can call callback function 2 argument, or return a promise. The value need to be array of strings.</p>
<p>Below is first, original code that shows example, how to create autocomplete menu.</p>
<pre class="javascript">var ul;
var cmd;
var empty = {
options: [],
args: []
};
var commands = {
'get-command': {
options: ['name', 'age', 'description', 'address'],
args: ['clear']
},
'git': {
args: ['commit', 'push', 'pull'],
options: ['amend', 'hard', 'version', 'help']
},
'get-name': empty,
'get-age': empty,
'get-money': empty
};
var ul;
var term = $('body').terminal($.noop, {
onInit: function(term) {
var wrapper = term.cmd().find('.cursor').wrap('<span/>').parent()
.addClass('cmd-wrapper');
ul = $('<ul></ul>').appendTo(wrapper);
ul.on('click', 'li', function() {
term.insert($(this).text());
ul.empty();
});
},
keydown: function(e) {
var term = this;
// setTimeout because terminal is adding characters in keypress
// we use keydown because we need to prevent default action for
// tab and still execute custom code
setTimeout(function() {
ul.empty();
var command = term.get_command();
var name = command.match(/^([^\s]*)/)[0];
if (name) {
var word = term.before_cursor(true);
var regex = new RegExp('^' + $.terminal.escape_regex(word));
var list;
if (name == word) {
list = Object.keys(commands);
} else if (command.match(/\s/)) {
if (commands[name]) {
if (word.match(/^--/)) {
list = commands[name].options.map(function(option) {
return '--' + option;
});
} else {
list = commands[name].args;
}
}
}
if (word.length >= 2 && list) {
var matched = [];
for (var i=list.length; i--;) {
if (regex.test(list[i])) {
matched.push(list[i]);
}
}
var insert = false;
if (e.which == 9) {
insert = term.complete(matched);
}
if (matched.length && !insert) {
ul.hide();
for (var i=0; i<matched.length; ++i) {
var str = matched[i].replace(regex, '');
$('<li>' + str + '</li>').appendTo(ul);
}
ul.show();
}
}
}
}, 0);
if (e.which == 9) {
return false;
}
}
});</pre>
<p>See <a href="https://codepen.io/jcubic/pen/MJyYEx?editors=0110">demo in action</a>.</p>
</article>
<article id="csrf">
<header><h2><abbr title="Cross-Site Request Forgery">CSRF</abbr></h2></header>
<p>Example that add CSRF Protection to the terminal:</p>
<pre class="javascript">jQuery(function($) {
var CSRF_HEADER = "X-CSRF-TOKEN";
var csrfToken;
$('<div/>').appendTo('body').terminal("test.php", {
request: function(jxhr, request) {
if (csrfToken) {
jxhr.setRequestHeader(CSRF_HEADER, csrfToken);
}
},
response: function(jxhr, response) {
if (!response.error) {
csrfToken = jxhr.getResponseHeader(CSRF_HEADER);
}
},
width: 600,
height: 480,
});
});</pre>
<p>Note that this will break if you Open the app in more than one tab. To fix the issue you can use
my other library <a href="https://github.com/jcubic/sysend.js">sysend.js</a> and share the token.</p>
<pre class="javascript">jQuery(function($) {
var CSRF_HEADER = "X-CSRF-TOKEN";
var csrfToken;
sysend.on('csrfToken', function(token) {
csrfToken = token;
});
$('<div/>').appendTo('body').terminal("test.php", {
request: function(jxhr, request) {
if (csrfToken) {
jxhr.setRequestHeader(CSRF_HEADER, csrfToken);
}
sysend.broadcast('csrfToken', csrfToken);
},
response: function(jxhr, response) {
if (!response.error) {
csrfToken = jxhr.getResponseHeader(CSRF_HEADER);
}
},
width: 600,
height: 480,
});
});</pre>
</article>
<article id="syntax_highlight">
<header><h2>SQL Syntax highlighter</h2></header>
<p>Here is example to how to add syntax highlighting for mysql keywords</p>
<pre class="javascript">// mysql keywords
var uppercase = [
'ACCESSIBLE', 'ADD', 'ALL', 'ALTER', 'ANALYZE', 'AND', 'AS', 'ASC',
'ASENSITIVE', 'BEFORE', 'BETWEEN', 'BIGINT', 'BINARY', 'BLOB',
'BOTH', 'BY', 'CALL', 'CASCADE', 'CASE', 'CHANGE', 'CHAR',
'CHARACTER', 'CHECK', 'COLLATE', 'COLUMN', 'CONDITION',
'CONSTRAINT', 'CONTINUE', 'CONVERT', 'CREATE', 'CROSS',
'CURRENT_DATE', 'CURRENT_TIME', 'CURRENT_TIMESTAMP', 'CURRENT_USER',
'CURSOR', 'DATABASE', 'DATABASES', 'DAY_HOUR', 'DAY_MICROSECOND',
'DAY_MINUTE', 'DAY_SECOND', 'DEC', 'DECIMAL', 'DECLARE', 'DEFAULT',
'DELAYED', 'DELETE', 'DESC', 'DESCRIBE', 'DETERMINISTIC',
'DISTINCT', 'DISTINCTROW', 'DIV', 'DOUBLE', 'DROP', 'DUAL', 'EACH',
'ELSE', 'ELSEIF', 'ENCLOSED', 'ESCAPED', 'EXISTS', 'EXIT',
'EXPLAIN', 'FALSE', 'FETCH', 'FLOAT', 'FLOAT4', 'FLOAT8', 'FOR',
'FORCE', 'FOREIGN', 'FROM', 'FULLTEXT', 'GRANT', 'GROUP', 'HAVING',
'HIGH_PRIORITY', 'HOUR_MICROSECOND', 'HOUR_MINUTE', 'HOUR_SECOND',
'IF', 'IGNORE', 'IN', 'INDEX', 'INFILE', 'INNER', 'INOUT',
'INSENSITIVE', 'INSERT', 'INT', 'INT1', 'INT2', 'INT3', 'INT4',
'INT8', 'INTEGER', 'INTERVAL', 'INTO', 'IS', 'ITERATE', 'JOIN',
'KEY', 'KEYS', 'KILL', 'LEADING', 'LEAVE', 'LEFT', 'LIKE', 'LIMIT',
'LINEAR', 'LINES', 'LOAD', 'LOCALTIME', 'LOCALTIMESTAMP', 'LOCK',
'LONG', 'LONGBLOB', 'LONGTEXT', 'LOOP', 'LOW_PRIORITY',
'MASTER_SSL_VERIFY_SERVER_CERT', 'MATCH', 'MEDIUMBLOB', 'MEDIUMINT',
'MEDIUMTEXT', 'MIDDLEINT', 'MINUTE_MICROSECOND', 'MINUTE_SECOND',
'MOD', 'MODIFIES', 'NATURAL', 'NOT', 'NO_WRITE_TO_BINLOG', 'NULL',
'NUMERIC', 'ON', 'OPTIMIZE', 'OPTION', 'OPTIONALLY', 'OR', 'ORDER',
'OUT', 'OUTER', 'OUTFILE', 'PRECISION', 'PRIMARY', 'PROCEDURE',
'PURGE', 'RANGE', 'READ', 'READS', 'READ_WRITE', 'REAL',
'REFERENCES', 'REGEXP', 'RELEASE', 'RENAME', 'REPEAT', 'REPLACE',
'REQUIRE', 'RESTRICT', 'RETURN', 'REVOKE', 'RIGHT', 'RLIKE',
'SCHEMA', 'SCHEMAS', 'SECOND_MICROSECOND', 'SELECT', 'SENSITIVE',
'SEPARATOR', 'SET', 'SHOW', 'SMALLINT', 'SPATIAL', 'SPECIFIC',
'SQL', 'SQLEXCEPTION', 'SQLSTATE', 'SQLWARNING', 'SQL_BIG_RESULT',
'SQL_CALC_FOUND_ROWS', 'SQL_SMALL_RESULT', 'SSL', 'STARTING',
'STRAIGHT_JOIN', 'TABLE', 'TERMINATED', 'THEN', 'TINYBLOB',
'TINYINT', 'TINYTEXT', 'TO', 'TRAILING', 'TRIGGER', 'TRUE', 'UNDO',
'UNION', 'UNIQUE', 'UNLOCK', 'UNSIGNED', 'UPDATE', 'USAGE', 'USE',
'USING', 'UTC_DATE', 'UTC_TIME', 'UTC_TIMESTAMP', 'VALUES',
'VARBINARY', 'VARCHAR', 'VARCHARACTER', 'VARYING', 'WHEN', 'WHERE',
'WHILE', 'WITH', 'WRITE', 'XOR', 'YEAR_MONTH', 'ZEROFILL'];
var keywords = uppercase.concat(uppercase.map(function(keyword) {
return keyword.toLowerCase();
}));
$.terminal.defaults.formatters.push(function(string) {
return string.split(/((?:\s|&nbsp;)+)/).map(function(string) {
if (keywords.indexOf(string) != -1) {
return '[[b;white;]' + string + ']';
} else {
return string;
}
}).join('');
});</pre>
<p>If you want to add formatting for different sql command and not for main interpterer you can use stack of formatters. It require version >=1.0 that introduce extra option for interpreter. The example will work for any number of nested interpreters even you call push new in your mysql command.</p>
<pre class="javascript">// this regex will allow mixed case like SeLect
var re = new RegExp('^(' + uppercase.join('|') + ')$', 'i');
function mysql_formatter(string) {
return string.split(/((?:\s|&nbsp;)+)/).map(function(string) {
if (re.test(string)) {
return '[[b;white;]' + string + ']';
} else {
return string;
}
}).join('');
}
var formatters = [$.terminal.defaults.formatters];
$('body').terminal(function(command, term) {
if (command.match(/^\s*mysql\s*$/)) {
term.push(function(query) {
term.echo('executing ' + query, {formatters: false});
}, {
prompt: 'mysql> ',
name: 'mysql',
// extra property saved in interpreter
formatters: [mysql_formatter],
completion: keywords
});
}
}, {
onPush: function(before, after) {
$.terminal.defaults.formatters = after.formatters || [];
formatters.push($.terminal.defaults.formatters);
},
onPop: function(before, after) {
formatters.pop();
if (formatters.length > 0) {
$.terminal.defaults.formatters = formatters[formatters.length-1];
}
}
});</pre>
</article>
<article id="tilda">
<header><h2>Quake like terminal</h2></header>
<p>See <a href="tilda-demo.html">demo</a>.</p>
<p>Below is code for small plugin called tilda.</p>
<pre class="javascript">(function($) {
$.fn.tilda = function(eval, options) {
if ($('body').data('tilda')) {
return $('body').data('tilda').terminal;
}
this.addClass('tilda');
options = options || {};
eval = eval || function(command, term) {
term.echo("you don't set eval for tilda");
};
var settings = {
prompt: 'tilda> ',
name: 'tilda',
height: 100,
enabled: false,
greetings: 'Quake like console',
keypress: function(e) {
if (e.which == 96) {
return false;
}
}
};
if (options) {
$.extend(settings, options);
}
this.append('<div class="td"></div>');
var self = this;
self.terminal = this.find('.td').terminal(eval,
settings);
var focus = false;
$(document.documentElement).keypress(function(e) {
if (e.charCode == 96) {
self.slideToggle('fast');
self.terminal.command_line.set('');
self.terminal.focus(focus = !focus);
}
});
$('body').data('tilda', this);
this.hide();
return self;
};
})(jQuery);</pre>
<p>See <a href="tilda-demo.html">demo</a>.</p>
</article>
<article>
<header id="dterm"><h2>Terminal in jQuery UI Dialog</h2></header>
<p>Bellow is small plugin dterm.</p>
<pre class="javascript">(function($) {
$.extend_if_has = function(desc, source, array) {
for (var i=array.length;i--;) {
if (typeof source[array[i]] != 'undefined') {
desc[array[i]] = source[array[i]];
}
}
return desc;
};
$.fn.dterm = function(interpeter, options) {
var defaults = Object.keys($.terminal.defaults);
var op = $.extend_if_has({}, options, defaults);
var term = this.append('<div/>').
terminal(interpeter, op);
if (!options.title) {
options.title = 'JQuery Terminal Emulator';
}
if (options.logoutOnClose) {
options.close = function(e, ui) {
term.logout();
term.clear();
};
} else {
options.close = function(e, ui) {
term.focus(false);
};
}
var self = this;
if (window.IntersectionObserver) {
var visibility_observer = new IntersectionObserver(function() {
if (self.is(':visible')) {
terminal.enable().resize();
} else {
self.disable();
}
}, {
root: document.body
});
visibility_observer.observe(terminal[0]);
}
this.dialog($.extend({}, options, {
resizeStop: function() {
var content = self.find('.ui-dialog-content');
terminal.resize(content.width(), content.height());
},
open: function(event, ui) {
if (!window.IntersectionObserver) {
setTimeout(function() {
terminal.enable().resize();
}, 100);
}
if (typeof options.open == 'function') {
options.open(event, ui);
}
},
show: 'fade',
closeOnEscape: false
}));
self.terminal = terminal;
return self;
};
})(jQuery);</pre>
<p id="biwascheme"><strong>Demo Scheme interpreter inside JQuery UI Dialog.</strong></p>
<p>Click on button to <button id="open_term">open dialog</button> with scheme interpreter inside UI Dialog.</p>
<p><strong>Hint:</strong> you can use JQuery from scheme. There is defined $ function and functions for all jquery object methods, they names start with coma and they always return jquery object so you can do chaining.</p>
<p><strong>NOTE:</strong> you should include jQuery Terminal css file after jQuery UI one otherwise you will have white text in terminal, insided of gray.</p>
<p>Interpreter allow to use <strong>multiline expressions</strong>. When you type not finished S-Expresion it change the prompt with set_prompt, contatenate current command with previous not finished expression and when you close last parentises end press enter it evaluate whole expression.</p>
<p>If you want to call:</p>
<pre class="javascript">$("body").css("background-color", "black");</pre>
<p>use</p>
<!-- only for syntax highlight -->
<pre class="javascript">(.css ($ "body") "background-color" "black")</pre>
<p>To attach event you can use lambda expressions.</p>
<pre class="javascript">(.click ($ ".terminal") (lambda () (display "click")))</pre>
<p>this will attach click event to terminal.</p>
<div id="dialogterm"></div>
</article>
<article id="multiple-interpreters">
<header><h2>Multiple interpreters</h2></header>
<p>All interpreters are stored on the stack which which you can manipulate with terminal methods pop an push.</p>
<p>See <a title="JQuery Terminal Emulator Demo" href="multiple-interpreters-demo.html">demo</a>.</p>
<p>In belowed code there are defied three commands:</p>
<ul>
<li>js - which run javascript interpreter</li>
<li>mysql - which call json-rpc service to execute mysql commands.</li>
<li>test - it display "pong" if you type "ping" </li>
</ul>
<pre class="javascript">jQuery(function($) {
$('html').terminal(function(cmd, term) {
if (cmd == 'help') {
term.echo("available commands are mysql, js, test");
} else if (cmd == 'test'){
term.push(function(cmd, term) {
if (command == 'help') {
term.echo('type "ping" it will display "pong"');
} else if (cmd == 'ping') {
term.echo('pong');
} else {
term.echo('unknown command "' + cmd + '"');
}
}, {
prompt: 'test> ',
name: 'test'});
} else if (command == "js") {
term.push(function(command, term) {
var result = window.eval(command);
if (result != undefined) {
term.echo(String(result));
}
}, {
name: 'js',
prompt: 'js> '});
} else if (command == 'mysql') {
term.push(function(command, term) {
term.pause();
//$.jrpc is helper function which
//creates json-rpc request
$.jrpc("mysql-rpc-demo.php",
"query",
[command],
function(data) {
term.resume();
if (data.error) {
if (data.error.error && data.error.error.message) {
term.error(data.error.error.message); // php error
} else {
term.error(data.error.message); // json rpc error
}
} else {
if (typeof data.result == 'boolean') {
term.echo(data.result ?
'success' :
'fail');
} else {
var len = data.result.length;
for(var i=0;i<len; ++i) {
term.echo(data.result[i].join(' | '));
}
}
}
},
function(xhr, status, error) {
term.error('[AJAX] ' + status +
' - Server reponse is: \n' +
xhr.responseText);
term.resume();
}); // rpc call
}, {
greetings: "This is example of using mysql"+
" from terminal\n you are allowed to exe"+
"cute: select, insert, update and delete"+
" from/to table:\n table test(integer_"+
"value integer, varchar_value varchar(255))",
prompt: "mysql> "});
} else {
term.echo("unknow command " + command);
}
}, {
greetings: "multiple terminals demo use help"+
" to see available commands"
});});</pre>
<p>If you want to display ascii table like real mysql command, take a look at <a href="https://github.com/jcubic/leash/blob/1843d8f4dd9f2e4696f2086184c23624027acb9f/leash-src.js#L511">asci_table function in leash project</a>, it use <a href="https://github.com/timoxley/wcwidth">wcwidth</a> to calcuate the width of the characters but if you don't care about chenese characters you can replace it with <code>string.length</code>.</p>
<p>PHP code for mysql service: </p>
<pre class="php"><?php
require('json_rpc.php');
$conn = mysql_connect('localhost', 'user', 'password');
mysql_select_db('database');
class MysqlDemo {
public function query($query) {
if (preg_match("/create|drop/", $query)) {
throw new Exception("Sorry you are not allowed to ".
"execute '" . $query . "'");
}
if (!preg_match("/(select.*from *test|insert *into *".
"test.*|delete *from *test|update *t".
"est)/", $query)) {
throw new Exception("Sorry you can't execute '" .
$query . "' you are only allow".
"ed to select, insert, delete ".
"or update 'test' table");
}
if ($res = mysql_query($query)) {
if ($res === true) {
return true;
}
if (mysql_num_rows($res) > 0) {
while ($row = mysql_fetch_row($res)) {
$result[] = $row;
}
return $result;
} else {
return array();
}
} else {
throw new Exception("MySQL Error: ".mysql_error());
}
}
}
handle_json_rpc(new MysqlDemo());
?></pre>
<p>See <a title="JQuery Terminal Emulator Demo" href="multiple-interpreters-demo.html">demo</a>.</p>
</article>
<article id="starwars">
<header><h2>Star Wars Animation</h2></header>
<p>This is Star Wars ASCIIMation created by Simon Jansen <br/><a href="https://www.asciimation.co.nz/">https://www.asciimation.co.nz/</a></p>
<div id="starwarsterm" style="--rows: 14; --cols: 67"></div>
<pre class="javascript">$(function() {
var frames = [];
var LINES_PER_FRAME = 14;
var DELAY = 67;
//star_wars is array of lines from 'js/star_wars.js'
var lines = star_wars.length;
for (var i=0; i<lines; i+=LINES_PER_FRAME) {
frames.push(star_wars.slice(i, i+LINES_PER_FRAME));
}
var stop = false;
//to show greetings after clearing the terminal
function greetings(term) {
term.echo('STAR WARS ASCIIMACTION\n'+
'Simon Jansen (C) 1997 - 2008\n'+
'www.asciimation.co.nz\n\n'+
'type "play" to start animation, '+
'press CTRL+D to stop');
}
function play(term, delay) {
var i = 0;
var next_delay;
if (delay == undefined) {
delay = DELAY;
}
function display() {
if (i == frames.length) {
i = 0;
}
term.clear();
if (frames[i][0].match(/[0-9]+/)) {
next_delay = frames[i][0] * delay;
} else {
next_delay = delay;
}
term.echo(frames[i++].slice(1).join('\n')+'\n');
if (!stop) {
setTimeout(display, next_delay);
} else {
term.clear();
greetings(term);
i = 0;
}
}
display();
}
$('#starwarsterm').terminal(function(command, term){
if (command == 'play') {
term.pause();
stop = false;
play(term);
}
}, {
width: 500,
height: 230,
prompt: 'starwars> ',
greetings: null,
onInit: function(term) {
greetings(term);
},
keypress: function(e, term) {
if (e.which == 100 && e.ctrlKey) {
stop = true;
term.resume();
return false;
}
}
});
});</pre>
</article>
<article id="ask">
<header><h2>Ask before executing a command</h2></header>
<p>Someone ask me how to create, command that ask users before executing, and here is the code, it will keep asking until eather yes or no will be entered (or short y/n).</p>
<pre class="javascript">$('#term').terminal(function(command, term) {
if (command == 'foo') {
var history = term.history();
history.disable();
term.push(function(command) {
if (command.match(/^(y|yes)$/i)) {
term.echo('execute your command here');
term.pop();
history.enable();
} else if (command.match(/^(n|no)$/i)) {
term.pop();
history.enable();
}
}, {
prompt: 'Are you sure? '
});
}
});</pre>
</article>
<article id="user-typing">
<header><h2>Animation that emulate user typing</h2></header>
<p><strong>NOTE:</strong> in version 2.24.0 typing animation was added to the library. No animate all you have to do is:</p>
<pre class="javascript">term.typing('echo', 100, 'Hello', function() { });
term.typing('prompt', 100, 'name: ', function() {
});
</pre>
<p>The function also return a promise so you can use return value instead of a callback function.</p>
<p>Someone else asked if it's posible to create animation like user typing. Here is the code that emulate user typing on initialization of the terminal and before every ajax call, which can finish after animation.</p>
<div class="term"></div>
<pre class="javascript">$(function() {
var anim = false;
function typed(finish_typing) {
return function(term, message, delay, finish) {
anim = true;
var prompt = term.get_prompt();
var c = 0;
if (message.length > 0) {
term.set_prompt('');
var new_prompt = '';
var interval = setInterval(function() {
var chr = $.terminal.substring(message, c, c+1);
new_prompt += chr;
term.set_prompt(new_prompt);
c++;
if (c == length(message)) {
clearInterval(interval);
// execute in next interval
setTimeout(function() {
// swap command with prompt
finish_typing(term, message, prompt);
anim = false
finish && finish();
}, delay);
}
}, delay);
}
};
}
function length(string) {
string = $.terminal.strip(string);
return $('<span>' + string + '</span>').text().length;
}
var typed_prompt = typed(function(term, message, prompt) {
term.set_prompt(message + ' ');
});
var typed_message = typed(function(term, message, prompt) {
term.echo(message)
term.set_prompt(prompt);
});
$('body').terminal(function(cmd, term) {
var finish = false;
var msg = "Wait I'm executing ajax call";
term.set_prompt('> ');
typed_message(term, msg, 200, function() {
finish = true;
});
var args = {command: cmd};
$.get('commands.php', args, function(result) {
(function wait() {
if (finish) {
term.echo(result);
} else {
setTimeout(wait, 500);
}
})();
});
}, {
name: 'xxx',
greetings: null,
width: 500,
height: 300,
onInit: function(term) {
// first question
var msg = "Wellcome to my terminal";
typed_message(term, msg, 200, function() {
typed_prompt(term, "what's your name:", 100);
});
},
keydown: function(e) {
//disable keyboard when animating
if (anim) {
return false;
}
}
});
});</pre>
</article>
<article id="progress-bar">
<header><h2>Progress bar animation</h2></header>
<p>You can test it by executing command `progress 30`.</p>
<div class="term"></div>
<p>Here is the code for progres bar animation:</p>
<pre class="javascript">jQuery(function($) {
function progress(percent, width) {
var size = Math.round(width*percent/100);
var left = '', taken = '', i;
for (i=size; i--;) {
taken += '=';
}
if (taken.length > 0) {
taken = taken.replace(/=$/, '>');
}
for (i=width-size; i--;) {
left += ' ';
}