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