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

activityimporter.php 12.1 KB
Newer Older
1 2 3 4 5 6
<?php
/**
 * StatusNet - the distributed open-source microblogging tool
 * Copyright (C) 2010, StatusNet, Inc.
 *
 * class to import activities as part of a user's timeline
7
 *
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
 * PHP version 5
 *
 * 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  Cache
 * @package   StatusNet
 * @author    Evan Prodromou <evan@status.net>
 * @copyright 2010 StatusNet, Inc.
 * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
 * @link      http://status.net/
 */

if (!defined('STATUSNET')) {
    // This check helps protect against security problems;
    // your code file can't be executed directly from the web.
    exit(1);
}

/**
 * Class comment
 *
 * @category  General
 * @package   StatusNet
 * @author    Evan Prodromou <evan@status.net>
 * @copyright 2010 StatusNet, Inc.
 * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
 * @link      http://status.net/
 */
class ActivityImporter extends QueueHandler
{
    private $trusted = false;

    /**
     * Function comment
     *
     * @param
     *
     * @return
     */
    function handle($data)
    {
        list($user, $author, $activity, $trusted) = $data;

        $this->trusted = $trusted;

64 65
        $done = null;

66 67 68
        try {
            if (Event::handle('StartImportActivity',
                              array($user, $author, $activity, $trusted, &$done))) {
69 70 71 72 73 74 75 76 77 78 79
                switch ($activity->verb) {
                case ActivityVerb::FOLLOW:
                    $this->subscribeProfile($user, $author, $activity);
                    break;
                case ActivityVerb::JOIN:
                    $this->joinGroup($user, $activity);
                    break;
                case ActivityVerb::POST:
                    $this->postNote($user, $author, $activity);
                    break;
                default:
80 81
                    // TRANS: Client exception thrown when using an unknown verb for the activity importer.
                    throw new ClientException(sprintf(_("Unknown verb: \"%s\"."),$activity->verb));
82
                }
83
                Event::handle('EndImportActivity',
84 85
                              array($user, $author, $activity, $trusted));
                $done = true;
86
            }
87 88 89
        } catch (Exception $e) {
            common_log(LOG_ERR, $e->getMessage());
            $done = true;
90
        }
91
        return $done;
92
    }
93

94 95 96 97 98
    function subscribeProfile($user, $author, $activity)
    {
        $profile = $user->getProfile();

        if ($activity->objects[0]->id == $author->id) {
99
            if (!$this->trusted) {
100
                // TRANS: Client exception thrown when trying to force a subscription for an untrusted user.
101
                throw new ClientException(_('Cannot force subscription for untrusted user.'));
102 103
            }

104
            $other = $activity->actor;
105
            $otherUser = User::getKV('uri', $other->id);
106

107 108 109
            if (!empty($otherUser)) {
                $otherProfile = $otherUser->getProfile();
            } else {
110 111
                // TRANS: Client exception thrown when trying to force a remote user to subscribe.
                throw new Exception(_('Cannot force remote user to subscribe.'));
112 113 114 115 116
            }

            // XXX: don't do this for untrusted input!

            Subscription::start($otherProfile, $profile);
117
        } else if (empty($activity->actor)
118 119 120 121 122 123 124
                   || $activity->actor->id == $author->id) {

            $other = $activity->objects[0];

            $otherProfile = Profile::fromUri($other->id);

            if (empty($otherProfile)) {
125
                // TRANS: Client exception thrown when trying to subscribe to an unknown profile.
126
                throw new ClientException(_('Unknown profile.'));
127 128 129 130
            }

            Subscription::start($profile, $otherProfile);
        } else {
131
            // TRANS: Client exception thrown when trying to import an event not related to the importing user.
132
            throw new Exception(_('This activity seems unrelated to our user.'));
133 134 135 136 137 138 139 140 141
        }
    }

    function joinGroup($user, $activity)
    {
        // XXX: check that actor == subject

        $uri = $activity->objects[0]->id;

142
        $group = User_group::getKV('uri', $uri);
143 144 145 146

        if (empty($group)) {
            $oprofile = Ostatus_profile::ensureActivityObjectProfile($activity->objects[0]);
            if (!$oprofile->isGroup()) {
147
                // TRANS: Client exception thrown when trying to join a remote group that is not a group.
148
                throw new ClientException(_('Remote profile is not a group!'));
149 150 151 152 153 154
            }
            $group = $oprofile->localGroup();
        }

        assert(!empty($group));

155
        if ($user->isMember($group)) {
156 157
            // TRANS: Client exception thrown when trying to join a group the importing user is already a member of.
            throw new ClientException(_("User is already a member of this group."));
158 159
        }

160
        $user->joinGroup($group);
161 162 163 164
    }

    // XXX: largely cadged from Ostatus_profile::processNote()

165
    function postNote($user, $author, $activity)
166 167 168 169 170
    {
        $note = $activity->objects[0];

        $sourceUri = $note->id;

171
        $notice = Notice::getKV('uri', $sourceUri);
172 173

        if (!empty($notice)) {
174

175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
            common_log(LOG_INFO, "Notice {$sourceUri} already exists.");

            if ($this->trusted) {

                $profile = $notice->getProfile();

                $uri = $profile->getUri();

                if ($uri == $author->id) {
                    common_log(LOG_INFO, "Updating notice author from $author->id to $user->uri");
                    $orig = clone($notice);
                    $notice->profile_id = $user->id;
                    $notice->update($orig);
                    return;
                } else {
190 191
                    // TRANS: Client exception thrown when trying to import a notice by another user.
                    // TRANS: %1$s is the source URI of the notice, %2$s is the URI of the author.
192 193
                    throw new ClientException(sprintf(_('Already know about notice %1$s and '.
                                                        ' it has a different author %2$s.'),
194 195
                                                      $sourceUri, $uri));
                }
196
            } else {
197
                // TRANS: Client exception thrown when trying to overwrite the author information for a non-trusted user during import.
198
                throw new ClientException(_('Not overwriting author info for non-trusted user.'));
199
            }
200 201 202 203 204 205 206 207 208 209 210 211
        }

        // Use summary as fallback for content

        if (!empty($note->content)) {
            $sourceContent = $note->content;
        } else if (!empty($note->summary)) {
            $sourceContent = $note->summary;
        } else if (!empty($note->title)) {
            $sourceContent = $note->title;
        } else {
            // @fixme fetch from $sourceUrl?
212 213
            // TRANS: Client exception thrown when trying to import a notice without content.
            // TRANS: %s is the notice URI.
214
            throw new ClientException(sprintf(_('No content for notice %s.'),$sourceUri));
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229
        }

        // Get (safe!) HTML and text versions of the content

        $rendered = $this->purify($sourceContent);
        $content = html_entity_decode(strip_tags($rendered), ENT_QUOTES, 'UTF-8');

        $shortened = $user->shortenLinks($content);

        $options = array('is_local' => Notice::LOCAL_PUBLIC,
                         'uri' => $sourceUri,
                         'rendered' => $rendered,
                         'replies' => array(),
                         'groups' => array(),
                         'tags' => array(),
230 231
                         'urls' => array(),
                         'distribute' => false);
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246

        // Check for optional attributes...

        if (!empty($activity->time)) {
            $options['created'] = common_sql_date($activity->time);
        }

        if ($activity->context) {
            // Any individual or group attn: targets?

            list($options['groups'], $options['replies']) = $this->filterAttention($activity->context->attention);

            // Maintain direct reply associations
            // @fixme what about conversation ID?
            if (!empty($activity->context->replyToID)) {
247
                $orig = Notice::getKV('uri',
248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
                                          $activity->context->replyToID);
                if (!empty($orig)) {
                    $options['reply_to'] = $orig->id;
                }
            }

            $location = $activity->context->location;

            if ($location) {
                $options['lat'] = $location->lat;
                $options['lon'] = $location->lon;
                if ($location->location_id) {
                    $options['location_ns'] = $location->location_ns;
                    $options['location_id'] = $location->location_id;
                }
            }
        }

        // Atom categories <-> hashtags

        foreach ($activity->categories as $cat) {
            if ($cat->term) {
                $term = common_canonical_tag($cat->term);
                if ($term) {
                    $options['tags'][] = $term;
                }
            }
        }

        // Atom enclosures -> attachment URLs
        foreach ($activity->enclosures as $href) {
            // @fixme save these locally or....?
            $options['urls'][] = $href;
        }

283 284
        common_log(LOG_INFO, "Saving notice {$options['uri']}");

285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301
        $saved = Notice::saveNew($user->id,
                                 $content,
                                 'restore', // TODO: restore the actual source
                                 $options);

        return $saved;
    }

    function filterAttention($attn)
    {
        $groups = array();
        $replies = array();

        foreach (array_unique($attn) as $recipient) {

            // Is the recipient a local user?

302
            $user = User::getKV('uri', $recipient);
303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322

            if ($user) {
                // @fixme sender verification, spam etc?
                $replies[] = $recipient;
                continue;
            }

            // Is the recipient a remote group?
            $oprofile = Ostatus_profile::ensureProfileURI($recipient);

            if ($oprofile) {
                if (!$oprofile->isGroup()) {
                    // may be canonicalized or something
                    $replies[] = $oprofile->uri;
                }
                continue;
            }

            // Is the recipient a local group?
            // @fixme uri on user_group isn't reliable yet
323
            // $group = User_group::getKV('uri', $recipient);
324 325 326
            $id = OStatusPlugin::localGroupFromUrl($recipient);

            if ($id) {
327
                $group = User_group::getKV('id', $id);
328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344
                if ($group) {
                    // Deliver to all members of this local group if allowed.
                    $profile = $sender->localProfile();
                    if ($profile->isMember($group)) {
                        $groups[] = $group->id;
                    } else {
                        common_log(LOG_INFO, "Skipping reply to local group {$group->nickname} as sender {$profile->id} is not a member");
                    }
                    continue;
                } else {
                    common_log(LOG_INFO, "Skipping reply to bogus group $recipient");
                }
            }
        }

        return array($groups, $replies);
    }
345

346 347 348

    function purify($content)
    {
349 350
        require_once INSTALLDIR.'/extlib/htmLawed/htmLawed.php';

351 352
        $config = array('safe' => 1,
                        'deny_attribute' => 'id,style,on*');
353

354 355 356
        return htmLawed($content, $config);
    }
}