825f5fa9cfd440331236268808ae1447b6df5c90
[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 - 2011 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      void
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                         } else {
114                                 // Could not find our hostname
115                                 $helperInstance->debugOutput(sprintf("[%s:] WARNING: Cannot resolve my own IP address.",
116                                         $helperInstance->__toString()
117                                 ));
118                         }
119                 } catch (FrameworkException $e) {
120                         // Output debug message
121                         $helperInstance->debugOutput(sprintf("[%s:] Problem while resolving own IP address: [%s|%s]:%s",
122                                 $helperInstance->__toString(),
123                                 $e->__toString(),
124                                 $e->getHexCode(),
125                                 $e->getMessage()
126                         ));
127                 }
128
129                 // Set it in configuration
130                 FrameworkConfiguration::getInstance()->setServerAddress($ip);
131         }
132
133         /**
134          * Determines own remote IP address (e.g. can be used to probe if we are
135          * reachable from outside by determining external IP and then connect to it.
136          * This is accomblished by connecting to the IP of www.ship-simu.org which
137          * should default to 188.138.90.169 and requesting /ip.php which does only
138          * return the content of $_SERVER['REMOTE_ADDR']. Of course, this method
139          * requires a working Internet connection.
140          *
141          * This method is taken from a user comment on php.net and heavily rewritten.
142          * Compare to following link:
143          * http://de.php.net/manual/en/function.socket-create.php#49368
144          *
145          * @return      $externalAddress        The determined external IP address
146          * @throws      InvalidSocketException  If socket initialization wents wrong or if an errors occurs
147          * @todo        This should be moved out to an external class, e.g. HttpClient
148          * @todo        Make IP, host name, port and script name configurable
149          */
150         public static function determineExternalIp () {
151                 // Get helper instance
152                 $helperInstance = new ConsoleTools();
153
154                 // First get a socket
155                 // @TODO Add some DNS caching here
156                 $socketResource = fsockopen('188.138.90.169', 80, $errorNo, $errorStr, 5);
157
158                 // Check if there was an error else
159                 if ($errorNo > 0) {
160                         // Then throw again
161                         throw new InvalidSocketException(array($helperInstance, gettype($socketResource), $errorNo, $errorStr), BaseListener::EXCEPTION_INVALID_SOCKET);
162                 } // END - if
163
164                 // Prepare the GET request
165                 $request  = 'GET /ip.php HTTP/1.0' . self::HTTP_EOL;
166                 $request .= 'Host: ship-simu.org' . self::HTTP_EOL;
167                 $request .= 'User-Agent: ' . self::HTTP_USER_AGENT . self::HTTP_EOL;
168                 $request .= 'Connection: close' . self::HTTP_EOL;
169                 $request .= self::HTTP_EOL;
170
171                 // Send it to the socket
172                 fwrite($socketResource, $request);
173
174                 // Init IP (this will always be the last line)
175                 $externalAddress = 'invalid';
176
177                 // And read the reply
178                 while (!feof($socketResource)) {
179                         $externalAddress = fgets($socketResource, 128);
180                 } // END - while
181
182                 // Close socket
183                 fclose($socketResource);
184
185                 // Return determined external IP
186                 return $externalAddress;
187         }
188
189         /**
190          * Analyzes the 'environment', mostly $_SERVER, for presence of elements
191          * which indicates clearly that e.g. this script has been executed from
192          * console or web.
193          *
194          * @return      $type   The analyzed type, can be 'http' or 'console'
195          */
196         public static function analyzeEnvironmentForType () {
197                 // Default is the console
198                 $type = 'console';
199
200                 // Now, do we have a request method, or query string set?
201                 if ((isset($_SERVER['REQUEST_METHOD'])) || (isset($_SERVER['QUERY_STRING']))) {
202                         // Possibly HTTP request
203                         $type = 'http';
204                 } // END - if
205
206                 // Return it
207                 return $type;
208         }
209
210         /**
211          * Analyzes the 'environment', mostly $_SERVER, for presence of elements
212          * which indicates clearly that e.g. this script has been executed from
213          * console or web. This method should be used for class names, they
214          * currently are named differently. Here is a list to clarify this:
215          *
216          *   Request type | Class type
217          * -----------------------------
218          *      http      |    web
219          *     console    |  console
220          *
221          * @return      $type   The analyzed type, can be 'http' or 'console'
222          */
223         public static function analyzeEnvironmentForClassType () {
224                 // Default is the console
225                 $type = 'console';
226
227                 // Now, do we have a request method, or query string set?
228                 if ((isset($_SERVER['REQUEST_METHOD'])) || (isset($_SERVER['QUERY_STRING']))) {
229                         // Possibly HTTP request
230                         $type = 'web';
231                 } // END - if
232
233                 // Return it
234                 return $type;
235         }
236 }
237
238 // [EOF]
239 ?>