Rewritten to static method
[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, 2010 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         /**
26          * Protected constructor
27          *
28          * @return      void
29          */
30         protected function __construct () {
31                 // Call parent constructor
32                 parent::__construct(__CLASS__);
33         }
34
35         /**
36          * Tries to resolve an IP address from given hostname. Currently only IPv
37          * addresses are resolved.
38          *
39          * @param       $hostname       Host name we shall resolve
40          * @return      $ip                     IP address resolved from host name
41          * @todo        We should connect this to a caching class to cache DNS requests
42          */
43         protected function resolveIpAddress ($hostname) {
44                 // Debug message
45                 $this->debugOutput(sprintf("[%s:] Our host name is: <span class=\"data\">%s</span>",
46                         $this->__toString(),
47                         $hostname
48                 ));
49
50                 // Default is an invalid one
51                 $ip = '0.0.0.0';
52
53                 // Resolve it
54                 // @TODO Here should the cacher be implemented
55                 $ipResolved = gethostbyname($hostname);
56
57                 // Was it fine?
58                 if (($ipResolved !== false) && ($ipResolved != $hostname)) {
59                         // Okay, this works!
60                         $ip = $ipResolved;
61
62                         // Debug message
63                         $this->debugOutput(sprintf("[%s:] Resolved IP address is: <span class=\"data\">%s</span>\n",
64                                 $this->__toString(),
65                                 $ip
66                         ));
67                 } else {
68                         // Problem while resolving IP address
69                         $this->debugOutput(sprintf("[%s:] Problem resolving IP address for host <span class=\"data\">%s</span>. Please check your /etc/hosts file.",
70                                 $this->__toString(),
71                                 $hostname
72                         ));
73                 }
74
75                 // Return resolved IP
76                 return $ip;
77         }
78
79         /**
80          * Aquires the IP address of this host by reading the /etc/hostname file
81          * and solving it. It is now stored in configuration
82          *
83          * @return      void
84          */
85         public static function acquireSelfIPAddress () {
86                 // Local IP by default
87                 $ip = '127.0.0.1';
88
89                 // Get a new instance
90                 $helperInstance = new ConsoleTools();
91
92                 try {
93                         // Get a file pointer
94                         $io = FrameworkFileInputPointer::createFrameworkFileInputPointer('/etc/hostname');
95
96                         // Read the file
97                         $hostname = trim($io->readFromFile());
98
99                         // Close the file
100                         $io->closeFile();
101
102                         // Resolve the IP number
103                         $ip = $helperInstance->resolveIpAddress($hostname);
104                 } catch (FileIoException $e) {
105                         // Fall-back to 'SESSION_SVR' which found on my Sun Station
106                         if (isset($_SERVER['SESSION_SVR'])) {
107                                 // Resolve it
108                                 $ip = $helperInstance->resolveIpAddress($_SERVER['SESSION_SVR']);
109                         } else {
110                                 // Could not find our hostname
111                                 $helperInstance->debugOutput(sprintf("[%s:] WARNING: Cannot resolve my own IP address.",
112                                         $helperInstance->__toString()
113                                 ));
114                         }
115                 } catch (FrameworkException $e) {
116                         // Output debug message
117                         $helperInstance->debugOutput(sprintf("[%s:] Problem while resolving own IP address: [%s|%s]:%s",
118                                 $helperInstance->__toString(),
119                                 $e->__toString(),
120                                 $e->getHexCode(),
121                                 $e->getMessage()
122                         ));
123                 }
124
125                 // Set it in configuration
126                 FrameworkConfiguration::getInstance()->setServerAddress($ip);
127         }
128
129         /**
130          * Determines own remote IP address (e.g. can be used to probe if we are
131          * reachable from outside by determining external IP and then connect to it.
132          * This is accomblished by connecting to the IP of www.ship-simu.org which
133          * should default to 217.172.186.31. Of course, this method requires a valid
134          * and working Internet connection to work properly.
135          *
136          * This method is taken and lightly rewritten from a user comment on php.net:
137          * http://de.php.net/manual/en/function.socket-create.php#49368
138          *
139          * @param       $dest                           IP destination we should connect to
140          * @param       $port                           Port destination we should connect to
141          * @return      $externalAddress        The determined external IP address
142          * @throws      InvalidSocketException  If socket initialization wents wrong or if an errors occurs
143          */
144         public static function determineExternalIp ($dest = '217.172.186.31', $port = 80) {
145                 // Get helper instance
146                 $helperInstance = new ConsoleTools();
147
148                 // First get a socket
149                 $socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
150
151                 // Is it valid?
152                 if (!is_resource($socket)) {
153                         // Throw InvalidSocketException
154                         throw new InvalidSocketException (array($helperInstance, gettype($socket), 0, 'unknown'));
155                 } // END - if
156
157                 // Get socket error code for verification
158                 $socketError = socket_last_error($socket);
159
160                 // Check if there was an error else
161                 if ($socketError > 0) {
162                         // Then throw again
163                         throw new InvalidSocketException(array($helperInstance, gettype($socket), $socketError, socket_strerror($socketError)), BaseListener::EXCEPTION_INVALID_SOCKET);
164                 } // END - if
165
166                 // Connect to the destination
167                 socket_connect($socket, $dest, $port);
168
169                 // Get the socket address (our external IP) and port (ignored)
170                 socket_getsockname($socket, $externalAddress, $ourPort);
171
172                 // Close the socket
173                 socket_close($socket);
174
175                 // Return determined external IP
176                 return $externalAddress;
177         }
178
179         /**
180          * Analyzes the 'environment', mostly $_SERVER, for presence of elements
181          * which indicates clearly that e.g. this script has been executed from
182          * console or web.
183          *
184          * @return      $type   The analyzed type, can be 'http' or 'console'
185          */
186         public static function analyzeEnvironmentForType () {
187                 // Default is the console
188                 $type = 'console';
189
190                 // Now, do we have a request method, or query string set?
191                 if ((isset($_SERVER['REQUEST_METHOD'])) || (isset($_SERVER['QUERY_STRING']))) {
192                         // Possibly HTTP request
193                         $type = 'http';
194                 } // END - if
195
196                 // Return it
197                 return $type;
198         }
199
200         /**
201          * Analyzes the 'environment', mostly $_SERVER, for presence of elements
202          * which indicates clearly that e.g. this script has been executed from
203          * console or web. This method should be used for class names, they
204          * currently are named differently. Here is a list to clarify this:
205          *
206          *   Request type | Class type
207          * -----------------------------
208          *      http      |    web
209          *     console    |  console
210          *
211          * @return      $type   The analyzed type, can be 'http' or 'console'
212          */
213         public static function analyzeEnvironmentForClassType () {
214                 // Default is the console
215                 $type = 'console';
216
217                 // Now, do we have a request method, or query string set?
218                 if ((isset($_SERVER['REQUEST_METHOD'])) || (isset($_SERVER['QUERY_STRING']))) {
219                         // Possibly HTTP request
220                         $type = 'web';
221                 } // END - if
222
223                 // Return it
224                 return $type;
225         }
226 }
227
228 // [EOF]
229 ?>