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