]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/activityimporter.php
I'm still not sure when it's useful to reset a notice's author
[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
48 class ActivityImporter extends QueueHandler
49 {
50     private $trusted = false;
51
52     /**
53      * Function comment
54      *
55      * @param
56      *
57      * @return
58      */
59
60     function handle($data)
61     {
62         list($user, $author, $activity, $trusted) = $data;
63
64         $this->trusted = $trusted;
65
66         try {
67             switch ($activity->verb) {
68             case ActivityVerb::FOLLOW:
69                 $this->subscribeProfile($user, $author, $activity);
70                 break;
71             case ActivityVerb::JOIN:
72                 $this->joinGroup($user, $activity);
73                 break;
74             case ActivityVerb::POST:
75                 $this->postNote($user, $author, $activity);
76                 break;
77             default:
78                 throw new Exception("Unknown verb: {$activity->verb}");
79             }
80         } catch (ClientException $ce) {
81             common_log(LOG_WARNING, $ce->getMessage());
82             return true;
83         } catch (ServerException $se) {
84             common_log(LOG_ERR, $se->getMessage());
85             return false;
86         } catch (Exception $e) {
87             common_log(LOG_ERR, $e->getMessage());
88             return false;
89         }
90         return true;
91     }
92     
93     function subscribeProfile($user, $author, $activity)
94     {
95         $profile = $user->getProfile();
96
97         if ($activity->objects[0]->id == $author->id) {
98
99             if (!$this->trusted) {
100                 throw new ClientException(_("Can't force subscription for untrusted user."));
101             }
102
103             $other = $activity->actor;
104             $otherUser = User::staticGet('uri', $other->id);
105             
106             if (!empty($otherUser)) {
107                 $otherProfile = $otherUser->getProfile();
108             } else {
109                 throw new Exception("Can't force remote user to subscribe.");
110             }
111
112             // XXX: don't do this for untrusted input!
113
114             Subscription::start($otherProfile, $profile);
115
116         } else if (empty($activity->actor) 
117                    || $activity->actor->id == $author->id) {
118
119             $other = $activity->objects[0];
120
121             $otherProfile = Profile::fromUri($other->id);
122
123             if (empty($otherProfile)) {
124                 throw new ClientException(_("Unknown profile."));
125             }
126
127             Subscription::start($profile, $otherProfile);
128         } else {
129             throw new Exception("This activity seems unrelated to our user.");
130         }
131     }
132
133     function joinGroup($user, $activity)
134     {
135         // XXX: check that actor == subject
136
137         $uri = $activity->objects[0]->id;
138
139         $group = User_group::staticGet('uri', $uri);
140
141         if (empty($group)) {
142             $oprofile = Ostatus_profile::ensureActivityObjectProfile($activity->objects[0]);
143             if (!$oprofile->isGroup()) {
144                 throw new ClientException("Remote profile is not a group!");
145             }
146             $group = $oprofile->localGroup();
147         }
148
149         assert(!empty($group));
150
151         if ($user->isMember($group)) {
152             throw new ClientException("User is already a member of this group.");
153         }
154
155         if (Event::handle('StartJoinGroup', array($group, $user))) {
156             Group_member::join($group->id, $user->id);
157             Event::handle('EndJoinGroup', array($group, $user));
158         }
159     }
160
161     // XXX: largely cadged from Ostatus_profile::processNote()
162
163     function postNote($user, $author, $activity)
164     {
165         $note = $activity->objects[0];
166
167         $sourceUri = $note->id;
168
169         $notice = Notice::staticGet('uri', $sourceUri);
170
171         if (!empty($notice)) {
172             
173             common_log(LOG_INFO, "Notice {$sourceUri} already exists.");
174
175             if ($this->trusted) {
176
177                 $profile = $notice->getProfile();
178
179                 $uri = $profile->getUri();
180
181                 if ($uri == $author->id) {
182                     common_log(LOG_INFO, "Updating notice author from $author->id to $user->uri");
183                     $orig = clone($notice);
184                     $notice->profile_id = $user->id;
185                     $notice->update($orig);
186                     return;
187                 } else {
188                     throw new ClientException(sprintf(_("Already know about notice %s and ".
189                                                         " it's got a different author %s."),
190                                                       $sourceUri, $uri));
191                 }
192             }
193         }
194
195         // Use summary as fallback for content
196
197         if (!empty($note->content)) {
198             $sourceContent = $note->content;
199         } else if (!empty($note->summary)) {
200             $sourceContent = $note->summary;
201         } else if (!empty($note->title)) {
202             $sourceContent = $note->title;
203         } else {
204             // @fixme fetch from $sourceUrl?
205             // @todo i18n FIXME: use sprintf and add i18n.
206             throw new ClientException("No content for notice {$sourceUri}.");
207         }
208
209         // Get (safe!) HTML and text versions of the content
210
211         $rendered = $this->purify($sourceContent);
212         $content = html_entity_decode(strip_tags($rendered), ENT_QUOTES, 'UTF-8');
213
214         $shortened = $user->shortenLinks($content);
215
216         $options = array('is_local' => Notice::LOCAL_PUBLIC,
217                          'uri' => $sourceUri,
218                          'rendered' => $rendered,
219                          'replies' => array(),
220                          'groups' => array(),
221                          'tags' => array(),
222                          'urls' => array(),
223                          'distribute' => false);
224
225         // Check for optional attributes...
226
227         if (!empty($activity->time)) {
228             $options['created'] = common_sql_date($activity->time);
229         }
230
231         if ($activity->context) {
232             // Any individual or group attn: targets?
233
234             list($options['groups'], $options['replies']) = $this->filterAttention($activity->context->attention);
235
236             // Maintain direct reply associations
237             // @fixme what about conversation ID?
238             if (!empty($activity->context->replyToID)) {
239                 $orig = Notice::staticGet('uri',
240                                           $activity->context->replyToID);
241                 if (!empty($orig)) {
242                     $options['reply_to'] = $orig->id;
243                 }
244             }
245
246             $location = $activity->context->location;
247
248             if ($location) {
249                 $options['lat'] = $location->lat;
250                 $options['lon'] = $location->lon;
251                 if ($location->location_id) {
252                     $options['location_ns'] = $location->location_ns;
253                     $options['location_id'] = $location->location_id;
254                 }
255             }
256         }
257
258         // Atom categories <-> hashtags
259
260         foreach ($activity->categories as $cat) {
261             if ($cat->term) {
262                 $term = common_canonical_tag($cat->term);
263                 if ($term) {
264                     $options['tags'][] = $term;
265                 }
266             }
267         }
268
269         // Atom enclosures -> attachment URLs
270         foreach ($activity->enclosures as $href) {
271             // @fixme save these locally or....?
272             $options['urls'][] = $href;
273         }
274
275         common_log(LOG_INFO, "Saving notice {$options['uri']}");
276
277         $saved = Notice::saveNew($user->id,
278                                  $content,
279                                  'restore', // TODO: restore the actual source
280                                  $options);
281
282         return $saved;
283     }
284
285     function filterAttention($attn)
286     {
287         $groups = array();
288         $replies = array();
289
290         foreach (array_unique($attn) as $recipient) {
291
292             // Is the recipient a local user?
293
294             $user = User::staticGet('uri', $recipient);
295
296             if ($user) {
297                 // @fixme sender verification, spam etc?
298                 $replies[] = $recipient;
299                 continue;
300             }
301
302             // Is the recipient a remote group?
303             $oprofile = Ostatus_profile::ensureProfileURI($recipient);
304
305             if ($oprofile) {
306                 if (!$oprofile->isGroup()) {
307                     // may be canonicalized or something
308                     $replies[] = $oprofile->uri;
309                 }
310                 continue;
311             }
312
313             // Is the recipient a local group?
314             // @fixme uri on user_group isn't reliable yet
315             // $group = User_group::staticGet('uri', $recipient);
316             $id = OStatusPlugin::localGroupFromUrl($recipient);
317
318             if ($id) {
319                 $group = User_group::staticGet('id', $id);
320                 if ($group) {
321                     // Deliver to all members of this local group if allowed.
322                     $profile = $sender->localProfile();
323                     if ($profile->isMember($group)) {
324                         $groups[] = $group->id;
325                     } else {
326                         common_log(LOG_INFO, "Skipping reply to local group {$group->nickname} as sender {$profile->id} is not a member");
327                     }
328                     continue;
329                 } else {
330                     common_log(LOG_INFO, "Skipping reply to bogus group $recipient");
331                 }
332             }
333         }
334
335         return array($groups, $replies);
336     }
337  
338
339     function purify($content)
340     {
341         $config = array('safe' => 1,
342                         'deny_attribute' => 'id,style,on*');
343         return htmLawed($content, $config);
344     }
345 }