3 * GNU Social - a federating social network
4 * Copyright (C) 2014, Free Software Foundation, Inc.
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.
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.
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/>.
20 if (!defined('GNUSOCIAL')) { exit(1); }
23 * Superclass for plugins which add Activity types and such
27 * @author Mikael Nordfeldth <mmn@hethane.se>
28 * @copyright 2014 Free Software Foundation, Inc.
29 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
30 * @link http://gnu.io/social
32 abstract class ActivityHandlerPlugin extends Plugin
35 * Returns a key string which represents this activity in HTML classes,
36 * ids etc, as when offering selection of what type of post to make.
37 * In MicroAppPlugin, this is paired with the user-visible localizable appTitle().
39 * @return string (compatible with HTML classes)
41 abstract function tag();
44 * Return a list of ActivityStreams object type IRIs
45 * which this micro-app handles. Default implementations
46 * of the base class will use this list to check if a
47 * given ActivityStreams object belongs to us, via
48 * $this->isMyNotice() or $this->isMyActivity.
50 * An empty list means any type is ok. (Favorite verb etc.)
52 * @return array of strings
54 abstract function types();
57 * Return a list of ActivityStreams verb IRIs which
58 * this micro-app handles. Default implementations
59 * of the base class will use this list to check if a
60 * given ActivityStreams verb belongs to us, via
61 * $this->isMyNotice() or $this->isMyActivity.
63 * All micro-app classes must override this method.
65 * @return array of strings
67 public function verbs() {
68 return array(ActivityVerb::POST);
72 * Check if a given ActivityStreams activity should be handled by this
75 * The default implementation checks against the activity type list
76 * returned by $this->types(), and requires that exactly one matching
77 * object be present. You can override this method to expand
78 * your checks or to compare the activity's verb, etc.
80 * @param Activity $activity
83 function isMyActivity(Activity $act) {
84 return (count($act->objects) == 1
85 && ($act->objects[0] instanceof ActivityObject)
86 && $this->isMyVerb($act->verb)
87 && $this->isMyType($act->objects[0]->type));
91 * Check if a given notice object should be handled by this micro-app
94 * The default implementation checks against the activity type list
95 * returned by $this->types(). You can override this method to expand
96 * your checks, but follow the execution chain to get it right.
98 * @param Notice $notice
101 function isMyNotice(Notice $notice) {
102 return $this->isMyVerb($notice->verb) && $this->isMyType($notice->object_type);
105 function isMyVerb($verb) {
106 $verb = $verb ?: ActivityVerb::POST; // post is the default verb
107 return ActivityUtils::compareTypes($verb, $this->verbs());
110 function isMyType($type) {
111 return count($this->types())===0 || ActivityUtils::compareTypes($type, $this->types());
115 * Given a parsed ActivityStreams activity, your plugin
116 * gets to figure out how to actually save it into a notice
117 * and any additional data structures you require.
119 * This function is deprecated and in the future, Notice::saveActivity
120 * should be called from onStartHandleFeedEntryWithProfile in this class
121 * (which instead turns to saveObjectFromActivity).
123 * @param Activity $activity
124 * @param Profile $actor
125 * @param array $options=array()
127 * @return Notice the resulting notice
129 public function saveNoticeFromActivity(Activity $activity, Profile $actor, array $options=array())
131 // Any plugin which has not implemented saveObjectFromActivity _must_
132 // override this function until they are migrated (this function will
133 // be deleted when all plugins are migrated to saveObjectFromActivity).
135 if (isset($this->oldSaveNew)) {
136 throw new ServerException('A function has been called for new saveActivity functionality, but is still set with an oldSaveNew configuration');
139 return Notice::saveActivity($activity, $actor, $options);
143 * Given a parsed ActivityStreams activity, your plugin gets
144 * to figure out itself how to store the additional data into
145 * the database, besides the base data stored by the core.
147 * This will handle just about all events where an activity
148 * object gets saved, whether it is via AtomPub, OStatus
149 * (PuSH and Salmon transports), or ActivityStreams-based
150 * backup/restore of account data.
152 * You should be able to accept as input the output from an
153 * asActivity() call on the stored object. Where applicable,
154 * try to use existing ActivityStreams structures and object
155 * types, and be liberal in accepting input from what might
156 * be other compatible apps.
158 * All micro-app classes must override this method.
160 * @fixme are there any standard options?
162 * @param Activity $activity
163 * @param Profile $actor
164 * @param array $options=array()
166 * @return Notice the resulting notice
168 protected function saveObjectFromActivity(Activity $activity, Notice $stored, array $options=array())
170 throw new ServerException('This function should be abstract when all plugins have migrated to saveObjectFromActivity');
174 * This usually gets called from Notice::saveActivity after a Notice object has been created,
175 * so it contains a proper id and a uri for the object to be saved.
177 public function onStoreActivityObject(Activity $act, Notice $stored, array $options=array(), &$object) {
178 // $this->oldSaveNew is there during a migration period of plugins, to start using
179 // Notice::saveActivity instead of Notice::saveNew
180 if (!$this->isMyActivity($act) || isset($this->oldSaveNew)) {
183 $object = $this->saveObjectFromActivity($act, $stored, $options);
185 $act->context->attention = array_merge($act->context->attention, $object->getAttentionArray());
186 } catch (Exception $e) {
187 common_debug('WARNING: Could not get attention list from object '.get_class($object).'!');
193 * Given an existing Notice object, your plugin gets to
194 * figure out how to arrange it into an ActivityStreams
197 * This will be how your specialized notice gets output in
198 * Atom feeds and JSON-based ActivityStreams output, including
199 * account backup/restore and OStatus (PuSH and Salmon transports).
201 * You should be able to round-trip data from this format back
202 * through $this->saveNoticeFromActivity(). Where applicable, try
203 * to use existing ActivityStreams structures and object types,
204 * and consider interop with other compatible apps.
206 * All micro-app classes must override this method.
208 * @fixme this outputs an ActivityObject, not an Activity. Any compat issues?
210 * @param Notice $notice
212 * @return ActivityObject
214 abstract function activityObjectFromNotice(Notice $notice);
217 * When a notice is deleted, you'll be called here for a chance
218 * to clean up any related resources.
220 * All micro-app classes must override this method.
222 * @param Notice $notice
224 abstract function deleteRelated(Notice $notice);
226 protected function notifyMentioned(Notice $stored, array &$mentioned_ids)
228 // pass through silently by default
232 * Called when generating Atom XML ActivityStreams output from an
233 * ActivityObject belonging to this plugin. Gives the plugin
234 * a chance to add custom output.
236 * Note that you can only add output of additional XML elements,
237 * not change existing stuff here.
239 * If output is already handled by the base Activity classes,
240 * you can leave this base implementation as a no-op.
242 * @param ActivityObject $obj
243 * @param XMLOutputter $out to add elements at end of object
245 function activityObjectOutputAtom(ActivityObject $obj, XMLOutputter $out)
247 // default is a no-op
251 * Called when generating JSON ActivityStreams output from an
252 * ActivityObject belonging to this plugin. Gives the plugin
253 * a chance to add custom output.
255 * Modify the array contents to your heart's content, and it'll
256 * all get serialized out as JSON.
258 * If output is already handled by the base Activity classes,
259 * you can leave this base implementation as a no-op.
261 * @param ActivityObject $obj
262 * @param array &$out JSON-targeted array which can be modified
264 public function activityObjectOutputJson(ActivityObject $obj, array &$out)
266 // default is a no-op
270 * When a notice is deleted, delete the related objects
271 * by calling the overridable $this->deleteRelated().
273 * @param Notice $notice Notice being deleted
275 * @return boolean hook value
277 function onNoticeDeleteRelated(Notice $notice)
279 if ($this->isMyNotice($notice)) {
280 $this->deleteRelated($notice);
283 // Always continue this event in our activity handling plugins.
288 * @param Notice $stored The notice being distributed
289 * @param array &$mentioned_ids List of profiles (from $stored->getReplies())
291 public function onStartNotifyMentioned(Notice $stored, array &$mentioned_ids)
293 if (!$this->isMyNotice($stored)) {
297 $this->notifyMentioned($stored, $mentioned_ids);
299 // If it was _our_ notice, only we should do anything with the mentions.
304 * Render a notice as one of our objects
306 * @param Notice $notice Notice to render
307 * @param ActivityObject &$object Empty object to fill
309 * @return boolean hook value
311 function onStartActivityObjectFromNotice(Notice $notice, &$object)
313 if (!$this->isMyNotice($notice)) {
318 $object = $this->activityObjectFromNotice($notice);
319 } catch (NoResultException $e) {
320 $object = null; // because getKV returns null on failure
326 * Handle a posted object from PuSH
328 * @param Activity $activity activity to handle
329 * @param Profile $actor Profile for the feed
331 * @return boolean hook value
333 function onStartHandleFeedEntryWithProfile(Activity $activity, Profile $profile, &$notice)
335 if (!$this->isMyActivity($activity)) {
339 // We are guaranteed to get a Profile back from checkAuthorship (or it throws an exception)
340 $profile = ActivityUtils::checkAuthorship($activity, $profile);
342 $object = $activity->objects[0];
344 $options = array('uri' => $object->id,
345 'url' => $object->link,
346 'is_local' => Notice::REMOTE,
347 'source' => 'ostatus');
349 if (!isset($this->oldSaveNew)) {
350 $notice = Notice::saveActivity($activity, $profile, $options);
352 $notice = $this->saveNoticeFromActivity($activity, $profile, $options);
359 * Handle a posted object from Salmon
361 * @param Activity $activity activity to handle
362 * @param mixed $target user or group targeted
364 * @return boolean hook value
367 function onStartHandleSalmonTarget(Activity $activity, $target)
369 if (!$this->isMyActivity($activity)) {
373 $this->log(LOG_INFO, "Checking {$activity->id} as a valid Salmon slap.");
375 if ($target instanceof User_group || $target->isGroup()) {
376 $uri = $target->getUri();
377 if (!array_key_exists($uri, $activity->context->attention)) {
378 // @todo FIXME: please document (i18n).
379 // TRANS: Client exception thrown when ...
380 throw new ClientException(_('Object not posted to this group.'));
382 } elseif ($target instanceof Profile && $target->isLocal()) {
384 // FIXME: Shouldn't favorites show up with a 'target' activityobject?
385 if (!ActivityUtils::compareTypes($activity->verb, array(ActivityVerb::POST)) && isset($activity->objects[0])) {
386 // If this is not a post, it's a verb targeted at something (such as a Favorite attached to a note)
387 if (!empty($activity->objects[0]->id)) {
388 $activity->context->replyToID = $activity->objects[0]->id;
391 if (!empty($activity->context->replyToID)) {
392 $original = Notice::getKV('uri', $activity->context->replyToID);
394 if ((!$original instanceof Notice || $original->profile_id != $target->id)
395 && !array_key_exists($target->getUri(), $activity->context->attention)) {
396 // @todo FIXME: Please document (i18n).
397 // TRANS: Client exception when ...
398 throw new ClientException(_('Object not posted to this user.'));
401 // TRANS: Server exception thrown when a micro app plugin uses a target that cannot be handled.
402 throw new ServerException(_('Do not know how to handle this kind of target.'));
405 $oactor = Ostatus_profile::ensureActivityObjectProfile($activity->actor);
406 $actor = $oactor->localProfile();
408 // FIXME: will this work in all cases? I made it work for Favorite...
409 if (ActivityUtils::compareTypes($activity->verb, array(ActivityVerb::POST))) {
410 $object = $activity->objects[0];
415 $options = array('uri' => $object->id,
416 'url' => $object->link,
417 'is_local' => Notice::REMOTE,
418 'source' => 'ostatus');
420 if (!isset($this->oldSaveNew)) {
421 $notice = Notice::saveActivity($activity, $actor, $options);
423 $notice = $this->saveNoticeFromActivity($activity, $actor, $options);
430 * Handle object posted via AtomPub
432 * @param Activity &$activity Activity that was posted
433 * @param User $user User that posted it
434 * @param Notice &$notice Resulting notice
436 * @return boolean hook value
438 function onStartAtomPubNewActivity(Activity &$activity, $user, &$notice)
440 if (!$this->isMyActivity($activity)) {
444 $options = array('source' => 'atompub');
446 // $user->getProfile() is a Profile
447 $notice = $this->saveNoticeFromActivity($activity,
455 * Handle object imported from a backup file
457 * @param User $user User to import for
458 * @param ActivityObject $author Original author per import file
459 * @param Activity $activity Activity to import
460 * @param boolean $trusted Is this a trusted user?
461 * @param boolean &$done Is this done (success or unrecoverable error)
463 * @return boolean hook value
465 function onStartImportActivity($user, $author, Activity $activity, $trusted, &$done)
467 if (!$this->isMyActivity($activity)) {
471 $obj = $activity->objects[0];
473 $options = array('uri' => $object->id,
474 'url' => $object->link,
475 'source' => 'restore');
477 // $user->getProfile() is a Profile
478 $saved = $this->saveNoticeFromActivity($activity,
482 if (!empty($saved)) {
490 * Event handler gives the plugin a chance to add custom
491 * Atom XML ActivityStreams output from a previously filled-out
494 * The atomOutput method is called if it's one of
495 * our matching types.
497 * @param ActivityObject $obj
498 * @param XMLOutputter $out to add elements at end of object
499 * @return boolean hook return value
501 function onEndActivityObjectOutputAtom(ActivityObject $obj, XMLOutputter $out)
503 if (in_array($obj->type, $this->types())) {
504 $this->activityObjectOutputAtom($obj, $out);
510 * Event handler gives the plugin a chance to add custom
511 * JSON ActivityStreams output from a previously filled-out
514 * The activityObjectOutputJson method is called if it's one of
515 * our matching types.
517 * @param ActivityObject $obj
518 * @param array &$out JSON-targeted array which can be modified
519 * @return boolean hook return value
521 function onEndActivityObjectOutputJson(ActivityObject $obj, array &$out)
523 if (in_array($obj->type, $this->types())) {
524 $this->activityObjectOutputJson($obj, $out);
529 public function onStartOpenNoticeListItemElement(NoticeListItem $nli)
531 if (!$this->isMyNotice($nli->notice)) {
535 $this->openNoticeListItemElement($nli);
537 Event::handle('EndOpenNoticeListItemElement', array($nli));
541 public function onStartCloseNoticeListItemElement(NoticeListItem $nli)
543 if (!$this->isMyNotice($nli->notice)) {
547 $this->closeNoticeListItemElement($nli);
549 Event::handle('EndCloseNoticeListItemElement', array($nli));
553 protected function openNoticeListItemElement(NoticeListItem $nli)
555 $id = (empty($nli->repeat)) ? $nli->notice->id : $nli->repeat->id;
556 $class = 'h-entry notice ' . $this->tag();
557 if ($nli->notice->scope != 0 && $nli->notice->scope != 1) {
558 $class .= ' limited-scope';
560 $nli->out->elementStart('li', array('class' => $class,
561 'id' => 'notice-' . $id));
564 protected function closeNoticeListItemElement(NoticeListItem $nli)
566 $nli->out->elementEnd('li');
570 // FIXME: This is overriden in MicroAppPlugin but shouldn't have to be
571 public function onStartShowNoticeItem(NoticeListItem $nli)
573 if (!$this->isMyNotice($nli->notice)) {
578 $this->showNoticeListItem($nli);
579 } catch (Exception $e) {
580 $nli->out->element('p', 'error', 'Error showing notice: '.htmlspecialchars($e->getMessage()));
583 Event::handle('EndShowNoticeItem', array($nli));
587 protected function showNoticeListItem(NoticeListItem $nli)
590 $nli->showNoticeAttachments();
591 $nli->showNoticeInfo();
592 $nli->showNoticeOptions();
594 $nli->showNoticeLink();
595 $nli->showNoticeSource();
596 $nli->showNoticeLocation();
600 $nli->showNoticeOptions();
603 public function onStartShowNoticeContent(Notice $stored, HTMLOutputter $out, Profile $scoped=null)
605 if (!$this->isMyNotice($stored)) {
609 $out->text($stored->getContent());