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