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