]> git.mxchange.org Git - core.git/blob - framework/main/classes/tools/console/class_ConsoleTools.php
Some updates:
[core.git] / framework / main / classes / tools / console / class_ConsoleTools.php
1 <?php
2 // Own namespace
3 namespace Org\Mxchange\CoreFramework\Console\Tools;
4
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;
12
13 // Import SPL stuff
14 use \SplFileInfo;
15
16 /**
17  * This class contains static helper functions for console applications
18  *
19  * @author              Roland Haeder <webmaster@shipsimu.org>
20  * @version             0.0.0
21 <<<<<<< HEAD:framework/main/classes/tools/console/class_ConsoleTools.php
22  * @copyright   Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Hub Developer Team
23 =======
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
28  *
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.
33  *
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.
38  *
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/>.
41  */
42 class ConsoleTools extends BaseFrameworkSystem {
43         // Constants
44         const HTTP_EOL = "\r\n";
45         const HTTP_USER_AGENT = 'ConsoleTools/1.0';
46
47         /**
48          * Default is that this class is noisy
49          */
50         private static $quietResolver = FALSE;
51
52         /**
53          * Protected constructor
54          *
55          * @return      void
56          */
57         protected function __construct () {
58                 // Call parent constructor
59                 parent::__construct(__CLASS__);
60
61                 // Cache configuration entry
62                 self::$quietResolver = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('quiet_dns_resolver');
63         }
64
65         /**
66          * Checks wether proxy configuration is used
67          *
68          * @return      $isUsed         Wether proxy is used
69          */
70         protected function isProxyUsed () {
71                 // Do we have cache?
72                 if (!isset($GLOBALS[__METHOD__])) {
73                         // Determine it
74                         $GLOBALS[__METHOD__] = (($this->getConfigInstance()->getConfigEntry('proxy_host') != '') && ($this->getConfigInstance()->getConfigEntry('proxy_port') > 0));
75                 } // END - if
76
77                 // Return cache
78                 return $GLOBALS[__METHOD__];
79         }
80
81         /**
82          * Sets up a proxy tunnel for given hostname and through resource
83          *
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
88          */
89         protected function setupProxyTunnel ($host, $port, $socketResource) {
90                 // Initialize array
91                 $response = array('', '', '');
92                 $proxyTunnel = '';
93
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;
98
99                 // Use login data to proxy? (username at least!)
100                 if ($this->getConfigInstance()->getConfigEntry('proxy_username') != '') {
101                         // Add it as well
102                         $encodedAuth = base64_encode($this->getConfigInstance()->getConfigEntry('proxy_username') . ':' . $this->getConfigInstance()->getConfigEntry('proxy_password'));
103                         $proxyTunnel .= 'Proxy-Authorization: Basic ' . $encodedAuth . self::HTTP_EOL;
104                 } // END - if
105
106                 // Add last new-line
107                 $proxyTunnel .= self::HTTP_EOL;
108                 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CONSOLE-TOOLS[' . __METHOD__ . ':' . __LINE__ . ']: proxyTunnel=' . $proxyTunnel);
109
110                 // Write request
111                 fwrite($socketResource, $proxyTunnel);
112
113                 // Got response?
114                 if (feof($socketResource)) {
115                         // No response received
116                         return $response;
117                 } // END - if
118
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')) {
123                         // Invalid response!
124                         return $response;
125                 } // END - if
126
127                 // All fine!
128                 return $respArray;
129         }
130
131         /**
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
133          *
134          * @param       $rawData        Raw data from /etc/hostname file
135          * @return      $hostname       Extracted host name
136          */
137         protected function extractHostnameFromRawData ($rawData) {
138                 // Default is invalid
139                 $hostname = 'invalid';
140
141                 // Try to "explode" it
142                 $data = explode(PHP_EOL, $rawData);
143
144                 // "Walk" through it
145                 foreach ($data as $line) {
146                         // Trim it
147                         $line = trim($line);
148
149                         // Begins with a hash (#) = comment?
150                         if (substr($line, 0, 1) == '#') {
151                                 // Then skip it
152                                 continue;
153                         } // END - if
154
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);
159
160                                 // Make sure only a key=value pair goes through
161                                 assert(count($hostData) == 2);
162
163                                 // Try to get it and abort
164                                 $hostname = str_replace(array('"', chr(39)), array('', ''), $hostData[1]);
165                                 break;
166                         } else {
167                                 // Use it directly
168                                 $hostname = $line;
169                                 break;
170                         }
171                 } // END - foreach
172
173                 // Return it
174                 return $hostname;
175         }
176
177         /**
178          * Tries to resolve an IP address from given hostname. Currently only IPv
179          * addresses are resolved.
180          *
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
184          */
185         public static function resolveIpAddress ($hostname) {
186                 // Quiet?
187                 if (self::$quietResolver !== TRUE) {
188                         // Debug message
189                         self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] Host name to resolve is: %s',
190                                 __CLASS__,
191                                 $hostname
192                         ));
193                 } // END - if
194
195                 // Default is false
196                 $ipAddress = false;
197
198                 // Is a dot at the end?
199                 if (substr($hostname, -1, 1) != '.') {
200                         /*
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.
206                          */
207                         $hostname .= '.';
208                 } // END - if
209
210                 // Resolve it
211                 // @TODO Here should the cacher be implemented
212                 $ipResolved = gethostbyname($hostname);
213
214                 // Was it fine?
215                 if (($ipResolved !== false) && ($ipResolved != $hostname)) {
216                         // Okay, this works!
217                         $ipAddress = $ipResolved;
218
219                         // Quiet?
220                         if (self::$quietResolver !== TRUE) {
221                                 // Debug message
222                                 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] Resolved IP address is: %s',
223                                         __CLASS__,
224                                         $ipAddress
225                                 ));
226                         } // END - if
227                 } else {
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.',
230                                 __CLASS__,
231                                 $hostname
232                         ));
233                 }
234
235                 // Return resolved IP
236                 return $ipAddress;
237         }
238
239         /**
240          * Aquires the IP address of this host by reading the /etc/hostname file
241          * and solving it. It is now stored in configuration
242          *
243          * @return      $ipAddress      Aquired IPv4 address
244          */
245         public static function acquireSelfIpAddress () {
246                 // Local IP by default
247                 $ipAddress = '127.0.0.1';
248
249                 // Get a new instance
250                 $helperInstance = new ConsoleTools();
251
252                 // Get SplFileInfo instance
253                 $infoInstance = new SplFileInfo($helperInstance->getConfigInstance()->getConfigEntry('hostname_file'));
254
255                 try {
256                         // Get a file pointer
257                         $fileInstance = ObjectFactory::createObjectByConfiguredName('file_raw_input_class', array($infoInstance));
258
259                         // Read the file
260                         $rawData = trim($fileInstance->readFromFile());
261
262                         // Close the file
263                         $fileInstance->closeFile();
264
265                         // Extract hostname from it
266                         $hostname = $helperInstance->extractHostnameFromRawData($rawData);
267
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'])) {
273                                 // Resolve it
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']);
278                         } else {
279                                 // Could not find our hostname
280                                 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] WARNING: Cannot resolve my own IP address.',
281                                         $helperInstance->__toString()
282                                 ));
283                         }
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(),
288                                 $e->__toString(),
289                                 $e->getHexCode(),
290                                 $e->getMessage()
291                         ));
292                 }
293
294                 // Return it
295                 return $ipAddress;
296         }
297
298         /**
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.
305          *
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
309          *
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
314          */
315         public static function determineExternalAddress () {
316                 // Get helper instance
317                 $helperInstance = new ConsoleTools();
318
319                 // First get a socket
320                 // @TODO Add some DNS caching here
321
322                 // Open connection
323                 if ($helperInstance->isProxyUsed() === true) {
324                         // Resolve hostname into IP address
325                         $ipAddress = self::resolveIpAddress($helperInstance->getConfigInstance()->getConfigEntry('proxy_host'));
326
327                         // Connect to host through proxy connection
328                         $socketResource = fsockopen($ipAddress, $helperInstance->getConfigInstance()->getConfigEntry('proxy_port'), $errorNo, $errorStr, 30);
329                 } else {
330                         // Connect to host directly
331                         $socketResource = fsockopen('188.138.90.169', 80, $errorNo, $errorStr, 30);
332                 }
333
334                 // Check if there was an error else
335                 if ($errorNo > 0) {
336                         // Then throw again
337                         throw new InvalidSocketException(array($helperInstance, $socketResource, $errorNo, $errorStr), BaseFrameworkSystem::EXCEPTION_INVALID_SOCKET);
338                 } // END - if
339
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;
345
346                 // Do we use proxy?
347                 if ($helperInstance->isProxyUsed() === true) {
348                         // CONNECT method?
349                         if ($helperInstance->getConfigInstance()->getConfigEntry('proxy_connect_method') == 'Y') {
350                                 // Setup proxy tunnel
351                                 $response = $helperInstance->setupProxyTunnel('shipsimu.org', 80, $socketResource);
352
353                                 // If the response is invalid, abort
354                                 if ((count($response) == 3) && (empty($response[0])) && (empty($response[1])) && (empty($response[2]))) {
355                                         // Invalid response!
356                                         $helperInstance->debugBackTrace('Proxy tunnel not working: response=' . print_r($response, true));
357                                 } // END - if
358                         } else {
359                                 // Add header for proxy
360                                 $request .= 'Proxy-Connection: Keep-Alive' . self::HTTP_EOL;
361                         }
362                 } // END - if
363
364                 // Add last HTTP_EOL
365                 $request .= self::HTTP_EOL;
366
367                 // Send it to the socket
368                 fwrite($socketResource, $request);
369
370                 // Init IP (this will always be the last line)
371                 $externalAddress = 'invalid';
372
373                 // And read the reply
374                 while (!feof($socketResource)) {
375                         // Get line
376                         $externalAddress = trim(fgets($socketResource, 128));
377
378                         // Detect HTTP response
379                         if ((substr($externalAddress, 0, 7) == 'HTTP/1.') && (substr($externalAddress, -6, 6) != '200 OK')) {
380                                 // Stop processing
381                                 break;
382                         } // END - if
383                 } // END - while
384
385                 // Close socket
386                 fclose($socketResource);
387
388
389                 // Debug message
390                 /* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CONSOLE-TOOLS[' . __METHOD__ . ':' . __LINE__ . ']: Resolved external address: ' . $externalAddress);
391
392                 // Return determined external address
393                 return $externalAddress;
394         }
395
396         /**
397          * Analyzes the 'environment', mostly $_SERVER, for presence of elements
398          * which indicates clearly that e.g. this script has been executed from
399          * console or web.
400          *
401          * @return      $type   The analyzed type, can be 'http' or 'console'
402          */
403         public static function analyzeEnvironmentForType () {
404                 // Default is the console
405                 $type = 'console';
406
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
410                         $type = 'http';
411                 } // END - if
412
413                 // Return it
414                 return $type;
415         }
416
417         /**
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:
422          *
423          *   Request type | Class type
424          * -----------------------------
425          *      http      |    web
426          *     console    |  console
427          *
428          * @return      $type   The analyzed type, can be 'http' or 'console'
429          */
430         public static function analyzeEnvironmentForClassType () {
431                 // Default is the console
432                 $type = 'console';
433
434                 // Now, do we have a request method, or query string set?
435                 if (self::analyzeEnvironmentForType() == 'http') {
436                         // Possibly HTTP request
437                         $type = 'web';
438                 } // END - if
439
440                 // Return it
441                 return $type;
442         }
443
444 }