ActivityHandlerPlugin.php 22 KB

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