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