]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/microappplugin.php
Update translator documentation.
[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                 in_array($activity->objects[0]->type, $types));
197     }
198
199     /**
200      * Called when generating Atom XML ActivityStreams output from an
201      * ActivityObject belonging to this plugin. Gives the plugin
202      * a chance to add custom output.
203      *
204      * Note that you can only add output of additional XML elements,
205      * not change existing stuff here.
206      *
207      * If output is already handled by the base Activity classes,
208      * you can leave this base implementation as a no-op.
209      *
210      * @param ActivityObject $obj
211      * @param XMLOutputter $out to add elements at end of object
212      */
213     function activityObjectOutputAtom(ActivityObject $obj, XMLOutputter $out)
214     {
215         // default is a no-op
216     }
217
218     /**
219      * Called when generating JSON ActivityStreams output from an
220      * ActivityObject belonging to this plugin. Gives the plugin
221      * a chance to add custom output.
222      *
223      * Modify the array contents to your heart's content, and it'll
224      * all get serialized out as JSON.
225      *
226      * If output is already handled by the base Activity classes,
227      * you can leave this base implementation as a no-op.
228      *
229      * @param ActivityObject $obj
230      * @param array &$out JSON-targeted array which can be modified
231      */
232     public function activityObjectOutputJson(ActivityObject $obj, array &$out)
233     {
234         // default is a no-op
235     }
236
237     /**
238      * When a notice is deleted, delete the related objects
239      * by calling the overridable $this->deleteRelated().
240      *
241      * @param Notice $notice Notice being deleted
242      *
243      * @return boolean hook value
244      */
245     function onNoticeDeleteRelated($notice)
246     {
247         if ($this->isMyNotice($notice)) {
248             $this->deleteRelated($notice);
249         }
250
251         return true;
252     }
253
254     /**
255      * Output the HTML for this kind of object in a list
256      *
257      * @param NoticeListItem $nli The list item being shown.
258      *
259      * @return boolean hook value
260      *
261      * @fixme WARNING WARNING WARNING this closes a 'div' that is implicitly opened in BookmarkPlugin's showNotice implementation
262      */
263     function onStartShowNoticeItem($nli)
264     {
265         if (!$this->isMyNotice($nli->notice)) {
266             return true;
267         }
268
269         $adapter = $this->adaptNoticeListItem($nli);
270
271         if (!empty($adapter)) {
272             $adapter->showNotice();
273             $adapter->showNoticeAttachments();
274             $adapter->showNoticeInfo();
275             $adapter->showNoticeOptions();
276         } else {
277             $this->oldShowNotice($nli);
278         }
279
280         return false;
281     }
282
283     /**
284      * Given a notice list item, returns an adapter specific
285      * to this plugin.
286      *
287      * @param NoticeListItem $nli item to adapt
288      *
289      * @return NoticeListItemAdapter adapter or null
290      */
291     function adaptNoticeListItem($nli)
292     {
293       return null;
294     }
295
296     function oldShowNotice($nli)
297     {
298         $out = $nli->out;
299         $notice = $nli->notice;
300
301         try {
302             $this->showNotice($notice, $out);
303         } catch (Exception $e) {
304             common_log(LOG_ERR, $e->getMessage());
305             // try to fall back
306             $out->elementStart('div');
307             $nli->showAuthor();
308             $nli->showContent();
309         }
310
311         $nli->showNoticeLink();
312         $nli->showNoticeSource();
313         $nli->showNoticeLocation();
314         $nli->showContext();
315         $nli->showRepeat();
316
317         $out->elementEnd('div');
318
319         $nli->showNoticeOptions();
320     }
321
322     /**
323      * Render a notice as one of our objects
324      *
325      * @param Notice         $notice  Notice to render
326      * @param ActivityObject &$object Empty object to fill
327      *
328      * @return boolean hook value
329      */
330     function onStartActivityObjectFromNotice($notice, &$object)
331     {
332         if ($this->isMyNotice($notice)) {
333             $object = $this->activityObjectFromNotice($notice);
334             return false;
335         }
336
337         return true;
338     }
339
340     /**
341      * Handle a posted object from PuSH
342      *
343      * @param Activity        $activity activity to handle
344      * @param Ostatus_profile $oprofile Profile for the feed
345      *
346      * @return boolean hook value
347      */
348     function onStartHandleFeedEntryWithProfile($activity, $oprofile)
349     {
350         if ($this->isMyActivity($activity)) {
351
352             $actor = $oprofile->checkAuthorship($activity);
353
354             if (empty($actor)) {
355                 // TRANS: Client exception thrown when no author for an activity was found.
356                 throw new ClientException(_('Cannot get author for activity.'));
357             }
358
359             $object = $activity->objects[0];
360
361             $options = array('uri' => $object->id,
362                              'url' => $object->link,
363                              'is_local' => Notice::REMOTE_OMB,
364                              'source' => 'ostatus');
365
366             // $actor is an ostatus_profile
367             $this->saveNoticeFromActivity($activity, $actor->localProfile(), $options);
368
369             return false;
370         }
371
372         return true;
373     }
374
375     /**
376      * Handle a posted object from Salmon
377      *
378      * @param Activity $activity activity to handle
379      * @param mixed    $target   user or group targeted
380      *
381      * @return boolean hook value
382      */
383
384     function onStartHandleSalmonTarget($activity, $target)
385     {
386         if ($this->isMyActivity($activity)) {
387             $this->log(LOG_INFO, "Checking {$activity->id} as a valid Salmon slap.");
388
389             if ($target instanceof User_group) {
390                 $uri = $target->getUri();
391                 if (!in_array($uri, $activity->context->attention)) {
392                     // @todo FIXME: please document (i18n).
393                     // TRANS: Client exception thrown when ...
394                     throw new ClientException(_('Bookmark not posted to this group.'));
395                 }
396             } else if ($target instanceof User) {
397                 $uri      = $target->uri;
398                 $original = null;
399                 if (!empty($activity->context->replyToID)) {
400                     $original = Notice::staticGet('uri',
401                                                   $activity->context->replyToID);
402                 }
403                 if (!in_array($uri, $activity->context->attention) &&
404                     (empty($original) ||
405                      $original->profile_id != $target->id)) {
406                     // @todo FIXME: Please document (i18n).
407                     // TRANS: Client exception when ...
408                     throw new ClientException(_('Object not posted to this user.'));
409                 }
410             } else {
411                 // TRANS: Server exception thrown when a micro app plugin uses a target that cannot be handled.
412                 throw new ServerException(_('Do not know how to handle this kind of target.'));
413             }
414
415             $actor = Ostatus_profile::ensureActivityObjectProfile($activity->actor);
416
417             $object = $activity->objects[0];
418
419             $options = array('uri' => $object->id,
420                              'url' => $object->link,
421                              'is_local' => Notice::REMOTE_OMB,
422                              'source' => 'ostatus');
423
424             // $actor is an ostatus_profile
425             $this->saveNoticeFromActivity($activity, $actor->localProfile(), $options);
426
427             return false;
428         }
429
430         return true;
431     }
432
433     /**
434      * Handle object posted via AtomPub
435      *
436      * @param Activity &$activity Activity that was posted
437      * @param User     $user      User that posted it
438      * @param Notice   &$notice   Resulting notice
439      *
440      * @return boolean hook value
441      */
442     function onStartAtomPubNewActivity(&$activity, $user, &$notice)
443     {
444         if ($this->isMyActivity($activity)) {
445
446             $options = array('source' => 'atompub');
447
448             // $user->getProfile() is a Profile
449             $this->saveNoticeFromActivity($activity,
450                                           $user->getProfile(),
451                                           $options);
452
453             return false;
454         }
455
456         return true;
457     }
458
459     /**
460      * Handle object imported from a backup file
461      *
462      * @param User           $user     User to import for
463      * @param ActivityObject $author   Original author per import file
464      * @param Activity       $activity Activity to import
465      * @param boolean        $trusted  Is this a trusted user?
466      * @param boolean        &$done    Is this done (success or unrecoverable error)
467      *
468      * @return boolean hook value
469      */
470     function onStartImportActivity($user, $author, $activity, $trusted, &$done)
471     {
472         if ($this->isMyActivity($activity)) {
473
474             $obj = $activity->objects[0];
475
476             $options = array('uri' => $object->id,
477                              'url' => $object->link,
478                              'source' => 'restore');
479
480             // $user->getProfile() is a Profile
481             $saved = $this->saveNoticeFromActivity($activity,
482                                                    $user->getProfile(),
483                                                    $options);
484
485             if (!empty($saved)) {
486                 $done = true;
487             }
488
489             return false;
490         }
491
492         return true;
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     function onStartShowEntryForms(&$tabs)
536     {
537         $tabs[$this->tag()] = $this->appTitle();
538         return true;
539     }
540
541     function onStartMakeEntryForm($tag, $out, &$form)
542     {
543         if ($tag == $this->tag()) {
544             $form = $this->entryForm($out);
545             return false;
546         }
547
548         return true;
549     }
550
551     function showNotice($notice, $out)
552     {
553         // TRANS: Server exception thrown when a micro app plugin developer has not done his job too well.
554         throw new ServerException(_('You must implement either adaptNoticeListItem() or showNotice().'));
555     }
556 }