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