activityhandlerplugin.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638
  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 Profile $actor
  152. * @param array $options=array()
  153. *
  154. * @return Notice the resulting notice
  155. */
  156. protected function saveObjectFromActivity(Activity $activity, Notice $stored, array $options=array())
  157. {
  158. throw new ServerException('This function should be abstract when all plugins have migrated to saveObjectFromActivity');
  159. }
  160. /*
  161. * This usually gets called from Notice::saveActivity after a Notice object has been created,
  162. * so it contains a proper id and a uri for the object to be saved.
  163. */
  164. public function onStoreActivityObject(Activity $act, Notice $stored, array $options=array(), &$object) {
  165. // $this->oldSaveNew is there during a migration period of plugins, to start using
  166. // Notice::saveActivity instead of Notice::saveNew
  167. if (!$this->isMyActivity($act) || isset($this->oldSaveNew)) {
  168. return true;
  169. }
  170. $object = $this->saveObjectFromActivity($act, $stored, $options);
  171. try {
  172. $act->context->attention = array_merge($act->context->attention, $object->getAttentionArray());
  173. } catch (Exception $e) {
  174. common_debug('WARNING: Could not get attention list from object '.get_class($object).'!');
  175. }
  176. return false;
  177. }
  178. /**
  179. * Given an existing Notice object, your plugin gets to
  180. * figure out how to arrange it into an ActivityStreams
  181. * object.
  182. *
  183. * This will be how your specialized notice gets output in
  184. * Atom feeds and JSON-based ActivityStreams output, including
  185. * account backup/restore and OStatus (PuSH and Salmon transports).
  186. *
  187. * You should be able to round-trip data from this format back
  188. * through $this->saveNoticeFromActivity(). Where applicable, try
  189. * to use existing ActivityStreams structures and object types,
  190. * and consider interop with other compatible apps.
  191. *
  192. * All micro-app classes must override this method.
  193. *
  194. * @fixme this outputs an ActivityObject, not an Activity. Any compat issues?
  195. *
  196. * @param Notice $notice
  197. *
  198. * @return ActivityObject
  199. */
  200. abstract function activityObjectFromNotice(Notice $notice);
  201. /**
  202. * When a notice is deleted, you'll be called here for a chance
  203. * to clean up any related resources.
  204. *
  205. * All micro-app classes must override this method.
  206. *
  207. * @param Notice $notice
  208. */
  209. abstract function deleteRelated(Notice $notice);
  210. protected function notifyMentioned(Notice $stored, array &$mentioned_ids)
  211. {
  212. // pass through silently by default
  213. }
  214. /**
  215. * Called when generating Atom XML ActivityStreams output from an
  216. * ActivityObject belonging to this plugin. Gives the plugin
  217. * a chance to add custom output.
  218. *
  219. * Note that you can only add output of additional XML elements,
  220. * not change existing stuff here.
  221. *
  222. * If output is already handled by the base Activity classes,
  223. * you can leave this base implementation as a no-op.
  224. *
  225. * @param ActivityObject $obj
  226. * @param XMLOutputter $out to add elements at end of object
  227. */
  228. function activityObjectOutputAtom(ActivityObject $obj, XMLOutputter $out)
  229. {
  230. // default is a no-op
  231. }
  232. /**
  233. * Called when generating JSON ActivityStreams output from an
  234. * ActivityObject belonging to this plugin. Gives the plugin
  235. * a chance to add custom output.
  236. *
  237. * Modify the array contents to your heart's content, and it'll
  238. * all get serialized out as JSON.
  239. *
  240. * If output is already handled by the base Activity classes,
  241. * you can leave this base implementation as a no-op.
  242. *
  243. * @param ActivityObject $obj
  244. * @param array &$out JSON-targeted array which can be modified
  245. */
  246. public function activityObjectOutputJson(ActivityObject $obj, array &$out)
  247. {
  248. // default is a no-op
  249. }
  250. /**
  251. * When a notice is deleted, delete the related objects
  252. * by calling the overridable $this->deleteRelated().
  253. *
  254. * @param Notice $notice Notice being deleted
  255. *
  256. * @return boolean hook value
  257. */
  258. function onNoticeDeleteRelated(Notice $notice)
  259. {
  260. if ($this->isMyNotice($notice)) {
  261. $this->deleteRelated($notice);
  262. }
  263. // Always continue this event in our activity handling plugins.
  264. return true;
  265. }
  266. /**
  267. * @param Notice $stored The notice being distributed
  268. * @param array &$mentioned_ids List of profiles (from $stored->getReplies())
  269. */
  270. public function onStartNotifyMentioned(Notice $stored, array &$mentioned_ids)
  271. {
  272. if (!$this->isMyNotice($stored)) {
  273. return true;
  274. }
  275. $this->notifyMentioned($stored, $mentioned_ids);
  276. // If it was _our_ notice, only we should do anything with the mentions.
  277. return false;
  278. }
  279. /**
  280. * Render a notice as one of our objects
  281. *
  282. * @param Notice $notice Notice to render
  283. * @param ActivityObject &$object Empty object to fill
  284. *
  285. * @return boolean hook value
  286. */
  287. function onStartActivityObjectFromNotice(Notice $notice, &$object)
  288. {
  289. if (!$this->isMyNotice($notice)) {
  290. return true;
  291. }
  292. try {
  293. $object = $this->activityObjectFromNotice($notice);
  294. } catch (NoResultException $e) {
  295. $object = null; // because getKV returns null on failure
  296. }
  297. return false;
  298. }
  299. /**
  300. * Handle a posted object from PuSH
  301. *
  302. * @param Activity $activity activity to handle
  303. * @param Profile $actor Profile for the feed
  304. *
  305. * @return boolean hook value
  306. */
  307. function onStartHandleFeedEntryWithProfile(Activity $activity, Profile $profile, &$notice)
  308. {
  309. if (!$this->isMyActivity($activity)) {
  310. return true;
  311. }
  312. // We are guaranteed to get a Profile back from checkAuthorship (or it throws an exception)
  313. $profile = ActivityUtils::checkAuthorship($activity, $profile);
  314. $object = $activity->objects[0];
  315. $options = array('uri' => $object->id,
  316. 'url' => $object->link,
  317. 'is_local' => Notice::REMOTE,
  318. 'source' => 'ostatus');
  319. if (!isset($this->oldSaveNew)) {
  320. $notice = Notice::saveActivity($activity, $profile, $options);
  321. } else {
  322. $notice = $this->saveNoticeFromActivity($activity, $profile, $options);
  323. }
  324. return false;
  325. }
  326. /**
  327. * Handle a posted object from Salmon
  328. *
  329. * @param Activity $activity activity to handle
  330. * @param mixed $target user or group targeted
  331. *
  332. * @return boolean hook value
  333. */
  334. function onStartHandleSalmonTarget(Activity $activity, $target)
  335. {
  336. if (!$this->isMyActivity($activity)) {
  337. return true;
  338. }
  339. $this->log(LOG_INFO, "Checking {$activity->id} as a valid Salmon slap.");
  340. if ($target instanceof User_group || $target->isGroup()) {
  341. $uri = $target->getUri();
  342. if (!array_key_exists($uri, $activity->context->attention)) {
  343. // @todo FIXME: please document (i18n).
  344. // TRANS: Client exception thrown when ...
  345. throw new ClientException(_('Object not posted to this group.'));
  346. }
  347. } elseif ($target instanceof Profile && $target->isLocal()) {
  348. $original = null;
  349. // FIXME: Shouldn't favorites show up with a 'target' activityobject?
  350. if (!ActivityUtils::compareTypes($activity->verb, array(ActivityVerb::POST)) && isset($activity->objects[0])) {
  351. // If this is not a post, it's a verb targeted at something (such as a Favorite attached to a note)
  352. if (!empty($activity->objects[0]->id)) {
  353. $activity->context->replyToID = $activity->objects[0]->id;
  354. }
  355. }
  356. if (!empty($activity->context->replyToID)) {
  357. $original = Notice::getKV('uri', $activity->context->replyToID);
  358. }
  359. if ((!$original instanceof Notice || $original->profile_id != $target->id)
  360. && !array_key_exists($target->getUri(), $activity->context->attention)) {
  361. // @todo FIXME: Please document (i18n).
  362. // TRANS: Client exception when ...
  363. throw new ClientException(_('Object not posted to this user.'));
  364. }
  365. } else {
  366. // TRANS: Server exception thrown when a micro app plugin uses a target that cannot be handled.
  367. throw new ServerException(_('Do not know how to handle this kind of target.'));
  368. }
  369. $oactor = Ostatus_profile::ensureActivityObjectProfile($activity->actor);
  370. $actor = $oactor->localProfile();
  371. // FIXME: will this work in all cases? I made it work for Favorite...
  372. if (ActivityUtils::compareTypes($activity->verb, array(ActivityVerb::POST))) {
  373. $object = $activity->objects[0];
  374. } else {
  375. $object = $activity;
  376. }
  377. $options = array('uri' => $object->id,
  378. 'url' => $object->link,
  379. 'is_local' => Notice::REMOTE,
  380. 'source' => 'ostatus');
  381. if (!isset($this->oldSaveNew)) {
  382. $notice = Notice::saveActivity($activity, $actor, $options);
  383. } else {
  384. $notice = $this->saveNoticeFromActivity($activity, $actor, $options);
  385. }
  386. return false;
  387. }
  388. /**
  389. * Handle object posted via AtomPub
  390. *
  391. * @param Activity &$activity Activity that was posted
  392. * @param Profile $scoped Profile of user posting
  393. * @param Notice &$notice Resulting notice
  394. *
  395. * @return boolean hook value
  396. */
  397. // FIXME: Make sure we can really do strong Notice typing with a $notice===null without having =null here
  398. public function onStartAtomPubNewActivity(Activity &$activity, Profile $scoped, Notice &$notice)
  399. {
  400. if (!$this->isMyActivity($activity)) {
  401. return true;
  402. }
  403. $options = array('source' => 'atompub');
  404. $notice = $this->saveNoticeFromActivity($activity, $scoped, $options);
  405. Event::handle('EndAtomPubNewActivity', array($activity, $scoped, $notice));
  406. return false;
  407. }
  408. /**
  409. * Handle object imported from a backup file
  410. *
  411. * @param User $user User to import for
  412. * @param ActivityObject $author Original author per import file
  413. * @param Activity $activity Activity to import
  414. * @param boolean $trusted Is this a trusted user?
  415. * @param boolean &$done Is this done (success or unrecoverable error)
  416. *
  417. * @return boolean hook value
  418. */
  419. function onStartImportActivity($user, $author, Activity $activity, $trusted, &$done)
  420. {
  421. if (!$this->isMyActivity($activity)) {
  422. return true;
  423. }
  424. $obj = $activity->objects[0];
  425. $options = array('uri' => $object->id,
  426. 'url' => $object->link,
  427. 'source' => 'restore');
  428. // $user->getProfile() is a Profile
  429. $saved = $this->saveNoticeFromActivity($activity,
  430. $user->getProfile(),
  431. $options);
  432. if (!empty($saved)) {
  433. $done = true;
  434. }
  435. return false;
  436. }
  437. /**
  438. * Event handler gives the plugin a chance to add custom
  439. * Atom XML ActivityStreams output from a previously filled-out
  440. * ActivityObject.
  441. *
  442. * The atomOutput method is called if it's one of
  443. * our matching types.
  444. *
  445. * @param ActivityObject $obj
  446. * @param XMLOutputter $out to add elements at end of object
  447. * @return boolean hook return value
  448. */
  449. function onEndActivityObjectOutputAtom(ActivityObject $obj, XMLOutputter $out)
  450. {
  451. if (in_array($obj->type, $this->types())) {
  452. $this->activityObjectOutputAtom($obj, $out);
  453. }
  454. return true;
  455. }
  456. /**
  457. * Event handler gives the plugin a chance to add custom
  458. * JSON ActivityStreams output from a previously filled-out
  459. * ActivityObject.
  460. *
  461. * The activityObjectOutputJson method is called if it's one of
  462. * our matching types.
  463. *
  464. * @param ActivityObject $obj
  465. * @param array &$out JSON-targeted array which can be modified
  466. * @return boolean hook return value
  467. */
  468. function onEndActivityObjectOutputJson(ActivityObject $obj, array &$out)
  469. {
  470. if (in_array($obj->type, $this->types())) {
  471. $this->activityObjectOutputJson($obj, $out);
  472. }
  473. return true;
  474. }
  475. public function onStartOpenNoticeListItemElement(NoticeListItem $nli)
  476. {
  477. if (!$this->isMyNotice($nli->notice)) {
  478. return true;
  479. }
  480. $this->openNoticeListItemElement($nli);
  481. Event::handle('EndOpenNoticeListItemElement', array($nli));
  482. return false;
  483. }
  484. public function onStartCloseNoticeListItemElement(NoticeListItem $nli)
  485. {
  486. if (!$this->isMyNotice($nli->notice)) {
  487. return true;
  488. }
  489. $this->closeNoticeListItemElement($nli);
  490. Event::handle('EndCloseNoticeListItemElement', array($nli));
  491. return false;
  492. }
  493. protected function openNoticeListItemElement(NoticeListItem $nli)
  494. {
  495. $id = (empty($nli->repeat)) ? $nli->notice->id : $nli->repeat->id;
  496. $class = 'h-entry notice ' . $this->tag();
  497. if ($nli->notice->scope != 0 && $nli->notice->scope != 1) {
  498. $class .= ' limited-scope';
  499. }
  500. $nli->out->elementStart('li', array('class' => $class,
  501. 'id' => 'notice-' . $id));
  502. }
  503. protected function closeNoticeListItemElement(NoticeListItem $nli)
  504. {
  505. $nli->out->elementEnd('li');
  506. }
  507. // FIXME: This is overriden in MicroAppPlugin but shouldn't have to be
  508. public function onStartShowNoticeItem(NoticeListItem $nli)
  509. {
  510. if (!$this->isMyNotice($nli->notice)) {
  511. return true;
  512. }
  513. try {
  514. $this->showNoticeListItem($nli);
  515. } catch (Exception $e) {
  516. $nli->out->element('p', 'error', 'Error showing notice: '.htmlspecialchars($e->getMessage()));
  517. }
  518. Event::handle('EndShowNoticeItem', array($nli));
  519. return false;
  520. }
  521. protected function showNoticeListItem(NoticeListItem $nli)
  522. {
  523. $nli->showNotice();
  524. $nli->showNoticeAttachments();
  525. $nli->showNoticeInfo();
  526. $nli->showNoticeOptions();
  527. $nli->showNoticeLink();
  528. $nli->showNoticeSource();
  529. $nli->showNoticeLocation();
  530. $nli->showPermalink();
  531. $nli->showRepeat();
  532. $nli->showNoticeOptions();
  533. }
  534. public function onStartShowNoticeItemNotice(NoticeListItem $nli)
  535. {
  536. if (!$this->isMyNotice($nli->notice)) {
  537. return true;
  538. }
  539. $this->showNoticeItemNotice($nli);
  540. Event::handle('EndShowNoticeItemNotice', array($nli));
  541. return false;
  542. }
  543. protected function showNoticeItemNotice(NoticeListItem $nli)
  544. {
  545. $nli->showNoticeTitle();
  546. $nli->showAuthor();
  547. $nli->showAddressees();
  548. $nli->showContent();
  549. }
  550. public function onStartShowNoticeContent(Notice $stored, HTMLOutputter $out, Profile $scoped=null)
  551. {
  552. if (!$this->isMyNotice($stored)) {
  553. return true;
  554. }
  555. $this->showNoticeContent($stored, $out, $scoped);
  556. return false;
  557. }
  558. protected function showNoticeContent(Notice $stored, HTMLOutputter $out, Profile $scoped=null)
  559. {
  560. $out->text($stored->getContent());
  561. }
  562. }