3 namespace Org\Mxchange\CoreFramework\Console\Tools;
5 // Import framework stuff
6 use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
7 use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
8 use Org\Mxchange\CoreFramework\Filesystem\FileNotFoundException;
9 use Org\Mxchange\CoreFramework\Generic\FrameworkException;
10 use Org\Mxchange\CoreFramework\Object\BaseFrameworkSystem;
11 use Org\Mxchange\CoreFramework\Socket\InvalidSocketException;
17 * This class contains static helper functions for console applications
19 * @author Roland Haeder <webmaster@shipsimu.org>
21 <<<<<<< HEAD:framework/main/classes/tools/console/class_ConsoleTools.php
22 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Hub Developer Team
24 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2016 Core Developer Team
25 >>>>>>> Some updates::inc/main/classes/console/class_ConsoleTools.php
26 * @license GNU GPL 3.0 or any newer version
27 * @link http://www.shipsimu.org
29 * This program is free software: you can redistribute it and/or modify
30 * it under the terms of the GNU General Public License as published by
31 * the Free Software Foundation, either version 3 of the License, or
32 * (at your option) any later version.
34 * This program is distributed in the hope that it will be useful,
35 * but WITHOUT ANY WARRANTY; without even the implied warranty of
36 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
37 * GNU General Public License for more details.
39 * You should have received a copy of the GNU General Public License
40 * along with this program. If not, see <http://www.gnu.org/licenses/>.
42 class ConsoleTools extends BaseFrameworkSystem {
44 const HTTP_EOL = "\r\n";
45 const HTTP_USER_AGENT = 'ConsoleTools/1.0';
48 * Default is that this class is noisy
50 private static $quietResolver = FALSE;
53 * Protected constructor
57 protected function __construct () {
58 // Call parent constructor
59 parent::__construct(__CLASS__);
61 // Cache configuration entry
62 self::$quietResolver = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('quiet_dns_resolver');
66 * Checks wether proxy configuration is used
68 * @return $isUsed Wether proxy is used
70 protected function isProxyUsed () {
72 if (!isset($GLOBALS[__METHOD__])) {
74 $GLOBALS[__METHOD__] = (($this->getConfigInstance()->getConfigEntry('proxy_host') != '') && ($this->getConfigInstance()->getConfigEntry('proxy_port') > 0));
78 return $GLOBALS[__METHOD__];
82 * Sets up a proxy tunnel for given hostname and through resource
84 * @param $host Host to connect to
85 * @param $port Port number to connect to
86 * @param $socketResource Resource of a socket
87 * @return $response Response array
89 protected function setupProxyTunnel ($host, $port, $socketResource) {
91 $response = array('', '', '');
94 // Generate CONNECT request header
95 $proxyTunnel .= 'CONNECT ' . $host . ':' . $port . ' HTTP/1.1' . self::HTTP_EOL;
96 $proxyTunnel .= 'Host: ' . $host . ':' . $port . self::HTTP_EOL;
97 $proxyTunnel .= 'Proxy-Connection: Keep-Alive' . self::HTTP_EOL;
99 // Use login data to proxy? (username at least!)
100 if ($this->getConfigInstance()->getConfigEntry('proxy_username') != '') {
102 $encodedAuth = base64_encode($this->getConfigInstance()->getConfigEntry('proxy_username') . ':' . $this->getConfigInstance()->getConfigEntry('proxy_password'));
103 $proxyTunnel .= 'Proxy-Authorization: Basic ' . $encodedAuth . self::HTTP_EOL;
107 $proxyTunnel .= self::HTTP_EOL;
108 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CONSOLE-TOOLS[' . __METHOD__ . ':' . __LINE__ . ']: proxyTunnel=' . $proxyTunnel);
111 fwrite($socketResource, $proxyTunnel);
114 if (feof($socketResource)) {
115 // No response received
119 // Read the first line
120 $resp = trim(fgets($socketResource, 10240));
121 $respArray = explode(' ', $resp);
122 if (((strtolower($respArray[0]) !== 'http/1.0') && (strtolower($respArray[0]) !== 'http/1.1')) || ($respArray[1] != '200')) {
132 * Tried to extract hostname from given raw data. On a Genntoo system, this could be multiple lines with # as comments. So try to get rid of it
134 * @param $rawData Raw data from /etc/hostname file
135 * @return $hostname Extracted host name
137 protected function extractHostnameFromRawData ($rawData) {
138 // Default is invalid
139 $hostname = 'invalid';
141 // Try to "explode" it
142 $data = explode(PHP_EOL, $rawData);
145 foreach ($data as $line) {
149 // Begins with a hash (#) = comment?
150 if (substr($line, 0, 1) == '#') {
155 // Has an equals sign?
156 if (strpos($line, '=') !== false) {
157 // Then "explode" it again, right part is hostname in quotes
158 $hostData = explode('=', $line);
160 // Make sure only a key=value pair goes through
161 assert(count($hostData) == 2);
163 // Try to get it and abort
164 $hostname = str_replace(array('"', chr(39)), array('', ''), $hostData[1]);
178 * Tries to resolve an IP address from given hostname. Currently only IPv
179 * addresses are resolved.
181 * @param $hostname Host name we shall resolve
182 * @return $ipAddress IPv4 address resolved from host name
183 * @todo This should be connected to a caching class to cache DNS requests
185 public static function resolveIpAddress ($hostname) {
187 if (self::$quietResolver !== TRUE) {
189 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] Host name to resolve is: %s',
198 // Is a dot at the end?
199 if (substr($hostname, -1, 1) != '.') {
201 * Then append it to prevent lookup of invalid host names through
202 * all search-domains. This will greatly improve lookup performance
203 * and has no disadvantages for anybody. A dot at the end of a
204 * domain btw means full-qualified domain, do not prepend to any
205 * other domain, basically.
211 // @TODO Here should the cacher be implemented
212 $ipResolved = gethostbyname($hostname);
215 if (($ipResolved !== false) && ($ipResolved != $hostname)) {
217 $ipAddress = $ipResolved;
220 if (self::$quietResolver !== TRUE) {
222 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] Resolved IP address is: %s',
228 // Problem while resolving IP address
229 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] Problem resolving IP address for host %s. Please check your /etc/hosts file.',
235 // Return resolved IP
240 * Aquires the IP address of this host by reading the /etc/hostname file
241 * and solving it. It is now stored in configuration
243 * @return $ipAddress Aquired IPv4 address
245 public static function acquireSelfIpAddress () {
246 // Local IP by default
247 $ipAddress = '127.0.0.1';
249 // Get a new instance
250 $helperInstance = new ConsoleTools();
252 // Get SplFileInfo instance
253 $infoInstance = new SplFileInfo($helperInstance->getConfigInstance()->getConfigEntry('hostname_file'));
256 // Get a file pointer
257 $fileInstance = ObjectFactory::createObjectByConfiguredName('file_raw_input_class', array($infoInstance));
260 $rawData = trim($fileInstance->readFromFile());
263 $fileInstance->closeFile();
265 // Extract hostname from it
266 $hostname = $helperInstance->extractHostnameFromRawData($rawData);
268 // Resolve the IP number
269 $ipAddress = self::resolveIpAddress($hostname);
270 } catch (FileNotFoundException $e) {
271 // Fall-back to 'SESSION_SVR' which found on my Sun Station
272 if (isset($_SERVER['SESSION_SVR'])) {
274 $ipAddress = self::resolveIpAddress($_SERVER['SESSION_SVR']);
275 } elseif (isset($_SERVER['COMPUTERNAME'])) {
276 // May happen on some Windows XP systems, so also try this
277 $ipAddress = self::resolveIpAddress($_SERVER['COMPUTERNAME']);
279 // Could not find our hostname
280 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] WARNING: Cannot resolve my own IP address.',
281 $helperInstance->__toString()
284 } catch (FrameworkException $e) {
285 // Output debug message
286 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] Problem while resolving own IP address: [%s|%s]:%s',
287 $helperInstance->__toString(),
299 * Determines own remote IP address (e.g. can be used to probe if we are
300 * reachable from outside by determining external address and then connect to it.
301 * This is accomblished by connecting to the IP of www.shipsimu.org which
302 * should default to 188.138.90.169 and requesting /ip.php which does only
303 * return the content of $_SERVER['REMOTE_ADDR']. Of course, this method
304 * requires a working Internet connection.
306 * This method is taken from a user comment on php.net and heavily rewritten.
307 * Compare to following link:
308 * http://de.php.net/manual/en/function.socket-create.php#49368
310 * @return $externalAddress The determined external address address
311 * @throws InvalidSocketException If socket initialization wents wrong or if an errors occurs
312 * @todo This should be moved out to an external class, e.g. HttpClient
313 * @todo Make IP, host name, port and script name configurable
315 public static function determineExternalAddress () {
316 // Get helper instance
317 $helperInstance = new ConsoleTools();
319 // First get a socket
320 // @TODO Add some DNS caching here
323 if ($helperInstance->isProxyUsed() === true) {
324 // Resolve hostname into IP address
325 $ipAddress = self::resolveIpAddress($helperInstance->getConfigInstance()->getConfigEntry('proxy_host'));
327 // Connect to host through proxy connection
328 $socketResource = fsockopen($ipAddress, $helperInstance->getConfigInstance()->getConfigEntry('proxy_port'), $errorNo, $errorStr, 30);
330 // Connect to host directly
331 $socketResource = fsockopen('188.138.90.169', 80, $errorNo, $errorStr, 30);
334 // Check if there was an error else
337 throw new InvalidSocketException(array($helperInstance, $socketResource, $errorNo, $errorStr), BaseFrameworkSystem::EXCEPTION_INVALID_SOCKET);
340 // Prepare the GET request
341 $request = 'GET ' . ($helperInstance->isProxyUsed() === true ? 'http://shipsimu.org' : '') . '/ip.php HTTP/1.0' . self::HTTP_EOL;
342 $request .= 'Host: shipsimu.org' . self::HTTP_EOL;
343 $request .= 'User-Agent: ' . self::HTTP_USER_AGENT . self::HTTP_EOL;
344 $request .= 'Connection: close' . self::HTTP_EOL;
347 if ($helperInstance->isProxyUsed() === true) {
349 if ($helperInstance->getConfigInstance()->getConfigEntry('proxy_connect_method') == 'Y') {
350 // Setup proxy tunnel
351 $response = $helperInstance->setupProxyTunnel('shipsimu.org', 80, $socketResource);
353 // If the response is invalid, abort
354 if ((count($response) == 3) && (empty($response[0])) && (empty($response[1])) && (empty($response[2]))) {
356 $helperInstance->debugBackTrace('Proxy tunnel not working: response=' . print_r($response, true));
359 // Add header for proxy
360 $request .= 'Proxy-Connection: Keep-Alive' . self::HTTP_EOL;
365 $request .= self::HTTP_EOL;
367 // Send it to the socket
368 fwrite($socketResource, $request);
370 // Init IP (this will always be the last line)
371 $externalAddress = 'invalid';
373 // And read the reply
374 while (!feof($socketResource)) {
376 $externalAddress = trim(fgets($socketResource, 128));
378 // Detect HTTP response
379 if ((substr($externalAddress, 0, 7) == 'HTTP/1.') && (substr($externalAddress, -6, 6) != '200 OK')) {
386 fclose($socketResource);
390 /* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CONSOLE-TOOLS[' . __METHOD__ . ':' . __LINE__ . ']: Resolved external address: ' . $externalAddress);
392 // Return determined external address
393 return $externalAddress;
397 * Analyzes the 'environment', mostly $_SERVER, for presence of elements
398 * which indicates clearly that e.g. this script has been executed from
401 * @return $type The analyzed type, can be 'http' or 'console'
403 public static function analyzeEnvironmentForType () {
404 // Default is the console
407 // Now, do we have a request method, or query string set?
408 if ((isset($_SERVER['REQUEST_METHOD'])) || (isset($_SERVER['QUERY_STRING']))) {
409 // Possibly HTTP request
418 * Analyzes the 'environment', mostly $_SERVER, for presence of elements
419 * which indicates clearly that e.g. this script has been executed from
420 * console or web. This method should be used for class names, they
421 * currently are named differently. Here is a list to clarify this:
423 * Request type | Class type
424 * -----------------------------
428 * @return $type The analyzed type, can be 'http' or 'console'
430 public static function analyzeEnvironmentForClassType () {
431 // Default is the console
434 // Now, do we have a request method, or query string set?
435 if (self::analyzeEnvironmentForType() == 'http') {
436 // Possibly HTTP request