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