TemplateEngine is known as WebTemplateEngine (most parts are in BasTemplateEngine...
[shipsimu.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, this is free software
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                 // Set part description
61                 $this->setObjectDescription("Standard random number generator");
62
63                 // Create unique ID number
64                 $this->generateUniqueId();
65
66                 // Clean up a little
67                 $this->removeNumberFormaters();
68                 $this->removeSystemArray();
69         }
70
71         /**
72          * Creates an instance of this class
73          *
74          * @param       $extraInstance  An extra instance for more salt (default: null)
75          * @return      $rngInstance    An instance of this random number generator
76          */
77         public final static function createRandomNumberGenerator (FrameworkInterface $extraInstance = null) {
78                 // Get a new instance
79                 $rngInstance = new RandomNumberGenerator();
80
81                 // Initialize the RNG now
82                 $rngInstance->initRng($extraInstance);
83
84                 // Return the instance
85                 return $rngInstance;
86         }
87
88         /**
89          * Initializes the random number generator
90          *
91          * @param       $extraInstance  An extra instance for more salt (default: null)
92          * @return      void
93          * @todo        Add site key for stronger salt!
94          */
95         protected function initRng ($extraInstance) {
96                 // Get the prime number from config
97                 $this->prime = $this->getConfigInstance()->readConfig('math_prime');
98
99                 // Calculate the extra number which is always the same unless you give
100                 // a better prime number
101                 $this->extraNumber = ($this->prime * $this->prime / (pi() ^ 2));
102
103                 // Seed mt_rand()
104                 mt_srand((double) sqrt(microtime() * 100000000 * $this->extraNumber));
105
106                 // Set the server IP to cluster
107                 $serverIp = "cluster";
108
109                 // Do we have a single server?
110                 if ($this->getConfigInstance()->readConfig('is_single_server') == "Y") {
111                         // Then use that IP for extra security
112                         $serverIp = getenv('SERVER_ADDR');
113                 } // END - if
114
115                 // Yet-another fixed salt. This is not dependend on server software or date
116                 if ($extraInstance instanceof FrameworkInterface) {
117                         // With extra instance information
118                         $this->fixedSalt = sha1($serverIp . ":" . $extraInstance->__toString() . ":" . serialize($this->getDatabaseInstance()->getConnectionData()) . ":" . $extraInstance->getObjectDescription());
119                 } else {
120                         // Without extra information
121                         $this->fixedSalt = sha1($serverIp . ":" . serialize($this->getDatabaseInstance()->getConnectionData()));
122                 }
123
124                 // One-way data we need for "extra-salting" the random number
125                 $this->extraSalt = sha1($this->fixedSalt . ":" . getenv('SERVER_SOFTWARE') . ":" . $this->getConfigInstance()->readConfig('date_key') . $this->getConfigInstance()->readConfig('base_url'));
126
127                 // Get config entry for max salt length
128                 $this->rndStrLen = $this->getConfigInstance()->readConfig('rnd_str_length');
129         }
130
131         /**
132          * Makes a pseudo-random string useable for salts
133          *
134          * @param       $length                 Length of the string, default: 128
135          * @return      $randomString   The pseudo-random string
136          */
137         public function randomString ($length = -1) {
138                 // Is the number <1, then fix it to default length
139                 if ($length < 1) $length = $this->rndStrLen;
140
141                 // Initialize the string
142                 $randomString = "";
143
144                 // And generate it
145                 for ($idx = 0; $idx < $length; $idx++) {
146                         // Add a random character and add it to our string
147                         $randomString .= chr($this->randomNumber(0, 255));
148                 }
149
150                 // Return the random string a little mixed up
151                 return str_shuffle($randomString);
152         }
153
154         /**
155          * Generate a pseudo-random integer number in a given range
156          *
157          * @param       $min    Min value to generate
158          * @param       $max    Max value to generate
159          * @return      $num    Pseudo-random number
160          * @todo        I had a better random number generator here but now it is somewhere lost :(
161          */
162         public function randomNumber ($min, $max) {
163                 return mt_rand($min, $max);
164         }
165
166         /**
167          * Getter for extra salt
168          *
169          * @return      $extraSalt
170          */
171         public final function getExtraSalt () {
172                 return $this->extraSalt;
173         }
174
175         /**
176          * Getter for fixed salt
177          *
178          * @return      $fixedSalt
179          */
180         public final function getFixedSalt () {
181                 return $this->fixedSalt;
182         }
183 }
184
185 // [EOF]
186 ?>