@@ -2,41 +2,50 @@ package phpfuncs
22
33import (
44 "bytes"
5- "fmt"
65 "log"
76 "os"
87 "os/exec"
8+ "regexp"
9+ "strings"
910)
1011
12+ var rPatt * regexp.Regexp
13+
14+
15+ func init () {
16+ rPatt = regexp .MustCompile (`[^\w@%+=:,./-]` )
17+ }
18+
1119// Exec - Start a command on system
1220//
1321// Original : https://www.php.net/manual/tr/function.exec.php
1422//
1523// exec() executes the given command.
16- func Exec (of string ) {
24+ func Exec (of string ) string {
1725 var out bytes.Buffer
1826 cmd := exec .Command (of )
1927 cmd .Stdout = & out
2028 err := cmd .Run ()
2129 if err != nil {
2230 log .Fatal (err )
2331 }
32+ return out .String ()
2433}
2534
2635// ShellExec - Execute command via shell and return the complete output as a string
2736//
2837// Original : https://www.php.net/manual/en/function.shell-exec.php
2938//
3039// This function is identical to the backtick operator.
31- func ShellExec (of string ) {
40+ func ShellExec (of string ) string {
3241 var out bytes.Buffer
3342 cmd := exec .Command (of )
3443 cmd .Stdout = & out
3544 err := cmd .Run ()
3645 if err != nil {
3746 log .Fatal (err )
3847 }
39- fmt . Printf ( "%q \n " , out .String () )
48+ return out .String ()
4049}
4150
4251// Exit - Output a message and terminate the current script
@@ -56,3 +65,33 @@ func Exit(of int) {
5665func Die (of int ) {
5766 os .Exit (of )
5867}
68+
69+ // Escapeshellarg - Escape a string to be used as a shell argument
70+ //
71+ // Original: https://www.php.net/manual/en/function.escapeshellarg.php
72+ //
73+ func Escapeshellarg (s string ) string {
74+ if len (s ) == 0 {return "''" }
75+
76+ if rPatt .MatchString (s ) {
77+ return "'" + strings .ReplaceAll (s , "'" , "'\" '\" '" ) + "'"
78+ }
79+
80+ return s
81+ }
82+
83+ // Escapeshellcmd - Escape shell metacharacters
84+ //
85+ // Original: https://www.php.net/manual/en/function.escapeshellcmd.php
86+ //
87+ func Escapeshellcmd (s string ) string {
88+ cmds := Explode (s , " " ) // I know thats maybe not proper way...
89+
90+ z := make ([]string , len (cmds ))
91+
92+ for i ,s := range cmds {
93+ z [i ] = Escapeshellarg (s )
94+ }
95+
96+ return Join (" " ,z )
97+ }
0 commit comments