]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/AnonymousFave/AnonymousFavePlugin.php
Merge branch 'master' into 0.9.x
[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->elementStart('span', array('class' => 'fave-tally-title'));
206             // TRANS: Label for tally for number of times a notice was favored.
207             $out->raw(sprintf(_m("Favored")));
208             $out->elementEnd('span');
209             $out->elementStart('span', array('class' => 'fave-tally'));
210             $out->raw($tally->count);
211             $out->elementEnd('span');
212             $out->elementEnd('div');
213         }
214     }
215
216     function onEndFavorNotice($profile, $notice)
217     {
218         $tally = Fave_tally::increment($notice->id);
219     }
220
221     function onEndDisfavorNotice($profile, $notice)
222     {
223         $tally = Fave_tally::decrement($notice->id);
224     }
225
226     static function createAnonProfile()
227     {
228         // Get the anon user's IP, and turn it into a nickname
229         list($proxy, $ip) = common_client_ip();
230
231         // IP + time + random number should help to avoid collisions
232         $baseNickname = $ip . '-' . time() . '-' . common_good_rand(5);
233
234         $profile = new Profile();
235         $profile->nickname = $baseNickname;
236         $id = $profile->insert();
237
238         if (!$id) {
239             // TRANS: Server exception.
240             throw new ServerException(_m("Couldn't create anonymous user session."));
241         }
242
243         // Stick the Profile ID into the nickname
244         $orig = clone($profile);
245
246         $profile->nickname = 'anon-' . $id . '-' . $baseNickname;
247         $result = $profile->update($orig);
248
249         if (!$result) {
250             // TRANS: Server exception.
251             throw new ServerException(_m("Couldn't create anonymous user session."));
252         }
253
254         common_log(
255             LOG_INFO,
256             "AnonymousFavePlugin - created profile for anonymous user from IP: "
257             . $ip
258             . ', nickname = '
259             . $profile->nickname
260         );
261
262         return $profile;
263     }
264
265     static function getAnonProfile()
266     {
267
268         $token = $_SESSION['anon_token'];
269         $anon = base64_decode($token);
270
271         $profile = null;
272
273         if (!empty($anon) && substr($anon, 0, 5) == 'anon-') {
274             $parts = explode('-', $anon);
275             $id = $parts[1];
276             // Do Profile lookup by ID instead of nickname for safety/performance
277             $profile = Profile::staticGet('id', $id);
278         } else {
279             $profile = AnonymousFavePlugin::createAnonProfile();
280             // Obfuscate so it's hard to figure out the Profile ID
281             $_SESSION['anon_token'] = base64_encode($profile->nickname);
282         }
283
284         return $profile;
285     }
286
287     /**
288      * Determine whether a given NoticeListItem should have the
289      * anonymous fave/disfave form
290      *
291      * @param NoticeListItem $item
292      *
293      * @return boolean false if the profile associated with the notice is
294      *                       in the list of restricted profiles, otherwise
295      *                       return true
296      */
297     function hasAnonFaving($item)
298     {
299         $profile = Profile::staticGet('id', $item->notice->profile_id);
300         if (in_array($profile->nickname, $this->restricted)) {
301             return false;
302         }
303
304         return true;
305     }
306
307     /**
308      * Provide plugin version information.
309      *
310      * This data is used when showing the version page.
311      *
312      * @param array &$versions array of version data arrays; see EVENTS.txt
313      *
314      * @return boolean hook value
315      */
316     function onPluginVersion(&$versions)
317     {
318         $url = 'http://status.net/wiki/Plugin:AnonymousFave';
319
320         $versions[] = array('name' => 'AnonymousFave',
321             'version' => ANONYMOUS_FAVE_PLUGIN_VERSION,
322             'author' => 'Zach Copley',
323             'homepage' => $url,
324             'rawdescription' =>
325             // TRANS: Plugin description.
326             _m('Allow anonymous users to favorite notices.'));
327
328         return true;
329     }
330
331 }