]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/Realtime/RealtimePlugin.php
Merge branch 'master' into social-master
[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 $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         if ($notice->is_local == Notice::LOCAL_PUBLIC ||
177             ($notice->is_local == Notice::REMOTE && !common_config('public', 'localonly'))) {
178             $paths[] = array('public', null, null);
179         }
180
181         // Add to the tags timeline
182
183         $tags = $this->getNoticeTags($notice);
184
185         if (!empty($tags)) {
186             foreach ($tags as $tag) {
187                 $paths[] = array('tag', $tag, null);
188             }
189         }
190
191         // Add to inbox timelines
192         // XXX: do a join
193
194         $ni = $notice->whoGets();
195
196         foreach (array_keys($ni) as $user_id) {
197             $user = User::getKV('id', $user_id);
198             $paths[] = array('all', $user->nickname, null);
199         }
200
201         // Add to the replies timeline
202
203         $reply = new Reply();
204         $reply->notice_id = $notice->id;
205
206         if ($reply->find()) {
207             while ($reply->fetch()) {
208                 $user = User::getKV('id', $reply->profile_id);
209                 if (!empty($user)) {
210                     $paths[] = array('replies', $user->nickname, null);
211                 }
212             }
213         }
214
215         // Add to the group timeline
216         // XXX: join
217
218         $gi = new Group_inbox();
219         $gi->notice_id = $notice->id;
220
221         if ($gi->find()) {
222             while ($gi->fetch()) {
223                 $ug = User_group::getKV('id', $gi->group_id);
224                 $paths[] = array('showgroup', $ug->nickname, null);
225             }
226         }
227
228         if (count($paths) > 0) {
229
230             $json = $this->noticeAsJson($notice);
231
232             $this->_connect();
233
234             // XXX: We should probably fan-out here and do a
235             // new queue item for each path
236
237             foreach ($paths as $path) {
238
239                 list($action, $arg1, $arg2) = $path;
240
241                 $channels = Realtime_channel::getAllChannels($action, $arg1, $arg2);
242                 $this->log(LOG_INFO, sprintf(_("%d candidate channels for notice %d"),
243                                              count($channels), 
244                                              $notice->id));
245
246                 foreach ($channels as $channel) {
247
248                     // XXX: We should probably fan-out here and do a
249                     // new queue item for each user/path combo
250
251                     if (is_null($channel->user_id)) {
252                         $profile = null;
253                     } else {
254                         $profile = Profile::getKV('id', $channel->user_id);
255                     }
256                     if ($notice->inScope($profile)) {
257                         $this->log(LOG_INFO, 
258                                    sprintf(_("Delivering notice %d to channel (%s, %s, %s) for user '%s'"),
259                                            $notice->id,
260                                            $channel->action,
261                                            $channel->arg1,
262                                            $channel->arg2,
263                                            ($profile) ? ($profile->nickname) : "<public>"));
264                         $timeline = $this->_pathToChannel(array($channel->channel_key));
265                         $this->_publish($timeline, $json);
266                     }
267                 }
268             }
269
270             $this->_disconnect();
271         }
272
273         return true;
274     }
275
276     function onStartShowBody($action)
277     {
278         $realtime = $action->boolean('realtime');
279         if (!$realtime) {
280             return true;
281         }
282
283         $action->elementStart('body',
284                               (common_current_user()) ? array('id' => $action->trimmed('action'),
285                                                               'class' => 'user_in realtime-popup')
286                               : array('id' => $action->trimmed('action'),
287                                       'class'=> 'realtime-popup'));
288
289         // XXX hack to deal with JS that tries to get the
290         // root url from page output
291
292         $action->elementStart('address');
293
294         if (common_config('singleuser', 'enabled')) {
295             $user = User::singleUser();
296             $url = common_local_url('showstream', array('nickname' => $user->nickname));
297         } else {
298             $url = common_local_url('public');
299         }
300
301         $action->element('a', array('class' => 'url',
302                                     'href' => $url),
303                          '');
304
305         $action->elementEnd('address');
306
307         $action->showContentBlock();
308         $action->showScripts();
309         $action->elementEnd('body');
310         return false; // No default processing
311     }
312
313     function noticeAsJson(Notice $notice)
314     {
315         // FIXME: this code should be abstracted to a neutral third
316         // party, like Notice::asJson(). I'm not sure of the ethics
317         // of refactoring from within a plugin, so I'm just abusing
318         // the ApiAction method. Don't do this unless you're me!
319
320         $act = new ApiAction('/dev/null');
321
322         $arr = $act->twitterStatusArray($notice, true);
323         $arr['url'] = $notice->getUrl(true);
324         $arr['html'] = htmlspecialchars($notice->rendered);
325         $arr['source'] = htmlspecialchars($arr['source']);
326         $arr['conversation_url'] = $notice->getConversationUrl();
327
328         $profile = $notice->getProfile();
329         $arr['user']['profile_url'] = $profile->profileurl;
330
331         // Add needed repeat data
332
333         if (!empty($notice->repeat_of)) {
334             $original = Notice::getKV('id', $notice->repeat_of);
335             if ($original instanceof Notice) {
336                 $arr['retweeted_status']['url'] = $original->getUrl(true);
337                 $arr['retweeted_status']['html'] = htmlspecialchars($original->rendered);
338                 $arr['retweeted_status']['source'] = htmlspecialchars($original->source);
339                 $originalProfile = $original->getProfile();
340                 $arr['retweeted_status']['user']['profile_url'] = $originalProfile->profileurl;
341                 $arr['retweeted_status']['conversation_url'] = $original->getConversationUrl();
342             }
343             unset($original);
344         }
345
346         return $arr;
347     }
348
349     function getNoticeTags(Notice $notice)
350     {
351         $tags = null;
352
353         $nt = new Notice_tag();
354         $nt->notice_id = $notice->id;
355
356         if ($nt->find()) {
357             $tags = array();
358             while ($nt->fetch()) {
359                 $tags[] = $nt->tag;
360             }
361         }
362
363         $nt->free();
364         $nt = null;
365
366         return $tags;
367     }
368
369     function _getScripts()
370     {
371         $urlpath = self::staticPath(str_replace('Plugin','',__CLASS__),
372                                     'js/realtimeupdate.js');
373         return array($urlpath);
374     }
375
376     /**
377      * Export any i18n messages that need to be loaded at runtime...
378      *
379      * @param Action $action
380      * @param array $messages
381      *
382      * @return boolean hook return value
383      */
384     function onEndScriptMessages(Action $action, &$messages)
385     {
386         // TRANS: Text label for realtime view "play" button, usually replaced by an icon.
387         $messages['realtime_play'] = _m('BUTTON', 'Play');
388         // TRANS: Tooltip for realtime view "play" button.
389         $messages['realtime_play_tooltip'] = _m('TOOLTIP', 'Play');
390         // TRANS: Text label for realtime view "pause" button
391         $messages['realtime_pause'] = _m('BUTTON', 'Pause');
392         // TRANS: Tooltip for realtime view "pause" button
393         $messages['realtime_pause_tooltip'] = _m('TOOLTIP', 'Pause');
394         // TRANS: Text label for realtime view "popup" button, usually replaced by an icon.
395         $messages['realtime_popup'] = _m('BUTTON', 'Pop up');
396         // TRANS: Tooltip for realtime view "popup" button.
397         $messages['realtime_popup_tooltip'] = _m('TOOLTIP', 'Pop up in a window');
398
399         return true;
400     }
401
402     function _updateInitialize($timeline, $user_id)
403     {
404         return "RealtimeUpdate.init($user_id, \"$this->showurl\"); ";
405     }
406
407     function _connect()
408     {
409     }
410
411     function _publish($timeline, $json)
412     {
413     }
414
415     function _disconnect()
416     {
417     }
418
419     function _pathToChannel($path)
420     {
421         return '';
422     }
423
424
425     function _getTimeline($action)
426     {
427         $channel = $this->_getChannel($action);
428         if (empty($channel)) {
429             return null;
430         }
431
432         return $this->_pathToChannel(array($channel->channel_key));
433     }
434
435     function _getChannel($action)
436     {
437         $timeline = null;
438         $arg1     = null;
439         $arg2     = null;
440
441         $action_name = $action->trimmed('action');
442
443         // FIXME: lists
444         // FIXME: search (!)
445         // FIXME: profile + tag
446
447         switch ($action_name) {
448          case 'public':
449             // no arguments
450             break;
451          case 'tag':
452             $tag = $action->trimmed('tag');
453             if (!empty($tag)) {
454                 $arg1 = $tag;
455             } else {
456                 $this->log(LOG_NOTICE, "Unexpected 'tag' action without tag argument");
457                 return null;
458             }
459             break;
460          case 'showstream':
461          case 'all':
462          case 'replies':
463          case 'showgroup':
464             $nickname = common_canonical_nickname($action->trimmed('nickname'));
465             if (!empty($nickname)) {
466                 $arg1 = $nickname;
467             } else {
468                 $this->log(LOG_NOTICE, "Unexpected $action_name action without nickname argument.");
469                 return null;
470             }
471             break;
472          default:
473             return null;
474         }
475
476         $user = common_current_user();
477
478         $user_id = (!empty($user)) ? $user->id : null;
479
480         $channel = Realtime_channel::getChannel($user_id,
481                                                 $action_name,
482                                                 $arg1,
483                                                 $arg2);
484
485         return $channel;
486     }
487
488     function onStartReadWriteTables(&$alwaysRW, &$rwdb)
489     {
490         $alwaysRW[] = 'realtime_channel';
491         return true;
492     }
493 }