]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/activityhandlerplugin.php
b826a705ace80dd80f2cfe39c12c05769398dcc2
[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      * 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(). 
38      *
39      * @return string (compatible with HTML classes)
40      */ 
41     abstract function tag();
42
43     /**
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.
49      *
50      * An empty list means any type is ok. (Favorite verb etc.)
51      *
52      * @return array of strings
53      */
54     abstract function types();
55
56     /**
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.
62      *
63      * All micro-app classes must override this method.
64      *
65      * @return array of strings
66      */
67     public function verbs() {
68         return array(ActivityVerb::POST);
69     }
70
71     /**
72      * Check if a given ActivityStreams activity should be handled by this
73      * micro-app plugin.
74      *
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.
79      *
80      * @param Activity $activity
81      * @return boolean
82      */
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));
88     }
89
90     /**
91      * Check if a given notice object should be handled by this micro-app
92      * plugin.
93      *
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.
97      *
98      * @param Notice $notice
99      * @return boolean
100      */
101     function isMyNotice(Notice $notice) {
102         return $this->isMyVerb($notice->verb) && $this->isMyType($notice->object_type);
103     }
104
105     function isMyVerb($verb) {
106         $verb = $verb ?: ActivityVerb::POST;    // post is the default verb
107         return ActivityUtils::compareVerbs($verb, $this->verbs());
108     }
109
110     function isMyType($type) {
111         return count($this->types())===0 || ActivityUtils::compareTypes($type, $this->types());
112     }
113
114     /**
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.
118      *
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).
122      *
123      * @param Activity $activity
124      * @param Profile $actor
125      * @param array $options=array()
126      *
127      * @return Notice the resulting notice
128      */
129     public function saveNoticeFromActivity(Activity $activity, Profile $actor, array $options=array())
130     {
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).
134
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');
137         }
138
139         return Notice::saveActivity($activity, $actor, $options);
140     }
141
142     /**
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.
146     *
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.
151     *
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.
157     *
158     * All micro-app classes must override this method.
159     *
160     * @fixme are there any standard options?
161     *
162     * @param Activity $activity
163     * @param Notice   $stored       The notice in our database for this certain object
164     * @param array $options=array()
165     *
166     * @return object    If the verb handling plugin creates an object, it can be returned here (otherwise true)
167     * @throws exception On any error.
168     */
169     protected function saveObjectFromActivity(Activity $activity, Notice $stored, array $options=array())
170     {
171         throw new ServerException('This function should be abstract when all plugins have migrated to saveObjectFromActivity');
172     }
173
174     /*
175      * This usually gets called from Notice::saveActivity after a Notice object has been created,
176      * so it contains a proper id and a uri for the object to be saved.
177      */
178     public function onStoreActivityObject(Activity $act, Notice $stored, array $options, &$object) {
179         // $this->oldSaveNew is there during a migration period of plugins, to start using
180         // Notice::saveActivity instead of Notice::saveNew
181         if (!$this->isMyActivity($act) || isset($this->oldSaveNew)) {
182             return true;
183         }
184         $object = $this->saveObjectFromActivity($act, $stored, $options);
185         try {
186             // In the future we probably want to use something like ActivityVerb_DataObject for the kind
187             // of objects which are returned from saveObjectFromActivity.
188             if ($object instanceof Managed_DataObject) {
189                 // If the verb handling plugin figured out some more attention URIs, add them here to the
190                 // original activity. This is only done if a separate object is actually needed to be saved.
191                 $act->context->attention = array_merge($act->context->attention, $object->getAttentionArray());
192             }
193         } catch (Exception $e) {
194             common_debug('WARNING: Could not get attention list from object '.get_class($object).'!');
195         }
196         return false;
197     }
198
199     /**
200      * Given an existing Notice object, your plugin gets to
201      * figure out how to arrange it into an ActivityStreams
202      * object.
203      *
204      * This will be how your specialized notice gets output in
205      * Atom feeds and JSON-based ActivityStreams output, including
206      * account backup/restore and OStatus (PuSH and Salmon transports).
207      *
208      * You should be able to round-trip data from this format back
209      * through $this->saveNoticeFromActivity(). Where applicable, try
210      * to use existing ActivityStreams structures and object types,
211      * and consider interop with other compatible apps.
212      *
213      * All micro-app classes must override this method.
214      *
215      * @fixme this outputs an ActivityObject, not an Activity. Any compat issues?
216      *
217      * @param Notice $notice
218      *
219      * @return ActivityObject
220      */
221     abstract function activityObjectFromNotice(Notice $notice);
222
223     /**
224      * When a notice is deleted, you'll be called here for a chance
225      * to clean up any related resources.
226      *
227      * All micro-app classes must override this method.
228      *
229      * @param Notice $notice
230      */
231     abstract function deleteRelated(Notice $notice);
232
233     protected function notifyMentioned(Notice $stored, array &$mentioned_ids)
234     {
235         // pass through silently by default
236
237         // If we want to stop any other plugin from notifying based on this activity, return false instead.
238         return true;
239     }
240
241     /**
242      * Called when generating Atom XML ActivityStreams output from an
243      * ActivityObject belonging to this plugin. Gives the plugin
244      * a chance to add custom output.
245      *
246      * Note that you can only add output of additional XML elements,
247      * not change existing stuff here.
248      *
249      * If output is already handled by the base Activity classes,
250      * you can leave this base implementation as a no-op.
251      *
252      * @param ActivityObject $obj
253      * @param XMLOutputter $out to add elements at end of object
254      */
255     function activityObjectOutputAtom(ActivityObject $obj, XMLOutputter $out)
256     {
257         // default is a no-op
258     }
259
260     /**
261      * Called when generating JSON ActivityStreams output from an
262      * ActivityObject belonging to this plugin. Gives the plugin
263      * a chance to add custom output.
264      *
265      * Modify the array contents to your heart's content, and it'll
266      * all get serialized out as JSON.
267      *
268      * If output is already handled by the base Activity classes,
269      * you can leave this base implementation as a no-op.
270      *
271      * @param ActivityObject $obj
272      * @param array &$out JSON-targeted array which can be modified
273      */
274     public function activityObjectOutputJson(ActivityObject $obj, array &$out)
275     {
276         // default is a no-op
277     }
278
279     /**
280      * When a notice is deleted, delete the related objects
281      * by calling the overridable $this->deleteRelated().
282      *
283      * @param Notice $notice Notice being deleted
284      *
285      * @return boolean hook value
286      */
287     public function onNoticeDeleteRelated(Notice $notice)
288     {
289         if ($this->isMyNotice($notice)) {
290             try {
291                 $this->deleteRelated($notice);
292             } catch (AlreadyFulfilledException $e) {
293                 // Nothing to see here, it's obviously already gone...
294             }
295         }
296
297         // Always continue this event in our activity handling plugins.
298         return true;
299     }
300
301     /**
302      * @param Notice $stored            The notice being distributed
303      * @param array  &$mentioned_ids    List of profiles (from $stored->getReplies())
304      */
305     public function onStartNotifyMentioned(Notice $stored, array &$mentioned_ids)
306     {
307         if (!$this->isMyNotice($stored)) {
308             return true;
309         }
310
311         return $this->notifyMentioned($stored, $mentioned_ids);
312     }
313
314     /**
315      * Render a notice as one of our objects
316      *
317      * @param Notice         $notice  Notice to render
318      * @param ActivityObject &$object Empty object to fill
319      *
320      * @return boolean hook value
321      */
322     function onStartActivityObjectFromNotice(Notice $notice, &$object)
323     {
324         if (!$this->isMyNotice($notice)) {
325             return true;
326         }
327
328         $object = $this->activityObjectFromNotice($notice);
329         return false;
330     }
331
332     /**
333      * Handle a posted object from PuSH
334      *
335      * @param Activity        $activity activity to handle
336      * @param Profile         $actor Profile for the feed
337      *
338      * @return boolean hook value
339      */
340     function onStartHandleFeedEntryWithProfile(Activity $activity, Profile $profile, &$notice)
341     {
342         if (!$this->isMyActivity($activity)) {
343             return true;
344         }
345
346         // We are guaranteed to get a Profile back from checkAuthorship (or it throws an exception)
347         $profile = ActivityUtils::checkAuthorship($activity, $profile);
348
349         $object = $activity->objects[0];
350
351         $options = array('uri' => $object->id,
352                          'url' => $object->link,
353                          'is_local' => Notice::REMOTE,
354                          'source' => 'ostatus');
355
356         if (!isset($this->oldSaveNew)) {
357             $notice = Notice::saveActivity($activity, $profile, $options);
358         } else {
359             $notice = $this->saveNoticeFromActivity($activity, $profile, $options);
360         }
361
362         return false;
363     }
364
365     /**
366      * Handle a posted object from Salmon
367      *
368      * @param Activity $activity activity to handle
369      * @param mixed    $target   user or group targeted
370      *
371      * @return boolean hook value
372      */
373
374     function onStartHandleSalmonTarget(Activity $activity, $target)
375     {
376         if (!$this->isMyActivity($activity)) {
377             return true;
378         }
379         if (!isset($this->oldSaveNew)) {
380             // Handle saveActivity in OStatus class for incoming salmon, remove this event
381             // handler when all plugins have gotten rid of "oldSaveNew".
382             return true;
383         }
384
385         $this->log(LOG_INFO, get_called_class()." checking {$activity->id} as a valid Salmon slap.");
386
387         if ($target instanceof User_group || $target->isGroup()) {
388             $uri = $target->getUri();
389             if (!array_key_exists($uri, $activity->context->attention)) {
390                 // @todo FIXME: please document (i18n).
391                 // TRANS: Client exception thrown when ...
392                 throw new ClientException(_('Object not posted to this group.'));
393             }
394         } elseif ($target instanceof Profile && $target->isLocal()) {
395             $original = null;
396             // FIXME: Shouldn't favorites show up with a 'target' activityobject?
397             if (!ActivityUtils::compareVerbs($activity->verb, array(ActivityVerb::POST)) && isset($activity->objects[0])) {
398                 // If this is not a post, it's a verb targeted at something (such as a Favorite attached to a note)
399                 if (!empty($activity->objects[0]->id)) {
400                     $activity->context->replyToID = $activity->objects[0]->id;
401                 }
402             }
403             if (!empty($activity->context->replyToID)) {
404                 $original = Notice::getKV('uri', $activity->context->replyToID);
405             }
406             if ((!$original instanceof Notice || $original->profile_id != $target->id)
407                     && !array_key_exists($target->getUri(), $activity->context->attention)) {
408                 // @todo FIXME: Please document (i18n).
409                 // TRANS: Client exception when ...
410                 throw new ClientException(_('Object not posted to this user.'));
411             }
412         } else {
413             // TRANS: Server exception thrown when a micro app plugin uses a target that cannot be handled.
414             throw new ServerException(_('Do not know how to handle this kind of target.'));
415         }
416
417         $oactor = Ostatus_profile::ensureActivityObjectProfile($activity->actor);
418         $actor = $oactor->localProfile();
419
420         // FIXME: will this work in all cases? I made it work for Favorite...
421         if (ActivityUtils::compareVerbs($activity->verb, array(ActivityVerb::POST))) {
422             $object = $activity->objects[0];
423         } else {
424             $object = $activity;
425         }
426
427         $options = array('uri' => $object->id,
428                          'url' => $object->link,
429                          'is_local' => Notice::REMOTE,
430                          'source' => 'ostatus');
431
432         $notice = $this->saveNoticeFromActivity($activity, $actor, $options);
433
434         return false;
435     }
436
437     /**
438      * Handle object posted via AtomPub
439      *
440      * @param Activity  $activity Activity that was posted
441      * @param Profile   $scoped   Profile of user posting
442      * @param Notice   &$notice   Resulting notice
443      *
444      * @return boolean hook value
445      */
446     public function onStartAtomPubNewActivity(Activity $activity, Profile $scoped, Notice &$notice=null)
447     {
448         if (!$this->isMyActivity($activity)) {
449             return true;
450         }
451
452         $options = array('source' => 'atompub');
453
454         $notice = $this->saveNoticeFromActivity($activity, $scoped, $options);
455
456         return false;
457     }
458
459     /**
460      * Handle object imported from a backup file
461      *
462      * @param User           $user     User to import for
463      * @param ActivityObject $author   Original author per import file
464      * @param Activity       $activity Activity to import
465      * @param boolean        $trusted  Is this a trusted user?
466      * @param boolean        &$done    Is this done (success or unrecoverable error)
467      *
468      * @return boolean hook value
469      */
470     function onStartImportActivity($user, $author, Activity $activity, $trusted, &$done)
471     {
472         if (!$this->isMyActivity($activity)) {
473             return true;
474         }
475
476         $obj = $activity->objects[0];
477
478         $options = array('uri' => $object->id,
479                          'url' => $object->link,
480                          'source' => 'restore');
481
482         // $user->getProfile() is a Profile
483         $saved = $this->saveNoticeFromActivity($activity,
484                                                $user->getProfile(),
485                                                $options);
486
487         if (!empty($saved)) {
488             $done = true;
489         }
490
491         return false;
492     }
493
494     /**
495      * Event handler gives the plugin a chance to add custom
496      * Atom XML ActivityStreams output from a previously filled-out
497      * ActivityObject.
498      *
499      * The atomOutput method is called if it's one of
500      * our matching types.
501      *
502      * @param ActivityObject $obj
503      * @param XMLOutputter $out to add elements at end of object
504      * @return boolean hook return value
505      */
506     function onEndActivityObjectOutputAtom(ActivityObject $obj, XMLOutputter $out)
507     {
508         if (in_array($obj->type, $this->types())) {
509             $this->activityObjectOutputAtom($obj, $out);
510         }
511         return true;
512     }
513
514     /**
515      * Event handler gives the plugin a chance to add custom
516      * JSON ActivityStreams output from a previously filled-out
517      * ActivityObject.
518      *
519      * The activityObjectOutputJson method is called if it's one of
520      * our matching types.
521      *
522      * @param ActivityObject $obj
523      * @param array &$out JSON-targeted array which can be modified
524      * @return boolean hook return value
525      */
526     function onEndActivityObjectOutputJson(ActivityObject $obj, array &$out)
527     {
528         if (in_array($obj->type, $this->types())) {
529             $this->activityObjectOutputJson($obj, $out);
530         }
531         return true;
532     }
533
534     public function onStartOpenNoticeListItemElement(NoticeListItem $nli)
535     {   
536         if (!$this->isMyNotice($nli->notice)) {
537             return true;
538         }
539
540         $this->openNoticeListItemElement($nli);
541
542         Event::handle('EndOpenNoticeListItemElement', array($nli));
543         return false;
544     }
545
546     public function onStartCloseNoticeListItemElement(NoticeListItem $nli)
547     {   
548         if (!$this->isMyNotice($nli->notice)) {
549             return true;
550         }
551
552         $this->closeNoticeListItemElement($nli);
553
554         Event::handle('EndCloseNoticeListItemElement', array($nli));
555         return false;
556     }
557
558     protected function openNoticeListItemElement(NoticeListItem $nli)
559     {
560         $id = (empty($nli->repeat)) ? $nli->notice->id : $nli->repeat->id;
561         $class = 'h-entry notice ' . $this->tag();
562         if ($nli->notice->scope != 0 && $nli->notice->scope != 1) {
563             $class .= ' limited-scope';
564         }
565         $nli->out->elementStart('li', array('class' => $class,
566                                             'id' => 'notice-' . $id));
567     }
568
569     protected function closeNoticeListItemElement(NoticeListItem $nli)
570     {
571         $nli->out->elementEnd('li');
572     }
573
574
575     // FIXME: This is overriden in MicroAppPlugin but shouldn't have to be
576     public function onStartShowNoticeItem(NoticeListItem $nli)
577     {   
578         if (!$this->isMyNotice($nli->notice)) {
579             return true;
580         }
581
582         try {
583             $this->showNoticeListItem($nli);
584         } catch (Exception $e) {
585             common_log(LOG_ERR, 'Error showing notice '.$nli->getNotice()->getID().': ' . $e->getMessage());
586             $nli->out->element('p', 'error', sprintf(_('Error showing notice: %s'), $e->getMessage()));
587         }
588
589         Event::handle('EndShowNoticeItem', array($nli));
590         return false;
591     }
592
593     protected function showNoticeListItem(NoticeListItem $nli)
594     {
595         $nli->showNoticeHeaders();
596         $nli->showContent();
597         $nli->showNoticeFooter();
598     }
599
600     public function onStartShowNoticeItemNotice(NoticeListItem $nli)
601     {
602         if (!$this->isMyNotice($nli->notice)) {
603             return true;
604         }
605
606         $this->showNoticeItemNotice($nli);
607
608         Event::handle('EndShowNoticeItemNotice', array($nli));
609         return false;
610     }
611
612     protected function showNoticeItemNotice(NoticeListItem $nli)
613     {
614         $nli->showNoticeTitle();
615         $nli->showAuthor();
616         $nli->showAddressees();
617         $nli->showContent();
618     }
619
620     public function onStartShowNoticeContent(Notice $stored, HTMLOutputter $out, Profile $scoped=null)
621     {
622         if (!$this->isMyNotice($stored)) {
623             return true;
624         }
625
626         try {
627             $this->showNoticeContent($stored, $out, $scoped);
628         } catch (Exception $e) {
629             $out->element('div', 'error', $e->getMessage());
630         }
631         return false;
632     }
633
634     protected function showNoticeContent(Notice $stored, HTMLOutputter $out, Profile $scoped=null)
635     {
636         $out->text($stored->getContent());
637     }
638 }