]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/activityhandlerplugin.php
Favorites are now being stored from activities
[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      * (which instead turns to saveObjectFromActivity).
115      *
116      * @param Activity $activity
117      * @param Profile $actor
118      * @param array $options=array()
119      *
120      * @return Notice the resulting notice
121      */
122     public function saveNoticeFromActivity(Activity $activity, Profile $actor, array $options=array())
123     {
124         // Any plugin which has not implemented saveObjectFromActivity _must_
125         // override this function until they are migrated (this function will
126         // be deleted when all plugins are migrated to saveObjectFromActivity).
127
128         if (isset($this->oldSaveNew)) {
129             throw new ServerException('A function has been called for new saveActivity functionality, but is still set with an oldSaveNew configuration');
130         }
131
132         return Notice::saveActivity($activity, $actor, $options);
133     }
134
135     /**
136     * Given a parsed ActivityStreams activity, your plugin gets
137     * to figure out itself how to store the additional data into
138     * the database, besides the base data stored by the core.
139     *
140     * This will handle just about all events where an activity
141     * object gets saved, whether it is via AtomPub, OStatus
142     * (PuSH and Salmon transports), or ActivityStreams-based
143     * backup/restore of account data.
144     *
145     * You should be able to accept as input the output from an
146     * asActivity() call on the stored object. Where applicable,
147     * try to use existing ActivityStreams structures and object
148     * types, and be liberal in accepting input from what might
149     * be other compatible apps.
150     *
151     * All micro-app classes must override this method.
152     *
153     * @fixme are there any standard options?
154     *
155     * @param Activity $activity
156     * @param Profile $actor
157     * @param array $options=array()
158     *
159     * @return Notice the resulting notice
160     */
161     protected function saveObjectFromActivity(Activity $activity, Notice $stored, array $options=array())
162     {
163         throw new ServerException('This function should be abstract when all plugins have migrated to saveObjectFromActivity');
164     }
165
166     /*
167      * This usually gets called from Notice::saveActivity after a Notice object has been created,
168      * so it contains a proper id and a uri for the object to be saved.
169      */
170     public function onStoreActivityObject(Activity $act, Notice $stored, array $options=array(), &$object) {
171         // $this->oldSaveNew is there during a migration period of plugins, to start using
172         // Notice::saveActivity instead of Notice::saveNew
173         if (!$this->isMyActivity($act) || isset($this->oldSaveNew)) {
174             return true;
175         }
176         $object = $this->saveObjectFromActivity($act, $stored, $options);
177         try {
178             $act->context->attention = array_merge($act->context->attention, $object->getAttentionArray());
179         } catch (Exception $e) {
180             common_debug('WARNING: Could not get attention list from object '.get_class($object).'!');
181         }
182         return false;
183     }
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     /**
210      * When a notice is deleted, you'll be called here for a chance
211      * to clean up any related resources.
212      *
213      * All micro-app classes must override this method.
214      *
215      * @param Notice $notice
216      */
217     abstract function deleteRelated(Notice $notice);
218
219     /**
220      * Called when generating Atom XML ActivityStreams output from an
221      * ActivityObject belonging to this plugin. Gives the plugin
222      * a chance to add custom output.
223      *
224      * Note that you can only add output of additional XML elements,
225      * not change existing stuff here.
226      *
227      * If output is already handled by the base Activity classes,
228      * you can leave this base implementation as a no-op.
229      *
230      * @param ActivityObject $obj
231      * @param XMLOutputter $out to add elements at end of object
232      */
233     function activityObjectOutputAtom(ActivityObject $obj, XMLOutputter $out)
234     {
235         // default is a no-op
236     }
237
238     /**
239      * Called when generating JSON ActivityStreams output from an
240      * ActivityObject belonging to this plugin. Gives the plugin
241      * a chance to add custom output.
242      *
243      * Modify the array contents to your heart's content, and it'll
244      * all get serialized out as JSON.
245      *
246      * If output is already handled by the base Activity classes,
247      * you can leave this base implementation as a no-op.
248      *
249      * @param ActivityObject $obj
250      * @param array &$out JSON-targeted array which can be modified
251      */
252     public function activityObjectOutputJson(ActivityObject $obj, array &$out)
253     {
254         // default is a no-op
255     }
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             return true;
269         }
270
271         $this->deleteRelated($notice);
272     }
273
274     /**
275      * Render a notice as one of our objects
276      *
277      * @param Notice         $notice  Notice to render
278      * @param ActivityObject &$object Empty object to fill
279      *
280      * @return boolean hook value
281      */
282     function onStartActivityObjectFromNotice(Notice $notice, &$object)
283     {
284         if (!$this->isMyNotice($notice)) {
285             return true;
286         }
287
288         try {
289             $object = $this->activityObjectFromNotice($notice);
290         } catch (NoResultException $e) {
291             $object = null; // because getKV returns null on failure
292         }
293         return false;
294     }
295
296     /**
297      * Handle a posted object from PuSH
298      *
299      * @param Activity        $activity activity to handle
300      * @param Profile         $actor Profile for the feed
301      *
302      * @return boolean hook value
303      */
304     function onStartHandleFeedEntryWithProfile(Activity $activity, Profile $profile, &$notice)
305     {
306         if (!$this->isMyActivity($activity)) {
307             return true;
308         }
309
310         // We are guaranteed to get a Profile back from checkAuthorship (or it throws an exception)
311         $profile = ActivityUtils::checkAuthorship($activity, $profile);
312
313         $object = $activity->objects[0];
314
315         $options = array('uri' => $object->id,
316                          'url' => $object->link,
317                          'is_local' => Notice::REMOTE,
318                          'source' => 'ostatus');
319
320         if (!isset($this->oldSaveNew)) {
321             $notice = Notice::saveActivity($activity, $profile, $options);
322         } else {
323             $notice = $this->saveNoticeFromActivity($activity, $profile, $options);
324         }
325
326         return false;
327     }
328
329     /**
330      * Handle a posted object from Salmon
331      *
332      * @param Activity $activity activity to handle
333      * @param mixed    $target   user or group targeted
334      *
335      * @return boolean hook value
336      */
337
338     function onStartHandleSalmonTarget(Activity $activity, $target)
339     {
340         if (!$this->isMyActivity($activity)) {
341             return true;
342         }
343
344         $this->log(LOG_INFO, "Checking {$activity->id} as a valid Salmon slap.");
345
346         if ($target instanceof User_group || $target->isGroup()) {
347             $uri = $target->getUri();
348             if (!array_key_exists($uri, $activity->context->attention)) {
349                 // @todo FIXME: please document (i18n).
350                 // TRANS: Client exception thrown when ...
351                 throw new ClientException(_('Object not posted to this group.'));
352             }
353         } elseif ($target instanceof Profile && $target->isLocal()) {
354             common_debug(get_called_class() . ' got a salmon slap against target profile ID: '.$target->id);
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
377         common_debug(get_called_class() . ' ensuring ActivityObject profile for '.$activity->actor->id);
378         $actor = Ostatus_profile::ensureActivityObjectProfile($activity->actor);
379
380         // FIXME: will this work in all cases? I made it work for Favorite...
381         if (ActivityUtils::compareTypes($activity->verb, array(ActivityVerb::POST))) {
382             $object = $activity->objects[0];
383         } else {
384             $object = $activity;
385         }
386
387         $options = array('uri' => $object->id,
388                          'url' => $object->link,
389                          'is_local' => Notice::REMOTE,
390                          'source' => 'ostatus');
391
392         // $actor is an ostatus_profile
393         common_debug(get_called_class() . ' going to save notice from activity!');
394         if (!isset($this->oldSaveNew)) {
395             $notice = Notice::saveActivity($activity, $target, $options);
396         } else {
397             $notice = $this->saveNoticeFromActivity($activity, $target, $options);
398         }
399
400         return false;
401     }
402
403     /**
404      * Handle object posted via AtomPub
405      *
406      * @param Activity &$activity Activity that was posted
407      * @param User     $user      User that posted it
408      * @param Notice   &$notice   Resulting notice
409      *
410      * @return boolean hook value
411      */
412     function onStartAtomPubNewActivity(Activity &$activity, $user, &$notice)
413     {
414         if (!$this->isMyActivity($activity)) {
415             return true;
416         }
417
418         $options = array('source' => 'atompub');
419
420         // $user->getProfile() is a Profile
421         $notice = $this->saveNoticeFromActivity($activity,
422                                                 $user->getProfile(),
423                                                 $options);
424
425         return false;
426     }
427
428     /**
429      * Handle object imported from a backup file
430      *
431      * @param User           $user     User to import for
432      * @param ActivityObject $author   Original author per import file
433      * @param Activity       $activity Activity to import
434      * @param boolean        $trusted  Is this a trusted user?
435      * @param boolean        &$done    Is this done (success or unrecoverable error)
436      *
437      * @return boolean hook value
438      */
439     function onStartImportActivity($user, $author, Activity $activity, $trusted, &$done)
440     {
441         if (!$this->isMyActivity($activity)) {
442             return true;
443         }
444
445         $obj = $activity->objects[0];
446
447         $options = array('uri' => $object->id,
448                          'url' => $object->link,
449                          'source' => 'restore');
450
451         // $user->getProfile() is a Profile
452         $saved = $this->saveNoticeFromActivity($activity,
453                                                $user->getProfile(),
454                                                $options);
455
456         if (!empty($saved)) {
457             $done = true;
458         }
459
460         return false;
461     }
462
463     /**
464      * Event handler gives the plugin a chance to add custom
465      * Atom XML ActivityStreams output from a previously filled-out
466      * ActivityObject.
467      *
468      * The atomOutput method is called if it's one of
469      * our matching types.
470      *
471      * @param ActivityObject $obj
472      * @param XMLOutputter $out to add elements at end of object
473      * @return boolean hook return value
474      */
475     function onEndActivityObjectOutputAtom(ActivityObject $obj, XMLOutputter $out)
476     {
477         if (in_array($obj->type, $this->types())) {
478             $this->activityObjectOutputAtom($obj, $out);
479         }
480         return true;
481     }
482
483     /**
484      * Event handler gives the plugin a chance to add custom
485      * JSON ActivityStreams output from a previously filled-out
486      * ActivityObject.
487      *
488      * The activityObjectOutputJson method is called if it's one of
489      * our matching types.
490      *
491      * @param ActivityObject $obj
492      * @param array &$out JSON-targeted array which can be modified
493      * @return boolean hook return value
494      */
495     function onEndActivityObjectOutputJson(ActivityObject $obj, array &$out)
496     {
497         if (in_array($obj->type, $this->types())) {
498             $this->activityObjectOutputJson($obj, $out);
499         }
500         return true;
501     }
502 }