]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/RegisterThrottle/RegisterThrottlePlugin.php
7e2dde80fa1f2d9cdb363aae7f97f800cc7c7ee4
[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
56     public $regLimits = array(604800 => 10, // per week
57                               86400 => 5, // per day
58                               3600 => 3); // per hour
59
60     /**
61      * Disallow registration if a silenced user has registered from
62      * this IP address.
63      */
64
65     public $silenced = true;
66
67     /**
68      * Whether we're enabled; prevents recursion.
69      */
70
71     static private $enabled = true;
72
73     /**
74      * Database schema setup
75      *
76      * We store user registrations in a table registration_ip.
77      *
78      * @return boolean hook value; true means continue processing, false means stop.
79      */
80
81     function onCheckSchema()
82     {
83         $schema = Schema::get();
84
85         // For storing user-submitted flags on profiles
86
87         $schema->ensureTable('registration_ip',
88                              array(new ColumnDef('user_id', 'integer', null,
89                                                  false, 'PRI'),
90                                    new ColumnDef('ipaddress', 'varchar', 15, false, 'MUL'),
91                                    new ColumnDef('created', 'timestamp', null, false, 'MUL')));
92
93         return true;
94     }
95
96     /**
97      * Load related modules when needed
98      *
99      * @param string $cls Name of the class to be loaded
100      *
101      * @return boolean hook value; true means continue processing, false means stop.
102      */
103
104     function onAutoload($cls)
105     {
106         $dir = dirname(__FILE__);
107
108         switch ($cls)
109         {
110         case 'Registration_ip':
111             include_once $dir . '/'.$cls.'.php';
112             return false;
113         default:
114             return true;
115         }
116     }
117
118     /**
119      * Called when someone tries to register.
120      *
121      * We check the IP here to determine if it goes over any of our
122      * configured limits.
123      *
124      * @param Action $action Action that is being executed
125      *
126      * @return boolean hook value
127      *
128      */
129     function onStartRegistrationTry($action)
130     {
131         $ipaddress = $this->_getIpAddress();
132
133         if (empty($ipaddress)) {
134             throw new ServerException(_m('Cannot find IP address.'));
135         }
136
137         foreach ($this->regLimits as $seconds => $limit) {
138
139             $this->debug("Checking $seconds ($limit)");
140
141             $reg = $this->_getNthReg($ipaddress, $limit);
142
143             if (!empty($reg)) {
144                 $this->debug("Got a {$limit}th registration.");
145                 $regtime = strtotime($reg->created);
146                 $now     = time();
147                 $this->debug("Comparing {$regtime} to {$now}");
148                 if ($now - $regtime < $seconds) {
149                     throw new Exception(_m("Too many registrations. Take a break and try again later."));
150                 }
151             }
152         }
153
154         // Check for silenced users
155
156         if ($this->silenced) {
157             $ids = Registration_ip::usersByIP($ipaddress);
158             foreach ($ids as $id) {
159                 $profile = Profile::staticGet('id', $id);
160                 if ($profile && $profile->isSilenced()) {
161                     throw new Exception(_("A banned user has registered from this address."));
162                 }
163             }
164         }
165
166         return true;
167     }
168
169     /**
170      * Called after someone registers.
171      *
172      * We record the successful registration and IP address.
173      *
174      * @param Action $action Action that is being executed
175      *
176      * @return boolean hook value
177      *
178      */
179
180     function onEndRegistrationTry($action)
181     {
182         $ipaddress = $this->_getIpAddress();
183
184         if (empty($ipaddress)) {
185             throw new ServerException(_m('Cannot find IP address.'));
186         }
187
188         $user = common_current_user();
189
190         if (empty($user)) {
191             throw new ServerException(_m('Cannot find user after successful registration.'));
192         }
193
194         $reg = new Registration_ip();
195
196         $reg->user_id   = $user->id;
197         $reg->ipaddress = $ipaddress;
198
199         $result = $reg->insert();
200
201         if (!$result) {
202             common_log_db_error($reg, 'INSERT', __FILE__);
203             // @todo throw an exception?
204         }
205
206         return true;
207     }
208
209     /**
210      * Check the version of the plugin.
211      *
212      * @param array &$versions Version array.
213      *
214      * @return boolean hook value
215      */
216
217     function onPluginVersion(&$versions)
218     {
219         $versions[] = array('name' => 'RegisterThrottle',
220                             'version' => STATUSNET_VERSION,
221                             'author' => 'Evan Prodromou',
222                             'homepage' => 'http://status.net/wiki/Plugin:RegisterThrottle',
223                             'description' =>
224                             _m('Throttles excessive registration from a single IP address.'));
225         return true;
226     }
227
228     /**
229      * Gets the current IP address.
230      *
231      * @return string IP address or null if not found.
232      */
233
234     private function _getIpAddress()
235     {
236         $keys = array('HTTP_X_FORWARDED_FOR',
237                       'CLIENT-IP',
238                       'REMOTE_ADDR');
239
240         foreach ($keys as $k) {
241             if (!empty($_SERVER[$k])) {
242                 return $_SERVER[$k];
243             }
244         }
245
246         return null;
247     }
248
249     /**
250      * Gets the Nth registration with the given IP address.
251      *
252      * @param string  $ipaddress Address to key on
253      * @param integer $n         Nth address
254      *
255      * @return Registration_ip nth registration or null if not found.
256      */
257
258     private function _getNthReg($ipaddress, $n)
259     {
260         $reg = new Registration_ip();
261
262         $reg->ipaddress = $ipaddress;
263
264         $reg->orderBy('created DESC');
265         $reg->limit($n - 1, 1);
266
267         if ($reg->find(true)) {
268             return $reg;
269         } else {
270             return null;
271         }
272     }
273
274     /**
275      * When silencing a user, silence all other users registered from that IP
276      * address.
277      *
278      * @param Profile $profile Person getting a new role
279      * @param string  $role    Role being assigned like 'moderator' or 'silenced'
280      *
281      * @return boolean hook value
282      */
283
284     function onEndGrantRole($profile, $role)
285     {
286         if (!self::$enabled) {
287             return true;
288         }
289
290         if ($role != Profile_role::SILENCED) {
291             return true;
292         }
293
294         if (!$this->silenced) {
295             return true;
296         }
297
298         $ri = Registration_ip::staticGet('user_id', $profile->id);
299
300         if (empty($ri)) {
301             return true;
302         }
303
304         $ids = Registration_ip::usersByIP($ri->ipaddress);
305
306         foreach ($ids as $id) {
307
308             if ($id == $profile->id) {
309                 continue;
310             }
311
312             $other = Profile::staticGet('id', $id);
313
314             if (empty($other)) {
315                 continue;
316             }
317
318             if ($other->isSilenced()) {
319                 continue;
320             }
321
322             $old = self::$enabled;
323             self::$enabled = false;
324             $other->silence();
325             self::$enabled = $old;
326         }
327     }
328 }