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