Some cleanups, more usage of ObjectFactory:
[core.git] / inc / classes / main / rng / class_RandomNumberGenerator.php
1 <?php
2 /**
3  * A standard random number generator
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 RandomNumberGenerator extends BaseFrameworkSystem {
25         /**
26          * Prime number for better pseudo random numbers
27          */
28         private $prime = 0;
29
30         /**
31          * Add this calculated number to the rng
32          */
33         private $extraNumber = 0;
34
35         /**
36          * Extra salt for secured hashing
37          */
38         private $extraSalt = '';
39
40         /**
41          * Fixed salt for secured hashing
42          */
43         private $fixedSalt = '';
44
45         /**
46          * Maximum length for random string
47          */
48         private $rndStrLen = 0;
49
50         /**
51          * Protected constructor
52          *
53          * @param       $className      Name of this class
54          * @return      void
55          */
56         protected function __construct ($className = __CLASS__) {
57                 // Call parent constructor
58                 parent::__construct($className);
59         }
60
61         /**
62          * Creates an instance of this class
63          *
64          * @param       $extraInstance  An extra instance for more salt (default: null)
65          * @return      $rngInstance    An instance of this random number generator
66          */
67         public static final function createRandomNumberGenerator (FrameworkInterface $extraInstance = NULL) {
68                 // Get a new instance
69                 $rngInstance = new RandomNumberGenerator();
70
71                 // Initialize the RNG now
72                 $rngInstance->initRng($extraInstance);
73
74                 // Return the instance
75                 return $rngInstance;
76         }
77
78         /**
79          * Initializes the random number generator
80          *
81          * @param       $extraInstance  An extra instance for more salt (default: null)
82          * @return      void
83          * @todo        Add site key for stronger salt!
84          */
85         protected function initRng ($extraInstance) {
86                 // Get the prime number from config
87                 $this->prime = $this->getConfigInstance()->getConfigEntry('math_prime');
88
89                 // Calculate the extra number which is always the same unless you give
90                 // a better prime number
91                 $this->extraNumber = ($this->prime * $this->prime / pow(pi(), 2));
92
93                 // Seed mt_rand()
94                 mt_srand((double) sqrt(microtime() * 100000000 * $this->extraNumber));
95
96                 // Set the server IP to cluster
97                 $serverIp = 'cluster';
98
99                 // Do we have a single server?
100                 if ($this->getConfigInstance()->getConfigEntry('is_single_server') == 'Y') {
101                         // Then use that IP for extra security
102                         $serverIp = $this->getConfigInstance()->detectServerAddress();
103                 } // END - if
104
105                 // Yet-another fixed salt. This is not dependend on server software or date
106                 if ($extraInstance instanceof FrameworkInterface) {
107                         // With extra instance information
108                         $this->fixedSalt = sha1(
109                                 $serverIp . ':' .
110                                 $extraInstance->__toString() . ':' .
111                                 serialize($this->getDatabaseInstance()->getConnectionData())
112                         );
113                 } else {
114                         // Without extra information
115                         $this->fixedSalt = sha1($serverIp . ':' . serialize($this->getDatabaseInstance()->getConnectionData()));
116                 }
117
118                 // One-way data we need for "extra-salting" the random number
119                 $this->extraSalt = sha1(
120                         $this->fixedSalt . ':' .
121                         getenv('SERVER_SOFTWARE') . ':' .
122                         $this->getConfigInstance()->getConfigEntry('date_key') . ':' .
123                         $this->getConfigInstance()->getConfigEntry('base_url')
124                 );
125
126                 // Get config entry for max salt length
127                 $this->rndStrLen = $this->getConfigInstance()->getConfigEntry('rnd_str_length');
128         }
129
130         /**
131          * Makes a pseudo-random string useable for salts
132          *
133          * @param       $length                 Length of the string, default: 128
134          * @return      $randomString   The pseudo-random string
135          */
136         public function randomString ($length = -1) {
137                 // Is the number <1, then fix it to default length
138                 if ($length < 1) {
139                         $length = $this->rndStrLen;
140                 } // END - if
141
142                 // Initialize the string
143                 $randomString = '';
144
145                 // And generate it
146                 for ($idx = 0; $idx < $length; $idx++) {
147                         // Add a random character and add it to our string
148                         $randomString .= chr($this->randomNumber(0, 255));
149                 } // END - for
150
151                 // Return the random string a little mixed up
152                 return str_shuffle($randomString);
153         }
154
155         /**
156          * Generate a pseudo-random integer number in a given range
157          *
158          * @param       $min    Min value to generate
159          * @param       $max    Max value to generate
160          * @return      $num    Pseudo-random number
161          * @todo        I had a better random number generator here but now it is somewhere lost :(
162          */
163         public function randomNumber ($min, $max) {
164                 return mt_rand($min, $max);
165         }
166
167         /**
168          * Getter for extra salt
169          *
170          * @return      $extraSalt
171          */
172         public final function getExtraSalt () {
173                 return $this->extraSalt;
174         }
175
176         /**
177          * Getter for fixed salt
178          *
179          * @return      $fixedSalt
180          */
181         public final function getFixedSalt () {
182                 return $this->fixedSalt;
183         }
184
185         /**
186          * Generates a key based on if we have extra (default) or fixed salt enabled
187          *
188          * @return      $key    The generated key for encryption
189          */
190         public function generateKey () {
191                 // Default is extra salt
192                 $key = md5($this->getExtraSalt());
193
194                 // Get key
195                 if ($this->getConfigInstance()->getConfigEntry('crypt_fixed_salt') == 'Y') {
196                         $key = md5($this->getFixedSalt());
197                 } // END - if
198
199                 // Return it
200                 return $key;
201         }
202 }
203
204 // [EOF]
205 ?>