Renamed Registry -> GenericRegistry to make it clear that this registry does
[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  * @copyright   Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Hub Developer Team
22  * @license             GNU GPL 3.0 or any newer version
23  * @link                http://www.shipsimu.org
24  *
25  * This program is free software: you can redistribute it and/or modify
26  * it under the terms of the GNU General Public License as published by
27  * the Free Software Foundation, either version 3 of the License, or
28  * (at your option) any later version.
29  *
30  * This program is distributed in the hope that it will be useful,
31  * but WITHOUT ANY WARRANTY; without even the implied warranty of
32  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
33  * GNU General Public License for more details.
34  *
35  * You should have received a copy of the GNU General Public License
36  * along with this program. If not, see <http://www.gnu.org/licenses/>.
37  */
38 class ConsoleTools extends BaseFrameworkSystem {
39         // Constants
40         const HTTP_EOL = "\r\n";
41         const HTTP_USER_AGENT = 'ConsoleTools/1.0';
42
43         /**
44          * Default is that this class is noisy
45          */
46         private static $quietResolver = FALSE;
47
48         /**
49          * Protected constructor
50          *
51          * @return      void
52          */
53         protected function __construct () {
54                 // Call parent constructor
55                 parent::__construct(__CLASS__);
56
57                 // Cache configuration entry
58                 self::$quietResolver = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('quiet_dns_resolver');
59         }
60
61         /**
62          * Checks wether proxy configuration is used
63          *
64          * @return      $isUsed         Wether proxy is used
65          */
66         protected function isProxyUsed () {
67                 // Do we have cache?
68                 if (!isset($GLOBALS[__METHOD__])) {
69                         // Determine it
70                         $GLOBALS[__METHOD__] = (($this->getConfigInstance()->getConfigEntry('proxy_host') != '') && ($this->getConfigInstance()->getConfigEntry('proxy_port') > 0));
71                 } // END - if
72
73                 // Return cache
74                 return $GLOBALS[__METHOD__];
75         }
76
77         /**
78          * Sets up a proxy tunnel for given hostname and through resource
79          *
80          * @param       $host                           Host to connect to
81          * @param       $port                           Port number to connect to
82          * @param       $socketResource         Resource of a socket
83          * @return      $response                       Response array
84          */
85         protected function setupProxyTunnel ($host, $port, $socketResource) {
86                 // Initialize array
87                 $response = array('', '', '');
88                 $proxyTunnel = '';
89
90                 // Generate CONNECT request header
91                 $proxyTunnel .= 'CONNECT ' . $host . ':' . $port . ' HTTP/1.1' . self::HTTP_EOL;
92                 $proxyTunnel .= 'Host: ' . $host . ':' . $port . self::HTTP_EOL;
93                 $proxyTunnel .= 'Proxy-Connection: Keep-Alive' . self::HTTP_EOL;
94
95                 // Use login data to proxy? (username at least!)
96                 if ($this->getConfigInstance()->getConfigEntry('proxy_username') != '') {
97                         // Add it as well
98                         $encodedAuth = base64_encode($this->getConfigInstance()->getConfigEntry('proxy_username') . ':' . $this->getConfigInstance()->getConfigEntry('proxy_password'));
99                         $proxyTunnel .= 'Proxy-Authorization: Basic ' . $encodedAuth . self::HTTP_EOL;
100                 } // END - if
101
102                 // Add last new-line
103                 $proxyTunnel .= self::HTTP_EOL;
104                 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CONSOLE-TOOLS[' . __METHOD__ . ':' . __LINE__ . ']: proxyTunnel=' . $proxyTunnel);
105
106                 // Write request
107                 fwrite($socketResource, $proxyTunnel);
108
109                 // Got response?
110                 if (feof($socketResource)) {
111                         // No response received
112                         return $response;
113                 } // END - if
114
115                 // Read the first line
116                 $resp = trim(fgets($socketResource, 10240));
117                 $respArray = explode(' ', $resp);
118                 if (((strtolower($respArray[0]) !== 'http/1.0') && (strtolower($respArray[0]) !== 'http/1.1')) || ($respArray[1] != '200')) {
119                         // Invalid response!
120                         return $response;
121                 } // END - if
122
123                 // All fine!
124                 return $respArray;
125         }
126
127         /**
128          * 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
129          *
130          * @param       $rawData        Raw data from /etc/hostname file
131          * @return      $hostname       Extracted host name
132          */
133         protected function extractHostnameFromRawData ($rawData) {
134                 // Default is invalid
135                 $hostname = 'invalid';
136
137                 // Try to "explode" it
138                 $data = explode(PHP_EOL, $rawData);
139
140                 // "Walk" through it
141                 foreach ($data as $line) {
142                         // Trim it
143                         $line = trim($line);
144
145                         // Begins with a hash (#) = comment?
146                         if (substr($line, 0, 1) == '#') {
147                                 // Then skip it
148                                 continue;
149                         } // END - if
150
151                         // Has an equals sign?
152                         if (strpos($line, '=') !== false) {
153                                 // Then "explode" it again, right part is hostname in quotes
154                                 $hostData = explode('=', $line);
155
156                                 // Make sure only a key=value pair goes through
157                                 assert(count($hostData) == 2);
158
159                                 // Try to get it and abort
160                                 $hostname = str_replace(array('"', chr(39)), array('', ''), $hostData[1]);
161                                 break;
162                         } else {
163                                 // Use it directly
164                                 $hostname = $line;
165                                 break;
166                         }
167                 } // END - foreach
168
169                 // Return it
170                 return $hostname;
171         }
172
173         /**
174          * Tries to resolve an IP address from given hostname. Currently only IPv
175          * addresses are resolved.
176          *
177          * @param       $hostname       Host name we shall resolve
178          * @return      $ipAddress      IPv4 address resolved from host name
179          * @todo        This should be connected to a caching class to cache DNS requests
180          */
181         public static function resolveIpAddress ($hostname) {
182                 // Quiet?
183                 if (self::$quietResolver !== TRUE) {
184                         // Debug message
185                         self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] Host name to resolve is: %s',
186                                 __CLASS__,
187                                 $hostname
188                         ));
189                 } // END - if
190
191                 // Default is false
192                 $ipAddress = false;
193
194                 // Is a dot at the end?
195                 if (substr($hostname, -1, 1) != '.') {
196                         /*
197                          * Then append it to prevent lookup of invalid host names through
198                          * all search-domains. This will greatly improve lookup performance
199                          * and has no disadvantages for anybody. A dot at the end of a
200                          * domain btw means full-qualified domain, do not prepend to any
201                          * other domain, basically.
202                          */
203                         $hostname .= '.';
204                 } // END - if
205
206                 // Resolve it
207                 // @TODO Here should the cacher be implemented
208                 $ipResolved = gethostbyname($hostname);
209
210                 // Was it fine?
211                 if (($ipResolved !== false) && ($ipResolved != $hostname)) {
212                         // Okay, this works!
213                         $ipAddress = $ipResolved;
214
215                         // Quiet?
216                         if (self::$quietResolver !== TRUE) {
217                                 // Debug message
218                                 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] Resolved IP address is: %s',
219                                         __CLASS__,
220                                         $ipAddress
221                                 ));
222                         } // END - if
223                 } else {
224                         // Problem while resolving IP address
225                         self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] Problem resolving IP address for host %s. Please check your /etc/hosts file.',
226                                 __CLASS__,
227                                 $hostname
228                         ));
229                 }
230
231                 // Return resolved IP
232                 return $ipAddress;
233         }
234
235         /**
236          * Aquires the IP address of this host by reading the /etc/hostname file
237          * and solving it. It is now stored in configuration
238          *
239          * @return      $ipAddress      Aquired IPv4 address
240          */
241         public static function acquireSelfIpAddress () {
242                 // Local IP by default
243                 $ipAddress = '127.0.0.1';
244
245                 // Get a new instance
246                 $helperInstance = new ConsoleTools();
247
248                 // Get SplFileInfo instance
249                 $infoInstance = new SplFileInfo($helperInstance->getConfigInstance()->getConfigEntry('hostname_file'));
250
251                 try {
252                         // Get a file pointer
253                         $fileInstance = ObjectFactory::createObjectByConfiguredName('file_raw_input_class', array($infoInstance));
254
255                         // Read the file
256                         $rawData = trim($fileInstance->readFromFile());
257
258                         // Close the file
259                         $fileInstance->closeFile();
260
261                         // Extract hostname from it
262                         $hostname = $helperInstance->extractHostnameFromRawData($rawData);
263
264                         // Resolve the IP number
265                         $ipAddress = self::resolveIpAddress($hostname);
266                 } catch (FileNotFoundException $e) {
267                         // Fall-back to 'SESSION_SVR' which found on my Sun Station
268                         if (isset($_SERVER['SESSION_SVR'])) {
269                                 // Resolve it
270                                 $ipAddress = self::resolveIpAddress($_SERVER['SESSION_SVR']);
271                         } elseif (isset($_SERVER['COMPUTERNAME'])) {
272                                 // May happen on some Windows XP systems, so also try this
273                                 $ipAddress = self::resolveIpAddress($_SERVER['COMPUTERNAME']);
274                         } else {
275                                 // Could not find our hostname
276                                 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] WARNING: Cannot resolve my own IP address.',
277                                         $helperInstance->__toString()
278                                 ));
279                         }
280                 } catch (FrameworkException $e) {
281                         // Output debug message
282                         self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] Problem while resolving own IP address: [%s|%s]:%s',
283                                 $helperInstance->__toString(),
284                                 $e->__toString(),
285                                 $e->getHexCode(),
286                                 $e->getMessage()
287                         ));
288                 }
289
290                 // Return it
291                 return $ipAddress;
292         }
293
294         /**
295          * Determines own remote IP address (e.g. can be used to probe if we are
296          * reachable from outside by determining external address and then connect to it.
297          * This is accomblished by connecting to the IP of www.shipsimu.org which
298          * should default to 188.138.90.169 and requesting /ip.php which does only
299          * return the content of $_SERVER['REMOTE_ADDR']. Of course, this method
300          * requires a working Internet connection.
301          *
302          * This method is taken from a user comment on php.net and heavily rewritten.
303          * Compare to following link:
304          * http://de.php.net/manual/en/function.socket-create.php#49368
305          *
306          * @return      $externalAddress        The determined external address address
307          * @throws      InvalidSocketException  If socket initialization wents wrong or if an errors occurs
308          * @todo        This should be moved out to an external class, e.g. HttpClient
309          * @todo        Make IP, host name, port and script name configurable
310          */
311         public static function determineExternalAddress () {
312                 // Get helper instance
313                 $helperInstance = new ConsoleTools();
314
315                 // First get a socket
316                 // @TODO Add some DNS caching here
317
318                 // Open connection
319                 if ($helperInstance->isProxyUsed() === true) {
320                         // Resolve hostname into IP address
321                         $ipAddress = self::resolveIpAddress($helperInstance->getConfigInstance()->getConfigEntry('proxy_host'));
322
323                         // Connect to host through proxy connection
324                         $socketResource = fsockopen($ipAddress, $helperInstance->getConfigInstance()->getConfigEntry('proxy_port'), $errorNo, $errorStr, 30);
325                 } else {
326                         // Connect to host directly
327                         $socketResource = fsockopen('188.138.90.169', 80, $errorNo, $errorStr, 30);
328                 }
329
330                 // Check if there was an error else
331                 if ($errorNo > 0) {
332                         // Then throw again
333                         throw new InvalidSocketException(array($helperInstance, $socketResource, $errorNo, $errorStr), BaseFrameworkSystem::EXCEPTION_INVALID_SOCKET);
334                 } // END - if
335
336                 // Prepare the GET request
337                 $request  = 'GET ' . ($helperInstance->isProxyUsed() === true ? 'http://shipsimu.org' : '') . '/ip.php HTTP/1.0' . self::HTTP_EOL;
338                 $request .= 'Host: shipsimu.org' . self::HTTP_EOL;
339                 $request .= 'User-Agent: ' . self::HTTP_USER_AGENT . self::HTTP_EOL;
340                 $request .= 'Connection: close' . self::HTTP_EOL;
341
342                 // Do we use proxy?
343                 if ($helperInstance->isProxyUsed() === true) {
344                         // CONNECT method?
345                         if ($helperInstance->getConfigInstance()->getConfigEntry('proxy_connect_method') == 'Y') {
346                                 // Setup proxy tunnel
347                                 $response = $helperInstance->setupProxyTunnel('shipsimu.org', 80, $socketResource);
348
349                                 // If the response is invalid, abort
350                                 if ((count($response) == 3) && (empty($response[0])) && (empty($response[1])) && (empty($response[2]))) {
351                                         // Invalid response!
352                                         $helperInstance->debugBackTrace('Proxy tunnel not working: response=' . print_r($response, true));
353                                 } // END - if
354                         } else {
355                                 // Add header for proxy
356                                 $request .= 'Proxy-Connection: Keep-Alive' . self::HTTP_EOL;
357                         }
358                 } // END - if
359
360                 // Add last HTTP_EOL
361                 $request .= self::HTTP_EOL;
362
363                 // Send it to the socket
364                 fwrite($socketResource, $request);
365
366                 // Init IP (this will always be the last line)
367                 $externalAddress = 'invalid';
368
369                 // And read the reply
370                 while (!feof($socketResource)) {
371                         // Get line
372                         $externalAddress = trim(fgets($socketResource, 128));
373
374                         // Detect HTTP response
375                         if ((substr($externalAddress, 0, 7) == 'HTTP/1.') && (substr($externalAddress, -6, 6) != '200 OK')) {
376                                 // Stop processing
377                                 break;
378                         } // END - if
379                 } // END - while
380
381                 // Close socket
382                 fclose($socketResource);
383
384
385                 // Debug message
386                 /* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CONSOLE-TOOLS[' . __METHOD__ . ':' . __LINE__ . ']: Resolved external address: ' . $externalAddress);
387
388                 // Return determined external address
389                 return $externalAddress;
390         }
391
392         /**
393          * Analyzes the 'environment', mostly $_SERVER, for presence of elements
394          * which indicates clearly that e.g. this script has been executed from
395          * console or web.
396          *
397          * @return      $type   The analyzed type, can be 'http' or 'console'
398          */
399         public static function analyzeEnvironmentForType () {
400                 // Default is the console
401                 $type = 'console';
402
403                 // Now, do we have a request method, or query string set?
404                 if ((isset($_SERVER['REQUEST_METHOD'])) || (isset($_SERVER['QUERY_STRING']))) {
405                         // Possibly HTTP request
406                         $type = 'http';
407                 } // END - if
408
409                 // Return it
410                 return $type;
411         }
412
413         /**
414          * Analyzes the 'environment', mostly $_SERVER, for presence of elements
415          * which indicates clearly that e.g. this script has been executed from
416          * console or web. This method should be used for class names, they
417          * currently are named differently. Here is a list to clarify this:
418          *
419          *   Request type | Class type
420          * -----------------------------
421          *      http      |    web
422          *     console    |  console
423          *
424          * @return      $type   The analyzed type, can be 'http' or 'console'
425          */
426         public static function analyzeEnvironmentForClassType () {
427                 // Default is the console
428                 $type = 'console';
429
430                 // Now, do we have a request method, or query string set?
431                 if (self::analyzeEnvironmentForType() == 'http') {
432                         // Possibly HTTP request
433                         $type = 'web';
434                 } // END - if
435
436                 // Return it
437                 return $type;
438         }
439
440 }