]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/microappplugin.php
Merge branch 'master' into 1.0.x
[quix0rs-gnu-social.git] / lib / microappplugin.php
1 <?php
2 /**
3  * StatusNet - the distributed open-source microblogging tool
4  * Copyright (C) 2011, StatusNet, Inc.
5  *
6  * Superclass for microapp plugin
7  *
8  * PHP version 5
9  *
10  * This program is free software: you can redistribute it and/or modify
11  * it under the terms of the GNU Affero General Public License as published by
12  * the Free Software Foundation, either version 3 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU Affero General Public License for more details.
19  *
20  * You should have received a copy of the GNU Affero General Public License
21  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
22  *
23  * @category  Microapp
24  * @package   StatusNet
25  * @author    Evan Prodromou <evan@status.net>
26  * @copyright 2011 StatusNet, Inc.
27  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
28  * @link      http://status.net/
29  */
30
31 if (!defined('STATUSNET')) {
32     // This check helps protect against security problems;
33     // your code file can't be executed directly from the web.
34     exit(1);
35 }
36
37 /**
38  * Superclass for microapp plugins
39  *
40  * This class lets you define micro-applications with different kinds of activities.
41  *
42  * The applications work more-or-less like other
43  *
44  * @category  Microapp
45  * @package   StatusNet
46  * @author    Evan Prodromou <evan@status.net>
47  * @copyright 2011 StatusNet, Inc.
48  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
49  * @link      http://status.net/
50  */
51 abstract class MicroAppPlugin extends Plugin
52 {
53     /**
54      * Returns a localized string which represents this micro-app,
55      * to be shown to users selecting what type of post to make.
56      * This is paired with the key string in $this->tag().
57      *
58      * All micro-app classes must override this method.
59      *
60      * @return string
61      */
62     abstract function appTitle();
63
64     /**
65      * Returns a key string which represents this micro-app in HTML
66      * ids etc, as when offering selection of what type of post to make.
67      * This is paired with the user-visible localizable $this->appTitle().
68      *
69      * All micro-app classes must override this method.
70      */
71     abstract function tag();
72
73     /**
74      * Return a list of ActivityStreams object type URIs
75      * which this micro-app handles. Default implementations
76      * of the base class will use this list to check if a
77      * given ActivityStreams object belongs to us, via
78      * $this->isMyNotice() or $this->isMyActivity.
79      *
80      * All micro-app classes must override this method.
81      *
82      * @fixme can we confirm that these types are the same
83      * for Atom and JSON streams? Any limitations or issues?
84      *
85      * @return array of strings
86      */
87     abstract function types();
88
89     /**
90      * Given a parsed ActivityStreams activity, your plugin
91      * gets to figure out how to actually save it into a notice
92      * and any additional data structures you require.
93      *
94      * This will handle things received via AtomPub, OStatus
95      * (PuSH and Salmon transports), or ActivityStreams-based
96      * backup/restore of account data.
97      *
98      * You should be able to accept as input the output from your
99      * $this->activityObjectFromNotice(). Where applicable, try to
100      * use existing ActivityStreams structures and object types,
101      * and be liberal in accepting input from what might be other
102      * compatible apps.
103      *
104      * All micro-app classes must override this method.
105      *
106      * @fixme are there any standard options?
107      *
108      * @param Activity $activity
109      * @param Profile $actor
110      * @param array $options=array()
111      *
112      * @return Notice the resulting notice
113      */
114     abstract function saveNoticeFromActivity($activity, $actor, $options=array());
115
116     /**
117      * Given an existing Notice object, your plugin gets to
118      * figure out how to arrange it into an ActivityStreams
119      * object.
120      *
121      * This will be how your specialized notice gets output in
122      * Atom feeds and JSON-based ActivityStreams output, including
123      * account backup/restore and OStatus (PuSH and Salmon transports).
124      *
125      * You should be able to round-trip data from this format back
126      * through $this->saveNoticeFromActivity(). Where applicable, try
127      * to use existing ActivityStreams structures and object types,
128      * and consider interop with other compatible apps.
129      *
130      * All micro-app classes must override this method.
131      *
132      * @fixme this outputs an ActivityObject, not an Activity. Any compat issues?
133      *
134      * @param Notice $notice
135      *
136      * @return ActivityObject
137      */
138     abstract function activityObjectFromNotice($notice);
139
140     /**
141      * When building the primary notice form, we'll fetch also some
142      * alternate forms for specialized types -- that's you!
143      *
144      * Return a custom Widget or Form object for the given output
145      * object, and it'll be included in the HTML output. Beware that
146      * your form may be initially hidden.
147      *
148      * All micro-app classes must override this method.
149      *
150      * @param HTMLOutputter $out
151      * @return Widget
152      */
153     abstract function entryForm($out);
154
155     /**
156      * When a notice is deleted, you'll be called here for a chance
157      * to clean up any related resources.
158      *
159      * All micro-app classes must override this method.
160      *
161      * @param Notice $notice
162      */
163     abstract function deleteRelated($notice);
164
165     /**
166      * Check if a given notice object should be handled by this micro-app
167      * plugin.
168      *
169      * The default implementation checks against the activity type list
170      * returned by $this->types(). You can override this method to expand
171      * your checks.
172      *
173      * @param Notice $notice
174      * @return boolean
175      */
176     function isMyNotice($notice) {
177         $types = $this->types();
178         return in_array($notice->object_type, $types);
179     }
180
181     /**
182      * Check if a given ActivityStreams activity should be handled by this
183      * micro-app plugin.
184      *
185      * The default implementation checks against the activity type list
186      * returned by $this->types(), and requires that exactly one matching
187      * object be present. You can override this method to expand
188      * your checks or to compare the activity's verb, etc.
189      *
190      * @param Activity $activity
191      * @return boolean
192      */
193     function isMyActivity($activity) {
194         $types = $this->types();
195         return (count($activity->objects) == 1 &&
196                 ($activity->objects[0] instanceof ActivityObject) &&
197                 in_array($activity->objects[0]->type, $types));
198     }
199
200     /**
201      * Called when generating Atom XML ActivityStreams output from an
202      * ActivityObject belonging to this plugin. Gives the plugin
203      * a chance to add custom output.
204      *
205      * Note that you can only add output of additional XML elements,
206      * not change existing stuff here.
207      *
208      * If output is already handled by the base Activity classes,
209      * you can leave this base implementation as a no-op.
210      *
211      * @param ActivityObject $obj
212      * @param XMLOutputter $out to add elements at end of object
213      */
214     function activityObjectOutputAtom(ActivityObject $obj, XMLOutputter $out)
215     {
216         // default is a no-op
217     }
218
219     /**
220      * Called when generating JSON ActivityStreams output from an
221      * ActivityObject belonging to this plugin. Gives the plugin
222      * a chance to add custom output.
223      *
224      * Modify the array contents to your heart's content, and it'll
225      * all get serialized out as JSON.
226      *
227      * If output is already handled by the base Activity classes,
228      * you can leave this base implementation as a no-op.
229      *
230      * @param ActivityObject $obj
231      * @param array &$out JSON-targeted array which can be modified
232      */
233     public function activityObjectOutputJson(ActivityObject $obj, array &$out)
234     {
235         // default is a no-op
236     }
237
238     /**
239      * When a notice is deleted, delete the related objects
240      * by calling the overridable $this->deleteRelated().
241      *
242      * @param Notice $notice Notice being deleted
243      *
244      * @return boolean hook value
245      */
246     function onNoticeDeleteRelated($notice)
247     {
248         if ($this->isMyNotice($notice)) {
249             $this->deleteRelated($notice);
250         }
251
252         return true;
253     }
254
255     /**
256      * Output the HTML for this kind of object in a list
257      *
258      * @param NoticeListItem $nli The list item being shown.
259      *
260      * @return boolean hook value
261      *
262      * @fixme WARNING WARNING WARNING this closes a 'div' that is implicitly opened in BookmarkPlugin's showNotice implementation
263      */
264     function onStartShowNoticeItem($nli)
265     {
266         if (!$this->isMyNotice($nli->notice)) {
267             return true;
268         }
269
270         $adapter = $this->adaptNoticeListItem($nli);
271
272         if (!empty($adapter)) {
273             $adapter->showNotice();
274             $adapter->showNoticeAttachments();
275             $adapter->showNoticeInfo();
276             $adapter->showNoticeOptions();
277         } else {
278             $this->oldShowNotice($nli);
279         }
280
281         return false;
282     }
283
284     /**
285      * Given a notice list item, returns an adapter specific
286      * to this plugin.
287      *
288      * @param NoticeListItem $nli item to adapt
289      *
290      * @return NoticeListItemAdapter adapter or null
291      */
292     function adaptNoticeListItem($nli)
293     {
294       return null;
295     }
296
297     function oldShowNotice($nli)
298     {
299         $out = $nli->out;
300         $notice = $nli->notice;
301
302         try {
303             $this->showNotice($notice, $out);
304         } catch (Exception $e) {
305             common_log(LOG_ERR, $e->getMessage());
306             // try to fall back
307             $out->elementStart('div');
308             $nli->showAuthor();
309             $nli->showContent();
310         }
311
312         $nli->showNoticeLink();
313         $nli->showNoticeSource();
314         $nli->showNoticeLocation();
315         $nli->showContext();
316         $nli->showRepeat();
317
318         $out->elementEnd('div');
319
320         $nli->showNoticeOptions();
321     }
322
323     /**
324      * Render a notice as one of our objects
325      *
326      * @param Notice         $notice  Notice to render
327      * @param ActivityObject &$object Empty object to fill
328      *
329      * @return boolean hook value
330      */
331     function onStartActivityObjectFromNotice($notice, &$object)
332     {
333         if ($this->isMyNotice($notice)) {
334             $object = $this->activityObjectFromNotice($notice);
335             return false;
336         }
337
338         return true;
339     }
340
341     /**
342      * Handle a posted object from PuSH
343      *
344      * @param Activity        $activity activity to handle
345      * @param Ostatus_profile $oprofile Profile for the feed
346      *
347      * @return boolean hook value
348      */
349     function onStartHandleFeedEntryWithProfile($activity, $oprofile, &$notice)
350     {
351         if ($this->isMyActivity($activity)) {
352
353             $actor = $oprofile->checkAuthorship($activity);
354
355             if (empty($actor)) {
356                 // TRANS: Client exception thrown when no author for an activity was found.
357                 throw new ClientException(_('Cannot get author for activity.'));
358             }
359
360             $object = $activity->objects[0];
361
362             $options = array('uri' => $object->id,
363                              'url' => $object->link,
364                              'is_local' => Notice::REMOTE,
365                              'source' => 'ostatus');
366
367             // $actor is an ostatus_profile
368             $notice = $this->saveNoticeFromActivity($activity, $actor->localProfile(), $options);
369
370             return false;
371         }
372
373         return true;
374     }
375
376     /**
377      * Handle a posted object from Salmon
378      *
379      * @param Activity $activity activity to handle
380      * @param mixed    $target   user or group targeted
381      *
382      * @return boolean hook value
383      */
384
385     function onStartHandleSalmonTarget($activity, $target)
386     {
387         if ($this->isMyActivity($activity)) {
388             $this->log(LOG_INFO, "Checking {$activity->id} as a valid Salmon slap.");
389
390             if ($target instanceof User_group) {
391                 $uri = $target->getUri();
392                 if (!in_array($uri, $activity->context->attention)) {
393                     // @todo FIXME: please document (i18n).
394                     // TRANS: Client exception thrown when ...
395                     throw new ClientException(_('Bookmark not posted to this group.'));
396                 }
397             } else if ($target instanceof User) {
398                 $uri      = $target->uri;
399                 $original = null;
400                 if (!empty($activity->context->replyToID)) {
401                     $original = Notice::staticGet('uri',
402                                                   $activity->context->replyToID);
403                 }
404                 if (!in_array($uri, $activity->context->attention) &&
405                     (empty($original) ||
406                      $original->profile_id != $target->id)) {
407                     // @todo FIXME: Please document (i18n).
408                     // TRANS: Client exception when ...
409                     throw new ClientException(_('Object not posted to this user.'));
410                 }
411             } else {
412                 // TRANS: Server exception thrown when a micro app plugin uses a target that cannot be handled.
413                 throw new ServerException(_('Do not know how to handle this kind of target.'));
414             }
415
416             $actor = Ostatus_profile::ensureActivityObjectProfile($activity->actor);
417
418             $object = $activity->objects[0];
419
420             $options = array('uri' => $object->id,
421                              'url' => $object->link,
422                              'is_local' => Notice::REMOTE,
423                              'source' => 'ostatus');
424
425             // $actor is an ostatus_profile
426             $this->saveNoticeFromActivity($activity, $actor->localProfile(), $options);
427
428             return false;
429         }
430
431         return true;
432     }
433
434     /**
435      * Handle object posted via AtomPub
436      *
437      * @param Activity &$activity Activity that was posted
438      * @param User     $user      User that posted it
439      * @param Notice   &$notice   Resulting notice
440      *
441      * @return boolean hook value
442      */
443     function onStartAtomPubNewActivity(&$activity, $user, &$notice)
444     {
445         if ($this->isMyActivity($activity)) {
446
447             $options = array('source' => 'atompub');
448
449             // $user->getProfile() is a Profile
450             $notice = $this->saveNoticeFromActivity($activity,
451                                                     $user->getProfile(),
452                                                     $options);
453
454             return false;
455         }
456
457         return true;
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, $trusted, &$done)
472     {
473         if ($this->isMyActivity($activity)) {
474
475             $obj = $activity->objects[0];
476
477             $options = array('uri' => $object->id,
478                              'url' => $object->link,
479                              'source' => 'restore');
480
481             // $user->getProfile() is a Profile
482             $saved = $this->saveNoticeFromActivity($activity,
483                                                    $user->getProfile(),
484                                                    $options);
485
486             if (!empty($saved)) {
487                 $done = true;
488             }
489
490             return false;
491         }
492
493         return true;
494     }
495
496     /**
497      * Event handler gives the plugin a chance to add custom
498      * Atom XML ActivityStreams output from a previously filled-out
499      * ActivityObject.
500      *
501      * The atomOutput method is called if it's one of
502      * our matching types.
503      *
504      * @param ActivityObject $obj
505      * @param XMLOutputter $out to add elements at end of object
506      * @return boolean hook return value
507      */
508     function onEndActivityObjectOutputAtom(ActivityObject $obj, XMLOutputter $out)
509     {
510         if (in_array($obj->type, $this->types())) {
511             $this->activityObjectOutputAtom($obj, $out);
512         }
513         return true;
514     }
515
516     /**
517      * Event handler gives the plugin a chance to add custom
518      * JSON ActivityStreams output from a previously filled-out
519      * ActivityObject.
520      *
521      * The activityObjectOutputJson method is called if it's one of
522      * our matching types.
523      *
524      * @param ActivityObject $obj
525      * @param array &$out JSON-targeted array which can be modified
526      * @return boolean hook return value
527      */
528     function onEndActivityObjectOutputJson(ActivityObject $obj, array &$out)
529     {
530         if (in_array($obj->type, $this->types())) {
531             $this->activityObjectOutputJson($obj, $out);
532         }
533         return true;
534     }
535
536     function onStartShowEntryForms(&$tabs)
537     {
538         $tabs[$this->tag()] = $this->appTitle();
539         return true;
540     }
541
542     function onStartMakeEntryForm($tag, $out, &$form)
543     {
544         if ($tag == $this->tag()) {
545             $form = $this->entryForm($out);
546             return false;
547         }
548
549         return true;
550     }
551
552     function showNotice($notice, $out)
553     {
554         // TRANS: Server exception thrown when a micro app plugin developer has not done his job too well.
555         throw new ServerException(_('You must implement either adaptNoticeListItem() or showNotice().'));
556     }
557 }