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

RealtimePlugin.php 15.4 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 25
 * @package   StatusNet
 * @author    Evan Prodromou <evan@status.net>
 * @copyright 2009 StatusNet, Inc.
Evan Prodromou's avatar
Evan Prodromou committed
26
 * @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
27
 * @link      http://status.net/
Evan Prodromou's avatar
Evan Prodromou committed
28 29
 */

30
if (!defined('STATUSNET') && !defined('LACONICA')) {
Evan Prodromou's avatar
Evan Prodromou committed
31 32 33 34
    exit(1);
}

/**
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
 *
 * @category Plugin
Evan Prodromou's avatar
Evan Prodromou committed
41 42
 * @package  StatusNet
 * @author   Evan Prodromou <evan@status.net>
Evan Prodromou's avatar
Evan Prodromou committed
43
 * @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
44
 * @link     http://status.net/
Evan Prodromou's avatar
Evan Prodromou committed
45
 */
46
class RealtimePlugin extends Plugin
Evan Prodromou's avatar
Evan Prodromou committed
47
{
48
    protected $showurl = null;
Evan Prodromou's avatar
Evan Prodromou committed
49

50 51 52 53
    /**
     * When it's time to initialize the plugin, calculate and
     * pass the URLs we need.
     */
54
    function onInitializePlugin()
Evan Prodromou's avatar
Evan Prodromou committed
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;
Evan Prodromou's avatar
Evan Prodromou committed
60
    }
61

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

69 70 71 72 73 74
    function onAutoload($cls)
    {
        $dir = dirname(__FILE__);

        switch ($cls)
        {
75 76 77 78
        case 'KeepalivechannelAction':
        case 'ClosechannelAction':
            include_once $dir . '/' . strtolower(mb_substr($cls, 0, -6)) . '.php';
            return false;
79 80 81 82 83 84 85
        case 'Realtime_channel':
            include_once $dir.'/'.$cls.'.php';
            return false;
        default:
            return true;
        }
    }
Evan Prodromou's avatar
Evan Prodromou committed
86

87 88 89 90 91 92 93 94
    /**
     * Hook for RouterInitialized event.
     *
     * @param Net_URL_Mapper $m path-to-action mapper
     * @return boolean hook return
     */
    function onRouterInitialized($m)
    {
95 96 97 98 99 100 101
        $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;
102 103
    }

Evan Prodromou's avatar
Evan Prodromou committed
104 105
    function onEndShowScripts($action)
    {
106 107 108 109 110 111 112
        $channel = $this->_getChannel($action);

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

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

114 115 116 117
        // If there's not a timeline on this page,
        // just return true

        if (empty($timeline)) {
118
            return true;
Evan Prodromou's avatar
Evan Prodromou committed
119 120
        }

121
        $base = $action->selfUrl();
Evan Prodromou's avatar
Evan Prodromou committed
122
        if (mb_strstr($base, '?')) {
123 124 125 126 127
            $url = $base . '&realtime=1';
        } else {
            $url = $base . '?realtime=1';
        }

128
        $scripts = $this->_getScripts();
Evan Prodromou's avatar
Evan Prodromou committed
129 130

        foreach ($scripts as $script) {
131
            $action->script($script);
Evan Prodromou's avatar
Evan Prodromou committed
132 133 134 135 136 137 138 139 140 141
        }

        $user = common_current_user();

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

Evan Prodromou's avatar
Evan Prodromou committed
142
        if ($action->boolean('realtime')) {
143 144 145
            $realtimeUI = ' RealtimeUpdate.initPopupWindow();';
        }
        else {
146
            $pluginPath = common_path('plugins/Realtime/');
147 148
            $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
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);
Evan Prodromou's avatar
Evan Prodromou committed
157 158 159

        return true;
    }
160 161 162

    function onEndShowStatusNetStyles($action)
    {
163
        $action->cssLink(Plugin::staticPath('Realtime', 'realtimeupdate.css'),
164 165
                         null,
                         'screen, projection, tv');
166 167
        return true;
    }
Evan Prodromou's avatar
Evan Prodromou committed
168

169
    function onHandleQueuedNotice($notice)
Evan Prodromou's avatar
Evan Prodromou committed
170
    {
171
        $paths = array();
Evan Prodromou's avatar
Evan Prodromou committed
172

Evan Prodromou's avatar
Evan Prodromou committed
173 174
        // Add to the author's timeline

175 176 177 178 179 180 181
        try {
            $profile = $notice->getProfile();
        } catch (Exception $e) {
            $this->log(LOG_ERR, $e->getMessage());
            return true;
        }

Evan Prodromou's avatar
Evan Prodromou committed
182 183 184
        $user = User::staticGet('id', $notice->profile_id);

        if (!empty($user)) {
185
            $paths[] = array('showstream', $user->nickname, null);
Evan Prodromou's avatar
Evan Prodromou committed
186 187 188
        }

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

190
        if ($notice->is_local == Notice::LOCAL_PUBLIC ||
Zach Copley's avatar
Zach Copley committed
191
            ($notice->is_local == Notice::REMOTE && !common_config('public', 'localonly'))) {
192
            $paths[] = array('public', null, null);
Evan Prodromou's avatar
Evan Prodromou committed
193 194
        }

Evan Prodromou's avatar
Evan Prodromou committed
195 196
        // Add to the tags timeline

Evan Prodromou's avatar
Evan Prodromou committed
197 198 199 200
        $tags = $this->getNoticeTags($notice);

        if (!empty($tags)) {
            foreach ($tags as $tag) {
201
                $paths[] = array('tag', $tag, null);
Evan Prodromou's avatar
Evan Prodromou committed
202 203 204
            }
        }

Evan Prodromou's avatar
Evan Prodromou committed
205 206 207
        // Add to inbox timelines
        // XXX: do a join

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

210 211
        foreach (array_keys($ni) as $user_id) {
            $user = User::staticGet('id', $user_id);
212
            $paths[] = array('all', $user->nickname, null);
Evan Prodromou's avatar
Evan Prodromou committed
213 214 215 216 217 218 219 220 221 222 223
        }

        // Add to the replies timeline

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

        if ($reply->find()) {
            while ($reply->fetch()) {
                $user = User::staticGet('id', $reply->profile_id);
                if (!empty($user)) {
224
                    $paths[] = array('replies', $user->nickname, null);
Evan Prodromou's avatar
Evan Prodromou committed
225 226 227 228 229 230 231 232 233 234 235 236 237
                }
            }
        }

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

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

        if ($gi->find()) {
            while ($gi->fetch()) {
                $ug = User_group::staticGet('id', $gi->group_id);
238
                $paths[] = array('showgroup', $ug->nickname, null);
Evan Prodromou's avatar
Evan Prodromou committed
239 240 241
            }
        }

242
        if (count($paths) > 0) {
Evan Prodromou's avatar
Evan Prodromou committed
243 244 245

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

246
            $this->_connect();
247

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

251
            foreach ($paths as $path) {
252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271

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

                $channels = Realtime_channel::getAllChannels($action, $arg1, $arg2);

                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 {
                        $profile = Profile::staticGet('id', $channel->user_id);
                    }
                    if ($notice->inScope($profile)) {
                        $timeline = $this->_pathToChannel(array($channel->channel_key));
                        $this->_publish($timeline, $json);
                    }
                }
Evan Prodromou's avatar
Evan Prodromou committed
272 273
            }

274
            $this->_disconnect();
Evan Prodromou's avatar
Evan Prodromou committed
275 276 277 278 279
        }

        return true;
    }

280 281 282 283 284 285 286 287 288
    function onStartShowBody($action)
    {
        $realtime = $action->boolean('realtime');
        if (!$realtime) {
            return true;
        }

        $action->elementStart('body',
                              (common_current_user()) ? array('id' => $action->trimmed('action'),
289 290 291
                                                              'class' => 'user_in realtime-popup')
                              : array('id' => $action->trimmed('action'),
                                      'class'=> 'realtime-popup'));
292 293 294

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

296
        $action->elementStart('address');
297 298 299 300 301 302 303 304

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

305
        $action->element('a', array('class' => 'url',
306
                                    'href' => $url),
307
                         '');
308

309 310
        $action->elementEnd('address');

311
        $action->showContentBlock();
312
        $action->showScripts();
313 314 315 316
        $action->elementEnd('body');
        return false; // No default processing
    }

Evan Prodromou's avatar
Evan Prodromou committed
317 318 319 320 321
    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
322
        // the ApiAction method. Don't do this unless you're me!
Evan Prodromou's avatar
Evan Prodromou committed
323

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

326
        $arr = $act->twitterStatusArray($notice, true);
Evan Prodromou's avatar
Evan Prodromou committed
327 328 329
        $arr['url'] = $notice->bestUrl();
        $arr['html'] = htmlspecialchars($notice->rendered);
        $arr['source'] = htmlspecialchars($arr['source']);
330
        $arr['conversation_url'] = $this->getConversationUrl($notice);
Evan Prodromou's avatar
Evan Prodromou committed
331 332 333 334

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

335 336 337 338 339 340 341 342 343 344
        // Add needed repeat data

        if (!empty($notice->repeat_of)) {
            $original = Notice::staticGet('id', $notice->repeat_of);
            if (!empty($original)) {
                $arr['retweeted_status']['url'] = $original->bestUrl();
                $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;
345
                $arr['retweeted_status']['conversation_url'] = $this->getConversationUrl($original);
346 347 348 349
            }
            $original = null;
        }

Evan Prodromou's avatar
Evan Prodromou committed
350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372
        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;
    }

373 374 375 376 377 378 379 380 381 382 383 384
    function getConversationUrl($notice)
    {
        $convurl = null;

        if ($notice->hasConversation()) {
            $conv = Conversation::staticGet(
                'id',
                $notice->conversation
            );
            $convurl = $conv->uri;

            if(empty($convurl)) {
385
                $msg = sprintf( "Could not find Conversation ID %d to make 'in context'"
386
                    . "link for Notice ID %d.",
387 388
                    $notice->conversation,
                    $notice->id
389
                );
390 391

                common_log(LOG_WARNING, $msg);
392 393
            } else {
                $convurl .= '#notice-' . $notice->id;
394 395 396 397 398 399
            }
        }

        return $convurl;
    }

400 401
    function _getScripts()
    {
402 403 404 405 406 407
        if (common_config('site', 'minify')) {
            $js = 'realtimeupdate.min.js';
        } else {
            $js = 'realtimeupdate.js';
        }
        return array(Plugin::staticPath('Realtime', $js));
408 409
    }

410
    /**
411 412 413 414 415 416
     * Export any i18n messages that need to be loaded at runtime...
     *
     * @param Action $action
     * @param array $messages
     *
     * @return boolean hook return value
417
     */
418
    function onEndScriptMessages($action, &$messages)
419
    {
420 421 422 423 424 425 426 427 428 429 430 431 432 433
        // 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;
434 435
    }

436
    function _updateInitialize($timeline, $user_id)
437
    {
438
        return "RealtimeUpdate.init($user_id, \"$this->showurl\"); ";
439 440 441 442 443 444
    }

    function _connect()
    {
    }

445
    function _publish($timeline, $json)
446 447 448 449 450 451
    {
    }

    function _disconnect()
    {
    }
452 453 454 455 456

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

458

459
    function _getTimeline($action)
460 461 462 463 464 465 466 467 468 469
    {
        $channel = $this->_getChannel($action);
        if (empty($channel)) {
            return null;
        }

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

    function _getChannel($action)
470 471
    {
        $timeline = null;
472 473 474
        $arg1     = null;
        $arg2     = null;

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

477 478 479 480
        // FIXME: lists
        // FIXME: search (!)
        // FIXME: profile + tag

Evan Prodromou's avatar
Evan Prodromou committed
481
        switch ($action_name) {
482
         case 'public':
483
            // no arguments
484 485 486
            break;
         case 'tag':
            $tag = $action->trimmed('tag');
487
            if (!empty($tag)) {
488 489
                $arg1 = $tag;
            } else {
490 491
                $this->log(LOG_NOTICE, "Unexpected 'tag' action without tag argument");
                return null;
492 493
            }
            break;
Evan Prodromou's avatar
Evan Prodromou committed
494 495 496 497 498 499
         case 'showstream':
         case 'all':
         case 'replies':
         case 'showgroup':
            $nickname = common_canonical_nickname($action->trimmed('nickname'));
            if (!empty($nickname)) {
500 501
                $arg1 = $nickname;
            } else {
502 503
                $this->log(LOG_NOTICE, "Unexpected $action_name action without nickname argument.");
                return null;
Evan Prodromou's avatar
Evan Prodromou committed
504 505
            }
            break;
506
         default:
507
            return null;
508 509
        }

510 511 512 513 514 515 516 517
        $user = common_current_user();

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

        $channel = Realtime_channel::getChannel($user_id,
                                                $action_name,
                                                $arg1,
                                                $arg2);
518 519

        return $channel;
520
    }
521

522 523
    function onStartReadWriteTables(&$alwaysRW, &$rwdb)
    {
524 525
        $alwaysRW[] = 'realtime_channel';
        return true;
526
    }
Evan Prodromou's avatar
Evan Prodromou committed
527
}