]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/Realtime/RealtimePlugin.php
XSS vulnerability when remote-subscribing
[quix0rs-gnu-social.git] / plugins / Realtime / RealtimePlugin.php
1 <?php
2 /**
3  * StatusNet, the distributed open-source microblogging tool
4  *
5  * Superclass for plugins that do "real time" updates of timelines using Ajax
6  *
7  * PHP version 5
8  *
9  * LICENCE: This program is free software: you can redistribute it and/or modify
10  * it under the terms of the GNU Affero General Public License as published by
11  * the Free Software Foundation, either version 3 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU Affero General Public License for more details.
18  *
19  * You should have received a copy of the GNU Affero General Public License
20  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
21  *
22  * @category  Plugin
23  * @package   StatusNet
24  * @author    Evan Prodromou <evan@status.net>
25  * @author    Mikael Nordfeldth <mmn@hethane.se>
26  * @copyright 2009 StatusNet, Inc.
27  * @copyright 2014 Free Software Foundation, Inc.
28  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
29  * @link      http://status.net/
30  */
31
32 if (!defined('GNUSOCIAL')) { exit(1); }
33
34 /**
35  * Superclass for plugin to do realtime updates
36  *
37  * Based on experience with the Comet and Meteor plugins,
38  * this superclass extracts out some of the common functionality
39  *
40  * Currently depends on Favorite plugin.
41  *
42  * @category Plugin
43  * @package  StatusNet
44  * @author   Evan Prodromou <evan@status.net>
45  * @license  http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
46  * @link     http://status.net/
47  */
48 class RealtimePlugin extends Plugin
49 {
50     protected $showurl = null;
51
52     /**
53      * When it's time to initialize the plugin, calculate and
54      * pass the URLs we need.
55      */
56     function onInitializePlugin()
57     {
58         // FIXME: need to find a better way to pass this pattern in
59         $this->showurl = common_local_url('shownotice',
60                                             array('notice' => '0000000000'));
61         return true;
62     }
63
64     function onCheckSchema()
65     {
66         $schema = Schema::get();
67         $schema->ensureTable('realtime_channel', Realtime_channel::schemaDef());
68         return true;
69     }
70
71     /**
72      * Hook for RouterInitialized event.
73      *
74      * @param URLMapper $m path-to-action mapper
75      * @return boolean hook return
76      */
77     public function onRouterInitialized(URLMapper $m)
78     {
79         $m->connect('main/channel/:channelkey/keepalive',
80                     array('action' => 'keepalivechannel'),
81                     array('channelkey' => '[a-z0-9]{32}'));
82         $m->connect('main/channel/:channelkey/close',
83                     array('action' => 'closechannel'),
84                     array('channelkey' => '[a-z0-9]{32}'));
85         return true;
86     }
87
88     function onEndShowScripts($action)
89     {
90         $channel = $this->_getChannel($action);
91
92         if (empty($channel)) {
93             return true;
94         }
95
96         $timeline = $this->_pathToChannel(array($channel->channel_key));
97
98         // If there's not a timeline on this page,
99         // just return true
100
101         if (empty($timeline)) {
102             return true;
103         }
104
105         $base = $action->selfUrl();
106         if (mb_strstr($base, '?')) {
107             $url = $base . '&realtime=1';
108         } else {
109             $url = $base . '?realtime=1';
110         }
111
112         $scripts = $this->_getScripts();
113
114         foreach ($scripts as $script) {
115             $action->script($script);
116         }
117
118         $user = common_current_user();
119
120         if (!empty($user->id)) {
121             $user_id = $user->id;
122         } else {
123             $user_id = 0;
124         }
125
126         if ($action->boolean('realtime')) {
127             $realtimeUI = ' RealtimeUpdate.initPopupWindow();';
128         }
129         else {
130             $pluginPath = common_path('plugins/Realtime/');
131             $keepalive = common_local_url('keepalivechannel', array('channelkey' => $channel->channel_key));
132             $close = common_local_url('closechannel', array('channelkey' => $channel->channel_key));
133             $realtimeUI = ' RealtimeUpdate.initActions('.json_encode($url).', '.json_encode($timeline).', '.json_encode($pluginPath).', '.json_encode($keepalive).', '.json_encode($close).'); ';
134         }
135
136         $script = ' $(document).ready(function() { '.
137           $realtimeUI.
138             $this->_updateInitialize($timeline, $user_id).
139           '}); ';
140         $action->inlineScript($script);
141
142         return true;
143     }
144
145     public function onEndShowStylesheets(Action $action)
146     {
147         $urlpath = self::staticPath(str_replace('Plugin','',__CLASS__),
148                                     'css/realtimeupdate.css');
149         $action->cssLink($urlpath, null, 'screen, projection, tv');
150         return true;
151     }
152
153     public function onHandleQueuedNotice(Notice $notice)
154     {
155         $paths = array();
156
157         // Add to the author's timeline
158
159         try {
160             $profile = $notice->getProfile();
161         } catch (Exception $e) {
162             $this->log(LOG_ERR, $e->getMessage());
163             return true;
164         }
165
166         try {
167             $user = $profile->getUser();
168             $paths[] = array('showstream', $user->nickname, null);
169         } catch (NoSuchUserException $e) {
170             // We really should handle the remote profile views too
171             $user = null;
172         }
173
174         // Add to the public timeline
175
176         $is_local = intval($notice->is_local);
177         if ($is_local === Notice::LOCAL_PUBLIC ||
178                 ($is_local === Notice::REMOTE && !common_config('public', 'localonly'))) {
179             $paths[] = array('public', null, null);
180         }
181
182         // Add to the tags timeline
183
184         $tags = $this->getNoticeTags($notice);
185
186         if (!empty($tags)) {
187             foreach ($tags as $tag) {
188                 $paths[] = array('tag', $tag, null);
189             }
190         }
191
192         // Add to inbox timelines
193         // XXX: do a join
194
195         $ni = $notice->whoGets();
196
197         foreach (array_keys($ni) as $user_id) {
198             $user = User::getKV('id', $user_id);
199             $paths[] = array('all', $user->nickname, null);
200         }
201
202         // Add to the replies timeline
203
204         $reply = new Reply();
205         $reply->notice_id = $notice->id;
206
207         if ($reply->find()) {
208             while ($reply->fetch()) {
209                 $user = User::getKV('id', $reply->profile_id);
210                 if (!empty($user)) {
211                     $paths[] = array('replies', $user->nickname, null);
212                 }
213             }
214         }
215
216         // Add to the group timeline
217         // XXX: join
218
219         $gi = new Group_inbox();
220         $gi->notice_id = $notice->id;
221
222         if ($gi->find()) {
223             while ($gi->fetch()) {
224                 $ug = User_group::getKV('id', $gi->group_id);
225                 $paths[] = array('showgroup', $ug->nickname, null);
226             }
227         }
228
229         if (count($paths) > 0) {
230
231             $json = $this->noticeAsJson($notice);
232
233             $this->_connect();
234
235             // XXX: We should probably fan-out here and do a
236             // new queue item for each path
237
238             foreach ($paths as $path) {
239
240                 list($action, $arg1, $arg2) = $path;
241
242                 $channels = Realtime_channel::getAllChannels($action, $arg1, $arg2);
243                 $this->log(LOG_INFO, sprintf(_("%d candidate channels for notice %d"),
244                                              count($channels), 
245                                              $notice->id));
246
247                 foreach ($channels as $channel) {
248
249                     // XXX: We should probably fan-out here and do a
250                     // new queue item for each user/path combo
251
252                     if (is_null($channel->user_id)) {
253                         $profile = null;
254                     } else {
255                         $profile = Profile::getKV('id', $channel->user_id);
256                     }
257                     if ($notice->inScope($profile)) {
258                         $this->log(LOG_INFO, 
259                                    sprintf(_("Delivering notice %d to channel (%s, %s, %s) for user '%s'"),
260                                            $notice->id,
261                                            $channel->action,
262                                            $channel->arg1,
263                                            $channel->arg2,
264                                            ($profile) ? ($profile->nickname) : "<public>"));
265                         $timeline = $this->_pathToChannel(array($channel->channel_key));
266                         $this->_publish($timeline, $json);
267                     }
268                 }
269             }
270
271             $this->_disconnect();
272         }
273
274         return true;
275     }
276
277     function onStartShowBody($action)
278     {
279         $realtime = $action->boolean('realtime');
280         if (!$realtime) {
281             return true;
282         }
283
284         $action->elementStart('body',
285                               (common_current_user()) ? array('id' => $action->trimmed('action'),
286                                                               'class' => 'user_in realtime-popup')
287                               : array('id' => $action->trimmed('action'),
288                                       'class'=> 'realtime-popup'));
289
290         // XXX hack to deal with JS that tries to get the
291         // root url from page output
292
293         $action->elementStart('address');
294
295         if (common_config('singleuser', 'enabled')) {
296             $user = User::singleUser();
297             $url = common_local_url('showstream', array('nickname' => $user->nickname));
298         } else {
299             $url = common_local_url('public');
300         }
301
302         $action->element('a', array('class' => 'url',
303                                     'href' => $url),
304                          '');
305
306         $action->elementEnd('address');
307
308         $action->showContentBlock();
309         $action->showScripts();
310         $action->elementEnd('body');
311         return false; // No default processing
312     }
313
314     function noticeAsJson($notice)
315     {
316         // FIXME: this code should be abstracted to a neutral third
317         // party, like Notice::asJson(). I'm not sure of the ethics
318         // of refactoring from within a plugin, so I'm just abusing
319         // the ApiAction method. Don't do this unless you're me!
320
321         $act = new ApiAction('/dev/null');
322
323         $arr = $act->twitterStatusArray($notice, true);
324         $arr['url'] = $notice->getUrl(true);
325         $arr['html'] = htmlspecialchars($notice->rendered);
326         $arr['source'] = htmlspecialchars($arr['source']);
327         $arr['conversation_url'] = $notice->getConversationUrl();
328
329         $profile = $notice->getProfile();
330         $arr['user']['profile_url'] = $profile->profileurl;
331
332         // Add needed repeat data
333
334         if (!empty($notice->repeat_of)) {
335             $original = Notice::getKV('id', $notice->repeat_of);
336             if ($original instanceof Notice) {
337                 $arr['retweeted_status']['url'] = $original->getUrl(true);
338                 $arr['retweeted_status']['html'] = htmlspecialchars($original->rendered);
339                 $arr['retweeted_status']['source'] = htmlspecialchars($original->source);
340                 $originalProfile = $original->getProfile();
341                 $arr['retweeted_status']['user']['profile_url'] = $originalProfile->profileurl;
342                 $arr['retweeted_status']['conversation_url'] = $original->getConversationUrl();
343             }
344             unset($original);
345         }
346
347         return $arr;
348     }
349
350     function getNoticeTags($notice)
351     {
352         $tags = null;
353
354         $nt = new Notice_tag();
355         $nt->notice_id = $notice->id;
356
357         if ($nt->find()) {
358             $tags = array();
359             while ($nt->fetch()) {
360                 $tags[] = $nt->tag;
361             }
362         }
363
364         $nt->free();
365         $nt = null;
366
367         return $tags;
368     }
369
370     function _getScripts()
371     {
372         $urlpath = self::staticPath(str_replace('Plugin','',__CLASS__),
373                                     'js/realtimeupdate.js');
374         return array($urlpath);
375     }
376
377     /**
378      * Export any i18n messages that need to be loaded at runtime...
379      *
380      * @param Action $action
381      * @param array $messages
382      *
383      * @return boolean hook return value
384      */
385     function onEndScriptMessages($action, &$messages)
386     {
387         // TRANS: Text label for realtime view "play" button, usually replaced by an icon.
388         $messages['realtime_play'] = _m('BUTTON', 'Play');
389         // TRANS: Tooltip for realtime view "play" button.
390         $messages['realtime_play_tooltip'] = _m('TOOLTIP', 'Play');
391         // TRANS: Text label for realtime view "pause" button
392         $messages['realtime_pause'] = _m('BUTTON', 'Pause');
393         // TRANS: Tooltip for realtime view "pause" button
394         $messages['realtime_pause_tooltip'] = _m('TOOLTIP', 'Pause');
395         // TRANS: Text label for realtime view "popup" button, usually replaced by an icon.
396         $messages['realtime_popup'] = _m('BUTTON', 'Pop up');
397         // TRANS: Tooltip for realtime view "popup" button.
398         $messages['realtime_popup_tooltip'] = _m('TOOLTIP', 'Pop up in a window');
399
400         return true;
401     }
402
403     function _updateInitialize($timeline, $user_id)
404     {
405         return "RealtimeUpdate.init($user_id, \"$this->showurl\"); ";
406     }
407
408     function _connect()
409     {
410     }
411
412     function _publish($timeline, $json)
413     {
414     }
415
416     function _disconnect()
417     {
418     }
419
420     function _pathToChannel($path)
421     {
422         return '';
423     }
424
425
426     function _getTimeline($action)
427     {
428         $channel = $this->_getChannel($action);
429         if (empty($channel)) {
430             return null;
431         }
432
433         return $this->_pathToChannel(array($channel->channel_key));
434     }
435
436     function _getChannel($action)
437     {
438         $timeline = null;
439         $arg1     = null;
440         $arg2     = null;
441
442         $action_name = $action->trimmed('action');
443
444         // FIXME: lists
445         // FIXME: search (!)
446         // FIXME: profile + tag
447
448         switch ($action_name) {
449          case 'public':
450             // no arguments
451             break;
452          case 'tag':
453             $tag = $action->trimmed('tag');
454             if (!empty($tag)) {
455                 $arg1 = $tag;
456             } else {
457                 $this->log(LOG_NOTICE, "Unexpected 'tag' action without tag argument");
458                 return null;
459             }
460             break;
461          case 'showstream':
462          case 'all':
463          case 'replies':
464          case 'showgroup':
465             $nickname = common_canonical_nickname($action->trimmed('nickname'));
466             if (!empty($nickname)) {
467                 $arg1 = $nickname;
468             } else {
469                 $this->log(LOG_NOTICE, "Unexpected $action_name action without nickname argument.");
470                 return null;
471             }
472             break;
473          default:
474             return null;
475         }
476
477         $user = common_current_user();
478
479         $user_id = (!empty($user)) ? $user->id : null;
480
481         $channel = Realtime_channel::getChannel($user_id,
482                                                 $action_name,
483                                                 $arg1,
484                                                 $arg2);
485
486         return $channel;
487     }
488
489     function onStartReadWriteTables(&$alwaysRW, &$rwdb)
490     {
491         $alwaysRW[] = 'realtime_channel';
492         return true;
493     }
494 }