]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/OStatus/lib/salmonaction.php
Test URLs against blacklist also on PuSH subscriptions.
[quix0rs-gnu-social.git] / plugins / OStatus / lib / salmonaction.php
1 <?php
2 /*
3  * StatusNet - the distributed open-source microblogging tool
4  * Copyright (C) 2010, StatusNet, Inc.
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU Affero General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU Affero General Public License for more details.
15  *
16  * You should have received a copy of the GNU Affero General Public License
17  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 /**
21  * @package OStatusPlugin
22  * @author James Walker <james@status.net>
23  */
24
25 if (!defined('GNUSOCIAL')) { exit(1); }
26
27 class SalmonAction extends Action
28 {
29     protected $needPost = true;
30
31     protected $oprofile = null; // Ostatus_profile of the actor
32     protected $actor    = null; // Profile object of the actor
33
34     var $format   = 'text'; // error messages will be printed in plaintext
35
36     var $xml      = null;
37     var $activity = null;
38     var $target   = null;
39
40     protected function prepare(array $args=array())
41     {
42         GNUsocial::setApi(true); // Send smaller error pages
43
44         parent::prepare($args);
45
46         if (!isset($_SERVER['CONTENT_TYPE'])) {
47             // TRANS: Client error. Do not translate "Content-type"
48             throw new ClientException(_m('Salmon requires a Content-type header.'));
49         }
50         $envxml = null;
51         switch ($_SERVER['CONTENT_TYPE']) {
52         case 'application/magic-envelope+xml':
53             $envxml = file_get_contents('php://input');
54             break;
55         case 'application/x-www-form-urlencoded':
56             $envxml = Magicsig::base64_url_decode($this->trimmed('xml'));
57             break;
58         default:
59             // TRANS: Client error. Do not translate the quoted "application/[type]" strings.
60             throw new ClientException(_m('Salmon requires "application/magic-envelope+xml". For Diaspora we also accept "application/x-www-form-urlencoded" with an "xml" parameter.', 415));
61         }
62
63         if (empty($envxml)) {
64             throw new ClientException('No magic envelope supplied in POST.');
65         }
66         try {
67             $magic_env = new MagicEnvelope($envxml);   // parse incoming XML as a MagicEnvelope
68
69             $entry = $magic_env->getPayload();  // Not cryptographically verified yet!
70             $this->activity = new Activity($entry->documentElement);
71             if (empty($this->activity->actor->id)) {
72                 common_log(LOG_ERR, "broken actor: " . var_export($this->activity->actor->id, true));
73                 common_log(LOG_ERR, "activity with no actor: " . var_export($this->activity, true));
74                 // TRANS: Exception.
75                 throw new ClientException(_m('Activity in salmon slap has no actor id.'));
76             }
77             // ensureProfiles sets $this->actor and $this->oprofile
78             $this->ensureProfiles();
79         } catch (Exception $e) {
80             common_debug('Salmon envelope parsing failed with: '.$e->getMessage());
81             // convert exception to ClientException
82             throw new ClientException($e->getMessage());
83         }
84
85         // Cryptographic verification test, throws exception on failure
86         $magic_env->verify($this->actor);
87
88         common_debug('Salmon slap is carrying activity URI=='._ve($this->activity->id));
89
90         return true;
91     }
92
93     /**
94      * Check the posted activity type and break out to appropriate processing.
95      */
96
97     protected function handle()
98     {
99         parent::handle();
100
101         assert($this->activity instanceof Activity);
102         assert($this->target instanceof Profile);
103
104         common_log(LOG_DEBUG, "Got a " . $this->activity->verb);
105
106         try {
107             $options = [ 'source' => 'ostatus' ];
108             common_debug('Save salmon slap directly with Notice::saveActivity for actor=='.$this->actor->getID());
109             $stored = Notice::saveActivity($this->activity, $this->actor, $options);
110             common_debug('Save salmon slap finished, notice id=='.$stored->getID());
111             return true;
112         } catch (AlreadyFulfilledException $e) {
113             // The action's results are already fulfilled. Maybe it was a
114             // duplicate? Maybe someone's database is out of sync?
115             // Let's just accept it and move on.
116             common_log(LOG_INFO, 'Salmon slap carried an event which had already been fulfilled.');
117             return true;
118         } catch (NoticeSaveException $e) {
119             common_debug('Notice::saveActivity did not save our '._ve($this->activity->verb).' activity, trying old-fashioned salmon saving.');
120         }
121
122         try {
123             if (Event::handle('StartHandleSalmonTarget', array($this->activity, $this->target)) &&
124                     Event::handle('StartHandleSalmon', array($this->activity))) {
125                 switch ($this->activity->verb) {
126                 case ActivityVerb::POST:
127                     $this->handlePost();
128                     break;
129                 case ActivityVerb::SHARE:
130                     $this->handleShare();
131                     break;
132                 case ActivityVerb::FOLLOW:
133                 case ActivityVerb::FRIEND:
134                     $this->handleFollow();
135                     break;
136                 case ActivityVerb::UNFOLLOW:
137                     $this->handleUnfollow();
138                     break;
139                 case ActivityVerb::JOIN:
140                     $this->handleJoin();
141                     break;
142                 case ActivityVerb::LEAVE:
143                     $this->handleLeave();
144                     break;
145                 case ActivityVerb::TAG:
146                     $this->handleTag();
147                     break;
148                 case ActivityVerb::UNTAG:
149                     $this->handleUntag();
150                     break;
151                 case ActivityVerb::UPDATE_PROFILE:
152                     $this->handleUpdateProfile();
153                     break;
154                 default:
155                     // TRANS: Client exception.
156                     throw new ClientException(_m('Unrecognized activity type.'));
157                 }
158                 Event::handle('EndHandleSalmon', array($this->activity));
159                 Event::handle('EndHandleSalmonTarget', array($this->activity, $this->target));
160             }
161         } catch (AlreadyFulfilledException $e) {
162             // The action's results are already fulfilled. Maybe it was a
163             // duplicate? Maybe someone's database is out of sync?
164             // Let's just accept it and move on.
165             common_log(LOG_INFO, 'Salmon slap carried an event which had already been fulfilled.');
166         }
167     }
168
169     function handlePost()
170     {
171         // TRANS: Client exception.
172         throw new ClientException(_m('This target does not understand posts.'));
173     }
174
175     function handleFollow()
176     {
177         // TRANS: Client exception.
178         throw new ClientException(_m('This target does not understand follows.'));
179     }
180
181     function handleUnfollow()
182     {
183         // TRANS: Client exception.
184         throw new ClientException(_m('This target does not understand unfollows.'));
185     }
186
187     function handleShare()
188     {
189         // TRANS: Client exception.
190         throw new ClientException(_m('This target does not understand share events.'));
191     }
192
193     function handleJoin()
194     {
195         // TRANS: Client exception.
196         throw new ClientException(_m('This target does not understand joins.'));
197     }
198
199     function handleLeave()
200     {
201         // TRANS: Client exception.
202         throw new ClientException(_m('This target does not understand leave events.'));
203     }
204
205     function handleTag()
206     {
207         // TRANS: Client exception.
208         throw new ClientException(_m('This target does not understand list events.'));
209     }
210
211     function handleUntag()
212     {
213         // TRANS: Client exception.
214         throw new ClientException(_m('This target does not understand unlist events.'));
215     }
216
217     /**
218      * Remote user sent us an update to their profile.
219      * If we already know them, accept the updates.
220      */
221     function handleUpdateProfile()
222     {
223         $oprofile = Ostatus_profile::getActorProfile($this->activity);
224         if ($oprofile instanceof Ostatus_profile) {
225             common_log(LOG_INFO, "Got a profile-update ping from $oprofile->uri");
226             $oprofile->updateFromActivityObject($this->activity->actor);
227         } else {
228             common_log(LOG_INFO, "Ignoring profile-update ping from unknown " . $this->activity->actor->id);
229         }
230     }
231
232     function ensureProfiles()
233     {
234         try {
235             $this->oprofile = Ostatus_profile::getActorProfile($this->activity);
236             if (!$this->oprofile instanceof Ostatus_profile) {
237                 throw new UnknownUriException($this->activity->actor->id);
238             }
239         } catch (UnknownUriException $e) {
240             // Apparently we didn't find the Profile object based on our URI,
241             // so OStatus doesn't have it with this URI in ostatus_profile.
242             // Try to look it up again, remote side may have changed from http to https
243             // or maybe publish an acct: URI now instead of an http: URL.
244             //
245             // Steps:
246             // 1. Check the newly received URI. Who does it say it is?
247             // 2. Compare these alleged identities to our local database.
248             // 3. If we found any locally stored identities, ask it about its aliases.
249             // 4. Do any of the aliases from our known identity match the recently introduced one?
250             //
251             // Example: We have stored http://example.com/user/1 but this URI says https://example.com/user/1
252             common_debug('No local Profile object found for a magicsigned activity author URI: '.$e->object_uri);
253             $disco = new Discovery();
254             $xrd = $disco->lookup($e->object_uri);
255             // Step 1: We got a bunch of discovery data for https://example.com/user/1 which includes
256             //         aliases https://example.com/user and hopefully our original http://example.com/user/1 too
257             $all_ids = array_merge(array($xrd->subject), $xrd->aliases);
258
259             if (!in_array($e->object_uri, $all_ids)) {
260                 common_debug('The activity author URI we got was not listed itself when doing discovery on it.');
261                 throw $e;
262             }
263
264             // Go through each reported alias from lookup to see if we know this already
265             foreach ($all_ids as $aliased_uri) {
266                 $oprofile = Ostatus_profile::getKV('uri', $aliased_uri);
267                 if (!$oprofile instanceof Ostatus_profile) {
268                     continue;   // unknown locally, check the next alias
269                 }
270                 // Step 2: We found the alleged http://example.com/user/1 URI in our local database,
271                 //         but this can't be trusted yet because anyone can publish any alias.
272                 common_debug('Found a local Ostatus_profile for "'.$e->object_uri.'" with this URI: '.$aliased_uri);
273
274                 // We found an existing OStatus profile, but is it really the same? Do a callback to the URI's origin
275                 // Step 3: lookup our previously known http://example.com/user/1 webfinger etc.
276                 $xrd = $disco->lookup($oprofile->getUri()); // getUri returns ->uri, which we filtered on earlier
277                 $doublecheck_aliases = array_merge(array($xrd->subject), $xrd->aliases);
278                 common_debug('Trying to match known "'.$aliased_uri.'" against its returned aliases: '.implode(' ', $doublecheck_aliases));
279                 // if we find our original URI here, it is a legitimate alias
280                 // Step 4: Is the newly introduced https://example.com/user/1 URI in the list of aliases
281                 //         presented by http://example.com/user/1 (i.e. do they both say they are the same identity?)
282                 if (in_array($e->object_uri, $doublecheck_aliases)) {
283                     $oprofile->updateUriKeys($e->object_uri, DiscoveryHints::fromXRD($xrd));
284                     $this->oprofile = $oprofile;
285                     break;  // don't iterate through aliases anymore
286                 }
287             }
288
289             // We might end up here after $all_ids is iterated through without a $this->oprofile value,
290             if (!$this->oprofile instanceof Ostatus_profile) {
291                 common_debug("We do not have a local profile to connect to this activity's author. Let's create one.");
292                 // ensureActivityObjectProfile throws exception on failure
293                 $this->oprofile = Ostatus_profile::ensureActivityObjectProfile($this->activity->actor);
294             }
295         }
296
297         assert($this->oprofile instanceof Ostatus_profile);
298
299         $this->actor = $this->oprofile->localProfile();
300     }
301
302     function saveNotice()
303     {
304         if (!$this->oprofile instanceof Ostatus_profile) {
305             common_debug('Ostatus_profile missing in ' . get_class(). ' profile: '.var_export($this->profile, true));
306         }
307         return $this->oprofile->processPost($this->activity, 'salmon');
308     }
309 }