salmonaction.php 13 KB

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