SharePlugin.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. <?php
  2. /*
  3. * GNU Social - a federating social network
  4. * Copyright (C) 2014, Free Software Foundation, 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. if (!defined('GNUSOCIAL')) { exit(1); }
  20. /**
  21. * @package Activity
  22. * @maintainer Mikael Nordfeldth <mmn@hethane.se>
  23. */
  24. class SharePlugin extends ActivityVerbHandlerPlugin
  25. {
  26. const PLUGIN_VERSION = '2.0.0';
  27. public function tag()
  28. {
  29. return 'share';
  30. }
  31. public function types()
  32. {
  33. return array();
  34. }
  35. public function verbs()
  36. {
  37. return array(ActivityVerb::SHARE);
  38. }
  39. // Share is a bit special and $act->objects[0] should be an Activity
  40. // instead of ActivityObject! Therefore also $act->objects[0]->type is not set.
  41. public function isMyActivity(Activity $act) {
  42. return (count($act->objects) == 1
  43. && ($act->objects[0] instanceof Activity)
  44. && $this->isMyVerb($act->verb));
  45. }
  46. public function onRouterInitialized(URLMapper $m)
  47. {
  48. // Web UI actions
  49. $m->connect('main/repeat', ['action' => 'repeat']);
  50. // Share for Twitter API ("Retweet")
  51. $m->connect('api/statuses/retweeted_by_me.:format',
  52. ['action' => 'ApiTimelineRetweetedByMe'],
  53. ['format' => '(xml|json|atom|as)']);
  54. $m->connect('api/statuses/retweeted_to_me.:format',
  55. ['action' => 'ApiTimelineRetweetedToMe'],
  56. ['format' => '(xml|json|atom|as)']);
  57. $m->connect('api/statuses/retweets_of_me.:format',
  58. ['action' => 'ApiTimelineRetweetsOfMe'],
  59. ['format' => '(xml|json|atom|as)']);
  60. $m->connect('api/statuses/retweet/:id.:format',
  61. ['action' => 'ApiStatusesRetweet'],
  62. ['id' => '[0-9]+',
  63. 'format' => '(xml|json)']);
  64. $m->connect('api/statuses/retweets/:id.:format',
  65. ['action' => 'ApiStatusesRetweets'],
  66. ['id' => '[0-9]+',
  67. 'format' => '(xml|json)']);
  68. }
  69. // FIXME: Set this to abstract public in lib/activityhandlerplugin.php when all plugins have migrated!
  70. protected function saveObjectFromActivity(Activity $act, Notice $stored, array $options=array())
  71. {
  72. assert($this->isMyActivity($act));
  73. // The below algorithm is mainly copied from the previous Ostatus_profile->processShare()
  74. if (count($act->objects) !== 1) {
  75. // TRANS: Client exception thrown when trying to share multiple activities at once.
  76. throw new ClientException(_m('Can only handle share activities with exactly one object.'));
  77. }
  78. $shared = $act->objects[0];
  79. if (!$shared instanceof Activity) {
  80. // TRANS: Client exception thrown when trying to share a non-activity object.
  81. throw new ClientException(_m('Can only handle shared activities.'));
  82. }
  83. $sharedUri = $shared->id;
  84. if (!empty($shared->objects[0]->id)) {
  85. // Because StatusNet since commit 8cc4660 sets $shared->id to a TagURI which
  86. // fucks up federation, because the URI is no longer recognised by the origin.
  87. // So we set it to the object ID if it exists, otherwise we trust $shared->id
  88. $sharedUri = $shared->objects[0]->id;
  89. }
  90. if (empty($sharedUri)) {
  91. throw new ClientException(_m('Shared activity does not have an id'));
  92. }
  93. try {
  94. // First check if we have the shared activity. This has to be done first, because
  95. // we can't use these functions to "ensureActivityObjectProfile" of a local user,
  96. // who might be the creator of the shared activity in question.
  97. $sharedNotice = Notice::getByUri($sharedUri);
  98. } catch (NoResultException $e) {
  99. // If no locally stored notice is found, process it!
  100. // TODO: Remember to check Deleted_notice!
  101. // TODO: If a post is shared that we can't retrieve - what to do?
  102. $other = Ostatus_profile::ensureActivityObjectProfile($shared->actor);
  103. $sharedNotice = Notice::saveActivity($shared, $other->localProfile(), array('source'=>'share'));
  104. } catch (FeedSubException $e) {
  105. // Remote feed could not be found or verified, should we
  106. // transform this into an "RT @user Blah, blah, blah..."?
  107. common_log(LOG_INFO, __METHOD__ . ' got a ' . get_class($e) . ': ' . $e->getMessage());
  108. return false;
  109. }
  110. // Setting this here because when the algorithm gets back to
  111. // Notice::saveActivity it will update the Notice object.
  112. $stored->repeat_of = $sharedNotice->getID();
  113. $stored->conversation = $sharedNotice->conversation;
  114. // We don't have to save a repeat in a separate table, we can
  115. // find repeats by just looking at the notice.repeat_of field.
  116. // By returning true here instead of something that evaluates
  117. // to false, we show that we have processed everything properly.
  118. return true;
  119. }
  120. // FIXME: Put this in lib/activityhandlerplugin.php when we're ready
  121. // with the other microapps/activityhandlers as well.
  122. // Also it should be StartNoticeAsActivity (with a prepped Activity, including ->context etc.)
  123. public function onEndNoticeAsActivity(Notice $stored, Activity $act, Profile $scoped=null)
  124. {
  125. if (!$this->isMyNotice($stored)) {
  126. return true;
  127. }
  128. $this->extendActivity($stored, $act, $scoped);
  129. return false;
  130. }
  131. public function extendActivity(Notice $stored, Activity $act, Profile $scoped=null)
  132. {
  133. // TODO: How to handle repeats of deleted notices?
  134. $target = Notice::getByID($stored->repeat_of);
  135. // TRANS: A repeat activity's title. %1$s is repeater's nickname
  136. // and %2$s is the repeated user's nickname.
  137. $act->title = sprintf(_('%1$s repeated a notice by %2$s'),
  138. $stored->getProfile()->getNickname(),
  139. $target->getProfile()->getNickname());
  140. $act->objects[] = $target->asActivity($scoped);
  141. }
  142. public function activityObjectFromNotice(Notice $stored)
  143. {
  144. // Repeat is a little bit special. As it's an activity, our
  145. // ActivityObject is instead turned into an Activity
  146. $object = new Activity();
  147. $object->actor = $stored->getProfile()->asActivityObject();
  148. $object->verb = ActivityVerb::SHARE;
  149. $object->content = $stored->getRendered();
  150. $this->extendActivity($stored, $object);
  151. return $object;
  152. }
  153. public function deleteRelated(Notice $notice)
  154. {
  155. // No action needed as we don't have a separate table for share objects.
  156. return true;
  157. }
  158. // Layout stuff
  159. /**
  160. * show a link to the author of repeat
  161. *
  162. * FIXME: Some repeat stuff still in lib/noticelistitem.php! ($nli->repeat etc.)
  163. */
  164. public function onEndShowNoticeInfo(NoticeListItem $nli)
  165. {
  166. if (!empty($nli->repeat)) {
  167. $repeater = $nli->repeat->getProfile();
  168. $attrs = array('href' => $repeater->getUrl(),
  169. 'class' => 'h-card p-author',
  170. 'title' => $repeater->getFancyName());
  171. $nli->out->elementStart('span', 'repeat');
  172. // TRANS: Addition in notice list item if notice was repeated. Followed by a span with a nickname.
  173. $nli->out->raw(_('Repeated by').' ');
  174. $nli->out->element('a', $attrs, $repeater->getNickname());
  175. $nli->out->elementEnd('span');
  176. }
  177. }
  178. public function onEndShowThreadedNoticeTailItems(NoticeListItem $nli, Notice $notice, &$threadActive)
  179. {
  180. if ($nli instanceof ThreadedNoticeListSubItem) {
  181. // The sub-items are replies to a conversation, thus we use different HTML elements etc.
  182. $item = new ThreadedNoticeListInlineRepeatsItem($notice, $nli->out);
  183. } else {
  184. $item = new ThreadedNoticeListRepeatsItem($notice, $nli->out);
  185. }
  186. $threadActive = $item->show() || $threadActive;
  187. return true;
  188. }
  189. /**
  190. * show the "repeat" form in the notice options element
  191. * FIXME: Don't let a NoticeListItemAdapter slip in here (or extend that from NoticeListItem)
  192. *
  193. * @return void
  194. */
  195. public function onEndShowNoticeOptionItems($nli)
  196. {
  197. // FIXME: Use bitmasks (but be aware that PUBLIC_SCOPE is 0!)
  198. // Also: AHHH, $scope and $scoped are scarily similar looking.
  199. $scope = $nli->notice->getScope();
  200. if ($scope === Notice::PUBLIC_SCOPE || $scope === Notice::SITE_SCOPE) {
  201. $scoped = Profile::current();
  202. if ($scoped instanceof Profile &&
  203. $scoped->getID() !== $nli->notice->getProfile()->getID()) {
  204. if ($scoped->hasRepeated($nli->notice)) {
  205. $nli->out->element('span', array('class' => 'repeated',
  206. // TRANS: Title for repeat form status in notice list when a notice has been repeated.
  207. 'title' => _('Notice repeated.')),
  208. // TRANS: Repeat form status in notice list when a notice has been repeated.
  209. _('Repeated'));
  210. } else {
  211. $repeat = new RepeatForm($nli->out, $nli->notice);
  212. $repeat->show();
  213. }
  214. }
  215. }
  216. }
  217. protected function showNoticeListItem(NoticeListItem $nli)
  218. {
  219. // pass
  220. }
  221. public function openNoticeListItemElement(NoticeListItem $nli)
  222. {
  223. // pass
  224. }
  225. public function closeNoticeListItemElement(NoticeListItem $nli)
  226. {
  227. // pass
  228. }
  229. // API stuff
  230. /**
  231. * Typically just used to fill out Twitter-compatible API status data.
  232. *
  233. * FIXME: Make all the calls before this end up with a Notice instead of ArrayWrapper please...
  234. */
  235. public function onNoticeSimpleStatusArray($notice, array &$status, Profile $scoped=null, array $args=array())
  236. {
  237. $status['repeated'] = $scoped instanceof Profile
  238. ? $scoped->hasRepeated($notice)
  239. : false;
  240. if ($status['repeated'] === true) {
  241. // Qvitter API wants the "repeated_id" value set too.
  242. $repeated = Notice::pkeyGet(array('profile_id' => $scoped->getID(),
  243. 'repeat_of' => $notice->getID(),
  244. 'verb' => ActivityVerb::SHARE));
  245. $status['repeated_id'] = $repeated->getID();
  246. }
  247. }
  248. public function onTwitterUserArray(Profile $profile, array &$userdata, Profile $scoped=null, array $args=array())
  249. {
  250. $userdata['favourites_count'] = Fave::countByProfile($profile);
  251. }
  252. // Command stuff
  253. /**
  254. * EndInterpretCommand for RepeatPlugin will handle the 'repeat' command
  255. * using the class RepeatCommand.
  256. *
  257. * @param string $cmd Command being run
  258. * @param string $arg Rest of the message (including address)
  259. * @param User $user User sending the message
  260. * @param Command &$result The resulting command object to be run.
  261. *
  262. * @return boolean hook value
  263. */
  264. public function onStartInterpretCommand($cmd, $arg, $user, &$result)
  265. {
  266. if ($result === false && in_array($cmd, array('repeat', 'rp', 'rt', 'rd'))) {
  267. if (empty($arg)) {
  268. $result = null;
  269. } else {
  270. list($other, $extra) = CommandInterpreter::split_arg($arg);
  271. if (!empty($extra)) {
  272. $result = null;
  273. } else {
  274. $result = new RepeatCommand($user, $other);
  275. }
  276. }
  277. return false;
  278. }
  279. return true;
  280. }
  281. public function onHelpCommandMessages(HelpCommand $help, array &$commands)
  282. {
  283. // TRANS: Help message for IM/SMS command "repeat #<notice_id>".
  284. $commands['repeat #<notice_id>'] = _m('COMMANDHELP', "repeat a notice with a given id");
  285. // TRANS: Help message for IM/SMS command "repeat <nickname>".
  286. $commands['repeat <nickname>'] = _m('COMMANDHELP', "repeat the last notice from user");
  287. }
  288. /**
  289. * Are we allowed to perform a certain command over the API?
  290. */
  291. public function onCommandSupportedAPI(Command $cmd, &$supported)
  292. {
  293. $supported = $supported || $cmd instanceof RepeatCommand;
  294. }
  295. protected function getActionTitle(ManagedAction $action, $verb, Notice $target, Profile $scoped)
  296. {
  297. // return page title
  298. }
  299. protected function doActionPreparation(ManagedAction $action, $verb, Notice $target, Profile $scoped)
  300. {
  301. // prepare Action?
  302. }
  303. protected function doActionPost(ManagedAction $action, $verb, Notice $target, Profile $scoped)
  304. {
  305. // handle repeat POST
  306. }
  307. protected function getActivityForm(ManagedAction $action, $verb, Notice $target, Profile $scoped)
  308. {
  309. return new RepeatForm($action, $target);
  310. }
  311. public function onPluginVersion(array &$versions)
  312. {
  313. $versions[] = array('name' => 'Share verb',
  314. 'version' => self::PLUGIN_VERSION,
  315. 'author' => 'Mikael Nordfeldth',
  316. 'homepage' => 'https://gnu.io/',
  317. 'rawdescription' =>
  318. // TRANS: Plugin description.
  319. _m('Shares (repeats) using ActivityStreams.'));
  320. return true;
  321. }
  322. }