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