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