]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/AnonymousFave/AnonymousFavePlugin.php
Allow turning off Anonymous Favoring for specific users' notices
[quix0rs-gnu-social.git] / plugins / AnonymousFave / AnonymousFavePlugin.php
1 <?php
2 /**
3  * StatusNet - the distributed open-source microblogging tool
4  * Copyright (C) 2010, StatusNet, Inc.
5  *
6  * A plugin to allow anonymous users to favorite notices
7  *
8  * If you want to keep certain users from having anonymous faving for their
9  * notices initialize the plugin with the restricted array, e.g.:
10  *
11  * addPlugin(
12  *     'AnonymousFave',
13  *     array('restricted' => array('spock', 'kirk', 'bones'))
14  * );
15  *
16  *
17  * PHP version 5
18  *
19  * This program is free software: you can redistribute it and/or modify
20  * it under the terms of the GNU Affero General Public License as published by
21  * the Free Software Foundation, either version 3 of the License, or
22  * (at your option) any later version.
23  *
24  * This program is distributed in the hope that it will be useful,
25  * but WITHOUT ANY WARRANTY; without even the implied warranty of
26  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
27  * GNU Affero General Public License for more details.
28  *
29  * You should have received a copy of the GNU Affero General Public License
30  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
31  *
32  * @category  Plugin
33  * @package   StatusNet
34  * @author    Zach Copley <zach@status.net>
35  * @copyright 2010 StatusNet, Inc.
36  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
37  * @link      http://status.net/
38  */
39
40 if (!defined('STATUSNET')) {
41     // This check helps protect against security problems;
42     // your code file can't be executed directly from the web.
43     exit(1);
44 }
45
46 define('ANONYMOUS_FAVE_PLUGIN_VERSION', '0.1');
47
48 /**
49  * Anonymous Fave plugin to allow anonymous (not logged in) users
50  * to favorite notices
51  *
52  * @category  Plugin
53  * @package   StatusNet
54  * @author    Zach Copley <zach@status.net>
55  * @copyright 2010 StatusNet, Inc.
56  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
57  * @link      http://status.net/
58  */
59
60 class AnonymousFavePlugin extends Plugin
61 {
62
63     // Array of users who should not have anon faving. The default is
64     // that anonymous faving is allowed for all users.
65     public $restricted = array();
66
67     function onArgsInitialize() {
68         // We always want a session because we're tracking anon users
69         common_ensure_session();
70     }
71
72     /**
73      * Hook for ensuring our tables are created
74      *
75      * Ensures the fave_tally table is there and has the right columns
76      *
77      * @return boolean hook return
78      */
79
80     function onCheckSchema()
81     {
82         $schema = Schema::get();
83
84         // For storing total number of times a notice has been faved
85
86         $schema->ensureTable('fave_tally',
87             array(
88                 new ColumnDef('notice_id', 'integer', null,  false, 'PRI'),
89                 new ColumnDef('count', 'integer', null, false),
90                 new ColumnDef(
91                     'modified',
92                     'timestamp',
93                     null,
94                     false,
95                     null,
96                     'CURRENT_TIMESTAMP',
97                     'on update CURRENT_TIMESTAMP'
98                 )
99             )
100         );
101
102         return true;
103     }
104
105     function onEndShowHTML($action)
106     {
107         if (!common_logged_in()) {
108             // Set a place to return to when submitting forms
109             common_set_returnto($action->selfUrl());
110         }
111     }
112
113     function onEndShowScripts($action)
114     {
115         // Setup ajax calls for favoriting. Usually this is only done when
116         // a user is logged in.
117         $action->inlineScript('SN.U.NoticeFavor();');
118     }
119
120     function onAutoload($cls)
121     {
122         $dir = dirname(__FILE__);
123
124         switch ($cls) {
125             case 'Fave_tally':
126                 include_once $dir . '/' . $cls . '.php';
127                 return false;
128             case 'AnonFavorAction':
129                 include_once $dir . '/' . strtolower(mb_substr($cls, 0, -6)) . '.php';
130                 return false;
131             case 'AnonDisFavorAction':
132                 include_once $dir . '/' . strtolower(mb_substr($cls, 0, -6)) . '.php';
133                 return false;
134             case 'AnonFavorForm':
135                 include_once $dir . '/anonfavorform.php';
136                 return false;
137             case 'AnonDisFavorForm':
138                 include_once $dir . '/anondisfavorform.php';
139                 return false;
140             default:
141                 return true;
142         }
143     }
144
145     function onStartInitializeRouter($m)
146     {
147         $m->connect('main/anonfavor', array('action' => 'AnonFavor'));
148         $m->connect('main/anondisfavor', array('action' => 'AnonDisFavor'));
149
150         return true;
151     }
152
153     function onStartShowNoticeOptions($item)
154     {
155         if (!common_logged_in()) {
156             $item->out->elementStart('div', 'notice-options');
157             $item->showFaveForm();
158             $item->out->elementEnd('div');
159         }
160
161         return true;
162     }
163
164     function onStartShowFaveForm($item)
165     {
166         if (!common_logged_in() && $this->hasAnonFaving($item)) {
167
168             $profile = AnonymousFavePlugin::getAnonProfile();
169             if (!empty($profile)) {
170                 if ($profile->hasFave($item->notice)) {
171                     $disfavor = new AnonDisFavorForm($item->out, $item->notice);
172                     $disfavor->show();
173                 } else {
174                     $favor = new AnonFavorForm($item->out, $item->notice);
175                     $favor->show();
176                 }
177             }
178         }
179
180         return true;
181     }
182
183     function onEndFavorNoticeForm($form, $notice)
184     {
185         $this->showTally($form->out, $notice);
186     }
187
188     function onEndDisFavorNoticeForm($form, $notice)
189     {
190         $this->showTally($form->out, $notice);
191     }
192
193     function showTally($out, $notice)
194     {
195         $tally = Fave_tally::ensureTally($notice->id);
196
197         if (!empty($tally)) {
198             $out->elementStart(
199                 'div',
200                 array(
201                     'id' => 'notice-' . $notice->id . '-tally',
202                     'class' => 'notice-tally'
203                 )
204             );
205             $out->raw(sprintf(_m("favored %d times"), $tally->count));
206             $out->elementEnd('div');
207         }
208     }
209
210     function onEndFavorNotice($profile, $notice)
211     {
212         $tally = Fave_tally::increment($notice->id);
213     }
214
215     function onEndDisfavorNotice($profile, $notice)
216     {
217         $tally = Fave_tally::decrement($notice->id);
218     }
219
220     static function createAnonProfile()
221     {
222         // Get the anon user's IP, and turn it into a nickname
223         list($proxy, $ip) = common_client_ip();
224
225         // IP + time + random number should help to avoid collisions
226         $baseNickname = $ip . '-' . time() . '-' . common_good_rand(5);
227
228         $profile = new Profile();
229         $profile->nickname = $baseNickname;
230         $id = $profile->insert();
231
232         if (!$id) {
233             throw new ServerException(_m("Couldn't create anonymous user session."));
234         }
235
236         // Stick the Profile ID into the nickname
237         $orig = clone($profile);
238
239         $profile->nickname = 'anon-' . $id . '-' . $baseNickname;
240         $result = $profile->update($orig);
241
242         if (!$result) {
243             throw new ServerException(_m("Couldn't create anonymous user session."));
244         }
245
246         common_log(
247             LOG_INFO,
248             "AnonymousFavePlugin - created profile for anonymous user from IP: "
249             . $ip
250             . ', nickname = '
251             . $profile->nickname
252         );
253
254         return $profile;
255     }
256
257     static function getAnonProfile()
258     {
259
260         $token = $_SESSION['anon_token'];
261         $anon = base64_decode($token);
262
263         $profile = null;
264
265         if (!empty($anon) && substr($anon, 0, 5) == 'anon-') {
266             $parts = explode('-', $anon);
267             $id = $parts[1];
268             // Do Profile lookup by ID instead of nickname for safety/performance
269             $profile = Profile::staticGet('id', $id);
270         } else {
271             $profile = AnonymousFavePlugin::createAnonProfile();
272             // Obfuscate so it's hard to figure out the Profile ID
273             $_SESSION['anon_token'] = base64_encode($profile->nickname);
274         }
275
276         return $profile;
277     }
278
279     /**
280      * Determine whether a given NoticeListItem should have the
281      * anonymous fave/disfave form
282      *
283      * @param NoticeListItem $item
284      *
285      * @return boolean false if the profile associated with the notice is
286      *                       in the list of restricted profiles, otherwise
287      *                       return true
288      */
289     function hasAnonFaving($item)
290     {
291         $profile = Profile::staticGet('id', $item->notice->profile_id);
292         if (in_array($profile->nickname, $this->restricted)) {
293             return false;
294         }
295
296         return true;
297     }
298
299     /**
300      * Provide plugin version information.
301      *
302      * This data is used when showing the version page.
303      *
304      * @param array &$versions array of version data arrays; see EVENTS.txt
305      *
306      * @return boolean hook value
307      */
308     function onPluginVersion(&$versions)
309     {
310         $url = 'http://status.net/wiki/Plugin:AnonymousFave';
311
312         $versions[] = array('name' => 'AnonymousFave',
313             'version' => ANONYMOUS_FAVE_PLUGIN_VERSION,
314             'author' => 'Zach Copley',
315             'homepage' => $url,
316             'rawdescription' =>
317             _m('Allow anonymous users to favorite notices.'));
318
319         return true;
320     }
321
322 }