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