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