]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/activityhandlerplugin.php
c8a46ae5efc4b55d9523a9bf387dc6b7c66adc97
[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 function is deprecated and in the future, Notice::saveActivity
113      * should be called from onStartHandleFeedEntryWithProfile in this class.
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 (which will be deleted when all plugins are migrated).
125
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
130         return Notice::saveActivity($activity, $actor, $options);
131     }
132
133     /*
134      * This usually gets called from Notice::saveActivity after a Notice object has been created,
135      * so it contains a proper id and a uri for the object to be saved.
136      */
137     public function onStoreActivityObject(Activity $act, Notice $stored, array $options=array(), &$object) {
138         // $this->oldSaveNew is there during a migration period of plugins, to start using
139         // Notice::saveActivity instead of Notice::saveNew
140         if (!$this->isMyActivity($act) || isset($this->oldSaveNew)) {
141             return true;
142         }
143         $object = $this->saveObjectFromActivity($act, $stored, $options);
144         try {
145             $act->context->attention = array_merge($act->context->attention, $object->getAttentionArray());
146         } catch (Exception $e) {
147             common_debug('WARNING: Could not get attention list from object '.get_class($object).'!');
148         }
149         return false;
150     }
151
152     /**
153      * Given an existing Notice object, your plugin gets to
154      * figure out how to arrange it into an ActivityStreams
155      * object.
156      *
157      * This will be how your specialized notice gets output in
158      * Atom feeds and JSON-based ActivityStreams output, including
159      * account backup/restore and OStatus (PuSH and Salmon transports).
160      *
161      * You should be able to round-trip data from this format back
162      * through $this->saveNoticeFromActivity(). Where applicable, try
163      * to use existing ActivityStreams structures and object types,
164      * and consider interop with other compatible apps.
165      *
166      * All micro-app classes must override this method.
167      *
168      * @fixme this outputs an ActivityObject, not an Activity. Any compat issues?
169      *
170      * @param Notice $notice
171      *
172      * @return ActivityObject
173      */
174     abstract function activityObjectFromNotice(Notice $notice);
175
176     /**
177      * When a notice is deleted, you'll be called here for a chance
178      * to clean up any related resources.
179      *
180      * All micro-app classes must override this method.
181      *
182      * @param Notice $notice
183      */
184     abstract function deleteRelated(Notice $notice);
185
186     /**
187      * Called when generating Atom XML ActivityStreams output from an
188      * ActivityObject belonging to this plugin. Gives the plugin
189      * a chance to add custom output.
190      *
191      * Note that you can only add output of additional XML elements,
192      * not change existing stuff here.
193      *
194      * If output is already handled by the base Activity classes,
195      * you can leave this base implementation as a no-op.
196      *
197      * @param ActivityObject $obj
198      * @param XMLOutputter $out to add elements at end of object
199      */
200     function activityObjectOutputAtom(ActivityObject $obj, XMLOutputter $out)
201     {
202         // default is a no-op
203     }
204
205     /**
206      * Called when generating JSON ActivityStreams output from an
207      * ActivityObject belonging to this plugin. Gives the plugin
208      * a chance to add custom output.
209      *
210      * Modify the array contents to your heart's content, and it'll
211      * all get serialized out as JSON.
212      *
213      * If output is already handled by the base Activity classes,
214      * you can leave this base implementation as a no-op.
215      *
216      * @param ActivityObject $obj
217      * @param array &$out JSON-targeted array which can be modified
218      */
219     public function activityObjectOutputJson(ActivityObject $obj, array &$out)
220     {
221         // default is a no-op
222     }
223
224     /**
225      * When a notice is deleted, delete the related objects
226      * by calling the overridable $this->deleteRelated().
227      *
228      * @param Notice $notice Notice being deleted
229      *
230      * @return boolean hook value
231      */
232     function onNoticeDeleteRelated(Notice $notice)
233     {
234         if (!$this->isMyNotice($notice)) {
235             return true;
236         }
237
238         $this->deleteRelated($notice);
239     }
240
241     /**
242      * Render a notice as one of our objects
243      *
244      * @param Notice         $notice  Notice to render
245      * @param ActivityObject &$object Empty object to fill
246      *
247      * @return boolean hook value
248      */
249     function onStartActivityObjectFromNotice(Notice $notice, &$object)
250     {
251         if (!$this->isMyNotice($notice)) {
252             return true;
253         }
254
255         $object = $this->activityObjectFromNotice($notice);
256         return false;
257     }
258
259     /**
260      * Handle a posted object from PuSH
261      *
262      * @param Activity        $activity activity to handle
263      * @param Profile         $actor Profile for the feed
264      *
265      * @return boolean hook value
266      */
267     function onStartHandleFeedEntryWithProfile(Activity $activity, Profile $profile, &$notice)
268     {
269         if (!$this->isMyActivity($activity)) {
270             return true;
271         }
272
273         // We are guaranteed to get a Profile back from checkAuthorship (or it throws an exception)
274         $profile = ActivityUtils::checkAuthorship($activity, $profile);
275
276         $object = $activity->objects[0];
277
278         $options = array('uri' => $object->id,
279                          'url' => $object->link,
280                          'is_local' => Notice::REMOTE,
281                          'source' => 'ostatus');
282
283         $notice = $this->saveNoticeFromActivity($activity, $profile, $options);
284
285         return false;
286     }
287
288     /**
289      * Handle a posted object from Salmon
290      *
291      * @param Activity $activity activity to handle
292      * @param mixed    $target   user or group targeted
293      *
294      * @return boolean hook value
295      */
296
297     function onStartHandleSalmonTarget(Activity $activity, $target)
298     {
299         if (!$this->isMyActivity($activity)) {
300             return true;
301         }
302
303         $this->log(LOG_INFO, "Checking {$activity->id} as a valid Salmon slap.");
304
305         if ($target instanceof User_group) {
306             $uri = $target->getUri();
307             if (!array_key_exists($uri, $activity->context->attention)) {
308                 // @todo FIXME: please document (i18n).
309                 // TRANS: Client exception thrown when ...
310                 throw new ClientException(_('Object not posted to this group.'));
311             }
312         } else if ($target instanceof User) {
313             $uri      = $target->uri;
314             $original = null;
315             if (!empty($activity->context->replyToID)) {
316                 $original = Notice::getKV('uri', $activity->context->replyToID);
317             }
318             if (!array_key_exists($uri, $activity->context->attention) &&
319                 (empty($original) ||
320                  $original->profile_id != $target->id)) {
321                 // @todo FIXME: Please document (i18n).
322                 // TRANS: Client exception when ...
323                 throw new ClientException(_('Object not posted to this user.'));
324             }
325         } else {
326             // TRANS: Server exception thrown when a micro app plugin uses a target that cannot be handled.
327             throw new ServerException(_('Do not know how to handle this kind of target.'));
328         }
329
330         $actor = Ostatus_profile::ensureActivityObjectProfile($activity->actor);
331
332         $object = $activity->objects[0];
333
334         $options = array('uri' => $object->id,
335                          'url' => $object->link,
336                          'is_local' => Notice::REMOTE,
337                          'source' => 'ostatus');
338
339         // $actor is an ostatus_profile
340         $this->saveNoticeFromActivity($activity, $actor->localProfile(), $options);
341
342         return false;
343     }
344
345     /**
346      * Handle object posted via AtomPub
347      *
348      * @param Activity &$activity Activity that was posted
349      * @param User     $user      User that posted it
350      * @param Notice   &$notice   Resulting notice
351      *
352      * @return boolean hook value
353      */
354     function onStartAtomPubNewActivity(Activity &$activity, $user, &$notice)
355     {
356         if (!$this->isMyActivity($activity)) {
357             return true;
358         }
359
360         $options = array('source' => 'atompub');
361
362         // $user->getProfile() is a Profile
363         $notice = $this->saveNoticeFromActivity($activity,
364                                                 $user->getProfile(),
365                                                 $options);
366
367         return false;
368     }
369
370     /**
371      * Handle object imported from a backup file
372      *
373      * @param User           $user     User to import for
374      * @param ActivityObject $author   Original author per import file
375      * @param Activity       $activity Activity to import
376      * @param boolean        $trusted  Is this a trusted user?
377      * @param boolean        &$done    Is this done (success or unrecoverable error)
378      *
379      * @return boolean hook value
380      */
381     function onStartImportActivity($user, $author, Activity $activity, $trusted, &$done)
382     {
383         if (!$this->isMyActivity($activity)) {
384             return true;
385         }
386
387         $obj = $activity->objects[0];
388
389         $options = array('uri' => $object->id,
390                          'url' => $object->link,
391                          'source' => 'restore');
392
393         // $user->getProfile() is a Profile
394         $saved = $this->saveNoticeFromActivity($activity,
395                                                $user->getProfile(),
396                                                $options);
397
398         if (!empty($saved)) {
399             $done = true;
400         }
401
402         return false;
403     }
404
405     /**
406      * Event handler gives the plugin a chance to add custom
407      * Atom XML ActivityStreams output from a previously filled-out
408      * ActivityObject.
409      *
410      * The atomOutput method is called if it's one of
411      * our matching types.
412      *
413      * @param ActivityObject $obj
414      * @param XMLOutputter $out to add elements at end of object
415      * @return boolean hook return value
416      */
417     function onEndActivityObjectOutputAtom(ActivityObject $obj, XMLOutputter $out)
418     {
419         if (in_array($obj->type, $this->types())) {
420             $this->activityObjectOutputAtom($obj, $out);
421         }
422         return true;
423     }
424
425     /**
426      * Event handler gives the plugin a chance to add custom
427      * JSON ActivityStreams output from a previously filled-out
428      * ActivityObject.
429      *
430      * The activityObjectOutputJson method is called if it's one of
431      * our matching types.
432      *
433      * @param ActivityObject $obj
434      * @param array &$out JSON-targeted array which can be modified
435      * @return boolean hook return value
436      */
437     function onEndActivityObjectOutputJson(ActivityObject $obj, array &$out)
438     {
439         if (in_array($obj->type, $this->types())) {
440             $this->activityObjectOutputJson($obj, $out);
441         }
442         return true;
443     }
444 }