activityhandlerplugin.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629
  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. * (PuSH 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 (PuSH 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 (AlreadyFulfilledException $e) {
  263. // Nothing to see here, it's obviously already gone...
  264. }
  265. }
  266. // Always continue this event in our activity handling plugins.
  267. return true;
  268. }
  269. /**
  270. * @param Notice $stored The notice being distributed
  271. * @param array &$mentioned_ids List of profiles (from $stored->getReplies())
  272. */
  273. public function onStartNotifyMentioned(Notice $stored, array &$mentioned_ids)
  274. {
  275. if (!$this->isMyNotice($stored)) {
  276. return true;
  277. }
  278. return $this->notifyMentioned($stored, $mentioned_ids);
  279. }
  280. /**
  281. * Render a notice as one of our objects
  282. *
  283. * @param Notice $notice Notice to render
  284. * @param ActivityObject &$object Empty object to fill
  285. *
  286. * @return boolean hook value
  287. */
  288. function onStartActivityObjectFromNotice(Notice $notice, &$object)
  289. {
  290. if (!$this->isMyNotice($notice)) {
  291. return true;
  292. }
  293. $object = $this->activityObjectFromNotice($notice);
  294. return false;
  295. }
  296. /**
  297. * Handle a posted object from PuSH
  298. *
  299. * @param Activity $activity activity to handle
  300. * @param Profile $actor Profile for the feed
  301. *
  302. * @return boolean hook value
  303. */
  304. function onStartHandleFeedEntryWithProfile(Activity $activity, Profile $profile, &$notice)
  305. {
  306. if (!$this->isMyActivity($activity)) {
  307. return true;
  308. }
  309. // We are guaranteed to get a Profile back from checkAuthorship (or it throws an exception)
  310. $profile = ActivityUtils::checkAuthorship($activity, $profile);
  311. $object = $activity->objects[0];
  312. $options = array('uri' => $object->id,
  313. 'url' => $object->link,
  314. 'is_local' => Notice::REMOTE,
  315. 'source' => 'ostatus');
  316. if (!isset($this->oldSaveNew)) {
  317. $notice = Notice::saveActivity($activity, $profile, $options);
  318. } else {
  319. $notice = $this->saveNoticeFromActivity($activity, $profile, $options);
  320. }
  321. return false;
  322. }
  323. /**
  324. * Handle a posted object from Salmon
  325. *
  326. * @param Activity $activity activity to handle
  327. * @param mixed $target user or group targeted
  328. *
  329. * @return boolean hook value
  330. */
  331. function onStartHandleSalmonTarget(Activity $activity, $target)
  332. {
  333. if (!$this->isMyActivity($activity)) {
  334. return true;
  335. }
  336. if (!isset($this->oldSaveNew)) {
  337. // Handle saveActivity in OStatus class for incoming salmon, remove this event
  338. // handler when all plugins have gotten rid of "oldSaveNew".
  339. return true;
  340. }
  341. $this->log(LOG_INFO, get_called_class()." checking {$activity->id} as a valid Salmon slap.");
  342. if ($target instanceof User_group || $target->isGroup()) {
  343. $uri = $target->getUri();
  344. if (!array_key_exists($uri, $activity->context->attention)) {
  345. // @todo FIXME: please document (i18n).
  346. // TRANS: Client exception thrown when ...
  347. throw new ClientException(_('Object not posted to this group.'));
  348. }
  349. } elseif ($target instanceof Profile && $target->isLocal()) {
  350. $original = null;
  351. // FIXME: Shouldn't favorites show up with a 'target' activityobject?
  352. if (!ActivityUtils::compareVerbs($activity->verb, array(ActivityVerb::POST)) && isset($activity->objects[0])) {
  353. // If this is not a post, it's a verb targeted at something (such as a Favorite attached to a note)
  354. if (!empty($activity->objects[0]->id)) {
  355. $activity->context->replyToID = $activity->objects[0]->id;
  356. }
  357. }
  358. if (!empty($activity->context->replyToID)) {
  359. $original = Notice::getKV('uri', $activity->context->replyToID);
  360. }
  361. if ((!$original instanceof Notice || $original->profile_id != $target->id)
  362. && !array_key_exists($target->getUri(), $activity->context->attention)) {
  363. // @todo FIXME: Please document (i18n).
  364. // TRANS: Client exception when ...
  365. throw new ClientException(_('Object not posted to this user.'));
  366. }
  367. } else {
  368. // TRANS: Server exception thrown when a micro app plugin uses a target that cannot be handled.
  369. throw new ServerException(_('Do not know how to handle this kind of target.'));
  370. }
  371. $oactor = Ostatus_profile::ensureActivityObjectProfile($activity->actor);
  372. $actor = $oactor->localProfile();
  373. // FIXME: will this work in all cases? I made it work for Favorite...
  374. if (ActivityUtils::compareVerbs($activity->verb, array(ActivityVerb::POST))) {
  375. $object = $activity->objects[0];
  376. } else {
  377. $object = $activity;
  378. }
  379. $options = array('uri' => $object->id,
  380. 'url' => $object->link,
  381. 'is_local' => Notice::REMOTE,
  382. 'source' => 'ostatus');
  383. $notice = $this->saveNoticeFromActivity($activity, $actor, $options);
  384. return false;
  385. }
  386. /**
  387. * Handle object posted via AtomPub
  388. *
  389. * @param Activity $activity Activity that was posted
  390. * @param Profile $scoped Profile of user posting
  391. * @param Notice &$notice Resulting notice
  392. *
  393. * @return boolean hook value
  394. */
  395. public function onStartAtomPubNewActivity(Activity $activity, Profile $scoped, Notice &$notice=null)
  396. {
  397. if (!$this->isMyActivity($activity)) {
  398. return true;
  399. }
  400. $options = array('source' => 'atompub');
  401. $notice = $this->saveNoticeFromActivity($activity, $scoped, $options);
  402. return false;
  403. }
  404. /**
  405. * Handle object imported from a backup file
  406. *
  407. * @param User $user User to import for
  408. * @param ActivityObject $author Original author per import file
  409. * @param Activity $activity Activity to import
  410. * @param boolean $trusted Is this a trusted user?
  411. * @param boolean &$done Is this done (success or unrecoverable error)
  412. *
  413. * @return boolean hook value
  414. */
  415. function onStartImportActivity($user, $author, Activity $activity, $trusted, &$done)
  416. {
  417. if (!$this->isMyActivity($activity)) {
  418. return true;
  419. }
  420. $obj = $activity->objects[0];
  421. $options = array('uri' => $object->id,
  422. 'url' => $object->link,
  423. 'source' => 'restore');
  424. // $user->getProfile() is a Profile
  425. $saved = $this->saveNoticeFromActivity($activity,
  426. $user->getProfile(),
  427. $options);
  428. if (!empty($saved)) {
  429. $done = true;
  430. }
  431. return false;
  432. }
  433. /**
  434. * Event handler gives the plugin a chance to add custom
  435. * Atom XML ActivityStreams output from a previously filled-out
  436. * ActivityObject.
  437. *
  438. * The atomOutput method is called if it's one of
  439. * our matching types.
  440. *
  441. * @param ActivityObject $obj
  442. * @param XMLOutputter $out to add elements at end of object
  443. * @return boolean hook return value
  444. */
  445. function onEndActivityObjectOutputAtom(ActivityObject $obj, XMLOutputter $out)
  446. {
  447. if (in_array($obj->type, $this->types())) {
  448. $this->activityObjectOutputAtom($obj, $out);
  449. }
  450. return true;
  451. }
  452. /**
  453. * Event handler gives the plugin a chance to add custom
  454. * JSON ActivityStreams output from a previously filled-out
  455. * ActivityObject.
  456. *
  457. * The activityObjectOutputJson method is called if it's one of
  458. * our matching types.
  459. *
  460. * @param ActivityObject $obj
  461. * @param array &$out JSON-targeted array which can be modified
  462. * @return boolean hook return value
  463. */
  464. function onEndActivityObjectOutputJson(ActivityObject $obj, array &$out)
  465. {
  466. if (in_array($obj->type, $this->types())) {
  467. $this->activityObjectOutputJson($obj, $out);
  468. }
  469. return true;
  470. }
  471. public function onStartOpenNoticeListItemElement(NoticeListItem $nli)
  472. {
  473. if (!$this->isMyNotice($nli->notice)) {
  474. return true;
  475. }
  476. $this->openNoticeListItemElement($nli);
  477. Event::handle('EndOpenNoticeListItemElement', array($nli));
  478. return false;
  479. }
  480. public function onStartCloseNoticeListItemElement(NoticeListItem $nli)
  481. {
  482. if (!$this->isMyNotice($nli->notice)) {
  483. return true;
  484. }
  485. $this->closeNoticeListItemElement($nli);
  486. Event::handle('EndCloseNoticeListItemElement', array($nli));
  487. return false;
  488. }
  489. protected function openNoticeListItemElement(NoticeListItem $nli)
  490. {
  491. $id = (empty($nli->repeat)) ? $nli->notice->id : $nli->repeat->id;
  492. $class = 'h-entry notice ' . $this->tag();
  493. if ($nli->notice->scope != 0 && $nli->notice->scope != 1) {
  494. $class .= ' limited-scope';
  495. }
  496. $nli->out->elementStart('li', array('class' => $class,
  497. 'id' => 'notice-' . $id));
  498. }
  499. protected function closeNoticeListItemElement(NoticeListItem $nli)
  500. {
  501. $nli->out->elementEnd('li');
  502. }
  503. // FIXME: This is overriden in MicroAppPlugin but shouldn't have to be
  504. public function onStartShowNoticeItem(NoticeListItem $nli)
  505. {
  506. if (!$this->isMyNotice($nli->notice)) {
  507. return true;
  508. }
  509. try {
  510. $this->showNoticeListItem($nli);
  511. } catch (Exception $e) {
  512. common_log(LOG_ERR, 'Error showing notice '.$nli->getNotice()->getID().': ' . $e->getMessage());
  513. $nli->out->element('p', 'error', sprintf(_('Error showing notice: %s'), $e->getMessage()));
  514. }
  515. Event::handle('EndShowNoticeItem', array($nli));
  516. return false;
  517. }
  518. protected function showNoticeListItem(NoticeListItem $nli)
  519. {
  520. $nli->showNoticeHeaders();
  521. $nli->showContent();
  522. $nli->showNoticeFooter();
  523. }
  524. public function onStartShowNoticeItemNotice(NoticeListItem $nli)
  525. {
  526. if (!$this->isMyNotice($nli->notice)) {
  527. return true;
  528. }
  529. $this->showNoticeItemNotice($nli);
  530. Event::handle('EndShowNoticeItemNotice', array($nli));
  531. return false;
  532. }
  533. protected function showNoticeItemNotice(NoticeListItem $nli)
  534. {
  535. $nli->showNoticeTitle();
  536. $nli->showAuthor();
  537. $nli->showAddressees();
  538. $nli->showContent();
  539. }
  540. public function onStartShowNoticeContent(Notice $stored, HTMLOutputter $out, Profile $scoped=null)
  541. {
  542. if (!$this->isMyNotice($stored)) {
  543. return true;
  544. }
  545. try {
  546. $this->showNoticeContent($stored, $out, $scoped);
  547. } catch (Exception $e) {
  548. $out->element('div', 'error', $e->getMessage());
  549. }
  550. return false;
  551. }
  552. protected function showNoticeContent(Notice $stored, HTMLOutputter $out, Profile $scoped=null)
  553. {
  554. $out->text($stored->getContent());
  555. }
  556. }