-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathWPide.php
executable file
·2023 lines (1501 loc) · 80.5 KB
/
WPide.php
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
/*
Plugin Name: WPide
Plugin URI: https://github.com/WPsites/WPide
Description: WordPress code editor with auto completion of both WordPress and PHP functions with reference, syntax highlighting, line numbers, tabbed editing, automatic backup.
Version: 2.4.0
Author: Simon @ WPsites
Author URI: http://www.wpsites.co.uk
*/
// Exit if accessed directly
if ( !defined( 'ABSPATH' ) ) exit;
if ( !class_exists( 'wpide' ) ) :
class wpide
{
public $site_url, $plugin_url, $git, $git_repo_path;
private $menu_hook;
function __construct() {
//add WPide to the menu
add_action( 'admin_menu', array( &$this, 'add_my_menu_page' ) );
add_action( 'admin_head', array( &$this, 'add_my_menu_icon' ) );
//hook for processing incoming image saves
if ( isset($_GET['wpide_save_image']) ){
//force local file method for testing - you could force other methods 'direct', 'ssh', 'ftpext' or 'ftpsockets'
$this->override_fs_method('direct');
add_action('admin_init', array( &$this, 'wpide_save_image') );
}
add_action( 'admin_init', array( &$this, 'setup_hooks' ) );
$this->site_url = get_bloginfo('url');
}
/**
* The main WPide loader (PHP4 compatable)
*
* @uses wpide::__construct() Setup the globals needed
*/
public function wpide() {
$this->__construct();
}
public function override_fs_method($method = 'direct'){
if ( defined('FS_METHOD') ){
define('WPIDE_FS_METHOD_FORCED_ELSEWHERE', FS_METHOD); //make a note of the forced method
}else{
define('FS_METHOD', $method); //force direct
}
}
public function setup_hooks() {
// force local file method until I've worked out how to implement the other methods
// main problem being password wouldn't/isn't saved between requests
// you could force other methods 'direct', 'ssh', 'ftpext' or 'ftpsockets'
$this->override_fs_method('direct');
// Uncomment any of these calls to add the functionality that you need.
// Will only enqueue on WPide page
add_action('admin_print_scripts-' . $this->menu_hook, array( &$this, 'add_admin_js' ) );
add_action('admin_print_styles-' . $this->menu_hook, array( &$this, 'add_admin_styles' ) );
add_action('admin_print_footer_scripts', array( &$this, 'print_find_dialog' ) );
add_action('admin_print_footer_scripts', array( &$this, 'print_settings_dialog' ) );
//setup jqueryFiletree list callback
add_action('wp_ajax_jqueryFileTree', array( &$this, 'jqueryFileTree_get_list' ) );
//setup ajax function to get file contents for editing
add_action('wp_ajax_wpide_get_file', array( &$this, 'wpide_get_file' ) );
//setup ajax function to save file contents and do automatic backup if needed
add_action('wp_ajax_wpide_save_file', array( &$this, 'wpide_save_file' ) );
//setup ajax function to rename file/folder
add_action('wp_ajax_wpide_rename_file', array( &$this, 'wpide_rename_file' ) );
//setup ajax function to delete file/folder
add_action('wp_ajax_wpide_delete_file', array( &$this, 'wpide_delete_file' ) );
//setup ajax function to handle upload
add_action('wp_ajax_wpide_upload_file', array( &$this, 'wpide_upload_file' ) );
//setup ajax function to handle download
add_action('wp_ajax_wpide_download_file', array( &$this, 'wpide_download_file' ) );
//setup ajax function to unzip file
add_action('wp_ajax_wpide_unzip_file', array( &$this, 'wpide_unzip_file' ) );
//setup ajax function to zip file
add_action('wp_ajax_wpide_zip_file', array( &$this, 'wpide_zip_file' ) );
//setup ajax function to create new item (folder, file etc)
add_action('wp_ajax_wpide_create_new', array( &$this, 'wpide_create_new' ) );
//setup ajax function to show local git repo changes
add_action('wp_ajax_wpide_git_status', array( &$this, 'git_status' ) );
//setup ajax function to show diff
add_action('wp_ajax_wpide_git_diff', array( &$this, 'git_diff' ) );
//setup ajax function to commit changes
add_action('wp_ajax_wpide_git_commit', array( &$this, 'git_commit' ) );
//setup ajax function to view the git log
add_action('wp_ajax_wpide_git_log', array( &$this, 'git_log' ) );
//setup ajax function to initiate a git repo
add_action('wp_ajax_wpide_git_init', array( &$this, 'git_init' ) );
//setup ajax function to clone a remote
add_action('wp_ajax_wpide_git_clone', array( &$this, 'git_clone' ) );
//setup ajax function to push to remote
add_action('wp_ajax_wpide_git_push', array( &$this, 'git_push' ) );
//setup ajax function to view/generate ssh key and known host file
add_action('wp_ajax_wpide_git_ssh_gen', array( &$this, 'git_ssh_gen' ) );
//setup ajax function to create new item (folder, file etc)
add_action('wp_ajax_wpide_image_edit_key', array( &$this, 'wpide_image_edit_key' ) );
//setup ajax function for startup to get some debug info, checking permissions etc
add_action('wp_ajax_wpide_startup_check', array( &$this, 'wpide_startup_check' ) );
//add a warning when navigating away from WPide
//it has to go after WordPress scripts otherwise WP clears the binding
// This has been implemented in load-editor.js
// add_action('admin_print_footer_scripts', array( &$this, 'add_admin_nav_warning' ), 99 );
// Add body class to collapse the wp sidebar nav
add_filter('admin_body_class', array( &$this, 'hide_wp_sidebar_nav' ), 11);
//hide the update nag
add_action('admin_menu', array( &$this, 'hide_wp_update_nag' ));
}
public function hide_wp_sidebar_nav($classes) {
global $hook_suffix;
if ( apply_filters( 'wpide_sidebar_folded', $hook_suffix === $this->menu_hook ) ) {
return str_replace("auto-fold", "", $classes) . ' folded';
}
}
public function hide_wp_update_nag() {
remove_action( 'admin_notices', 'update_nag', 3 );
}
public static function add_admin_nav_warning()
{
?>
<script type="text/javascript">
jQuery(document).ready(function($) {
window.onbeforeunload = function() {
return 'You are attempting to navigate away from WPide. Make sure you have saved any changes made to your files otherwise they will be forgotten.' ;
}
});
</script>
<?php
}
public static function add_admin_js(){
$plugin_path = plugin_dir_url( __FILE__ );
//include file tree
wp_enqueue_script('jquery-file-tree', plugins_url("jqueryFileTree.js", __FILE__ ) );
//include ace
wp_enqueue_script('ace', plugins_url("js/ace-1.2.0/ace.js", __FILE__ ) );
//include ace modes for css, javascript & php
wp_enqueue_script('ace-mode-css', $plugin_path . 'js/ace-1.2.0/mode-css.js');
wp_enqueue_script('ace-mode-less', $plugin_path . 'js/ace-1.2.0/mode-less.js');
wp_enqueue_script('ace-mode-javascript', $plugin_path . 'js/ace-1.2.0/mode-javascript.js');
wp_enqueue_script('ace-mode-php', $plugin_path . 'js/ace-1.2.0/mode-php.js');
//include ace theme
wp_enqueue_script('ace-theme', plugins_url("js/ace-1.2.0/theme-dawn.js", __FILE__ ) );//ambiance looks really nice for high contrast
// wordpress-completion tags
wp_enqueue_script('wpide-wordpress-completion', plugins_url("js/autocomplete/wordpress.js", __FILE__ ) );
// php-completion tags
wp_enqueue_script('wpide-php-completion', plugins_url("js/autocomplete/php.js", __FILE__ ) );
// load editor
wp_enqueue_script('wpide-load-editor', plugins_url("js/load-editor.js", __FILE__ ) );
// load filetree menu
wp_enqueue_script('wpide-load-filetree-menu', plugins_url("js/load-filetree-menu.js", __FILE__ ) );
// load autocomplete dropdown
wp_enqueue_script('wpide-dd', plugins_url("js/jquery.dd.js", __FILE__ ) );
// load jquery ui
wp_enqueue_script('jquery-ui', plugins_url("js/jquery-ui-1.9.2.custom.min.js", __FILE__ ), array('jquery'), '1.9.2');
// load color picker
wp_enqueue_script('ImageColorPicker', plugins_url("js/ImageColorPicker.js", __FILE__ ), array('jquery'), '0.3');
}
public static function add_admin_styles(){
//main wpide styles
wp_register_style( 'wpide_style', plugins_url('wpide.css', __FILE__) );
wp_enqueue_style( 'wpide_style' );
//filetree styles
wp_register_style( 'wpide_filetree_style', plugins_url('jqueryFileTree.css', __FILE__) );
wp_enqueue_style( 'wpide_filetree_style' );
//autocomplete dropdown styles
wp_register_style( 'wpide_dd_style', plugins_url('dd.css', __FILE__) );
wp_enqueue_style( 'wpide_dd_style' );
//jquery ui styles
wp_register_style( 'wpide_jqueryui_style', plugins_url('css/flick/jquery-ui-1.8.20.custom.css', __FILE__) );
wp_enqueue_style( 'wpide_jqueryui_style' );
}
public static function jqueryFileTree_get_list() {
//check the user has the permissions
check_admin_referer('plugin-name-action_wpidenonce');
if ( !current_user_can('edit_themes') )
wp_die('<p>'.__('You do not have sufficient permissions to edit templates for this site. SORRY').'</p>');
//setup wp_filesystem api
global $wp_filesystem;
$url = wp_nonce_url('admin.php?page=wpide','plugin-name-action_wpidenonce');
$form_fields = null; // for now, but at some point the login info should be passed in here
if (false === ($creds = request_filesystem_credentials($url, FS_METHOD, false, false, $form_fields) ) ) {
// no credentials yet, just produced a form for the user to fill in
return true; // stop the normal page form from displaying
}
if ( ! WP_Filesystem($creds) )
return false;
$_POST['dir'] = urldecode($_POST['dir']);
$root = apply_filters( 'wpide_filesystem_root', WP_CONTENT_DIR );
if( $wp_filesystem->exists($root . $_POST['dir']) ) {
$files = $wp_filesystem->dirlist($root . $_POST['dir']);
echo "<ul class=\"jqueryFileTree\" style=\"display: none;\">";
if( count($files) > 0 ) {
//build seperate arrays for folders and files
$dir_array = array();
$file_array = array();
foreach( $files as $file => $file_info ) {
if( $file != '.' && $file != '..' && $file_info['type']=='d' ) {
$file_string = strtolower( preg_replace("[._-]", "", $file) );
$dir_array[$file_string] = $file_info;
}elseif ( $file != '.' && $file != '..' && $file_info['type']=='f' ){
$file_string = strtolower( preg_replace("[._-]", "", $file) );
$file_array[$file_string] = $file_info;
}
}
//shot those arrays
ksort($dir_array);
ksort($file_array);
// All dirs
foreach( $dir_array as $file => $file_info ) {
echo "<li class=\"directory collapsed\" draggable=\"true\"><a href=\"#\" rel=\"" . htmlentities($_POST['dir'] . $file_info['name']) . "/\" draggable=\"false\">" . htmlentities($file_info['name']) . "</a></li>";
}
// All files
foreach( $file_array as $file => $file_info ) {
$ext = preg_replace('/^.*\./', '', $file_info['name']);
echo "<li class=\"file ext_$ext\" draggable=\"true\"><a href=\"#\" rel=\"" . htmlentities($_POST['dir'] . $file_info['name']) . "\" draggable=\"false\">" . htmlentities($file_info['name']) . "</a></li>";
}
}
//output toolbar for creating new file, folder etc
echo "<li class=\"create_new\"><a class='new_directory' title='Create a new directory here.' href=\"#\" rel=\"{type: 'directory', path: '" . htmlentities($_POST['dir']) . "'}\"></a> <a class='new_file' title='Create a new file here.' href=\"#\" rel=\"{type: 'file', path: '" . htmlentities($_POST['dir']) . "'}\"></a><br style='clear:both;' /></li>";
echo "</ul>";
}
die(); // this is required to return a proper result
}
public static function wpide_get_file() {
//check the user has the permissions
check_admin_referer('plugin-name-action_wpidenonce');
if ( !current_user_can('edit_themes') )
wp_die('<p>'.__('You do not have sufficient permissions to edit templates for this site. SORRY').'</p>');
//setup wp_filesystem api
global $wp_filesystem;
$url = wp_nonce_url('admin.php?page=wpide','plugin-name-action_wpidenonce');
$form_fields = null; // for now, but at some point the login info should be passed in here
if (false === ($creds = request_filesystem_credentials($url, FS_METHOD, false, false, $form_fields) ) ) {
// no credentials yet, just produced a form for the user to fill in
return true; // stop the normal page form from displaying
}
if ( ! WP_Filesystem($creds) )
return false;
$root = apply_filters( 'wpide_filesystem_root', WP_CONTENT_DIR );
$file_name = $root . stripslashes($_POST['filename']);
echo $wp_filesystem->get_contents($file_name);
die(); // this is required to return a proper result
}
public function git_ssh_gen(){
//errors need to be on while experimental
error_reporting(E_ALL);
ini_set("display_errors", 1);
$gitpath = preg_replace("#/$#", "", sanitize_text_field($_POST['sshpath']) );
//create the folder if doesn't exist
if (! file_exists($gitpath) ){
mkdir( $gitpath, 0700);
}
//create known hosts if doesn't exist
if (! file_exists($gitpath . "/known_hosts") ){
touch( $gitpath . "/known_hosts" );
chmod( $gitpath . "/known_hosts", 0700 );
}
//create keys if not exist
if (! file_exists($gitpath . "/id_rsa") || ! file_exists($gitpath . "/id_rsa.pub") ){
set_include_path(get_include_path() . PATH_SEPARATOR . plugin_dir_path(__FILE__) . 'git/phpseclib');
include('Crypt/RSA.php');
$rsa = new Crypt_RSA();
$rsa->setPublicKeyFormat(CRYPT_RSA_PUBLIC_FORMAT_OPENSSH);
extract($rsa->createKey()); // == $rsa->createKey(1024) where 1024 is the key size - $privatekey and $publickey
//create private key
file_put_contents($gitpath . "/id_rsa", $privatekey);
chmod( $gitpath . "/id_rsa", 0700 );
//create public key
file_put_contents($gitpath . "/id_rsa.pub", $publickey);
chmod( $gitpath . "/id_rsa.pub", 0700 );
}
//return public key
echo "\n\n". file_get_contents( $gitpath . "/id_rsa.pub" ) ."\n\n";
die();
}
public function git_open_repo(){
//errors need to be on while experimental
error_reporting(E_ALL);
ini_set("display_errors", 1);
require_once('git/autoload.php.dist');
$root = apply_filters( 'wpide_filesystem_root', WP_CONTENT_DIR ) . "/";
//check repo path entered or die
if ( !strlen($_POST['gitpath']) )
die("Error: Path to your git repository is required! (see settings)");
$this->git_repo_path = $root . sanitize_text_field( $_POST['gitpath'] );
$gitbinary = sanitize_text_field( stripslashes($_POST['gitbinary']) );
/*
if ( $gitbinary==="I'll guess.." ){ //the binary path
$thebinary = TQ\Git\Cli\Binary::locateBinary();
$this->git = TQ\Git\Repository\Repository::open($this->git_repo_path, new TQ\Git\Cli\Binary( $thebinary ), 0755 );
}else{
$thebinary = $_POST['gitbinary'];
$this->git = TQ\Git\Repository\Repository::open($this->git_repo_path, new TQ\Git\Cli\Binary( $thebinary ), 0755 );
}
*/
}
public function git_status() {
//check the user has the permissions
check_admin_referer('plugin-name-action_wpidenonce');
if ( !current_user_can('edit_themes') )
wp_die('<p>'.__('You do not have sufficient permissions to edit templates for this site. SORRY').'</p>');
$this->git_open_repo(); // make sure git repo is open
//echo branch
$branch = $this->git->getCurrentBranch();
echo "<p><strong>Current branch:</strong> " . $branch . "</p>";
// [0] => Array
//(
// [file] => WPide.php
// [x] =>
// [y] => M
// [renamed] =>
//)
$status = $this->git->getStatus();
$i=0;//row counter
if ( count($status) ){
//echo out rows of staged files
foreach ($status as $item){
echo "<div class='gitfilerow ". ($i % 2 != 0 ? "light" : "") ."'><span class='filename'>{$item['file']}</span> <input type='checkbox' name='". str_replace("=", '_', base64_encode($item['file']) ) ."' value='". base64_encode($item['file']) ."' checked />
<a href='". base64_encode($item['file']) ."' class='viewdiff'>[view diff]</a> <div class='gitdivdiff ". str_replace("=", '_', base64_encode($item['file']) ) ."'></div> </div>";
$i++;
}
}else{
echo "<p class='red'>No changed files in this repo so nothing to commit.</p>";
}
//output the commit message box
echo "<div id='gitdivcommit'><label>Commit message</label><br /><input type='text' id='gitmessage' name='message' class='message' />
<p><a href='#' class='button-primary'>Commit the staged chanages</a></p></div>";
die(); // this is required to return a proper result
}
public function git_log() {
//check the user has the permissions
check_admin_referer('plugin-name-action_wpidenonce');
if ( !current_user_can('edit_themes') )
wp_die('<p>'.__('You do not have sufficient permissions to edit templates for this site. SORRY').'</p>');
$this->git_open_repo(); // make sure git repo is open
$log = $this->git->getLog(50);
echo "<div class='git_log'>";
foreach($log as $item){
$matches = array();
$log_array = array();
$bits = explode("\n", $item);
foreach ($bits as $bit){
if ( preg_match_all("#(.*): (.*)#iS", trim($bit), $matches) ){
$key = $matches[1][0];
if (is_string($key) && trim($key) !== ""){
$log_array[ $key ] = trim( $matches[2][0] );
}
}
}
$commit_message = explode( end($log_array), $item);
$log_array[ 'message' ] = trim($commit_message[2]);
$commit = explode( reset($log_array), $item);
$log_array[ 'commit' ] = trim( str_replace( array("commit ", "Author:"), "", $commit[0] ) );
echo "<span class='input_row'>";
echo "<span class='message'>{$log_array[ 'message' ]}</span> {$log_array[ 'AuthorDate' ]} <span style='float:right;'>ID: {$log_array[ 'commit' ]}</span> ";
echo "</span>";
}
echo "</div>";
die(); // this is required to return a proper result
}
public function git_init() {
//check the user has the permissions
check_admin_referer('plugin-name-action_wpidenonce');
if ( !current_user_can('edit_themes') )
wp_die('<p>'.__('You do not have sufficient permissions to edit templates for this site. SORRY').'</p>');
$this->git_open_repo(); // make sure git repo is open
//create the local repo path if it doesn't exist
if ( !file_exists( $this->git->getRepositoryPath() ) )
mkdir( $this->git->getRepositoryPath() );
$result = $this->git->getBinary()->{'init'}($this->git->getRepositoryPath(), array(
));
//return $result->getStdOut(); //still not getting enough output from the push...
if ( $result->getStdErr() === ''){
echo $result->getStdOut();
}else{
echo $result->getStdErr();
}
die(); // this is required to return a proper result
}
public function git_clone() {
//check the user has the permissions
check_admin_referer('plugin-name-action_wpidenonce');
if ( !current_user_can('edit_themes') )
wp_die('<p>'.__('You do not have sufficient permissions to edit templates for this site. SORRY').'</p>');
$this->git_open_repo(); // make sure git repo is open
//just incase it's a private repo we will setup the keys
$sshpath = preg_replace("#/$#", "", $_POST['sshpath']); //get path replacing end slash if entered
putenv("GIT_SSH=". plugin_dir_path(__FILE__) . 'git/git-wrapper-nohostcheck.sh'); //tell Git about our wrapper script
/* See note on git_push re wrapper */
putenv("WPIDE_SSH_PATH=" . $sshpath); //no trailing slash - pass wp-content path to Git wrapper script
putenv("HOME=". plugin_dir_path(__FILE__) . 'git'); //no trailing slash - set home to the git directory (this may not be needed)
if ($_POST['repo_path'] === '' || is_null($_POST['repo_path']) ){
echo "<span class='input_row'>
<label>Clone a remote repository by entering it's remote path</label>
<input type='text' name='repo_path' id='repo_path' value=''> <em>It will be cloned into the repository path/folder defined in the Git settings.</em>
<p><a href='#' class='button-primary git_clone'>Clone</a></p>
</span>";
die();
}
$path = sanitize_text_field( $_POST['repo_path'] );
//create the local repo path if it doesn't exist
if ( !file_exists( $this->git->getRepositoryPath() ) )
mkdir( $this->git->getRepositoryPath() );
$result = $this->git->getBinary()->{'clone'}($this->git->getRepositoryPath(), array(
$path,
$this->git->getRepositoryPath(),
'--recursive'
));
//return $result->getStdOut(); //still not getting enough output from the push...
if ( $result->getStdErr() === ''){
$result = $result->getStdOut();
//format the output a little better
$result = str_replace('...', '...<br />', $result);
echo $result;
}else{
echo $result->getStdErr();
}
die(); // this is required to return a proper result
}
public function git_push() {
//check the user has the permissions
check_admin_referer('plugin-name-action_wpidenonce');
if ( !current_user_can('edit_themes') )
wp_die('<p>'.__('You do not have sufficient permissions to edit templates for this site. SORRY').'</p>');
$this->git_open_repo(); // make sure git repo is open
$sshpath = preg_replace("#/$#", "", $_POST['sshpath']); //get path replacing end slash if entered
putenv("GIT_SSH=". plugin_dir_path(__FILE__) . 'git/git-wrapper-nohostcheck.sh'); //tell Git about our wrapper script
/*
The wrapper we use above doesn't do a host check which means we can't guarentee the other side is who we think it is
We have this other wrapper which does a host check which we should swap to after the initial push/connection has been made
and the entry automatically added to known hosts but that logic isn't in place yet.
putenv("GIT_SSH=". plugin_dir_path(__FILE__) . 'git/git-wrapper.sh');
*/
putenv("WPIDE_SSH_PATH=" . $sshpath); //no trailing slash - pass wp-content path to Git wrapper script
putenv("HOME=". plugin_dir_path(__FILE__) . 'git'); //no trailing slash - set home to the git directory (this may not be needed)
echo "<pre>";
$push_result = $this->git->push( );
echo "</pre>";
if ($push_result === ''){
echo "Sucessfully pushed to your remote repo";
}else{
echo $push_result;
}
echo "<p>Git push completed.</p>";
die(); // this is required to return a proper result
}
public function git_diff() {
//check the user has the permissions
check_admin_referer('plugin-name-action_wpidenonce');
if ( !current_user_can('edit_themes') )
wp_die('<p>'.__('You do not have sufficient permissions to edit templates for this site. SORRY').'</p>');
$this->git_open_repo(); // make sure git repo is open
$file = sanitize_text_field( base64_decode( $_POST['file']) );
$result = $this->git->getBinary()->{'diff'}($this->git->getRepositoryPath(), array(
$file
));
//return $result->getStdOut(); //still not getting enough output from the push...
if ( $result->getStdErr() === ''){
$diff_lines = explode("\n", $result->getStdOut() );
foreach ($diff_lines as $a_line){
if ( preg_match("#^\+#", $a_line) ){
$a_class = 'plus';
}elseif ( preg_match("#^\-#", $a_line) ) {
$a_class = 'minus';
}else{
$a_class = '';
}
echo "<span class='diff_line {$a_class}'>{$a_line}</span>";
}
}else{
echo $result->getStdErr();
}
echo "<strong>Diff</strong>" . $diff_table;
die(); // this is required to return a proper result
}
public function git_commit() {
//check the user has the permissions
check_admin_referer('plugin-name-action_wpidenonce');
if ( !current_user_can('edit_themes') )
wp_die('<p>'.__('You do not have sufficient permissions to edit templates for this site. SORRY').'</p>');
$this->git_open_repo(); // make sure git repo is open
//putenv("GIT_AUTHOR_NAME=WPsites"); //author can be set using env but for now we set it during the commit
//putenv("[email protected]");
putenv("GIT_COMMITTER_NAME=WPide"); //commiter details, shows under author on github
putenv("[email protected]");
$files = array();
foreach ($_POST['files'] as $file){
$files[] = base64_decode( $file );
}
//get the current user to be used for the commit
$current_user = wp_get_current_user();
$this->git->add( $files );
$this->git->commit( sanitize_text_field( stripslashes($_POST['gitmessage']) ) , $files, "{$current_user->user_firstname} {$current_user->user_lastname} <{$current_user->user_email}>");
wpide::git_status();
die(); // this is required to return a proper result
}
public static function wpide_image_edit_key() {
//check the user has the permissions
check_admin_referer('plugin-name-action_wpidenonce');
if ( !current_user_can('edit_themes') )
wp_die('<p>'.__('You do not have sufficient permissions to edit templates for this site. SORRY').'</p>');
//create a nonce based on the image path
echo wp_create_nonce( 'wpide_image_edit' . $_POST['file'] );
}
public static function wpide_create_new() {
//check the user has the permissions
check_admin_referer('plugin-name-action_wpidenonce');
if ( !current_user_can('edit_themes') )
wp_die('<p>'.__('You do not have sufficient permissions to edit templates for this site. SORRY').'</p>');
//setup wp_filesystem api
global $wp_filesystem;
$url = wp_nonce_url('admin.php?page=wpide','plugin-name-action_wpidenonce');
$form_fields = null; // for now, but at some point the login info should be passed in here
if (false === ($creds = request_filesystem_credentials($url, FS_METHOD, false, false, $form_fields) ) ) {
// no credentials yet, just produced a form for the user to fill in
return true; // stop the normal page form from displaying
}
if ( ! WP_Filesystem($creds) )
return false;
$root = apply_filters( 'wpide_filesystem_root', WP_CONTENT_DIR );
//check all required vars are passed
if (strlen($_POST['path'])>0 && strlen($_POST['type'])>0 && strlen($_POST['file'])>0){
$filename = $_POST['file'];
$special_chars = array("?", "[", "]", "/", "\\", "=", "<", ">", ":", ";", ",", "'", "\"", "&", "$", "#", "*", "(", ")", "|", "~", "`", "!", "{", "}", chr(0));
$filename = preg_replace( "#\x{00a0}#siu", ' ', $filename );
$filename = str_replace( $special_chars, '', $filename );
$filename = str_replace( array( '%20', '+' ), '-', $filename );
$filename = preg_replace( '/[\r\n\t -]+/', '-', $filename );
$path = $_POST['path'];
if ($_POST['type'] == "directory"){
$write_result = $wp_filesystem->mkdir($root . $path . $filename, FS_CHMOD_DIR);
if ($write_result){
die("1"); //created
}else{
echo "Problem creating directory" . $root . $path . $filename;
}
}else if ($_POST['type'] == "file"){
//write the file
$write_result = $wp_filesystem->put_contents(
$root . $path . $filename,
'',
FS_CHMOD_FILE // predefined mode settings for WP files
);
if ($write_result){
die("1"); //created
}else{
echo "Problem creating file " . $root . $path . $filename;
}
}
//print_r($_POST);
}
echo "0";
die(); // this is required to return a proper result
}
public static function wpide_save_file() {
//check the user has the permissions
check_admin_referer('plugin-name-action_wpidenonce');
if ( !current_user_can('edit_themes') )
wp_die('<p>'.__('You do not have sufficient permissions to edit templates for this site. SORRY').'</p>');
$is_php = false;
/*
* Check file syntax of PHP files by parsing the PHP
* If a site is running low on memory this PHP parser library could well tip memory usage over the edge
* Especially if you are editing a large PHP file.
* Might be worth either making this syntax check optional or it only running if memory is available.
* Symptoms: no response on file save, and errors in your log like "Fatal error: Allowed memory size of 8388608 bytes exhausted…"
*/
if ( preg_match("#\.php$#i", $_POST['filename']) ){
$is_php = true;
require('PHP-Parser/lib/bootstrap.php');
ini_set('xdebug.max_nesting_level', 2000);
$code = stripslashes($_POST['content']);
$parser = new PHPParser_Parser(new PHPParser_Lexer);
try {
$stmts = $parser->parse($code);
} catch (PHPParser_Error $e) {
echo 'Parse Error: ', $e->getMessage();
die();
}
}
//setup wp_filesystem api
global $wp_filesystem;
$url = wp_nonce_url('admin.php?page=wpide','plugin-name-action_wpidenonce');
$form_fields = null; // for now, but at some point the login info should be passed in here
if (false === ($creds = request_filesystem_credentials($url, FS_METHOD, false, false, $form_fields) ) ) {
// no credentials yet, just produced a form for the user to fill in
return true; // stop the normal page form from displaying
}
if ( ! WP_Filesystem($creds) )
echo "Cannot initialise the WP file system API";
//save a copy of the file and create a backup just in case
$root = apply_filters( 'wpide_filesystem_root', WP_CONTENT_DIR );
$file_name = $root . stripslashes($_POST['filename']);
//set backup filename
$backup_path = 'backups' . preg_replace( "#\.php$#i", "_".date("Y-m-d-H").".php", $_POST['filename'] );
$backup_path_full = plugin_dir_path(__FILE__) . $backup_path;
//create backup directory if not there
$new_file_info = pathinfo($backup_path_full);
if (!$wp_filesystem->is_dir($new_file_info['dirname'])) wp_mkdir_p( $new_file_info['dirname'] ); //should use the filesytem api here but there isn't a comparable command right now
if ($is_php){
//create the backup file adding some php to the file to enable direct restore
global $current_user;
get_currentuserinfo();
$user_md5 = md5( serialize($current_user) );
$restore_php = '<?php /* start WPide restore code */
if ($_POST["restorewpnonce"] === "'. $user_md5.$_POST['_wpnonce'] .'"){
if ( file_put_contents ( "'.$file_name.'" , preg_replace("#<\?php /\* start WPide(.*)end WPide restore code \*/ \?>#s", "", file_get_contents("'.$backup_path_full.'") ) ) ){
echo "Your file has been restored, overwritting the recently edited file! \n\n The active editor still contains the broken or unwanted code. If you no longer need that content then close the tab and start fresh with the restored file.";
}
}else{
echo "-1";
}
die();
/* end WPide restore code */ ?>';
file_put_contents ( $backup_path_full , $restore_php . file_get_contents($file_name) );
}else{
//do normal backup
$wp_filesystem->copy( $file_name, $backup_path_full );
}
//save file
if( $wp_filesystem->put_contents( $file_name, stripslashes($_POST['content'])) ) {
//lets create an extra long nonce to make it less crackable
global $current_user;
get_currentuserinfo();
$user_md5 = md5( serialize($current_user) );
$result = "\"". $backup_path . ":::" . $user_md5 ."\"";
}
die($result); // this is required to return a proper result
}
public static function wpide_rename_file() {
global $wp_filesystem;
//check the user has the permissions
check_admin_referer('plugin-name-action_wpidenonce');
if ( !current_user_can( 'manage_options' ) )
wp_die('<p>'.__('You do not have sufficient permissions to modify files for this site. SORRY').'</p>');
$url = wp_nonce_url( 'admin.php?page=wpide', 'plugin-name-action_wpidenonce' );
$form_fields = null; // for now, but at some point the login info should be passed in here
$creds = request_filesystem_credentials( $url, FS_METHOD, false, false, $form_fields );
if ( false === $creds ) {
// no credentials yet, just produced a form for the user to fill in
return true; // stop the normal page form from displaying
}
if ( !WP_Filesystem( $creds ) )
echo "Cannot initialise the WP file system API";
$root = apply_filters( 'wpide_filesystem_root', WP_CONTENT_DIR );
$file_name = $root . stripslashes( $_POST['filename'] );
$new_name = dirname( $file_name ) . '/' . stripslashes( $_POST['newname'] );
if ( !$wp_filesystem->exists( $file_name ) ) {
echo 'The target file doesn\'t exist!';
exit;
}
if ( $wp_filesystem->exists( $new_name ) ) {
echo 'The destination file exists!';
exit;
}
// Move instead of rename
$renamed = $wp_filesystem->move( $file_name, $new_name );
if ( !$renamed ) {
echo 'The file could not be renamed!';
}
exit;
}
public static function wpide_delete_file() {
global $wp_filesystem;
//check the user has the permissions
check_admin_referer('plugin-name-action_wpidenonce');
if ( !current_user_can( 'manage_options' ) )
wp_die('<p>'.__('You do not have sufficient permissions to modify files for this site. SORRY').'</p>');
$url = wp_nonce_url( 'admin.php?page=wpide', 'plugin-name-action_wpidenonce' );
$form_fields = null; // for now, but at some point the login info should be passed in here
$creds = request_filesystem_credentials( $url, FS_METHOD, false, false, $form_fields );
if ( false === $creds ) {
// no credentials yet, just produced a form for the user to fill in
return true; // stop the normal page form from displaying
}
if ( !WP_Filesystem( $creds ) )
echo "Cannot initialise the WP file system API";
$root = apply_filters( 'wpide_filesystem_root', WP_CONTENT_DIR );
$file_name = $root . stripslashes($_POST['filename']);
if ( !$wp_filesystem->exists( $file_name ) ) {
echo 'The file doesn\'t exist!';
exit;
}
$deleted = $wp_filesystem->delete( $file_name );
if (!$deleted) {
echo 'The file couldn\'t be deleted.';
}
exit;
}
public static function wpide_upload_file() {
global $wp_filesystem;
//check the user has the permissions
check_admin_referer('plugin-name-action_wpidenonce');
if ( !current_user_can( 'manage_options' ) )
wp_die('<p>'.__('You do not have sufficient permissions to modify files for this site. SORRY').'</p>');
$url = wp_nonce_url( 'admin.php?page=wpide', 'plugin-name-action_wpidenonce' );
$form_fields = null; // for now, but at some point the login info should be passed in here
$creds = request_filesystem_credentials( $url, FS_METHOD, false, false, $form_fields );
if ( false === $creds ) {
// no credentials yet, just produced a form for the user to fill in
return true; // stop the normal page form from displaying
}
if ( !WP_Filesystem( $creds ) )
echo "Cannot initialise the WP file system API";
$root = apply_filters( 'wpide_filesystem_root', WP_CONTENT_DIR );
$destination_folder = $root . stripslashes( $_POST['destination'] );
foreach ( $_FILES as $file ) {
if ( !is_uploaded_file( $file['tmp_name'] ) ) {
continue;
}
$destination = $destination_folder . $file['name'];
if ( $wp_filesystem->exists( $destination ) ) {
exit( $file['name'] . ' already exists!' );
}
if ( !$wp_filesystem->move( $file['tmp_name'], $destination ) ) {
exit( $file['name'] . ' could not be moved.' );
}
if ( !$wp_filesystem->chmod( $destination ) ) {
exit( $file['name'] . ' could not be chmod.' );
}
}
exit;
}
public static function wpide_download_file() {
global $wp_filesystem;
//check the user has the permissions
check_admin_referer('plugin-name-action_wpidenonce');
if ( !current_user_can( 'manage_options' ) )
wp_die('<p>'.__('You do not have sufficient permissions to modify files for this site. SORRY').'</p>');
$url = wp_nonce_url( 'admin.php?page=wpide', 'plugin-name-action_wpidenonce' );
$form_fields = null; // for now, but at some point the login info should be passed in here
$creds = request_filesystem_credentials( $url, FS_METHOD, false, false, $form_fields );
if ( false === $creds ) {
// no credentials yet, just produced a form for the user to fill in
return true; // stop the normal page form from displaying