ActivityHandlerModule.php 23 KB

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