]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/activityhandlerplugin.php
Moved functions into ActivityHandlerPlugin from MicroAppPlugin
[quix0rs-gnu-social.git] / lib / activityhandlerplugin.php
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
20 if (!defined('GNUSOCIAL')) { exit(1); }
21
22 /**
23  * Superclass for plugins which add Activity types and such
24  *
25  * @category  Activity
26  * @package   GNUsocial
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
31  */
32 abstract class ActivityHandlerPlugin extends Plugin
33 {
34     /**
35      * Return a list of ActivityStreams object type IRIs
36      * which this micro-app handles. Default implementations
37      * of the base class will use this list to check if a
38      * given ActivityStreams object belongs to us, via
39      * $this->isMyNotice() or $this->isMyActivity.
40      *
41      * An empty list means any type is ok. (Favorite verb etc.)
42      *
43      * All micro-app classes must override this method.
44      *
45      * @return array of strings
46      */
47     abstract function types();
48
49     /**
50      * Return a list of ActivityStreams verb IRIs which
51      * this micro-app handles. Default implementations
52      * of the base class will use this list to check if a
53      * given ActivityStreams verb belongs to us, via
54      * $this->isMyNotice() or $this->isMyActivity.
55      *
56      * All micro-app classes must override this method.
57      *
58      * @return array of strings
59      */
60     function verbs() {
61         return array(ActivityVerb::POST);
62     }
63
64     /**
65      * Check if a given ActivityStreams activity should be handled by this
66      * micro-app plugin.
67      *
68      * The default implementation checks against the activity type list
69      * returned by $this->types(), and requires that exactly one matching
70      * object be present. You can override this method to expand
71      * your checks or to compare the activity's verb, etc.
72      *
73      * @param Activity $activity
74      * @return boolean
75      */
76     function isMyActivity(Activity $act) {
77         return (count($act->objects) == 1
78             && ($act->objects[0] instanceof ActivityObject)
79             && $this->isMyVerb($act->verb)
80             && $this->isMyType($act->objects[0]->type));
81     }
82
83     /**
84      * Check if a given notice object should be handled by this micro-app
85      * plugin.
86      *
87      * The default implementation checks against the activity type list
88      * returned by $this->types(). You can override this method to expand
89      * your checks, but follow the execution chain to get it right.
90      *
91      * @param Notice $notice
92      * @return boolean
93      */
94     function isMyNotice(Notice $notice) {
95         return $this->isMyVerb($notice->verb) && $this->isMyType($notice->object_type);
96     }
97
98     function isMyVerb($verb) {
99         $verb = $verb ?: ActivityVerb::POST;    // post is the default verb
100         return ActivityUtils::compareTypes($verb, $this->verbs());
101     }
102
103     function isMyType($type) {
104         return count($this->types())===0 || ActivityUtils::compareTypes($type, $this->types());
105     }
106
107     /**
108      * Given a parsed ActivityStreams activity, your plugin
109      * gets to figure out how to actually save it into a notice
110      * and any additional data structures you require.
111      *
112      * This will handle things received via AtomPub, OStatus
113      * (PuSH and Salmon transports), or ActivityStreams-based
114      * backup/restore of account data.
115      *
116      * You should be able to accept as input the output from your
117      * $this->activityObjectFromNotice(). Where applicable, try to
118      * use existing ActivityStreams structures and object types,
119      * and be liberal in accepting input from what might be other
120      * compatible apps.
121      *
122      * All micro-app classes must override this method.
123      *
124      * @fixme are there any standard options?
125      *
126      * @param Activity $activity
127      * @param Profile $actor
128      * @param array $options=array()
129      *
130      * @return Notice the resulting notice
131      */
132     abstract function saveNoticeFromActivity(Activity $activity, Profile $actor, array $options=array());
133
134     /**
135      * Given an existing Notice object, your plugin gets to
136      * figure out how to arrange it into an ActivityStreams
137      * object.
138      *
139      * This will be how your specialized notice gets output in
140      * Atom feeds and JSON-based ActivityStreams output, including
141      * account backup/restore and OStatus (PuSH and Salmon transports).
142      *
143      * You should be able to round-trip data from this format back
144      * through $this->saveNoticeFromActivity(). Where applicable, try
145      * to use existing ActivityStreams structures and object types,
146      * and consider interop with other compatible apps.
147      *
148      * All micro-app classes must override this method.
149      *
150      * @fixme this outputs an ActivityObject, not an Activity. Any compat issues?
151      *
152      * @param Notice $notice
153      *
154      * @return ActivityObject
155      */
156     abstract function activityObjectFromNotice(Notice $notice);
157
158     /**
159      * When a notice is deleted, you'll be called here for a chance
160      * to clean up any related resources.
161      *
162      * All micro-app classes must override this method.
163      *
164      * @param Notice $notice
165      */
166     abstract function deleteRelated(Notice $notice);
167
168     /**
169      * Called when generating Atom XML ActivityStreams output from an
170      * ActivityObject belonging to this plugin. Gives the plugin
171      * a chance to add custom output.
172      *
173      * Note that you can only add output of additional XML elements,
174      * not change existing stuff here.
175      *
176      * If output is already handled by the base Activity classes,
177      * you can leave this base implementation as a no-op.
178      *
179      * @param ActivityObject $obj
180      * @param XMLOutputter $out to add elements at end of object
181      */
182     function activityObjectOutputAtom(ActivityObject $obj, XMLOutputter $out)
183     {
184         // default is a no-op
185     }
186
187     /**
188      * Called when generating JSON ActivityStreams output from an
189      * ActivityObject belonging to this plugin. Gives the plugin
190      * a chance to add custom output.
191      *
192      * Modify the array contents to your heart's content, and it'll
193      * all get serialized out as JSON.
194      *
195      * If output is already handled by the base Activity classes,
196      * you can leave this base implementation as a no-op.
197      *
198      * @param ActivityObject $obj
199      * @param array &$out JSON-targeted array which can be modified
200      */
201     public function activityObjectOutputJson(ActivityObject $obj, array &$out)
202     {
203         // default is a no-op
204     }
205
206     /**
207      * When a notice is deleted, delete the related objects
208      * by calling the overridable $this->deleteRelated().
209      *
210      * @param Notice $notice Notice being deleted
211      *
212      * @return boolean hook value
213      */
214     function onNoticeDeleteRelated(Notice $notice)
215     {
216         if (!$this->isMyNotice($notice)) {
217             return true;
218         }
219
220         $this->deleteRelated($notice);
221     }
222
223     /**
224      * Render a notice as one of our objects
225      *
226      * @param Notice         $notice  Notice to render
227      * @param ActivityObject &$object Empty object to fill
228      *
229      * @return boolean hook value
230      */
231     function onStartActivityObjectFromNotice(Notice $notice, &$object)
232     {
233         if (!$this->isMyNotice($notice)) {
234             return true;
235         }
236
237         $object = $this->activityObjectFromNotice($notice);
238         return false;
239     }
240
241     /**
242      * Handle a posted object from PuSH
243      *
244      * @param Activity        $activity activity to handle
245      * @param Ostatus_profile $oprofile Profile for the feed
246      *
247      * @return boolean hook value
248      */
249     function onStartHandleFeedEntryWithProfile(Activity $activity, $oprofile, &$notice)
250     {
251         if (!$this->isMyActivity($activity)) {
252             return true;
253         }
254
255         $actor = $oprofile->checkAuthorship($activity);
256
257         if (!$actor instanceof Ostatus_profile) {
258             // TRANS: Client exception thrown when no author for an activity was found.
259             throw new ClientException(_('Cannot get author for activity.'));
260         }
261
262         $object = $activity->objects[0];
263
264         $options = array('uri' => $object->id,
265                          'url' => $object->link,
266                          'is_local' => Notice::REMOTE,
267                          'source' => 'ostatus');
268
269         // $actor is an ostatus_profile
270         $notice = $this->saveNoticeFromActivity($activity, $actor->localProfile(), $options);
271
272         return false;
273     }
274
275     /**
276      * Handle a posted object from Salmon
277      *
278      * @param Activity $activity activity to handle
279      * @param mixed    $target   user or group targeted
280      *
281      * @return boolean hook value
282      */
283
284     function onStartHandleSalmonTarget(Activity $activity, $target)
285     {
286         if (!$this->isMyActivity($activity)) {
287             return true;
288         }
289
290         $this->log(LOG_INFO, "Checking {$activity->id} as a valid Salmon slap.");
291
292         if ($target instanceof User_group) {
293             $uri = $target->getUri();
294             if (!array_key_exists($uri, $activity->context->attention)) {
295                 // @todo FIXME: please document (i18n).
296                 // TRANS: Client exception thrown when ...
297                 throw new ClientException(_('Object not posted to this group.'));
298             }
299         } else if ($target instanceof User) {
300             $uri      = $target->uri;
301             $original = null;
302             if (!empty($activity->context->replyToID)) {
303                 $original = Notice::getKV('uri', $activity->context->replyToID);
304             }
305             if (!array_key_exists($uri, $activity->context->attention) &&
306                 (empty($original) ||
307                  $original->profile_id != $target->id)) {
308                 // @todo FIXME: Please document (i18n).
309                 // TRANS: Client exception when ...
310                 throw new ClientException(_('Object not posted to this user.'));
311             }
312         } else {
313             // TRANS: Server exception thrown when a micro app plugin uses a target that cannot be handled.
314             throw new ServerException(_('Do not know how to handle this kind of target.'));
315         }
316
317         $actor = Ostatus_profile::ensureActivityObjectProfile($activity->actor);
318
319         $object = $activity->objects[0];
320
321         $options = array('uri' => $object->id,
322                          'url' => $object->link,
323                          'is_local' => Notice::REMOTE,
324                          'source' => 'ostatus');
325
326         // $actor is an ostatus_profile
327         $this->saveNoticeFromActivity($activity, $actor->localProfile(), $options);
328
329         return false;
330     }
331
332     /**
333      * Handle object posted via AtomPub
334      *
335      * @param Activity &$activity Activity that was posted
336      * @param User     $user      User that posted it
337      * @param Notice   &$notice   Resulting notice
338      *
339      * @return boolean hook value
340      */
341     function onStartAtomPubNewActivity(Activity &$activity, $user, &$notice)
342     {
343         if (!$this->isMyActivity($activity)) {
344             return true;
345         }
346
347         $options = array('source' => 'atompub');
348
349         // $user->getProfile() is a Profile
350         $notice = $this->saveNoticeFromActivity($activity,
351                                                 $user->getProfile(),
352                                                 $options);
353
354         return false;
355     }
356
357     /**
358      * Handle object imported from a backup file
359      *
360      * @param User           $user     User to import for
361      * @param ActivityObject $author   Original author per import file
362      * @param Activity       $activity Activity to import
363      * @param boolean        $trusted  Is this a trusted user?
364      * @param boolean        &$done    Is this done (success or unrecoverable error)
365      *
366      * @return boolean hook value
367      */
368     function onStartImportActivity($user, $author, Activity $activity, $trusted, &$done)
369     {
370         if (!$this->isMyActivity($activity)) {
371             return true;
372         }
373
374         $obj = $activity->objects[0];
375
376         $options = array('uri' => $object->id,
377                          'url' => $object->link,
378                          'source' => 'restore');
379
380         // $user->getProfile() is a Profile
381         $saved = $this->saveNoticeFromActivity($activity,
382                                                $user->getProfile(),
383                                                $options);
384
385         if (!empty($saved)) {
386             $done = true;
387         }
388
389         return false;
390     }
391
392     /**
393      * Event handler gives the plugin a chance to add custom
394      * Atom XML ActivityStreams output from a previously filled-out
395      * ActivityObject.
396      *
397      * The atomOutput method is called if it's one of
398      * our matching types.
399      *
400      * @param ActivityObject $obj
401      * @param XMLOutputter $out to add elements at end of object
402      * @return boolean hook return value
403      */
404     function onEndActivityObjectOutputAtom(ActivityObject $obj, XMLOutputter $out)
405     {
406         if (in_array($obj->type, $this->types())) {
407             $this->activityObjectOutputAtom($obj, $out);
408         }
409         return true;
410     }
411
412     /**
413      * Event handler gives the plugin a chance to add custom
414      * JSON ActivityStreams output from a previously filled-out
415      * ActivityObject.
416      *
417      * The activityObjectOutputJson method is called if it's one of
418      * our matching types.
419      *
420      * @param ActivityObject $obj
421      * @param array &$out JSON-targeted array which can be modified
422      * @return boolean hook return value
423      */
424     function onEndActivityObjectOutputJson(ActivityObject $obj, array &$out)
425     {
426         if (in_array($obj->type, $this->types())) {
427             $this->activityObjectOutputJson($obj, $out);
428         }
429         return true;
430     }
431 }