activityhandlerplugin.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644
  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::compareTypes($verb, $this->verbs());
  101. }
  102. function isMyType($type) {
  103. return count($this->types())===0 || ActivityUtils::compareTypes($type, $this->types());
  104. }
  105. /**
  106. * Given a parsed ActivityStreams activity, your plugin
  107. * gets to figure out how to actually save it into a notice
  108. * and any additional data structures you require.
  109. *
  110. * This function is deprecated and in the future, Notice::saveActivity
  111. * should be called from onStartHandleFeedEntryWithProfile in this class
  112. * (which instead turns to saveObjectFromActivity).
  113. *
  114. * @param Activity $activity
  115. * @param Profile $actor
  116. * @param array $options=array()
  117. *
  118. * @return Notice the resulting notice
  119. */
  120. public function saveNoticeFromActivity(Activity $activity, Profile $actor, array $options=array())
  121. {
  122. // Any plugin which has not implemented saveObjectFromActivity _must_
  123. // override this function until they are migrated (this function will
  124. // be deleted when all plugins are migrated to saveObjectFromActivity).
  125. if (isset($this->oldSaveNew)) {
  126. throw new ServerException('A function has been called for new saveActivity functionality, but is still set with an oldSaveNew configuration');
  127. }
  128. return Notice::saveActivity($activity, $actor, $options);
  129. }
  130. /**
  131. * Given a parsed ActivityStreams activity, your plugin gets
  132. * to figure out itself how to store the additional data into
  133. * the database, besides the base data stored by the core.
  134. *
  135. * This will handle just about all events where an activity
  136. * object gets saved, whether it is via AtomPub, OStatus
  137. * (PuSH and Salmon transports), or ActivityStreams-based
  138. * backup/restore of account data.
  139. *
  140. * You should be able to accept as input the output from an
  141. * asActivity() call on the stored object. Where applicable,
  142. * try to use existing ActivityStreams structures and object
  143. * types, and be liberal in accepting input from what might
  144. * be other compatible apps.
  145. *
  146. * All micro-app classes must override this method.
  147. *
  148. * @fixme are there any standard options?
  149. *
  150. * @param Activity $activity
  151. * @param Notice $stored The notice in our database for this certain object
  152. * @param array $options=array()
  153. *
  154. * @return object If the verb handling plugin creates an object, it can be returned here (otherwise true)
  155. * @throws exception On any error.
  156. */
  157. protected function saveObjectFromActivity(Activity $activity, Notice $stored, array $options=array())
  158. {
  159. throw new ServerException('This function should be abstract when all plugins have migrated to saveObjectFromActivity');
  160. }
  161. /*
  162. * This usually gets called from Notice::saveActivity after a Notice object has been created,
  163. * so it contains a proper id and a uri for the object to be saved.
  164. */
  165. public function onStoreActivityObject(Activity $act, Notice $stored, array $options, &$object) {
  166. // $this->oldSaveNew is there during a migration period of plugins, to start using
  167. // Notice::saveActivity instead of Notice::saveNew
  168. if (!$this->isMyActivity($act) || isset($this->oldSaveNew)) {
  169. return true;
  170. }
  171. $object = $this->saveObjectFromActivity($act, $stored, $options);
  172. try {
  173. // In the future we probably want to use something like ActivityVerb_DataObject for the kind
  174. // of objects which are returned from saveObjectFromActivity.
  175. if ($object instanceof Managed_DataObject) {
  176. // If the verb handling plugin figured out some more attention URIs, add them here to the
  177. // original activity. This is only done if a separate object is actually needed to be saved.
  178. $act->context->attention = array_merge($act->context->attention, $object->getAttentionArray());
  179. }
  180. } catch (Exception $e) {
  181. common_debug('WARNING: Could not get attention list from object '.get_class($object).'!');
  182. }
  183. return false;
  184. }
  185. /**
  186. * Given an existing Notice object, your plugin gets to
  187. * figure out how to arrange it into an ActivityStreams
  188. * object.
  189. *
  190. * This will be how your specialized notice gets output in
  191. * Atom feeds and JSON-based ActivityStreams output, including
  192. * account backup/restore and OStatus (PuSH and Salmon transports).
  193. *
  194. * You should be able to round-trip data from this format back
  195. * through $this->saveNoticeFromActivity(). Where applicable, try
  196. * to use existing ActivityStreams structures and object types,
  197. * and consider interop with other compatible apps.
  198. *
  199. * All micro-app classes must override this method.
  200. *
  201. * @fixme this outputs an ActivityObject, not an Activity. Any compat issues?
  202. *
  203. * @param Notice $notice
  204. *
  205. * @return ActivityObject
  206. */
  207. abstract function activityObjectFromNotice(Notice $notice);
  208. /**
  209. * When a notice is deleted, you'll be called here for a chance
  210. * to clean up any related resources.
  211. *
  212. * All micro-app classes must override this method.
  213. *
  214. * @param Notice $notice
  215. */
  216. abstract function deleteRelated(Notice $notice);
  217. protected function notifyMentioned(Notice $stored, array &$mentioned_ids)
  218. {
  219. // pass through silently by default
  220. }
  221. /**
  222. * Called when generating Atom XML ActivityStreams output from an
  223. * ActivityObject belonging to this plugin. Gives the plugin
  224. * a chance to add custom output.
  225. *
  226. * Note that you can only add output of additional XML elements,
  227. * not change existing stuff here.
  228. *
  229. * If output is already handled by the base Activity classes,
  230. * you can leave this base implementation as a no-op.
  231. *
  232. * @param ActivityObject $obj
  233. * @param XMLOutputter $out to add elements at end of object
  234. */
  235. function activityObjectOutputAtom(ActivityObject $obj, XMLOutputter $out)
  236. {
  237. // default is a no-op
  238. }
  239. /**
  240. * Called when generating JSON ActivityStreams output from an
  241. * ActivityObject belonging to this plugin. Gives the plugin
  242. * a chance to add custom output.
  243. *
  244. * Modify the array contents to your heart's content, and it'll
  245. * all get serialized out as JSON.
  246. *
  247. * If output is already handled by the base Activity classes,
  248. * you can leave this base implementation as a no-op.
  249. *
  250. * @param ActivityObject $obj
  251. * @param array &$out JSON-targeted array which can be modified
  252. */
  253. public function activityObjectOutputJson(ActivityObject $obj, array &$out)
  254. {
  255. // default is a no-op
  256. }
  257. /**
  258. * When a notice is deleted, delete the related objects
  259. * by calling the overridable $this->deleteRelated().
  260. *
  261. * @param Notice $notice Notice being deleted
  262. *
  263. * @return boolean hook value
  264. */
  265. function onNoticeDeleteRelated(Notice $notice)
  266. {
  267. if ($this->isMyNotice($notice)) {
  268. $this->deleteRelated($notice);
  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. $this->notifyMentioned($stored, $mentioned_ids);
  283. // If it was _our_ notice, only we should do anything with the mentions.
  284. return false;
  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. function onStartActivityObjectFromNotice(Notice $notice, &$object)
  295. {
  296. if (!$this->isMyNotice($notice)) {
  297. return true;
  298. }
  299. try {
  300. $object = $this->activityObjectFromNotice($notice);
  301. } catch (NoResultException $e) {
  302. $object = null; // because getKV returns null on failure
  303. }
  304. return false;
  305. }
  306. /**
  307. * Handle a posted object from PuSH
  308. *
  309. * @param Activity $activity activity to handle
  310. * @param Profile $actor Profile for the feed
  311. *
  312. * @return boolean hook value
  313. */
  314. function onStartHandleFeedEntryWithProfile(Activity $activity, Profile $profile, &$notice)
  315. {
  316. if (!$this->isMyActivity($activity)) {
  317. return true;
  318. }
  319. // We are guaranteed to get a Profile back from checkAuthorship (or it throws an exception)
  320. $profile = ActivityUtils::checkAuthorship($activity, $profile);
  321. $object = $activity->objects[0];
  322. $options = array('uri' => $object->id,
  323. 'url' => $object->link,
  324. 'is_local' => Notice::REMOTE,
  325. 'source' => 'ostatus');
  326. if (!isset($this->oldSaveNew)) {
  327. $notice = Notice::saveActivity($activity, $profile, $options);
  328. } else {
  329. $notice = $this->saveNoticeFromActivity($activity, $profile, $options);
  330. }
  331. return false;
  332. }
  333. /**
  334. * Handle a posted object from Salmon
  335. *
  336. * @param Activity $activity activity to handle
  337. * @param mixed $target user or group targeted
  338. *
  339. * @return boolean hook value
  340. */
  341. function onStartHandleSalmonTarget(Activity $activity, $target)
  342. {
  343. if (!$this->isMyActivity($activity)) {
  344. return true;
  345. }
  346. $this->log(LOG_INFO, "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::compareTypes($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::compareTypes($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. 'is_local' => Notice::REMOTE,
  387. 'source' => 'ostatus');
  388. if (!isset($this->oldSaveNew)) {
  389. $notice = Notice::saveActivity($activity, $actor, $options);
  390. } else {
  391. $notice = $this->saveNoticeFromActivity($activity, $actor, $options);
  392. }
  393. return false;
  394. }
  395. /**
  396. * Handle object posted via AtomPub
  397. *
  398. * @param Activity &$activity Activity that was posted
  399. * @param Profile $scoped Profile of user posting
  400. * @param Notice &$notice Resulting notice
  401. *
  402. * @return boolean hook value
  403. */
  404. // FIXME: Make sure we can really do strong Notice typing with a $notice===null without having =null here
  405. public function onStartAtomPubNewActivity(Activity &$activity, Profile $scoped, Notice &$notice)
  406. {
  407. if (!$this->isMyActivity($activity)) {
  408. return true;
  409. }
  410. $options = array('source' => 'atompub');
  411. $notice = $this->saveNoticeFromActivity($activity, $scoped, $options);
  412. Event::handle('EndAtomPubNewActivity', array($activity, $scoped, $notice));
  413. return false;
  414. }
  415. /**
  416. * Handle object imported from a backup file
  417. *
  418. * @param User $user User to import for
  419. * @param ActivityObject $author Original author per import file
  420. * @param Activity $activity Activity to import
  421. * @param boolean $trusted Is this a trusted user?
  422. * @param boolean &$done Is this done (success or unrecoverable error)
  423. *
  424. * @return boolean hook value
  425. */
  426. function onStartImportActivity($user, $author, Activity $activity, $trusted, &$done)
  427. {
  428. if (!$this->isMyActivity($activity)) {
  429. return true;
  430. }
  431. $obj = $activity->objects[0];
  432. $options = array('uri' => $object->id,
  433. 'url' => $object->link,
  434. 'source' => 'restore');
  435. // $user->getProfile() is a Profile
  436. $saved = $this->saveNoticeFromActivity($activity,
  437. $user->getProfile(),
  438. $options);
  439. if (!empty($saved)) {
  440. $done = true;
  441. }
  442. return false;
  443. }
  444. /**
  445. * Event handler gives the plugin a chance to add custom
  446. * Atom XML ActivityStreams output from a previously filled-out
  447. * ActivityObject.
  448. *
  449. * The atomOutput method is called if it's one of
  450. * our matching types.
  451. *
  452. * @param ActivityObject $obj
  453. * @param XMLOutputter $out to add elements at end of object
  454. * @return boolean hook return value
  455. */
  456. function onEndActivityObjectOutputAtom(ActivityObject $obj, XMLOutputter $out)
  457. {
  458. if (in_array($obj->type, $this->types())) {
  459. $this->activityObjectOutputAtom($obj, $out);
  460. }
  461. return true;
  462. }
  463. /**
  464. * Event handler gives the plugin a chance to add custom
  465. * JSON ActivityStreams output from a previously filled-out
  466. * ActivityObject.
  467. *
  468. * The activityObjectOutputJson method is called if it's one of
  469. * our matching types.
  470. *
  471. * @param ActivityObject $obj
  472. * @param array &$out JSON-targeted array which can be modified
  473. * @return boolean hook return value
  474. */
  475. function onEndActivityObjectOutputJson(ActivityObject $obj, array &$out)
  476. {
  477. if (in_array($obj->type, $this->types())) {
  478. $this->activityObjectOutputJson($obj, $out);
  479. }
  480. return true;
  481. }
  482. public function onStartOpenNoticeListItemElement(NoticeListItem $nli)
  483. {
  484. if (!$this->isMyNotice($nli->notice)) {
  485. return true;
  486. }
  487. $this->openNoticeListItemElement($nli);
  488. Event::handle('EndOpenNoticeListItemElement', array($nli));
  489. return false;
  490. }
  491. public function onStartCloseNoticeListItemElement(NoticeListItem $nli)
  492. {
  493. if (!$this->isMyNotice($nli->notice)) {
  494. return true;
  495. }
  496. $this->closeNoticeListItemElement($nli);
  497. Event::handle('EndCloseNoticeListItemElement', array($nli));
  498. return false;
  499. }
  500. protected function openNoticeListItemElement(NoticeListItem $nli)
  501. {
  502. $id = (empty($nli->repeat)) ? $nli->notice->id : $nli->repeat->id;
  503. $class = 'h-entry notice ' . $this->tag();
  504. if ($nli->notice->scope != 0 && $nli->notice->scope != 1) {
  505. $class .= ' limited-scope';
  506. }
  507. $nli->out->elementStart('li', array('class' => $class,
  508. 'id' => 'notice-' . $id));
  509. }
  510. protected function closeNoticeListItemElement(NoticeListItem $nli)
  511. {
  512. $nli->out->elementEnd('li');
  513. }
  514. // FIXME: This is overriden in MicroAppPlugin but shouldn't have to be
  515. public function onStartShowNoticeItem(NoticeListItem $nli)
  516. {
  517. if (!$this->isMyNotice($nli->notice)) {
  518. return true;
  519. }
  520. try {
  521. $this->showNoticeListItem($nli);
  522. } catch (Exception $e) {
  523. $nli->out->element('p', 'error', 'Error showing notice: '.htmlspecialchars($e->getMessage()));
  524. }
  525. Event::handle('EndShowNoticeItem', array($nli));
  526. return false;
  527. }
  528. protected function showNoticeListItem(NoticeListItem $nli)
  529. {
  530. $nli->showNotice();
  531. $nli->showNoticeAttachments();
  532. $nli->showNoticeInfo();
  533. $nli->showNoticeOptions();
  534. $nli->showNoticeLink();
  535. $nli->showNoticeSource();
  536. $nli->showNoticeLocation();
  537. $nli->showPermalink();
  538. $nli->showNoticeOptions();
  539. }
  540. public function onStartShowNoticeItemNotice(NoticeListItem $nli)
  541. {
  542. if (!$this->isMyNotice($nli->notice)) {
  543. return true;
  544. }
  545. $this->showNoticeItemNotice($nli);
  546. Event::handle('EndShowNoticeItemNotice', array($nli));
  547. return false;
  548. }
  549. protected function showNoticeItemNotice(NoticeListItem $nli)
  550. {
  551. $nli->showNoticeTitle();
  552. $nli->showAuthor();
  553. $nli->showAddressees();
  554. $nli->showContent();
  555. }
  556. public function onStartShowNoticeContent(Notice $stored, HTMLOutputter $out, Profile $scoped=null)
  557. {
  558. if (!$this->isMyNotice($stored)) {
  559. return true;
  560. }
  561. $this->showNoticeContent($stored, $out, $scoped);
  562. return false;
  563. }
  564. protected function showNoticeContent(Notice $stored, HTMLOutputter $out, Profile $scoped=null)
  565. {
  566. $out->text($stored->getContent());
  567. }
  568. }