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