]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/RegisterThrottle/RegisterThrottlePlugin.php
Merge branch 'master' into 1.0.x
[quix0rs-gnu-social.git] / plugins / RegisterThrottle / RegisterThrottlePlugin.php
1 <?php
2 /**
3  * StatusNet - the distributed open-source microblogging tool
4  * Copyright (C) 2010, StatusNet, Inc.
5  *
6  * Throttle registration by IP address
7  *
8  * PHP version 5
9  *
10  * This program is free software: you can redistribute it and/or modify
11  * it under the terms of the GNU Affero General Public License as published by
12  * the Free Software Foundation, either version 3 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU Affero General Public License for more details.
19  *
20  * You should have received a copy of the GNU Affero General Public License
21  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
22  *
23  * @category  Spam
24  * @package   StatusNet
25  * @author    Evan Prodromou <evan@status.net>
26  * @copyright 2010 StatusNet, Inc.
27  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
28  * @link      http://status.net/
29  */
30
31 if (!defined('STATUSNET')) {
32     exit(1);
33 }
34
35 /**
36  * Throttle registration by IP address
37  *
38  * We a) record IP address of registrants and b) throttle registrations.
39  *
40  * @category  Spam
41  * @package   StatusNet
42  * @author    Evan Prodromou <evan@status.net>
43  * @copyright 2010 StatusNet, Inc.
44  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
45  * @link      http://status.net/
46  */
47
48 class RegisterThrottlePlugin extends Plugin
49 {
50     /**
51      * Array of time spans in seconds to limits.
52      *
53      * Default is 3 registrations per hour, 5 per day, 10 per week.
54      */
55     public $regLimits = array(604800 => 10, // per week
56                               86400 => 5, // per day
57                               3600 => 3); // per hour
58
59     /**
60      * Disallow registration if a silenced user has registered from
61      * this IP address.
62      */
63     public $silenced = true;
64
65     /**
66      * Whether we're enabled; prevents recursion.
67      */
68     static private $enabled = true;
69
70     /**
71      * Database schema setup
72      *
73      * We store user registrations in a table registration_ip.
74      *
75      * @return boolean hook value; true means continue processing, false means stop.
76      */
77     function onCheckSchema()
78     {
79         $schema = Schema::get();
80
81         // For storing user-submitted flags on profiles
82         $schema->ensureTable('registration_ip',
83                              array(new ColumnDef('user_id', 'integer', null,
84                                                  false, 'PRI'),
85                                    new ColumnDef('ipaddress', 'varchar', 15, false, 'MUL'),
86                                    new ColumnDef('created', 'timestamp', null, false, 'MUL')));
87
88         return true;
89     }
90
91     /**
92      * Load related modules when needed
93      *
94      * @param string $cls Name of the class to be loaded
95      *
96      * @return boolean hook value; true means continue processing, false means stop.
97      */
98     function onAutoload($cls)
99     {
100         $dir = dirname(__FILE__);
101
102         switch ($cls)
103         {
104         case 'Registration_ip':
105             include_once $dir . '/'.$cls.'.php';
106             return false;
107         default:
108             return true;
109         }
110     }
111
112     /**
113      * Called when someone tries to register.
114      *
115      * We check the IP here to determine if it goes over any of our
116      * configured limits.
117      *
118      * @param Action $action Action that is being executed
119      *
120      * @return boolean hook value
121      */
122     function onStartRegistrationTry($action)
123     {
124         $ipaddress = $this->_getIpAddress();
125
126         if (empty($ipaddress)) {
127             // TRANS: Server exception thrown when no IP address can be found for a registation attempt.
128             throw new ServerException(_m('Cannot find IP address.'));
129         }
130
131         foreach ($this->regLimits as $seconds => $limit) {
132
133             $this->debug("Checking $seconds ($limit)");
134
135             $reg = $this->_getNthReg($ipaddress, $limit);
136
137             if (!empty($reg)) {
138                 $this->debug("Got a {$limit}th registration.");
139                 $regtime = strtotime($reg->created);
140                 $now     = time();
141                 $this->debug("Comparing {$regtime} to {$now}");
142                 if ($now - $regtime < $seconds) {
143                     // TRANS: Exception thrown when too many user have registered from one IP address within a given time frame.
144                     throw new Exception(_m('Too many registrations. Take a break and try again later.'));
145                 }
146             }
147         }
148
149         // Check for silenced users
150
151         if ($this->silenced) {
152             $ids = Registration_ip::usersByIP($ipaddress);
153             foreach ($ids as $id) {
154                 $profile = Profile::staticGet('id', $id);
155                 if ($profile && $profile->isSilenced()) {
156                     // TRANS: Exception thrown when attempting to register from an IP address from which silenced users have registered.
157                     throw new Exception(_m('A banned user has registered from this address.'));
158                 }
159             }
160         }
161
162         return true;
163     }
164
165     /**
166      * Called after someone registers, by any means.
167      *
168      * We record the successful registration and IP address.
169      *
170      * @param Profile $profile new user's profile
171      * @param User $user new user
172      *
173      * @return boolean hook value
174      */
175     function onEndUserRegister($profile, $user)
176     {
177         $ipaddress = $this->_getIpAddress();
178
179         if (empty($ipaddress)) {
180             // User registration can happen from command-line scripts etc.
181             return true;
182         }
183
184         $reg = new Registration_ip();
185
186         $reg->user_id   = $user->id;
187         $reg->ipaddress = $ipaddress;
188
189         $result = $reg->insert();
190
191         if (!$result) {
192             common_log_db_error($reg, 'INSERT', __FILE__);
193             // @todo throw an exception?
194         }
195
196         return true;
197     }
198
199     /**
200      * Check the version of the plugin.
201      *
202      * @param array &$versions Version array.
203      *
204      * @return boolean hook value
205      */
206     function onPluginVersion(&$versions)
207     {
208         $versions[] = array('name' => 'RegisterThrottle',
209                             'version' => STATUSNET_VERSION,
210                             'author' => 'Evan Prodromou',
211                             'homepage' => 'http://status.net/wiki/Plugin:RegisterThrottle',
212                             'description' =>
213                             // TRANS: Plugin description.
214                             _m('Throttles excessive registration from a single IP address.'));
215         return true;
216     }
217
218     /**
219      * Gets the current IP address.
220      *
221      * @return string IP address or null if not found.
222      */
223     private function _getIpAddress()
224     {
225         $keys = array('HTTP_X_FORWARDED_FOR',
226                       'HTTP_X_CLIENT',
227                       'CLIENT-IP',
228                       'REMOTE_ADDR');
229
230         foreach ($keys as $k) {
231             if (!empty($_SERVER[$k])) {
232                 return $_SERVER[$k];
233             }
234         }
235
236         return null;
237     }
238
239     /**
240      * Gets the Nth registration with the given IP address.
241      *
242      * @param string  $ipaddress Address to key on
243      * @param integer $n         Nth address
244      *
245      * @return Registration_ip nth registration or null if not found.
246      */
247     private function _getNthReg($ipaddress, $n)
248     {
249         $reg = new Registration_ip();
250
251         $reg->ipaddress = $ipaddress;
252
253         $reg->orderBy('created DESC');
254         $reg->limit($n - 1, 1);
255
256         if ($reg->find(true)) {
257             return $reg;
258         } else {
259             return null;
260         }
261     }
262
263     /**
264      * When silencing a user, silence all other users registered from that IP
265      * address.
266      *
267      * @param Profile $profile Person getting a new role
268      * @param string  $role    Role being assigned like 'moderator' or 'silenced'
269      *
270      * @return boolean hook value
271      */
272     function onEndGrantRole($profile, $role)
273     {
274         if (!self::$enabled) {
275             return true;
276         }
277
278         if ($role != Profile_role::SILENCED) {
279             return true;
280         }
281
282         if (!$this->silenced) {
283             return true;
284         }
285
286         $ri = Registration_ip::staticGet('user_id', $profile->id);
287
288         if (empty($ri)) {
289             return true;
290         }
291
292         $ids = Registration_ip::usersByIP($ri->ipaddress);
293
294         foreach ($ids as $id) {
295             if ($id == $profile->id) {
296                 continue;
297             }
298
299             $other = Profile::staticGet('id', $id);
300
301             if (empty($other)) {
302                 continue;
303             }
304
305             if ($other->isSilenced()) {
306                 continue;
307             }
308
309             $old = self::$enabled;
310             self::$enabled = false;
311             $other->silence();
312             self::$enabled = $old;
313         }
314     }
315 }