]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/AnonymousFave/AnonymousFavePlugin.php
The overloaded DB_DataObject function staticGet is now called getKV
[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 class AnonymousFavePlugin extends Plugin
60 {
61     // Array of users who should not have anon faving. The default is
62     // that anonymous faving is allowed for all users.
63     public $restricted = array();
64
65     function onArgsInitialize() {
66         // We always want a session because we're tracking anon users
67         common_ensure_session();
68     }
69
70     /**
71      * Hook for ensuring our tables are created
72      *
73      * Ensures the fave_tally table is there and has the right columns
74      *
75      * @return boolean hook return
76      */
77
78     function onCheckSchema()
79     {
80         $schema = Schema::get();
81
82         // For storing total number of times a notice has been faved
83
84         $schema->ensureTable('fave_tally',
85             array(
86                 new ColumnDef('notice_id', 'integer', null,  false, 'PRI'),
87                 new ColumnDef('count', 'integer', null, false),
88                 new ColumnDef(
89                     'modified',
90                     'timestamp',
91                     null,
92                     false,
93                     null,
94                     'CURRENT_TIMESTAMP',
95                     'on update CURRENT_TIMESTAMP'
96                 )
97             )
98         );
99
100         return true;
101     }
102
103     function onEndShowHTML($action)
104     {
105         if (!common_logged_in()) {
106             // Set a place to return to when submitting forms
107             common_set_returnto($action->selfUrl());
108         }
109     }
110
111     function onEndShowScripts($action)
112     {
113         // Setup ajax calls for favoriting. Usually this is only done when
114         // a user is logged in.
115         $action->inlineScript('SN.U.NoticeFavor();');
116     }
117
118     function onAutoload($cls)
119     {
120         $dir = dirname(__FILE__);
121
122         switch ($cls) {
123             case 'Fave_tally':
124                 include_once $dir . '/' . $cls . '.php';
125                 return false;
126             case 'AnonFavorAction':
127                 include_once $dir . '/' . strtolower(mb_substr($cls, 0, -6)) . '.php';
128                 return false;
129             case 'AnonDisFavorAction':
130                 include_once $dir . '/' . strtolower(mb_substr($cls, 0, -6)) . '.php';
131                 return false;
132             case 'AnonFavorForm':
133                 include_once $dir . '/anonfavorform.php';
134                 return false;
135             case 'AnonDisFavorForm':
136                 include_once $dir . '/anondisfavorform.php';
137                 return false;
138             default:
139                 return true;
140         }
141     }
142
143     function onStartInitializeRouter($m)
144     {
145         $m->connect('main/anonfavor', array('action' => 'AnonFavor'));
146         $m->connect('main/anondisfavor', array('action' => 'AnonDisFavor'));
147
148         return true;
149     }
150
151     function onStartShowNoticeOptions($item)
152     {
153         if (!common_logged_in()) {
154             $item->out->elementStart('div', 'notice-options');
155             $item->showFaveForm();
156             $item->out->elementEnd('div');
157         }
158
159         return true;
160     }
161
162     function onStartShowFaveForm($item)
163     {
164         if (!common_logged_in() && $this->hasAnonFaving($item)) {
165
166             $profile = AnonymousFavePlugin::getAnonProfile();
167             if (!empty($profile)) {
168                 if ($profile->hasFave($item->notice)) {
169                     $disfavor = new AnonDisFavorForm($item->out, $item->notice);
170                     $disfavor->show();
171                 } else {
172                     $favor = new AnonFavorForm($item->out, $item->notice);
173                     $favor->show();
174                 }
175             }
176         }
177
178         return true;
179     }
180
181     function onEndFavorNoticeForm($form, $notice)
182     {
183         $this->showTally($form->out, $notice);
184     }
185
186     function onEndDisFavorNoticeForm($form, $notice)
187     {
188         $this->showTally($form->out, $notice);
189     }
190
191     function showTally($out, $notice)
192     {
193         $tally = Fave_tally::ensureTally($notice->id);
194
195         if (!empty($tally)) {
196             $out->elementStart(
197                 'div',
198                 array(
199                     'id' => 'notice-' . $notice->id . '-tally',
200                     'class' => 'notice-tally'
201                 )
202             );
203             $out->elementStart('span', array('class' => 'fave-tally-title'));
204             // TRANS: Label for tally for number of times a notice was favored.
205             $out->raw(sprintf(_m("Favored")));
206             $out->elementEnd('span');
207             $out->elementStart('span', array('class' => 'fave-tally'));
208             $out->raw($tally->count);
209             $out->elementEnd('span');
210             $out->elementEnd('div');
211         }
212     }
213
214     function onEndFavorNotice($profile, $notice)
215     {
216         $tally = Fave_tally::increment($notice->id);
217     }
218
219     function onEndDisfavorNotice($profile, $notice)
220     {
221         $tally = Fave_tally::decrement($notice->id);
222     }
223
224     static function createAnonProfile()
225     {
226         // Get the anon user's IP, and turn it into a nickname
227         list($proxy, $ip) = common_client_ip();
228
229         // IP + time + random number should help to avoid collisions
230         $baseNickname = $ip . '-' . time() . '-' . common_good_rand(5);
231
232         $profile = new Profile();
233         $profile->nickname = $baseNickname;
234         $id = $profile->insert();
235
236         if (!$id) {
237             // TRANS: Server exception.
238             throw new ServerException(_m("Could not create anonymous user session."));
239         }
240
241         // Stick the Profile ID into the nickname
242         $orig = clone($profile);
243
244         $profile->nickname = 'anon-' . $id . '-' . $baseNickname;
245         $result = $profile->update($orig);
246
247         if (!$result) {
248             // TRANS: Server exception.
249             throw new ServerException(_m("Could not create anonymous user session."));
250         }
251
252         common_log(
253             LOG_INFO,
254             "AnonymousFavePlugin - created profile for anonymous user from IP: "
255             . $ip
256             . ', nickname = '
257             . $profile->nickname
258         );
259
260         return $profile;
261     }
262
263     static function getAnonProfile()
264     {
265
266         $token = $_SESSION['anon_token'];
267         $anon = base64_decode($token);
268
269         $profile = null;
270
271         if (!empty($anon) && substr($anon, 0, 5) == 'anon-') {
272             $parts = explode('-', $anon);
273             $id = $parts[1];
274             // Do Profile lookup by ID instead of nickname for safety/performance
275             $profile = Profile::getKV('id', $id);
276         } else {
277             $profile = AnonymousFavePlugin::createAnonProfile();
278             // Obfuscate so it's hard to figure out the Profile ID
279             $_SESSION['anon_token'] = base64_encode($profile->nickname);
280         }
281
282         return $profile;
283     }
284
285     /**
286      * Determine whether a given NoticeListItem should have the
287      * anonymous fave/disfave form
288      *
289      * @param NoticeListItem $item
290      *
291      * @return boolean false if the profile associated with the notice is
292      *                       in the list of restricted profiles, otherwise
293      *                       return true
294      */
295     function hasAnonFaving($item)
296     {
297         $profile = Profile::getKV('id', $item->notice->profile_id);
298         if (in_array($profile->nickname, $this->restricted)) {
299             return false;
300         }
301
302         return true;
303     }
304
305     /**
306      * Provide plugin version information.
307      *
308      * This data is used when showing the version page.
309      *
310      * @param array &$versions array of version data arrays; see EVENTS.txt
311      *
312      * @return boolean hook value
313      */
314     function onPluginVersion(&$versions)
315     {
316         $url = 'http://status.net/wiki/Plugin:AnonymousFave';
317
318         $versions[] = array('name' => 'AnonymousFave',
319             'version' => ANONYMOUS_FAVE_PLUGIN_VERSION,
320             'author' => 'Zach Copley',
321             'homepage' => $url,
322             'rawdescription' =>
323             // TRANS: Plugin description.
324             _m('Allow anonymous users to favorite notices.'));
325
326         return true;
327     }
328 }