ActivityHandlerPlugin.php 22 KB

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