/var/www/hkosl.com/b2b2c/webadmin/libraies/php-console/php-console/src/PhpConsole/EvalProvider.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
<?php

namespace PhpConsole;

/**
 * Execute PHP code with some security & accessibility tweaks
 *
 * @package PhpConsole
 * @version 3.1
 * @link http://php-console.com
 * @author Sergey Barbushin http://linkedin.com/in/barbushin
 * @copyright © Sergey Barbushin, 2011-2013. All rights reserved.
 * @license http://www.opensource.org/licenses/BSD-3-Clause "The BSD 3-Clause License"
 */
class EvalProvider {

    protected 
$sharedVars = array();
    protected 
$openBaseDirs = array();
    protected 
$codeCallbackHandlers = array();
    protected 
$globalsBackup;

    
/**
     * Execute PHP code handling execution time, output & exception
     * @param string $code
     * @return EvalResult
     */
    
public function evaluate($code) {
        
$code $this->applyHandlersToCode($code);
        
$code $this->adaptCodeToEval($code);

        
$this->backupGlobals();
        
$this->applyOpenBaseDirSetting();

        
$startTime microtime(true);
        static::
executeCode(''$this->sharedVars);
        
$selfTime microtime(true) - $startTime;

        
ob_start();
        
$result = new EvalResult();
        
$startTime microtime(true);
        try {
            
$result->return = static::executeCode($code$this->sharedVars);
        }
        catch(\
Throwable $exception) {
            
$result->exception $exception;
        }
        catch(\
Exception $exception) {
            
$result->exception $exception;
        }
        
$result->time abs(microtime(true) - $startTime $selfTime);
        
$result->output ob_get_clean();

        
$this->restoreGlobals();

        return 
$result;
    }

    
/**
     * Add callback that will be called with &$code var reference before code execution
     * @param $callback
     * @throws \Exception
     */
    
public function addCodeHandler($callback) {
        if(!
is_callable($callback)) {
            throw new \
Exception('Argument is not callable');
        }
        
$this->codeCallbackHandlers[] = $callback;
    }

    
/**
     * Call added code handlers
     * @param $code
     * @return mixed
     */
    
protected function applyHandlersToCode($code) {
        foreach(
$this->codeCallbackHandlers as $callback) {
            
call_user_func_array($callback, array(&$code));
        }
        return 
$code;
    }

    
/**
     * Store global vars data in backup var
     */
    
protected function backupGlobals() {
        
$this->globalsBackup = array();
        foreach(
$GLOBALS as $key => $value) {
            if(
$key != 'GLOBALS') {
                
$this->globalsBackup[$key] = $value;
            }
        }
    }

    
/**
     * Restore global vars data from backup var
     */
    
protected function restoreGlobals() {
        foreach(
$this->globalsBackup as $key => $value) {
            
$GLOBALS[$key] = $value;
        }
        foreach(
array_diff(array_keys($GLOBALS), array_keys($this->globalsBackup)) as $newKey) {
            if(
$newKey != 'GLOBALS') {
                unset(
$GLOBALS[$newKey]);
            }
        }
    }

    
/**
     * Execute code with shared vars
     * @param $_code
     * @param array $_sharedVars
     * @return mixed
     */
    
protected static function executeCode($_code, array $_sharedVars) {
        foreach(
$_sharedVars as $var => $value) {
            if(isset(
$GLOBALS[$var]) && $var[0] == '_') { // extract($this->sharedVars, EXTR_OVERWRITE) and $$var = $value do not overwrites global vars
                
$GLOBALS[$var] = $value;
            }
            elseif(!isset($
$var)) {
                $
$var $value;
            }
        }

        return eval(
$_code);
    }

    
/**
     * Prepare code PHP tags be correctly passed to eval() function
     * @param string $code
     * @return string
     */
    
protected function trimPhpTags($code) {
        
$replace = array(
            
'~^(\s*)<\?=~s' => '\1echo ',
            
'~^(\s*)<\?(php)?~is' => '\1',
            
'~\?>\s*$~s' => '',
            
'~<\?(php)?[\s;]*$~is' => '',
        );
        return 
preg_replace(array_keys($replace), $replace$code);
    }

    
/**
     * Add semicolon to the end of code if it's required
     * @param string $code
     * @return string
     */
    
protected function forceEndingSemicolon($code) {
        
$code rtrim($code"; \r\n");
        return 
$code[strlen($code) - 1] != '}' $code ';' $code;
    }

    
/**
     * Apply some default code handlers
     * @param string $code
     * @return string
     */
    
protected function adaptCodeToEval($code) {
        
$code $this->trimPhpTags($code);
        
$code $this->forceEndingSemicolon($code);
        return 
$code;
    }

    
/**
     * Protect response code access only to specified directories using http://www.php.net/manual/en/ini.core.php#ini.open-basedir
     * IMPORTANT: classes autoload methods will work only for specified directories
     * @param array $openBaseDirs
     */
    
public function setOpenBaseDirs(array $openBaseDirs) {
        
$this->openBaseDirs $openBaseDirs;
    }

    
/**
     * Autoload all PHP Console classes
     */
    
protected function forcePhpConsoleClassesAutoLoad() {
        foreach(new \
RecursiveIteratorIterator(new \RecursiveDirectoryIterator(__DIR__), \RecursiveIteratorIterator::LEAVES_ONLY) as $path) {
            
/** @var $path \SplFileInfo */
            
if($path->isFile() && $path->getExtension() == 'php' && $path->getFilename() !== 'PsrLogger.php') {
                require_once(
$path->getPathname());
            }
        }
    }

    
/**
     * Set actual "open_basedir" PHP ini option
     * @throws \Exception
     */
    
protected function applyOpenBaseDirSetting() {
        if(
$this->openBaseDirs) {
            
$value implode(PATH_SEPARATOR$this->openBaseDirs);
            if(
ini_get('open_basedir') != $value) {
                
$this->forcePhpConsoleClassesAutoLoad();
                if(
ini_set('open_basedir'$value) === false) {
                    throw new \
Exception('Unable to set "open_basedir" php.ini setting');
                }
            }
        }
    }

    
/**
     * Protect response code from reading/writing/including any files using http://www.php.net/manual/en/ini.core.php#ini.open-basedir
     * IMPORTANT: It does not protects from system(), exec(), passthru(), popen() & etc OS commands execution functions
     * IMPORTANT: Classes autoload methods will not work, so all required classes must be loaded before code evaluation
     */
    
public function disableFileAccessByOpenBaseDir() {
        
$this->setOpenBaseDirs(array(__DIR__ '/not_existed_dir' mt_rand()));
    }

    
/**
     * Add var that will be implemented in PHP code executed from PHP Console debug panel (will be implemented in PHP Console > v3.0)
     * @param $name
     * @param $var
     * @throws \Exception
     */
    
public function addSharedVar($name$var) {
        
$this->addSharedVarReference($name$var);
    }

    
/**
     * Add var that will be implemented in PHP code executed from PHP Console debug panel (will be implemented in PHP Console > v3.0)
     * @param $name
     * @param $var
     * @throws \Exception
     */
    
public function addSharedVarReference($name, &$var) {
        if(isset(
$this->sharedVars[$name])) {
            throw new \
Exception('Var with name "' $name '" already added');
        }
        
$this->sharedVars[$name] =& $var;
    }
}

class 
EvalResult {

    public 
$return;
    public 
$output;
    public 
$time;
    
/** @var  \Exception|null */
    
public $exception;
}