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