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