ActivityHandlerPlugin.php 22 KB

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