We are no longer offering accounts on this server. Consider https://gitlab.freedesktop.org/ as a place to host projects.

RealtimePlugin.php 15.1 KB
Newer Older
Evan Prodromou's avatar
Evan Prodromou committed
1 2
<?php
/**
Evan Prodromou's avatar
Evan Prodromou committed
3
 * StatusNet, the distributed open-source microblogging tool
Evan Prodromou's avatar
Evan Prodromou committed
4
 *
5
 * Superclass for plugins that do "real time" updates of timelines using Ajax
Evan Prodromou's avatar
Evan Prodromou committed
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
 *
 * PHP version 5
 *
 * LICENCE: This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * @category  Plugin
Evan Prodromou's avatar
Evan Prodromou committed
23 24
 * @package   StatusNet
 * @author    Evan Prodromou <evan@status.net>
25
 * @author    Mikael Nordfeldth <mmn@hethane.se>
Evan Prodromou's avatar
Evan Prodromou committed
26
 * @copyright 2009 StatusNet, Inc.
27
 * @copyright 2014 Free Software Foundation, Inc.
Evan Prodromou's avatar
Evan Prodromou committed
28
 * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
Evan Prodromou's avatar
Evan Prodromou committed
29
 * @link      http://status.net/
Evan Prodromou's avatar
Evan Prodromou committed
30 31
 */

32
if (!defined('GNUSOCIAL')) { exit(1); }
Evan Prodromou's avatar
Evan Prodromou committed
33 34

/**
35 36 37 38
 * Superclass for plugin to do realtime updates
 *
 * Based on experience with the Comet and Meteor plugins,
 * this superclass extracts out some of the common functionality
Evan Prodromou's avatar
Evan Prodromou committed
39
 *
40 41
 * Currently depends on Favorite plugin.
 *
Evan Prodromou's avatar
Evan Prodromou committed
42
 * @category Plugin
Evan Prodromou's avatar
Evan Prodromou committed
43 44
 * @package  StatusNet
 * @author   Evan Prodromou <evan@status.net>
Evan Prodromou's avatar
Evan Prodromou committed
45
 * @license  http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
Evan Prodromou's avatar
Evan Prodromou committed
46
 * @link     http://status.net/
Evan Prodromou's avatar
Evan Prodromou committed
47
 */
48
class RealtimePlugin extends Plugin
Evan Prodromou's avatar
Evan Prodromou committed
49
{
50
    protected $showurl = null;
Evan Prodromou's avatar
Evan Prodromou committed
51

52 53 54 55
    /**
     * When it's time to initialize the plugin, calculate and
     * pass the URLs we need.
     */
56
    function onInitializePlugin()
Evan Prodromou's avatar
Evan Prodromou committed
57
    {
58
        // FIXME: need to find a better way to pass this pattern in
59
        $this->showurl = common_local_url('shownotice',
60
                                            array('notice' => '0000000000'));
61
        return true;
Evan Prodromou's avatar
Evan Prodromou committed
62
    }
63

64 65 66 67 68 69
    function onCheckSchema()
    {
        $schema = Schema::get();
        $schema->ensureTable('realtime_channel', Realtime_channel::schemaDef());
        return true;
    }
70

71 72 73
    /**
     * Hook for RouterInitialized event.
     *
74
     * @param URLMapper $m path-to-action mapper
75 76
     * @return boolean hook return
     */
77
    public function onRouterInitialized(URLMapper $m)
78
    {
79 80 81 82 83 84 85
        $m->connect('main/channel/:channelkey/keepalive',
                    array('action' => 'keepalivechannel'),
                    array('channelkey' => '[a-z0-9]{32}'));
        $m->connect('main/channel/:channelkey/close',
                    array('action' => 'closechannel'),
                    array('channelkey' => '[a-z0-9]{32}'));
        return true;
86 87
    }

Evan Prodromou's avatar
Evan Prodromou committed
88 89
    function onEndShowScripts($action)
    {
90 91 92 93 94 95 96
        $channel = $this->_getChannel($action);

        if (empty($channel)) {
            return true;
        }

        $timeline = $this->_pathToChannel(array($channel->channel_key));
Evan Prodromou's avatar
Evan Prodromou committed
97

98 99 100 101
        // If there's not a timeline on this page,
        // just return true

        if (empty($timeline)) {
102
            return true;
Evan Prodromou's avatar
Evan Prodromou committed
103 104
        }

105
        $base = $action->selfUrl();
Evan Prodromou's avatar
Evan Prodromou committed
106
        if (mb_strstr($base, '?')) {
107 108 109 110 111
            $url = $base . '&realtime=1';
        } else {
            $url = $base . '?realtime=1';
        }

112
        $scripts = $this->_getScripts();
Evan Prodromou's avatar
Evan Prodromou committed
113 114

        foreach ($scripts as $script) {
115
            $action->script($script);
Evan Prodromou's avatar
Evan Prodromou committed
116 117 118 119 120 121 122 123 124 125
        }

        $user = common_current_user();

        if (!empty($user->id)) {
            $user_id = $user->id;
        } else {
            $user_id = 0;
        }

Evan Prodromou's avatar
Evan Prodromou committed
126
        if ($action->boolean('realtime')) {
127 128 129
            $realtimeUI = ' RealtimeUpdate.initPopupWindow();';
        }
        else {
130
            $pluginPath = common_path('plugins/Realtime/');
131 132
            $keepalive = common_local_url('keepalivechannel', array('channelkey' => $channel->channel_key));
            $close = common_local_url('closechannel', array('channelkey' => $channel->channel_key));
Evan Prodromou's avatar
Evan Prodromou committed
133
            $realtimeUI = ' RealtimeUpdate.initActions('.json_encode($url).', '.json_encode($timeline).', '.json_encode($pluginPath).', '.json_encode($keepalive).', '.json_encode($close).'); ';
134
        }
135

136
        $script = ' $(document).ready(function() { '.
137
          $realtimeUI.
138
            $this->_updateInitialize($timeline, $user_id).
139
          '}); ';
140
        $action->inlineScript($script);
Evan Prodromou's avatar
Evan Prodromou committed
141 142 143

        return true;
    }
144

145
    public function onEndShowStylesheets(Action $action)
146
    {
147 148 149
        $urlpath = self::staticPath(str_replace('Plugin','',__CLASS__),
                                    'css/realtimeupdate.css');
        $action->cssLink($urlpath, null, 'screen, projection, tv');
150 151
        return true;
    }
Evan Prodromou's avatar
Evan Prodromou committed
152

153
    public function onHandleQueuedNotice(Notice $notice)
Evan Prodromou's avatar
Evan Prodromou committed
154
    {
155
        $paths = array();
Evan Prodromou's avatar
Evan Prodromou committed
156

Evan Prodromou's avatar
Evan Prodromou committed
157 158
        // Add to the author's timeline

159 160 161 162 163 164 165
        try {
            $profile = $notice->getProfile();
        } catch (Exception $e) {
            $this->log(LOG_ERR, $e->getMessage());
            return true;
        }

166 167
        try {
            $user = $profile->getUser();
168
            $paths[] = array('showstream', $user->nickname, null);
169 170 171
        } catch (NoSuchUserException $e) {
            // We really should handle the remote profile views too
            $user = null;
Evan Prodromou's avatar
Evan Prodromou committed
172 173 174
        }

        // Add to the public timeline
Evan Prodromou's avatar
Evan Prodromou committed
175

176
        if ($notice->is_local == Notice::LOCAL_PUBLIC ||
Zach Copley's avatar
Zach Copley committed
177
            ($notice->is_local == Notice::REMOTE && !common_config('public', 'localonly'))) {
178
            $paths[] = array('public', null, null);
Evan Prodromou's avatar
Evan Prodromou committed
179 180
        }

Evan Prodromou's avatar
Evan Prodromou committed
181 182
        // Add to the tags timeline

Evan Prodromou's avatar
Evan Prodromou committed
183 184 185 186
        $tags = $this->getNoticeTags($notice);

        if (!empty($tags)) {
            foreach ($tags as $tag) {
187
                $paths[] = array('tag', $tag, null);
Evan Prodromou's avatar
Evan Prodromou committed
188 189 190
            }
        }

Evan Prodromou's avatar
Evan Prodromou committed
191 192 193
        // Add to inbox timelines
        // XXX: do a join

194
        $ni = $notice->whoGets();
Evan Prodromou's avatar
Evan Prodromou committed
195

196
        foreach (array_keys($ni) as $user_id) {
197
            $user = User::getKV('id', $user_id);
198
            $paths[] = array('all', $user->nickname, null);
Evan Prodromou's avatar
Evan Prodromou committed
199 200 201 202 203 204 205 206 207
        }

        // Add to the replies timeline

        $reply = new Reply();
        $reply->notice_id = $notice->id;

        if ($reply->find()) {
            while ($reply->fetch()) {
208
                $user = User::getKV('id', $reply->profile_id);
Evan Prodromou's avatar
Evan Prodromou committed
209
                if (!empty($user)) {
210
                    $paths[] = array('replies', $user->nickname, null);
Evan Prodromou's avatar
Evan Prodromou committed
211 212 213 214 215 216 217 218 219 220 221 222
                }
            }
        }

        // Add to the group timeline
        // XXX: join

        $gi = new Group_inbox();
        $gi->notice_id = $notice->id;

        if ($gi->find()) {
            while ($gi->fetch()) {
223
                $ug = User_group::getKV('id', $gi->group_id);
224
                $paths[] = array('showgroup', $ug->nickname, null);
Evan Prodromou's avatar
Evan Prodromou committed
225 226 227
            }
        }

228
        if (count($paths) > 0) {
Evan Prodromou's avatar
Evan Prodromou committed
229 230 231

            $json = $this->noticeAsJson($notice);

232
            $this->_connect();
233

234 235
            // XXX: We should probably fan-out here and do a
            // new queue item for each path
Evan Prodromou's avatar
Evan Prodromou committed
236

237
            foreach ($paths as $path) {
238 239 240 241

                list($action, $arg1, $arg2) = $path;

                $channels = Realtime_channel::getAllChannels($action, $arg1, $arg2);
Evan Prodromou's avatar
Evan Prodromou committed
242 243 244
                $this->log(LOG_INFO, sprintf(_("%d candidate channels for notice %d"),
                                             count($channels), 
                                             $notice->id));
245 246 247 248 249 250 251 252 253

                foreach ($channels as $channel) {

                    // XXX: We should probably fan-out here and do a
                    // new queue item for each user/path combo

                    if (is_null($channel->user_id)) {
                        $profile = null;
                    } else {
254
                        $profile = Profile::getKV('id', $channel->user_id);
255 256
                    }
                    if ($notice->inScope($profile)) {
Evan Prodromou's avatar
Evan Prodromou committed
257 258 259 260 261 262 263
                        $this->log(LOG_INFO, 
                                   sprintf(_("Delivering notice %d to channel (%s, %s, %s) for user '%s'"),
                                           $notice->id,
                                           $channel->action,
                                           $channel->arg1,
                                           $channel->arg2,
                                           ($profile) ? ($profile->nickname) : "<public>"));
264 265 266 267
                        $timeline = $this->_pathToChannel(array($channel->channel_key));
                        $this->_publish($timeline, $json);
                    }
                }
Evan Prodromou's avatar
Evan Prodromou committed
268 269
            }

270
            $this->_disconnect();
Evan Prodromou's avatar
Evan Prodromou committed
271 272 273 274 275
        }

        return true;
    }

276 277 278 279 280 281 282 283 284
    function onStartShowBody($action)
    {
        $realtime = $action->boolean('realtime');
        if (!$realtime) {
            return true;
        }

        $action->elementStart('body',
                              (common_current_user()) ? array('id' => $action->trimmed('action'),
285 286 287
                                                              'class' => 'user_in realtime-popup')
                              : array('id' => $action->trimmed('action'),
                                      'class'=> 'realtime-popup'));
288 289 290

        // XXX hack to deal with JS that tries to get the
        // root url from page output
Evan Prodromou's avatar
Evan Prodromou committed
291

292
        $action->elementStart('address');
293 294 295 296 297 298 299 300

        if (common_config('singleuser', 'enabled')) {
            $user = User::singleUser();
            $url = common_local_url('showstream', array('nickname' => $user->nickname));
        } else {
            $url = common_local_url('public');
        }

301
        $action->element('a', array('class' => 'url',
302
                                    'href' => $url),
303
                         '');
304

305 306
        $action->elementEnd('address');

307
        $action->showContentBlock();
308
        $action->showScripts();
309 310 311 312
        $action->elementEnd('body');
        return false; // No default processing
    }

Evan Prodromou's avatar
Evan Prodromou committed
313 314 315 316 317
    function noticeAsJson($notice)
    {
        // FIXME: this code should be abstracted to a neutral third
        // party, like Notice::asJson(). I'm not sure of the ethics
        // of refactoring from within a plugin, so I'm just abusing
318
        // the ApiAction method. Don't do this unless you're me!
Evan Prodromou's avatar
Evan Prodromou committed
319

320
        $act = new ApiAction('/dev/null');
Evan Prodromou's avatar
Evan Prodromou committed
321

322
        $arr = $act->twitterStatusArray($notice, true);
323
        $arr['url'] = $notice->getUrl();
Evan Prodromou's avatar
Evan Prodromou committed
324 325
        $arr['html'] = htmlspecialchars($notice->rendered);
        $arr['source'] = htmlspecialchars($arr['source']);
326
        $arr['conversation_url'] = $notice->getConversationUrl();
Evan Prodromou's avatar
Evan Prodromou committed
327 328 329 330

        $profile = $notice->getProfile();
        $arr['user']['profile_url'] = $profile->profileurl;

331 332 333
        // Add needed repeat data

        if (!empty($notice->repeat_of)) {
334
            $original = Notice::getKV('id', $notice->repeat_of);
335 336
            if ($original instanceof Notice) {
                $arr['retweeted_status']['url'] = $original->getUrl();
337 338 339 340
                $arr['retweeted_status']['html'] = htmlspecialchars($original->rendered);
                $arr['retweeted_status']['source'] = htmlspecialchars($original->source);
                $originalProfile = $original->getProfile();
                $arr['retweeted_status']['user']['profile_url'] = $originalProfile->profileurl;
341
                $arr['retweeted_status']['conversation_url'] = $original->getConversationUrl();
342
            }
343
            unset($original);
344 345
        }

Evan Prodromou's avatar
Evan Prodromou committed
346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368
        return $arr;
    }

    function getNoticeTags($notice)
    {
        $tags = null;

        $nt = new Notice_tag();
        $nt->notice_id = $notice->id;

        if ($nt->find()) {
            $tags = array();
            while ($nt->fetch()) {
                $tags[] = $nt->tag;
            }
        }

        $nt->free();
        $nt = null;

        return $tags;
    }

369 370
    function _getScripts()
    {
371 372 373
        $urlpath = self::staticPath(str_replace('Plugin','',__CLASS__),
                                    'js/realtimeupdate.js');
        return array($urlpath);
374 375
    }

376
    /**
377 378 379 380 381 382
     * Export any i18n messages that need to be loaded at runtime...
     *
     * @param Action $action
     * @param array $messages
     *
     * @return boolean hook return value
383
     */
384
    function onEndScriptMessages($action, &$messages)
385
    {
386 387 388 389 390 391 392 393 394 395 396 397 398 399
        // TRANS: Text label for realtime view "play" button, usually replaced by an icon.
        $messages['realtime_play'] = _m('BUTTON', 'Play');
        // TRANS: Tooltip for realtime view "play" button.
        $messages['realtime_play_tooltip'] = _m('TOOLTIP', 'Play');
        // TRANS: Text label for realtime view "pause" button
        $messages['realtime_pause'] = _m('BUTTON', 'Pause');
        // TRANS: Tooltip for realtime view "pause" button
        $messages['realtime_pause_tooltip'] = _m('TOOLTIP', 'Pause');
        // TRANS: Text label for realtime view "popup" button, usually replaced by an icon.
        $messages['realtime_popup'] = _m('BUTTON', 'Pop up');
        // TRANS: Tooltip for realtime view "popup" button.
        $messages['realtime_popup_tooltip'] = _m('TOOLTIP', 'Pop up in a window');

        return true;
400 401
    }

402
    function _updateInitialize($timeline, $user_id)
403
    {
404
        return "RealtimeUpdate.init($user_id, \"$this->showurl\"); ";
405 406 407 408 409 410
    }

    function _connect()
    {
    }

411
    function _publish($timeline, $json)
412 413 414 415 416 417
    {
    }

    function _disconnect()
    {
    }
418 419 420 421 422

    function _pathToChannel($path)
    {
        return '';
    }
423

424

425
    function _getTimeline($action)
426 427 428 429 430 431 432 433 434 435
    {
        $channel = $this->_getChannel($action);
        if (empty($channel)) {
            return null;
        }

        return $this->_pathToChannel(array($channel->channel_key));
    }

    function _getChannel($action)
436 437
    {
        $timeline = null;
438 439 440
        $arg1     = null;
        $arg2     = null;

Evan Prodromou's avatar
Evan Prodromou committed
441 442
        $action_name = $action->trimmed('action');

443 444 445 446
        // FIXME: lists
        // FIXME: search (!)
        // FIXME: profile + tag

Evan Prodromou's avatar
Evan Prodromou committed
447
        switch ($action_name) {
448
         case 'public':
449
            // no arguments
450 451 452
            break;
         case 'tag':
            $tag = $action->trimmed('tag');
453
            if (!empty($tag)) {
454 455
                $arg1 = $tag;
            } else {
456 457
                $this->log(LOG_NOTICE, "Unexpected 'tag' action without tag argument");
                return null;
458 459
            }
            break;
Evan Prodromou's avatar
Evan Prodromou committed
460 461 462 463 464 465
         case 'showstream':
         case 'all':
         case 'replies':
         case 'showgroup':
            $nickname = common_canonical_nickname($action->trimmed('nickname'));
            if (!empty($nickname)) {
466 467
                $arg1 = $nickname;
            } else {
468 469
                $this->log(LOG_NOTICE, "Unexpected $action_name action without nickname argument.");
                return null;
Evan Prodromou's avatar
Evan Prodromou committed
470 471
            }
            break;
472
         default:
473
            return null;
474 475
        }

476 477 478 479 480 481 482 483
        $user = common_current_user();

        $user_id = (!empty($user)) ? $user->id : null;

        $channel = Realtime_channel::getChannel($user_id,
                                                $action_name,
                                                $arg1,
                                                $arg2);
484 485

        return $channel;
486
    }
487

488 489
    function onStartReadWriteTables(&$alwaysRW, &$rwdb)
    {
490 491
        $alwaysRW[] = 'realtime_channel';
        return true;
492
    }
Evan Prodromou's avatar
Evan Prodromou committed
493
}