salmonaction.php 13 KB

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