Added new interfaces Handleable/-DataSet and ProtocolHandler (no content yet).
[core.git] / inc / classes / main / rng / class_RandomNumberGenerator.php
1 <?php
2 /**
3  * A standard random number generator
4  *
5  * @author              Roland Haeder <webmaster@shipsimu.org>
6  * @version             0.0.0
7  * @copyright   Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2014 Core Developer Team
8  * @license             GNU GPL 3.0 or any newer version
9  * @link                http://www.shipsimu.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          * Self instance
52          */
53         private static $selfInstance = NULL;
54
55         /**
56          * Protected constructor
57          *
58          * @param       $className      Name of this class
59          * @return      void
60          */
61         protected function __construct ($className = __CLASS__) {
62                 // Call parent constructor
63                 parent::__construct($className);
64         }
65
66         /**
67          * Creates an instance of this class
68          *
69          * @param       $extraInstance  An extra instance for more salt (default: null)
70          * @return      $rngInstance    An instance of this random number generator
71          */
72         public static final function createRandomNumberGenerator (FrameworkInterface $extraInstance = NULL) {
73                 // Is self instance set?
74                 if (is_null(self::$selfInstance)) {
75                         // Get a new instance
76                         $rngInstance = new RandomNumberGenerator();
77
78                         // Initialize the RNG now
79                         $rngInstance->initRng($extraInstance);
80
81                         // Set it "self"
82                         self::$selfInstance = $rngInstance;
83                 } else {
84                         // Use from self instance
85                         $rngInstance = self::$selfInstance;
86                 }
87
88                 // Return the instance
89                 return $rngInstance;
90         }
91
92         /**
93          * Initializes the random number generator
94          *
95          * @param       $extraInstance  An extra instance for more salt (default: null)
96          * @return      void
97          * @todo        Add site key for stronger salt!
98          */
99         protected function initRng ($extraInstance) {
100                 // Get the prime number from config
101                 $this->prime = $this->getConfigInstance()->getConfigEntry('math_prime');
102
103                 // Calculate the extra number which is always the same unless you give
104                 // a better prime number
105                 $this->extraNumber = ($this->prime * $this->prime / pow(pi(), 2));
106
107                 // Seed mt_rand()
108                 mt_srand((double) sqrt(microtime(TRUE) * 100000000 * $this->extraNumber));
109
110                 // Set the server IP to cluster
111                 $serverIp = 'cluster';
112
113                 // Do we have a single server?
114                 if ($this->getConfigInstance()->getConfigEntry('is_single_server') == 'Y') {
115                         // Then use that IP for extra security
116                         $serverIp = $this->getConfigInstance()->detectServerAddress();
117                 } // END - if
118
119                 // Yet-another fixed salt. This is not dependend on server software or date
120                 if ($extraInstance instanceof FrameworkInterface) {
121                         // With extra instance information
122                         $this->fixedSalt = sha1(
123                                 $serverIp . ':' .
124                                 $extraInstance->__toString() . ':' .
125                                 serialize($this->getDatabaseInstance()->getConnectionData())
126                         );
127                 } else {
128                         // Without extra information
129                         $this->fixedSalt = sha1($serverIp . ':' . serialize($this->getDatabaseInstance()->getConnectionData()));
130                 }
131
132                 // One-way data we need for "extra-salting" the random number
133                 $this->extraSalt = sha1(
134                         $this->fixedSalt . ':' .
135                         getenv('SERVER_SOFTWARE') . ':' .
136                         $this->getConfigInstance()->getConfigEntry('date_key') . ':' .
137                         $this->getConfigInstance()->getConfigEntry('base_url')
138                 );
139
140                 // Get config entry for max salt length
141                 $this->rndStrLen = $this->getConfigInstance()->getConfigEntry('rnd_str_length');
142         }
143
144         /**
145          * Makes a pseudo-random string useable for salts
146          *
147          * @param       $length                 Length of the string, default: 128
148          * @return      $randomString   The pseudo-random string
149          */
150         public function randomString ($length = -1) {
151                 // Is the number <1, then fix it to default length
152                 if ($length < 1) {
153                         $length = $this->rndStrLen;
154                 } // END - if
155
156                 // Initialize the string
157                 $randomString = '';
158
159                 // And generate it
160                 for ($idx = 0; $idx < $length; $idx++) {
161                         // Add a random character and add it to our string
162                         $randomString .= chr($this->randomNumber(0, 255));
163                 } // END - for
164
165                 // Return the random string a little mixed up
166                 return str_shuffle($randomString);
167         }
168
169         /**
170          * Generate a pseudo-random integer number in a given range
171          *
172          * @param       $min    Min value to generate
173          * @param       $max    Max value to generate
174          * @return      $num    Pseudo-random number
175          * @todo        I had a better random number generator here but now it is somewhere lost :(
176          */
177         public function randomNumber ($min, $max) {
178                 return mt_rand($min, $max);
179         }
180
181         /**
182          * Getter for extra salt
183          *
184          * @return      $extraSalt
185          */
186         public final function getExtraSalt () {
187                 return $this->extraSalt;
188         }
189
190         /**
191          * Getter for fixed salt
192          *
193          * @return      $fixedSalt
194          */
195         public final function getFixedSalt () {
196                 return $this->fixedSalt;
197         }
198
199         /**
200          * Generates a key based on if we have extra (default) or fixed salt enabled
201          *
202          * @return      $key    The generated key for encryption
203          */
204         public function generateKey () {
205                 // Default is extra salt
206                 $key = md5($this->getExtraSalt());
207
208                 // Get key
209                 if ($this->getConfigInstance()->getConfigEntry('crypt_fixed_salt') == 'Y') {
210                         $key = md5($this->getFixedSalt());
211                 } // END - if
212
213                 // Return it
214                 return $key;
215         }
216 }
217
218 // [EOF]
219 ?>