ActivityHandlerModule.php 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672
  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. * @package GNUsocial
  18. * @author Mikael Nordfeldth <mmn@hethane.se>
  19. * @copyright 2014 Free Software Foundation, Inc http://www.fsf.org
  20. * @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
  21. */
  22. defined('GNUSOCIAL') || die();
  23. /**
  24. * Superclass for plugins which add Activity types and such
  25. *
  26. * @category Activity
  27. * @package GNUsocial
  28. * @author Mikael Nordfeldth <mmn@hethane.se>
  29. * @copyright 2014 Free Software Foundation, Inc http://www.fsf.org
  30. * @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
  31. */
  32. abstract class ActivityHandlerModule extends Module
  33. {
  34. /**
  35. * Returns a key string which represents this activity in HTML classes,
  36. * ids etc, as when offering selection of what type of post to make.
  37. * In MicroAppPlugin, this is paired with the user-visible localizable appTitle().
  38. *
  39. * @return string (compatible with HTML classes)
  40. */
  41. abstract public function tag();
  42. /**
  43. * Return a list of ActivityStreams object type IRIs
  44. * which this micro-app handles. Default implementations
  45. * of the base class will use this list to check if a
  46. * given ActivityStreams object belongs to us, via
  47. * $this->isMyNotice() or $this->isMyActivity.
  48. *
  49. * An empty list means any type is ok. (Favorite verb etc.)
  50. *
  51. * @return array of strings
  52. */
  53. abstract public function types();
  54. /**
  55. * Return a list of ActivityStreams verb IRIs which
  56. * this micro-app handles. Default implementations
  57. * of the base class will use this list to check if a
  58. * given ActivityStreams verb belongs to us, via
  59. * $this->isMyNotice() or $this->isMyActivity.
  60. *
  61. * All micro-app classes must override this method.
  62. *
  63. * @return array of strings
  64. */
  65. public function verbs()
  66. {
  67. return array(ActivityVerb::POST);
  68. }
  69. /**
  70. * Check if a given ActivityStreams activity should be handled by this
  71. * micro-app plugin.
  72. *
  73. * The default implementation checks against the activity type list
  74. * returned by $this->types(), and requires that exactly one matching
  75. * object be present. You can override this method to expand
  76. * your checks or to compare the activity's verb, etc.
  77. *
  78. * @param Activity $activity
  79. * @return boolean
  80. */
  81. public function isMyActivity(Activity $act)
  82. {
  83. return (count($act->objects) == 1
  84. && ($act->objects[0] instanceof ActivityObject)
  85. && $this->isMyVerb($act->verb)
  86. && $this->isMyType($act->objects[0]->type));
  87. }
  88. /**
  89. * Check if a given notice object should be handled by this micro-app
  90. * plugin.
  91. *
  92. * The default implementation checks against the activity type list
  93. * returned by $this->types(). You can override this method to expand
  94. * your checks, but follow the execution chain to get it right.
  95. *
  96. * @param Notice $notice
  97. * @return boolean
  98. */
  99. public function isMyNotice(Notice $notice)
  100. {
  101. return $this->isMyVerb($notice->verb) && $this->isMyType($notice->object_type);
  102. }
  103. public function isMyVerb($verb)
  104. {
  105. $verb = $verb ?: ActivityVerb::POST; // post is the default verb
  106. return ActivityUtils::compareVerbs($verb, $this->verbs());
  107. }
  108. public function isMyType($type)
  109. {
  110. // Third argument to compareTypes is true, to allow for notices with empty object_type for example (verb-only)
  111. return count($this->types()) === 0 || ActivityUtils::compareTypes($type, $this->types());
  112. }
  113. /**
  114. * Given a parsed ActivityStreams activity, your plugin
  115. * gets to figure out how to actually save it into a notice
  116. * and any additional data structures you require.
  117. *
  118. * This function is deprecated and in the future, Notice::saveActivity
  119. * should be called from onStartHandleFeedEntryWithProfile in this class
  120. * (which instead turns to saveObjectFromActivity).
  121. *
  122. * @param Activity $activity
  123. * @param Profile $actor
  124. * @param array $options = []
  125. *
  126. * @return Notice the resulting notice
  127. */
  128. public function saveNoticeFromActivity(Activity $activity, Profile $actor, array $options = [])
  129. {
  130. // Any plugin which has not implemented saveObjectFromActivity _must_
  131. // override this function until they are migrated (this function will
  132. // be deleted when all plugins are migrated to saveObjectFromActivity).
  133. if (isset($this->oldSaveNew)) {
  134. throw new ServerException('A function has been called for new saveActivity functionality, but is still set with an oldSaveNew configuration');
  135. }
  136. return Notice::saveActivity($activity, $actor, $options);
  137. }
  138. /**
  139. * Given a parsed ActivityStreams activity, your plugin gets
  140. * to figure out itself how to store the additional data into
  141. * the database, besides the base data stored by the core.
  142. *
  143. * This will handle just about all events where an activity
  144. * object gets saved, whether it is via AtomPub, OStatus
  145. * (WebSub and Salmon transports), or ActivityStreams-based
  146. * backup/restore of account data.
  147. *
  148. * You should be able to accept as input the output from an
  149. * asActivity() call on the stored object. Where applicable,
  150. * try to use existing ActivityStreams structures and object
  151. * types, and be liberal in accepting input from what might
  152. * be other compatible apps.
  153. *
  154. * All micro-app classes must override this method.
  155. *
  156. * @fixme are there any standard options?
  157. *
  158. * @param Activity $activity
  159. * @param Notice $stored The notice in our database for this certain object
  160. * @param array $options = []
  161. *
  162. * @return object If the verb handling plugin creates an object, it can be returned here (otherwise true)
  163. * @throws exception On any error.
  164. */
  165. protected function saveObjectFromActivity(Activity $activity, Notice $stored, array $options = [])
  166. {
  167. throw new ServerException('This function should be abstract when all plugins have migrated to saveObjectFromActivity');
  168. }
  169. /*
  170. * This usually gets called from Notice::saveActivity after a Notice object has been created,
  171. * so it contains a proper id and a uri for the object to be saved.
  172. */
  173. public function onStoreActivityObject(Activity $act, Notice $stored, array $options, &$object)
  174. {
  175. // $this->oldSaveNew is there during a migration period of plugins, to start using
  176. // Notice::saveActivity instead of Notice::saveNew
  177. if (!$this->isMyActivity($act) || isset($this->oldSaveNew)) {
  178. return true;
  179. }
  180. $object = $this->saveObjectFromActivity($act, $stored, $options);
  181. return false;
  182. }
  183. /**
  184. * Given an existing Notice object, your plugin gets to
  185. * figure out how to arrange it into an ActivityStreams
  186. * object.
  187. *
  188. * This will be how your specialized notice gets output in
  189. * Atom feeds and JSON-based ActivityStreams output, including
  190. * account backup/restore and OStatus (WebSub and Salmon transports).
  191. *
  192. * You should be able to round-trip data from this format back
  193. * through $this->saveNoticeFromActivity(). Where applicable, try
  194. * to use existing ActivityStreams structures and object types,
  195. * and consider interop with other compatible apps.
  196. *
  197. * All micro-app classes must override this method.
  198. *
  199. * @fixme this outputs an ActivityObject, not an Activity. Any compat issues?
  200. *
  201. * @param Notice $notice
  202. *
  203. * @return ActivityObject
  204. */
  205. abstract public function activityObjectFromNotice(Notice $notice);
  206. /**
  207. * When a notice is deleted, you'll be called here for a chance
  208. * to clean up any related resources.
  209. *
  210. * All micro-app classes must override this method.
  211. *
  212. * @param Notice $notice
  213. */
  214. abstract public function deleteRelated(Notice $notice);
  215. protected function notifyMentioned(Notice $stored, array &$mentioned_ids)
  216. {
  217. // pass through silently by default
  218. // If we want to stop any other plugin from notifying based on this activity, return false instead.
  219. return true;
  220. }
  221. /**
  222. * Called when generating Atom XML ActivityStreams output from an
  223. * ActivityObject belonging to this plugin. Gives the plugin
  224. * a chance to add custom output.
  225. *
  226. * Note that you can only add output of additional XML elements,
  227. * not change existing stuff here.
  228. *
  229. * If output is already handled by the base Activity classes,
  230. * you can leave this base implementation as a no-op.
  231. *
  232. * @param ActivityObject $obj
  233. * @param XMLOutputter $out to add elements at end of object
  234. */
  235. public function activityObjectOutputAtom(ActivityObject $obj, XMLOutputter $out)
  236. {
  237. // default is a no-op
  238. }
  239. /**
  240. * Called when generating JSON ActivityStreams output from an
  241. * ActivityObject belonging to this plugin. Gives the plugin
  242. * a chance to add custom output.
  243. *
  244. * Modify the array contents to your heart's content, and it'll
  245. * all get serialized out as JSON.
  246. *
  247. * If output is already handled by the base Activity classes,
  248. * you can leave this base implementation as a no-op.
  249. *
  250. * @param ActivityObject $obj
  251. * @param array &$out JSON-targeted array which can be modified
  252. */
  253. public function activityObjectOutputJson(ActivityObject $obj, array &$out)
  254. {
  255. // default is a no-op
  256. }
  257. /**
  258. * When a notice is deleted, delete the related objects
  259. * by calling the overridable $this->deleteRelated().
  260. *
  261. * @param Notice $notice Notice being deleted
  262. *
  263. * @return boolean hook value
  264. */
  265. public function onNoticeDeleteRelated(Notice $notice)
  266. {
  267. if ($this->isMyNotice($notice)) {
  268. try {
  269. $this->deleteRelated($notice);
  270. } catch (NoProfileException $e) {
  271. // we failed because of database lookup failure, Notice has no recognized profile as creator
  272. // so we skip this. If we want to remove missing notices we should do a SQL constraints check
  273. // in the affected plugin.
  274. } catch (AlreadyFulfilledException $e) {
  275. // Nothing to see here, it's obviously already gone...
  276. }
  277. }
  278. // Always continue this event in our activity handling plugins.
  279. return true;
  280. }
  281. /**
  282. * @param Notice $stored The notice being distributed
  283. * @param array &$mentioned_ids List of profiles (from $stored->getReplies())
  284. */
  285. public function onStartNotifyMentioned(Notice $stored, array &$mentioned_ids)
  286. {
  287. if (!$this->isMyNotice($stored)) {
  288. return true;
  289. }
  290. return $this->notifyMentioned($stored, $mentioned_ids);
  291. }
  292. /**
  293. * Render a notice as one of our objects
  294. *
  295. * @param Notice $notice Notice to render
  296. * @param ActivityObject &$object Empty object to fill
  297. *
  298. * @return boolean hook value
  299. */
  300. public function onStartActivityObjectFromNotice(Notice $notice, &$object)
  301. {
  302. if (!$this->isMyNotice($notice)) {
  303. return true;
  304. }
  305. $object = $this->activityObjectFromNotice($notice);
  306. return false;
  307. }
  308. /**
  309. * Handle a posted object from WebSub
  310. *
  311. * @param Activity $activity activity to handle
  312. * @param Profile $actor Profile for the feed
  313. *
  314. * @return boolean hook value
  315. */
  316. public function onStartHandleFeedEntryWithProfile(Activity $activity, Profile $profile, &$notice)
  317. {
  318. if (!$this->isMyActivity($activity)) {
  319. return true;
  320. }
  321. // We are guaranteed to get a Profile back from checkAuthorship (or it throws an exception)
  322. $profile = ActivityUtils::checkAuthorship($activity, $profile);
  323. $object = $activity->objects[0];
  324. $options = [
  325. 'uri' => $object->id,
  326. 'url' => $object->link,
  327. 'self' => $object->selfLink,
  328. 'is_local' => Notice::REMOTE,
  329. 'source' => 'ostatus',
  330. ];
  331. if (!isset($this->oldSaveNew)) {
  332. $notice = Notice::saveActivity($activity, $profile, $options);
  333. } else {
  334. $notice = $this->saveNoticeFromActivity($activity, $profile, $options);
  335. }
  336. return false;
  337. }
  338. /**
  339. * Handle a posted object from Salmon
  340. *
  341. * @param Activity $activity activity to handle
  342. * @param mixed $target user or group targeted
  343. *
  344. * @return boolean hook value
  345. */
  346. public function onStartHandleSalmonTarget(Activity $activity, $target)
  347. {
  348. if (!$this->isMyActivity($activity)) {
  349. return true;
  350. }
  351. if (!isset($this->oldSaveNew)) {
  352. // Handle saveActivity in OStatus class for incoming salmon, remove this event
  353. // handler when all plugins have gotten rid of "oldSaveNew".
  354. return true;
  355. }
  356. $this->log(LOG_INFO, get_called_class() . " checking {$activity->id} as a valid Salmon slap.");
  357. if ($target instanceof User_group || $target->isGroup()) {
  358. $uri = $target->getUri();
  359. if (!array_key_exists($uri, $activity->context->attention)) {
  360. // @todo FIXME: please document (i18n).
  361. // TRANS: Client exception thrown when ...
  362. throw new ClientException(_('Object not posted to this group.'));
  363. }
  364. } elseif ($target instanceof Profile && $target->isLocal()) {
  365. $original = null;
  366. // FIXME: Shouldn't favorites show up with a 'target' activityobject?
  367. if (!ActivityUtils::compareVerbs($activity->verb, array(ActivityVerb::POST)) && isset($activity->objects[0])) {
  368. // If this is not a post, it's a verb targeted at something (such as a Favorite attached to a note)
  369. if (!empty($activity->objects[0]->id)) {
  370. $activity->context->replyToID = $activity->objects[0]->id;
  371. }
  372. }
  373. if (!empty($activity->context->replyToID)) {
  374. $original = Notice::getKV('uri', $activity->context->replyToID);
  375. }
  376. if ((!$original instanceof Notice || $original->profile_id != $target->id)
  377. && !array_key_exists($target->getUri(), $activity->context->attention)) {
  378. // @todo FIXME: Please document (i18n).
  379. // TRANS: Client exception when ...
  380. throw new ClientException(_('Object not posted to this user.'));
  381. }
  382. } else {
  383. // TRANS: Server exception thrown when a micro app plugin uses a target that cannot be handled.
  384. throw new ServerException(_('Do not know how to handle this kind of target.'));
  385. }
  386. $oactor = Ostatus_profile::ensureActivityObjectProfile($activity->actor);
  387. $actor = $oactor->localProfile();
  388. // FIXME: will this work in all cases? I made it work for Favorite...
  389. if (ActivityUtils::compareVerbs($activity->verb, array(ActivityVerb::POST))) {
  390. $object = $activity->objects[0];
  391. } else {
  392. $object = $activity;
  393. }
  394. $options = [
  395. 'uri' => $object->id,
  396. 'url' => $object->link,
  397. 'self' => $object->selfLink,
  398. 'is_local' => Notice::REMOTE,
  399. 'source' => 'ostatus',
  400. ];
  401. $notice = $this->saveNoticeFromActivity($activity, $actor, $options);
  402. return false;
  403. }
  404. /**
  405. * Handle object posted via AtomPub
  406. *
  407. * @param Activity $activity Activity that was posted
  408. * @param Profile $scoped Profile of user posting
  409. * @param Notice &$notice Resulting notice
  410. *
  411. * @return boolean hook value
  412. */
  413. public function onStartAtomPubNewActivity(Activity $activity, Profile $scoped, Notice &$notice = null)
  414. {
  415. if (!$this->isMyActivity($activity)) {
  416. return true;
  417. }
  418. $options = array('source' => 'atompub');
  419. $notice = $this->saveNoticeFromActivity($activity, $scoped, $options);
  420. return false;
  421. }
  422. /**
  423. * Handle object imported from a backup file
  424. *
  425. * @param User $user User to import for
  426. * @param ActivityObject $author Original author per import file
  427. * @param Activity $activity Activity to import
  428. * @param boolean $trusted Is this a trusted user?
  429. * @param boolean &$done Is this done (success or unrecoverable error)
  430. *
  431. * @return boolean hook value
  432. */
  433. public function onStartImportActivity($user, $author, Activity $activity, $trusted, &$done)
  434. {
  435. if (!$this->isMyActivity($activity)) {
  436. return true;
  437. }
  438. $obj = $activity->objects[0];
  439. $options = [
  440. 'uri' => $object->id,
  441. 'url' => $object->link,
  442. 'self' => $object->selfLink,
  443. 'source' => 'restore',
  444. ];
  445. // $user->getProfile() is a Profile
  446. $saved = $this->saveNoticeFromActivity(
  447. $activity,
  448. $user->getProfile(),
  449. $options
  450. );
  451. if (!empty($saved)) {
  452. $done = true;
  453. }
  454. return false;
  455. }
  456. /**
  457. * Event handler gives the plugin a chance to add custom
  458. * Atom XML ActivityStreams output from a previously filled-out
  459. * ActivityObject.
  460. *
  461. * The atomOutput method is called if it's one of
  462. * our matching types.
  463. *
  464. * @param ActivityObject $obj
  465. * @param XMLOutputter $out to add elements at end of object
  466. * @return boolean hook return value
  467. */
  468. public function onEndActivityObjectOutputAtom(ActivityObject $obj, XMLOutputter $out)
  469. {
  470. if (in_array($obj->type, $this->types())) {
  471. $this->activityObjectOutputAtom($obj, $out);
  472. }
  473. return true;
  474. }
  475. /**
  476. * Event handler gives the plugin a chance to add custom
  477. * JSON ActivityStreams output from a previously filled-out
  478. * ActivityObject.
  479. *
  480. * The activityObjectOutputJson method is called if it's one of
  481. * our matching types.
  482. *
  483. * @param ActivityObject $obj
  484. * @param array &$out JSON-targeted array which can be modified
  485. * @return boolean hook return value
  486. */
  487. public function onEndActivityObjectOutputJson(ActivityObject $obj, array &$out)
  488. {
  489. if (in_array($obj->type, $this->types())) {
  490. $this->activityObjectOutputJson($obj, $out);
  491. }
  492. return true;
  493. }
  494. public function onStartOpenNoticeListItemElement(NoticeListItem $nli)
  495. {
  496. if (!$this->isMyNotice($nli->notice)) {
  497. return true;
  498. }
  499. $this->openNoticeListItemElement($nli);
  500. Event::handle('EndOpenNoticeListItemElement', [$nli]);
  501. return false;
  502. }
  503. public function onStartCloseNoticeListItemElement(NoticeListItem $nli)
  504. {
  505. if (!$this->isMyNotice($nli->notice)) {
  506. return true;
  507. }
  508. $this->closeNoticeListItemElement($nli);
  509. Event::handle('EndCloseNoticeListItemElement', [$nli]);
  510. return false;
  511. }
  512. protected function openNoticeListItemElement(NoticeListItem $nli)
  513. {
  514. // Build up the attributes
  515. $attrs = [];
  516. // -> The id
  517. $id = (empty($nli->repeat)) ? $nli->notice->id : $nli->repeat->id;
  518. $id_decl = "notice-{$id}";
  519. $attrs['id'] = $id_decl;
  520. // -> The class
  521. $class = 'h-entry notice ' . $this->tag();
  522. if ($nli->notice->scope != 0 && $nli->notice->scope != 1) {
  523. $class .= ' limited-scope';
  524. }
  525. try {
  526. $class .= ' notice-source-' . common_to_alphanumeric($nli->notice->source);
  527. } catch (Exception $e) {
  528. // either source or what we filtered out was a zero-length string
  529. }
  530. $attrs['class'] = $class;
  531. // -> Robots
  532. if (!$nli->notice->isLocal()) {
  533. $attrs['data-nosnippet'] = 'true';
  534. }
  535. $nli->out->elementStart('li', $attrs);
  536. }
  537. protected function closeNoticeListItemElement(NoticeListItem $nli)
  538. {
  539. $nli->out->elementEnd('li');
  540. }
  541. // FIXME: This is overriden in MicroAppPlugin but shouldn't have to be
  542. public function onStartShowNoticeItem(NoticeListItem $nli)
  543. {
  544. if (!$this->isMyNotice($nli->notice)) {
  545. return true;
  546. }
  547. try {
  548. $this->showNoticeListItem($nli);
  549. } catch (Exception $e) {
  550. common_log(LOG_ERR, 'Error showing notice ' . $nli->getNotice()->getID() . ': ' . $e->getMessage());
  551. $nli->out->element('p', 'error', sprintf(_('Error showing notice: %s'), $e->getMessage()));
  552. }
  553. Event::handle('EndShowNoticeItem', array($nli));
  554. return false;
  555. }
  556. protected function showNoticeListItem(NoticeListItem $nli)
  557. {
  558. $nli->showNoticeHeaders();
  559. $nli->showContent();
  560. $nli->showNoticeFooter();
  561. }
  562. public function onStartShowNoticeItemNotice(NoticeListItem $nli)
  563. {
  564. if (!$this->isMyNotice($nli->notice)) {
  565. return true;
  566. }
  567. $this->showNoticeItemNotice($nli);
  568. Event::handle('EndShowNoticeItemNotice', array($nli));
  569. return false;
  570. }
  571. protected function showNoticeItemNotice(NoticeListItem $nli)
  572. {
  573. $nli->showNoticeTitle();
  574. $nli->showAuthor();
  575. $nli->showAddressees();
  576. $nli->showContent();
  577. }
  578. public function onStartShowNoticeContent(Notice $stored, HTMLOutputter $out, Profile $scoped = null)
  579. {
  580. if (!$this->isMyNotice($stored)) {
  581. return true;
  582. }
  583. try {
  584. $this->showNoticeContent($stored, $out, $scoped);
  585. } catch (Exception $e) {
  586. $out->element('div', 'error', $e->getMessage());
  587. }
  588. return false;
  589. }
  590. protected function showNoticeContent(Notice $stored, HTMLOutputter $out, Profile $scoped = null)
  591. {
  592. $out->text($stored->getContent());
  593. }
  594. }