Activitypub_notice.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. <?php
  2. // This file is part of GNU social - https://www.gnu.org/software/social
  3. //
  4. // GNU social is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Affero General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // GNU social is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Affero General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Affero General Public License
  15. // along with GNU social. If not, see <http://www.gnu.org/licenses/>.
  16. /**
  17. * ActivityPub implementation for GNU social
  18. *
  19. * @package GNUsocial
  20. * @author Diogo Cordeiro <diogo@fc.up.pt>
  21. * @copyright 2018-2019 Free Software Foundation, Inc http://www.fsf.org
  22. * @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
  23. * @link http://www.gnu.org/software/social/
  24. */
  25. defined('GNUSOCIAL') || die();
  26. /**
  27. * ActivityPub notice representation
  28. *
  29. * @category Plugin
  30. * @package GNUsocial
  31. * @author Diogo Cordeiro <diogo@fc.up.pt>
  32. * @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
  33. */
  34. class Activitypub_notice
  35. {
  36. /**
  37. * Generates a pretty notice from a Notice object
  38. *
  39. * @param Notice $notice
  40. * @return array array to be used in a response
  41. * @throws EmptyPkeyValueException
  42. * @throws InvalidUrlException
  43. * @throws ServerException
  44. * @throws Exception
  45. * @author Diogo Cordeiro <diogo@fc.up.pt>
  46. */
  47. public static function notice_to_array($notice)
  48. {
  49. $profile = $notice->getProfile();
  50. $attachments = [];
  51. foreach ($notice->attachments() as $attachment) {
  52. $attachments[] = Activitypub_attachment::attachment_to_array($attachment);
  53. }
  54. $tags = [];
  55. foreach ($notice->getTags() as $tag) {
  56. if ($tag != "") { // Hacky workaround to avoid stupid outputs
  57. $tags[] = Activitypub_tag::tag_to_array($tag);
  58. }
  59. }
  60. if ($notice->isPublic()) {
  61. $to = ['https://www.w3.org/ns/activitystreams#Public'];
  62. $cc = [common_local_url('apActorFollowers', ['id' => $profile->getID()])];
  63. } else {
  64. // Since we currently don't support sending unlisted/followers-only
  65. // notices, arriving here means we're instead answering to that type
  66. // of posts. Not having subscription policy working, its safer to
  67. // always send answers of type unlisted.
  68. $to = [];
  69. $cc = ['https://www.w3.org/ns/activitystreams#Public'];
  70. }
  71. foreach ($notice->getAttentionProfiles() as $to_profile) {
  72. $to[] = $href = $to_profile->getUri();
  73. $tags[] = Activitypub_mention_tag::mention_tag_to_array_from_values($href, $to_profile->getNickname() . '@' . parse_url($href, PHP_URL_HOST));
  74. }
  75. $item = [
  76. '@context' => 'https://www.w3.org/ns/activitystreams',
  77. 'id' => self::getUrl($notice),
  78. 'type' => 'Note',
  79. 'published' => str_replace(' ', 'T', $notice->getCreated()) . 'Z',
  80. 'url' => self::getUrl($notice),
  81. 'attributedTo' => $profile->getUri(),
  82. 'to' => $to,
  83. 'cc' => $cc,
  84. 'conversation' => $notice->getConversationUrl(),
  85. 'content' => $notice->getRendered(),
  86. 'isLocal' => $notice->isLocal(),
  87. 'attachment' => $attachments,
  88. 'tag' => $tags
  89. ];
  90. // Is this a reply?
  91. if (!empty($notice->reply_to)) {
  92. $item['inReplyTo'] = self::getUrl(Notice::getById($notice->reply_to));
  93. }
  94. // Do we have a location for this notice?
  95. try {
  96. $location = Notice_location::locFromStored($notice);
  97. $item['latitude'] = $location->lat;
  98. $item['longitude'] = $location->lon;
  99. } catch (Exception $e) {
  100. // Apparently no.
  101. }
  102. return $item;
  103. }
  104. /**
  105. * Create a Notice via ActivityPub Note Object.
  106. * Returns created Notice.
  107. *
  108. * @param array $object
  109. * @param Profile $actor_profile
  110. * @param bool $directMessage
  111. * @return Notice
  112. * @throws Exception
  113. * @author Diogo Cordeiro <diogo@fc.up.pt>
  114. */
  115. public static function create_notice(array $object, Profile $actor_profile = null, bool $directMessage = false): Notice
  116. {
  117. $id = $object['id']; // int
  118. $url = isset($object['url']) ? $object['url'] : $id; // string
  119. $content = $object['content']; // string
  120. // possible keys: ['inReplyTo', 'latitude', 'longitude']
  121. $settings = [];
  122. if (isset($object['inReplyTo'])) {
  123. $settings['inReplyTo'] = $object['inReplyTo'];
  124. }
  125. if (isset($object['latitude'])) {
  126. $settings['latitude'] = $object['latitude'];
  127. }
  128. if (isset($object['longitude'])) {
  129. $settings['longitude'] = $object['longitude'];
  130. }
  131. // Ensure Actor Profile
  132. if (is_null($actor_profile)) {
  133. if (isset($object['attributedTo'])) {
  134. $actor_profile = ActivityPub_explorer::get_profile_from_url($object['attributedTo']);
  135. } elseif (isset($object['actor'])) {
  136. $actor_profile = ActivityPub_explorer::get_profile_from_url($object['actor']);
  137. } else {
  138. throw new Exception("A notice can't be created without an actor.");
  139. }
  140. }
  141. $act = new Activity();
  142. $act->verb = ActivityVerb::POST;
  143. $act->time = time();
  144. $act->actor = $actor_profile->asActivityObject();
  145. $act->context = new ActivityContext();
  146. $options = ['source' => 'ActivityPub',
  147. 'uri' => $id,
  148. 'url' => $url,
  149. 'is_local' => self::getNotePolicyType($object, $actor_profile)];
  150. if ($directMessage) {
  151. $options['scope'] = Notice::MESSAGE_SCOPE;
  152. }
  153. // Is this a reply?
  154. if (isset($settings['inReplyTo'])) {
  155. try {
  156. $inReplyTo = ActivityPubPlugin::grab_notice_from_url($settings['inReplyTo']);
  157. $act->context->replyToID = $inReplyTo->getUri();
  158. $act->context->replyToUrl = $inReplyTo->getUrl();
  159. } catch (Exception $e) {
  160. // It failed to grab, maybe we got this note from another source
  161. // (e.g.: OStatus) that handles this differently or we really
  162. // failed to get it...
  163. // Welp, nothing that we can do about, let's
  164. // just fake we don't have such notice.
  165. }
  166. } else {
  167. $inReplyTo = null;
  168. }
  169. // Mentions
  170. $mentions = [];
  171. if (isset($object['tag']) && is_array($object['tag'])) {
  172. foreach ($object['tag'] as $tag) {
  173. if ($tag['type'] == 'Mention') {
  174. $mentions[] = $tag['href'];
  175. }
  176. }
  177. }
  178. $mentions_profiles = [];
  179. $discovery = new Activitypub_explorer;
  180. foreach ($mentions as $mention) {
  181. try {
  182. $mentions_profiles[] = $discovery->lookup($mention)[0];
  183. } catch (Exception $e) {
  184. // Invalid actor found, just let it go. // TODO: Fallback to OStatus
  185. }
  186. }
  187. unset($discovery);
  188. foreach ($mentions_profiles as $mp) {
  189. if (!$mp->hasBlocked($actor_profile)) {
  190. $act->context->attention[$mp->getUri()] = 'http://activitystrea.ms/schema/1.0/person';
  191. }
  192. }
  193. // Add location if that is set
  194. if (isset($settings['latitude'], $settings['longitude'])) {
  195. $act->context->location = Location::fromLatLon($settings['latitude'], $settings['longitude']);
  196. }
  197. /* Reject notice if it is too long (without the HTML)
  198. if (Notice::contentTooLong($content)) {
  199. throw new Exception('That\'s too long. Maximum notice size is %d character.');
  200. }*/
  201. $actobj = new ActivityObject();
  202. $actobj->type = ActivityObject::NOTE;
  203. $actobj->content = strip_tags($content, '<p><b><i><u><a><ul><ol><li>');
  204. // Finally add the activity object to our activity
  205. $act->objects[] = $actobj;
  206. $note = Notice::saveActivity($act, $actor_profile, $options);
  207. return $note;
  208. }
  209. /**
  210. * Validates a note.
  211. *
  212. * @param array $object
  213. * @return bool false if unacceptable for GS but valid ActivityPub object
  214. * @throws Exception if invalid ActivityPub object
  215. * @author Diogo Cordeiro <diogo@fc.up.pt>
  216. */
  217. public static function validate_note($object)
  218. {
  219. if (!isset($object['id'])) {
  220. common_debug('ActivityPub Notice Validator: Rejected because Object ID was not specified.');
  221. throw new Exception('Object ID not specified.');
  222. } elseif (!filter_var($object['id'], FILTER_VALIDATE_URL)) {
  223. common_debug('ActivityPub Notice Validator: Rejected because Object ID is invalid.');
  224. throw new Exception('Invalid Object ID.');
  225. }
  226. if (!isset($object['type']) || $object['type'] !== 'Note') {
  227. common_debug('ActivityPub Notice Validator: Rejected because of Type.');
  228. throw new Exception('Invalid Object type.');
  229. }
  230. if (isset($object['url']) && !filter_var($object['url'], FILTER_VALIDATE_URL)) {
  231. common_debug('ActivityPub Notice Validator: Rejected because Object URL is invalid.');
  232. throw new Exception('Invalid Object URL.');
  233. }
  234. if (!(isset($object['to']) && isset($object['cc']))) {
  235. common_debug('ActivityPub Notice Validator: Rejected because either Object CC or TO wasn\'t specified.');
  236. throw new Exception('Either Object CC or TO wasn\'t specified.');
  237. }
  238. if (!isset($object['content'])) {
  239. common_debug('ActivityPub Notice Validator: Rejected because Content was not specified (GNU social requires content in notes).');
  240. return false;
  241. }
  242. return true;
  243. }
  244. /**
  245. * Get the original representation URL of a given notice.
  246. *
  247. * @param Notice $notice notice from which to retrieve the URL
  248. * @return string URL
  249. * @throws InvalidUrlException
  250. * @throws Exception
  251. * @author Bruno Casteleiro <brunoccast@fc.up.pt>
  252. */
  253. public static function getUrl(Notice $notice): string
  254. {
  255. if ($notice->isLocal()) {
  256. return common_local_url('apNotice', ['id' => $notice->getID()]);
  257. } else {
  258. return $notice->getUrl();
  259. }
  260. }
  261. /**
  262. * Extract note policy type from note targets.
  263. *
  264. * @param array $note received Note
  265. * @param Profile $actor_profile Note author
  266. * @return int Notice policy type
  267. * @author Bruno Casteleiro <brunoccast@fc.up.pt>
  268. */
  269. public static function getNotePolicyType(array $note, Profile $actor_profile): int
  270. {
  271. if (in_array('https://www.w3.org/ns/activitystreams#Public', $note['to'])) {
  272. return $actor_profile->isLocal() ? Notice::LOCAL_PUBLIC : Notice::REMOTE;
  273. } else {
  274. // either an unlisted or followers-only note, we'll handle
  275. // both as a GATEWAY notice since this type is not visible
  276. // from the public timelines, hence partially enough while
  277. // we don't have subscription_policy working.
  278. return Notice::GATEWAY;
  279. }
  280. }
  281. }