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