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