60476a1e96526bbc7099336ac2651182fced256d
[core.git] / inc / classes / main / console / class_ConsoleTools.php
1 <?php
2 /**
3  * This class contains static helper functions for console applications
4  *
5  * @author              Roland Haeder <webmaster@ship-simu.org>
6  * @version             0.0.0
7  * @copyright   Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2012 Core Developer Team
8  * @license             GNU GPL 3.0 or any newer version
9  * @link                http://www.ship-simu.org
10  *
11  * This program is free software: you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation, either version 3 of the License, or
14  * (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program. If not, see <http://www.gnu.org/licenses/>.
23  */
24 class ConsoleTools extends BaseFrameworkSystem {
25         // Constants
26         const HTTP_EOL = "\r\n";
27         const HTTP_USER_AGENT = 'ConsoleTools/1.0';
28
29         /**
30          * Protected constructor
31          *
32          * @return      void
33          */
34         protected function __construct () {
35                 // Call parent constructor
36                 parent::__construct(__CLASS__);
37         }
38
39         /**
40          * Tries to resolve an IP address from given hostname. Currently only IPv
41          * addresses are resolved.
42          *
43          * @param       $hostname       Host name we shall resolve
44          * @return      $ip                     IP address resolved from host name
45          * @todo        We should connect this to a caching class to cache DNS requests
46          */
47         protected function resolveIpAddress ($hostname) {
48                 // Debug message
49                 $this->debugOutput(sprintf("[%s:] Our host name is: <span class=\"data\">%s</span>",
50                         $this->__toString(),
51                         $hostname
52                 ));
53
54                 // Default is an invalid one
55                 $ip = '0.0.0.0';
56
57                 // Resolve it
58                 // @TODO Here should the cacher be implemented
59                 $ipResolved = gethostbyname($hostname);
60
61                 // Was it fine?
62                 if (($ipResolved !== false) && ($ipResolved != $hostname)) {
63                         // Okay, this works!
64                         $ip = $ipResolved;
65
66                         // Debug message
67                         $this->debugOutput(sprintf("[%s:] Resolved IP address is: <span class=\"data\">%s</span>\n",
68                                 $this->__toString(),
69                                 $ip
70                         ));
71                 } else {
72                         // Problem while resolving IP address
73                         $this->debugOutput(sprintf("[%s:] Problem resolving IP address for host <span class=\"data\">%s</span>. Please check your /etc/hosts file.",
74                                 $this->__toString(),
75                                 $hostname
76                         ));
77                 }
78
79                 // Return resolved IP
80                 return $ip;
81         }
82
83         /**
84          * Aquires the IP address of this host by reading the /etc/hostname file
85          * and solving it. It is now stored in configuration
86          *
87          * @return      $ip             Aquired IP address
88          */
89         public static function acquireSelfIPAddress () {
90                 // Local IP by default
91                 $ip = '127.0.0.1';
92
93                 // Get a new instance
94                 $helperInstance = new ConsoleTools();
95
96                 try {
97                         // Get a file pointer
98                         $io = FrameworkFileInputPointer::createFrameworkFileInputPointer('/etc/hostname');
99
100                         // Read the file
101                         $hostname = trim($io->readFromFile());
102
103                         // Close the file
104                         $io->closeFile();
105
106                         // Resolve the IP number
107                         $ip = $helperInstance->resolveIpAddress($hostname);
108                 } catch (FileIoException $e) {
109                         // Fall-back to 'SESSION_SVR' which found on my Sun Station
110                         if (isset($_SERVER['SESSION_SVR'])) {
111                                 // Resolve it
112                                 $ip = $helperInstance->resolveIpAddress($_SERVER['SESSION_SVR']);
113                         } elseif (isset($_SERVER['COMPUTERNAME'])) {
114                                 // May happen on some XP systems, so also try this
115                                 $ip = $helperInstance->resolveIpAddress($_SERVER['COMPUTERNAME']);
116                         } else {
117                                 // Could not find our hostname
118                                 $helperInstance->debugOutput(sprintf("[%s:] WARNING: Cannot resolve my own IP address.",
119                                         $helperInstance->__toString()
120                                 ));
121                         }
122                 } catch (FrameworkException $e) {
123                         // Output debug message
124                         $helperInstance->debugOutput(sprintf("[%s:] Problem while resolving own IP address: [%s|%s]:%s",
125                                 $helperInstance->__toString(),
126                                 $e->__toString(),
127                                 $e->getHexCode(),
128                                 $e->getMessage()
129                         ));
130                 }
131
132                 // Set it in configuration
133                 FrameworkConfiguration::getSelfInstance()->setServerAddress($ip);
134
135                 // Return it
136                 return $ip;
137         }
138
139         /**
140          * Determines own remote IP address (e.g. can be used to probe if we are
141          * reachable from outside by determining external IP and then connect to it.
142          * This is accomblished by connecting to the IP of www.ship-simu.org which
143          * should default to 188.138.90.169 and requesting /ip.php which does only
144          * return the content of $_SERVER['REMOTE_ADDR']. Of course, this method
145          * requires a working Internet connection.
146          *
147          * This method is taken from a user comment on php.net and heavily rewritten.
148          * Compare to following link:
149          * http://de.php.net/manual/en/function.socket-create.php#49368
150          *
151          * @return      $externalAddress        The determined external IP address
152          * @throws      InvalidSocketException  If socket initialization wents wrong or if an errors occurs
153          * @todo        This should be moved out to an external class, e.g. HttpClient
154          * @todo        Make IP, host name, port and script name configurable
155          */
156         public static function determineExternalIp () {
157                 // Get helper instance
158                 $helperInstance = new ConsoleTools();
159
160                 // First get a socket
161                 // @TODO Add some DNS caching here
162                 $socketResource = fsockopen('188.138.90.169', 80, $errorNo, $errorStr, 5);
163
164                 // Check if there was an error else
165                 if ($errorNo > 0) {
166                         // Then throw again
167                         throw new InvalidSocketException(array($helperInstance, $socketResource, $errorNo, $errorStr), BaseListener::EXCEPTION_INVALID_SOCKET);
168                 } // END - if
169
170                 // Prepare the GET request
171                 $request  = 'GET /ip.php HTTP/1.0' . self::HTTP_EOL;
172                 $request .= 'Host: ship-simu.org' . self::HTTP_EOL;
173                 $request .= 'User-Agent: ' . self::HTTP_USER_AGENT . self::HTTP_EOL;
174                 $request .= 'Connection: close' . self::HTTP_EOL;
175                 $request .= self::HTTP_EOL;
176
177                 // Send it to the socket
178                 fwrite($socketResource, $request);
179
180                 // Init IP (this will always be the last line)
181                 $externalAddress = 'invalid';
182
183                 // And read the reply
184                 while (!feof($socketResource)) {
185                         $externalAddress = fgets($socketResource, 128);
186                 } // END - while
187
188                 // Close socket
189                 fclose($socketResource);
190
191                 // Return determined external IP
192                 return $externalAddress;
193         }
194
195         /**
196          * Analyzes the 'environment', mostly $_SERVER, for presence of elements
197          * which indicates clearly that e.g. this script has been executed from
198          * console or web.
199          *
200          * @return      $type   The analyzed type, can be 'http' or 'console'
201          */
202         public static function analyzeEnvironmentForType () {
203                 // Default is the console
204                 $type = 'console';
205
206                 // Now, do we have a request method, or query string set?
207                 if ((isset($_SERVER['REQUEST_METHOD'])) || (isset($_SERVER['QUERY_STRING']))) {
208                         // Possibly HTTP request
209                         $type = 'http';
210                 } // END - if
211
212                 // Return it
213                 return $type;
214         }
215
216         /**
217          * Analyzes the 'environment', mostly $_SERVER, for presence of elements
218          * which indicates clearly that e.g. this script has been executed from
219          * console or web. This method should be used for class names, they
220          * currently are named differently. Here is a list to clarify this:
221          *
222          *   Request type | Class type
223          * -----------------------------
224          *      http      |    web
225          *     console    |  console
226          *
227          * @return      $type   The analyzed type, can be 'http' or 'console'
228          */
229         public static function analyzeEnvironmentForClassType () {
230                 // Default is the console
231                 $type = 'console';
232
233                 // Now, do we have a request method, or query string set?
234                 if ((isset($_SERVER['REQUEST_METHOD'])) || (isset($_SERVER['QUERY_STRING']))) {
235                         // Possibly HTTP request
236                         $type = 'web';
237                 } // END - if
238
239                 // Return it
240                 return $type;
241         }
242 }
243
244 // [EOF]
245 ?>