]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/activityimporter.php
Merge commit 'refs/merge-requests/164' of git://gitorious.org/statusnet/mainline...
[quix0rs-gnu-social.git] / lib / activityimporter.php
1 <?php
2 /**
3  * StatusNet - the distributed open-source microblogging tool
4  * Copyright (C) 2010, StatusNet, Inc.
5  *
6  * class to import activities as part of a user's timeline
7  *
8  * PHP version 5
9  *
10  * This program is free software: you can redistribute it and/or modify
11  * it under the terms of the GNU Affero General Public License as published by
12  * the Free Software Foundation, either version 3 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU Affero General Public License for more details.
19  *
20  * You should have received a copy of the GNU Affero General Public License
21  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
22  *
23  * @category  Cache
24  * @package   StatusNet
25  * @author    Evan Prodromou <evan@status.net>
26  * @copyright 2010 StatusNet, Inc.
27  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
28  * @link      http://status.net/
29  */
30
31 if (!defined('STATUSNET')) {
32     // This check helps protect against security problems;
33     // your code file can't be executed directly from the web.
34     exit(1);
35 }
36
37 /**
38  * Class comment
39  *
40  * @category  General
41  * @package   StatusNet
42  * @author    Evan Prodromou <evan@status.net>
43  * @copyright 2010 StatusNet, Inc.
44  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
45  * @link      http://status.net/
46  */
47 class ActivityImporter extends QueueHandler
48 {
49     private $trusted = false;
50
51     /**
52      * Function comment
53      *
54      * @param
55      *
56      * @return
57      */
58     function handle($data)
59     {
60         list($user, $author, $activity, $trusted) = $data;
61
62         $this->trusted = $trusted;
63
64         $done = null;
65
66         try {
67             if (Event::handle('StartImportActivity',
68                               array($user, $author, $activity, $trusted, &$done))) {
69                 switch ($activity->verb) {
70                 case ActivityVerb::FOLLOW:
71                     $this->subscribeProfile($user, $author, $activity);
72                     break;
73                 case ActivityVerb::JOIN:
74                     $this->joinGroup($user, $activity);
75                     break;
76                 case ActivityVerb::POST:
77                     $this->postNote($user, $author, $activity);
78                     break;
79                 default:
80                     // TRANS: Client exception thrown when using an unknown verb for the activity importer.
81                     throw new ClientException(sprintf(_("Unknown verb: \"%s\"."),$activity->verb));
82                 }
83                 Event::handle('EndImportActivity',
84                               array($user, $author, $activity, $trusted));
85                 $done = true;
86             }
87         } catch (Exception $e) {
88             common_log(LOG_ERR, $e->getMessage());
89             $done = true;
90         }
91         return $done;
92     }
93
94     function subscribeProfile($user, $author, $activity)
95     {
96         $profile = $user->getProfile();
97
98         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::staticGet('uri', $other->id);
106
107             if (!empty($otherUser)) {
108                 $otherProfile = $otherUser->getProfile();
109             } else {
110                 // TRANS: Client exception thrown when trying to force a remote user to subscribe.
111                 throw new Exception(_('Cannot force remote user to subscribe.'));
112             }
113
114             // XXX: don't do this for untrusted input!
115
116             Subscription::start($otherProfile, $profile);
117         } else if (empty($activity->actor)
118                    || $activity->actor->id == $author->id) {
119
120             $other = $activity->objects[0];
121
122             $otherProfile = Profile::fromUri($other->id);
123
124             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             Subscription::start($profile, $otherProfile);
130         } 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     function joinGroup($user, $activity)
137     {
138         // XXX: check that actor == subject
139
140         $uri = $activity->objects[0]->id;
141
142         $group = User_group::staticGet('uri', $uri);
143
144         if (empty($group)) {
145             $oprofile = Ostatus_profile::ensureActivityObjectProfile($activity->objects[0]);
146             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             $group = $oprofile->localGroup();
151         }
152
153         assert(!empty($group));
154
155         if ($user->isMember($group)) {
156             // TRANS: Client exception thrown when trying to join a group the importing user is already a member of.
157             throw new ClientException(_("User is already a member of this group."));
158         }
159
160         $user->joinGroup($group);
161     }
162
163     // XXX: largely cadged from Ostatus_profile::processNote()
164
165     function postNote($user, $author, $activity)
166     {
167         $note = $activity->objects[0];
168
169         $sourceUri = $note->id;
170
171         $notice = Notice::staticGet('uri', $sourceUri);
172
173         if (!empty($notice)) {
174
175             common_log(LOG_INFO, "Notice {$sourceUri} already exists.");
176
177             if ($this->trusted) {
178
179                 $profile = $notice->getProfile();
180
181                 $uri = $profile->getUri();
182
183                 if ($uri == $author->id) {
184                     common_log(LOG_INFO, "Updating notice author from $author->id to $user->uri");
185                     $orig = clone($notice);
186                     $notice->profile_id = $user->id;
187                     $notice->update($orig);
188                     return;
189                 } else {
190                     // TRANS: Client exception thrown when trying to import a notice by another user.
191                     // TRANS: %1$s is the source URI of the notice, %2$s is the URI of the author.
192                     throw new ClientException(sprintf(_('Already know about notice %1$s and '.
193                                                         ' it has a different author %2$s.'),
194                                                       $sourceUri, $uri));
195                 }
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         // Use summary as fallback for content
203
204         if (!empty($note->content)) {
205             $sourceContent = $note->content;
206         } else if (!empty($note->summary)) {
207             $sourceContent = $note->summary;
208         } else if (!empty($note->title)) {
209             $sourceContent = $note->title;
210         } else {
211             // @fixme fetch from $sourceUrl?
212             // TRANS: Client exception thrown when trying to import a notice without content.
213             // TRANS: %s is the notice URI.
214             throw new ClientException(sprintf(_('No content for notice %s.'),$sourceUri));
215         }
216
217         // Get (safe!) HTML and text versions of the content
218
219         $rendered = $this->purify($sourceContent);
220         $content = html_entity_decode(strip_tags($rendered), ENT_QUOTES, 'UTF-8');
221
222         $shortened = $user->shortenLinks($content);
223
224         $options = array('is_local' => Notice::LOCAL_PUBLIC,
225                          'uri' => $sourceUri,
226                          'rendered' => $rendered,
227                          'replies' => array(),
228                          'groups' => array(),
229                          'tags' => array(),
230                          'urls' => array(),
231                          'distribute' => false);
232
233         // Check for optional attributes...
234
235         if (!empty($activity->time)) {
236             $options['created'] = common_sql_date($activity->time);
237         }
238
239         if ($activity->context) {
240             // Any individual or group attn: targets?
241
242             list($options['groups'], $options['replies']) = $this->filterAttention($activity->context->attention);
243
244             // Maintain direct reply associations
245             // @fixme what about conversation ID?
246             if (!empty($activity->context->replyToID)) {
247                 $orig = Notice::staticGet('uri',
248                                           $activity->context->replyToID);
249                 if (!empty($orig)) {
250                     $options['reply_to'] = $orig->id;
251                 }
252             }
253
254             $location = $activity->context->location;
255
256             if ($location) {
257                 $options['lat'] = $location->lat;
258                 $options['lon'] = $location->lon;
259                 if ($location->location_id) {
260                     $options['location_ns'] = $location->location_ns;
261                     $options['location_id'] = $location->location_id;
262                 }
263             }
264         }
265
266         // Atom categories <-> hashtags
267
268         foreach ($activity->categories as $cat) {
269             if ($cat->term) {
270                 $term = common_canonical_tag($cat->term);
271                 if ($term) {
272                     $options['tags'][] = $term;
273                 }
274             }
275         }
276
277         // Atom enclosures -> attachment URLs
278         foreach ($activity->enclosures as $href) {
279             // @fixme save these locally or....?
280             $options['urls'][] = $href;
281         }
282
283         common_log(LOG_INFO, "Saving notice {$options['uri']}");
284
285         $saved = Notice::saveNew($user->id,
286                                  $content,
287                                  'restore', // TODO: restore the actual source
288                                  $options);
289
290         return $saved;
291     }
292
293     function filterAttention($attn)
294     {
295         $groups = array();
296         $replies = array();
297
298         foreach (array_unique($attn) as $recipient) {
299
300             // Is the recipient a local user?
301
302             $user = User::staticGet('uri', $recipient);
303
304             if ($user) {
305                 // @fixme sender verification, spam etc?
306                 $replies[] = $recipient;
307                 continue;
308             }
309
310             // Is the recipient a remote group?
311             $oprofile = Ostatus_profile::ensureProfileURI($recipient);
312
313             if ($oprofile) {
314                 if (!$oprofile->isGroup()) {
315                     // may be canonicalized or something
316                     $replies[] = $oprofile->uri;
317                 }
318                 continue;
319             }
320
321             // Is the recipient a local group?
322             // @fixme uri on user_group isn't reliable yet
323             // $group = User_group::staticGet('uri', $recipient);
324             $id = OStatusPlugin::localGroupFromUrl($recipient);
325
326             if ($id) {
327                 $group = User_group::staticGet('id', $id);
328                 if ($group) {
329                     // Deliver to all members of this local group if allowed.
330                     $profile = $sender->localProfile();
331                     if ($profile->isMember($group)) {
332                         $groups[] = $group->id;
333                     } else {
334                         common_log(LOG_INFO, "Skipping reply to local group {$group->nickname} as sender {$profile->id} is not a member");
335                     }
336                     continue;
337                 } else {
338                     common_log(LOG_INFO, "Skipping reply to bogus group $recipient");
339                 }
340             }
341         }
342
343         return array($groups, $replies);
344     }
345
346
347     function purify($content)
348     {
349         require_once INSTALLDIR.'/extlib/htmLawed/htmLawed.php';
350
351         $config = array('safe' => 1,
352                         'deny_attribute' => 'id,style,on*');
353
354         return htmLawed($content, $config);
355     }
356 }