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