]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/microappplugin.php
use an adapter pattern to customize notice list item output
[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      * Custom HTML output for your special notice; called when a
142      * matching notice turns up in a NoticeListItem.
143      *
144      * All micro-app classes must override this method.
145      *
146      * @param Notice $notice
147      * @param HTMLOutputter $out
148      *
149      * @fixme WARNING WARNING WARNING base plugin stuff below tries to close
150      * a div that this function opens in the BookmarkPlugin child class.
151      * This is probably wrong.
152      */
153     abstract function showNotice($notice, $out);
154
155     /**
156      * When building the primary notice form, we'll fetch also some
157      * alternate forms for specialized types -- that's you!
158      *
159      * Return a custom Widget or Form object for the given output
160      * object, and it'll be included in the HTML output. Beware that
161      * your form may be initially hidden.
162      *
163      * All micro-app classes must override this method.
164      *
165      * @param HTMLOutputter $out
166      * @return Widget
167      */
168     abstract function entryForm($out);
169
170     /**
171      * When a notice is deleted, you'll be called here for a chance
172      * to clean up any related resources.
173      *
174      * All micro-app classes must override this method.
175      *
176      * @param Notice $notice
177      */
178     abstract function deleteRelated($notice);
179
180     /**
181      * Check if a given notice object should be handled by this micro-app
182      * plugin.
183      *
184      * The default implementation checks against the activity type list
185      * returned by $this->types(). You can override this method to expand
186      * your checks.
187      *
188      * @param Notice $notice
189      * @return boolean
190      */
191     function isMyNotice($notice) {
192         $types = $this->types();
193         return in_array($notice->object_type, $types);
194     }
195
196     /**
197      * Check if a given ActivityStreams activity should be handled by this
198      * micro-app plugin.
199      *
200      * The default implementation checks against the activity type list
201      * returned by $this->types(), and requires that exactly one matching
202      * object be present. You can override this method to expand
203      * your checks or to compare the activity's verb, etc.
204      *
205      * @param Activity $activity
206      * @return boolean
207      */
208     function isMyActivity($activity) {
209         $types = $this->types();
210         return (count($activity->objects) == 1 &&
211                 in_array($activity->objects[0]->type, $types));
212     }
213
214     /**
215      * Called when generating Atom XML ActivityStreams output from an
216      * ActivityObject belonging to this plugin. Gives the plugin
217      * a chance to add custom output.
218      *
219      * Note that you can only add output of additional XML elements,
220      * not change existing stuff here.
221      *
222      * If output is already handled by the base Activity classes,
223      * you can leave this base implementation as a no-op.
224      *
225      * @param ActivityObject $obj
226      * @param XMLOutputter $out to add elements at end of object
227      */
228     function activityObjectOutputAtom(ActivityObject $obj, XMLOutputter $out)
229     {
230         // default is a no-op
231     }
232
233     /**
234      * Called when generating JSON ActivityStreams output from an
235      * ActivityObject belonging to this plugin. Gives the plugin
236      * a chance to add custom output.
237      *
238      * Modify the array contents to your heart's content, and it'll
239      * all get serialized out as JSON.
240      *
241      * If output is already handled by the base Activity classes,
242      * you can leave this base implementation as a no-op.
243      *
244      * @param ActivityObject $obj
245      * @param array &$out JSON-targeted array which can be modified
246      */
247     public function activityObjectOutputJson(ActivityObject $obj, array &$out)
248     {
249         // default is a no-op
250     }
251
252     /**
253      * When a notice is deleted, delete the related objects
254      * by calling the overridable $this->deleteRelated().
255      *
256      * @param Notice $notice Notice being deleted
257      *
258      * @return boolean hook value
259      */
260     function onNoticeDeleteRelated($notice)
261     {
262         if ($this->isMyNotice($notice)) {
263             $this->deleteRelated($notice);
264         }
265
266         return true;
267     }
268
269     /**
270      * Output the HTML for this kind of object in a list
271      *
272      * @param NoticeListItem $nli The list item being shown.
273      *
274      * @return boolean hook value
275      *
276      * @fixme WARNING WARNING WARNING this closes a 'div' that is implicitly opened in BookmarkPlugin's showNotice implementation
277      */
278     function onStartShowNoticeItem($nli)
279     {
280         if (!$this->isMyNotice($nli->notice)) {
281             return true;
282         }
283
284         $adapter = $this->adaptNoticeListItem($nli);
285
286         if (!empty($adapter)) {
287             $adapter->show();
288         } else {
289             $this->oldShowNotice($nli);
290         }
291
292         return false;
293     }
294
295     /**
296      * Given a notice list item, returns an adapter specific
297      * to this plugin.
298      *
299      * @param NoticeListItem $nli item to adapt
300      *
301      * @return NoticeListItemAdapter adapter or null
302      */
303     function adaptNoticeListItem($nli)
304     {
305       return null;
306     }
307
308     function oldShowNotice($nli)
309     {
310         $out = $nli->out;
311         $notice = $nli->notice;
312
313         try {
314             $this->showNotice($notice, $out);
315         } catch (Exception $e) {
316             common_log(LOG_ERR, $e->getMessage());
317             // try to fall back
318             $out->elementStart('div');
319             $nli->showAuthor();
320             $nli->showContent();
321         }
322
323         $nli->showNoticeLink();
324         $nli->showNoticeSource();
325         $nli->showNoticeLocation();
326         $nli->showContext();
327         $nli->showRepeat();
328
329         $out->elementEnd('div');
330
331         $nli->showNoticeOptions();
332     }
333
334     /**
335      * Render a notice as one of our objects
336      *
337      * @param Notice         $notice  Notice to render
338      * @param ActivityObject &$object Empty object to fill
339      *
340      * @return boolean hook value
341      */
342     function onStartActivityObjectFromNotice($notice, &$object)
343     {
344         if ($this->isMyNotice($notice)) {
345             $object = $this->activityObjectFromNotice($notice);
346             return false;
347         }
348
349         return true;
350     }
351
352     /**
353      * Handle a posted object from PuSH
354      *
355      * @param Activity        $activity activity to handle
356      * @param Ostatus_profile $oprofile Profile for the feed
357      *
358      * @return boolean hook value
359      */
360     function onStartHandleFeedEntryWithProfile($activity, $oprofile)
361     {
362         if ($this->isMyActivity($activity)) {
363
364             $actor = $oprofile->checkAuthorship($activity);
365
366             if (empty($actor)) {
367                 // TRANS: Client exception thrown when no author for an activity was found.
368                 throw new ClientException(_('Cannot get author for activity.'));
369             }
370
371             $object = $activity->objects[0];
372
373             $options = array('uri' => $object->id,
374                              'url' => $object->link,
375                              'is_local' => Notice::REMOTE_OMB,
376                              'source' => 'ostatus');
377
378             // $actor is an ostatus_profile
379             $this->saveNoticeFromActivity($activity, $actor->localProfile(), $options);
380
381             return false;
382         }
383
384         return true;
385     }
386
387     /**
388      * Handle a posted object from Salmon
389      *
390      * @param Activity $activity activity to handle
391      * @param mixed    $target   user or group targeted
392      *
393      * @return boolean hook value
394      */
395
396     function onStartHandleSalmonTarget($activity, $target)
397     {
398         if ($this->isMyActivity($activity)) {
399             $this->log(LOG_INFO, "Checking {$activity->id} as a valid Salmon slap.");
400
401             if ($target instanceof User_group) {
402                 $uri = $target->getUri();
403                 if (!in_array($uri, $activity->context->attention)) {
404                     // @todo FIXME: please document (i18n).
405                     // TRANS: Client exception.
406                     throw new ClientException(_('Bookmark not posted to this group.'));
407                 }
408             } else if ($target instanceof User) {
409                 $uri      = $target->uri;
410                 $original = null;
411                 if (!empty($activity->context->replyToID)) {
412                     $original = Notice::staticGet('uri',
413                                                   $activity->context->replyToID);
414                 }
415                 if (!in_array($uri, $activity->context->attention) &&
416                     (empty($original) ||
417                      $original->profile_id != $target->id)) {
418                     // @todo FIXME: Please document (i18n).
419                     // TRANS: Client exception.
420                     throw new ClientException(_('Object not posted to this user.'));
421                 }
422             } else {
423                 // TRANS: Server exception thrown when a micro app plugin uses a target that cannot be handled.
424                 throw new ServerException(_('Do not know how to handle this kind of target.'));
425             }
426
427             $actor = Ostatus_profile::ensureActivityObjectProfile($activity->actor);
428
429             $object = $activity->objects[0];
430
431             $options = array('uri' => $object->id,
432                              'url' => $object->link,
433                              'is_local' => Notice::REMOTE_OMB,
434                              'source' => 'ostatus');
435
436             // $actor is an ostatus_profile
437             $this->saveNoticeFromActivity($activity, $actor->localProfile(), $options);
438
439             return false;
440         }
441
442         return true;
443     }
444
445     /**
446      * Handle object posted via AtomPub
447      *
448      * @param Activity &$activity Activity that was posted
449      * @param User     $user      User that posted it
450      * @param Notice   &$notice   Resulting notice
451      *
452      * @return boolean hook value
453      */
454     function onStartAtomPubNewActivity(&$activity, $user, &$notice)
455     {
456         if ($this->isMyActivity($activity)) {
457
458             $options = array('source' => 'atompub');
459
460             // $user->getProfile() is a Profile
461             $this->saveNoticeFromActivity($activity,
462                                           $user->getProfile(),
463                                           $options);
464
465             return false;
466         }
467
468         return true;
469     }
470
471     /**
472      * Handle object imported from a backup file
473      *
474      * @param User           $user     User to import for
475      * @param ActivityObject $author   Original author per import file
476      * @param Activity       $activity Activity to import
477      * @param boolean        $trusted  Is this a trusted user?
478      * @param boolean        &$done    Is this done (success or unrecoverable error)
479      *
480      * @return boolean hook value
481      */
482     function onStartImportActivity($user, $author, $activity, $trusted, &$done)
483     {
484         if ($this->isMyActivity($activity)) {
485
486             $obj = $activity->objects[0];
487
488             $options = array('uri' => $object->id,
489                              'url' => $object->link,
490                              'source' => 'restore');
491
492             // $user->getProfile() is a Profile
493             $saved = $this->saveNoticeFromActivity($activity,
494                                                    $user->getProfile(),
495                                                    $options);
496
497             if (!empty($saved)) {
498                 $done = true;
499             }
500
501             return false;
502         }
503
504         return true;
505     }
506
507     /**
508      * Event handler gives the plugin a chance to add custom
509      * Atom XML ActivityStreams output from a previously filled-out
510      * ActivityObject.
511      *
512      * The atomOutput method is called if it's one of
513      * our matching types.
514      *
515      * @param ActivityObject $obj
516      * @param XMLOutputter $out to add elements at end of object
517      * @return boolean hook return value
518      */
519     function onEndActivityObjectOutputAtom(ActivityObject $obj, XMLOutputter $out)
520     {
521         if (in_array($obj->type, $this->types())) {
522             $this->activityObjectOutputAtom($obj, $out);
523         }
524         return true;
525     }
526
527     /**
528      * Event handler gives the plugin a chance to add custom
529      * JSON ActivityStreams output from a previously filled-out
530      * ActivityObject.
531      *
532      * The activityObjectOutputJson method is called if it's one of
533      * our matching types.
534      *
535      * @param ActivityObject $obj
536      * @param array &$out JSON-targeted array which can be modified
537      * @return boolean hook return value
538      */
539     function onEndActivityObjectOutputJson(ActivityObject $obj, array &$out)
540     {
541         if (in_array($obj->type, $this->types())) {
542             $this->activityObjectOutputJson($obj, $out);
543         }
544         return true;
545     }
546
547     function onStartShowEntryForms(&$tabs)
548     {
549         $tabs[$this->tag()] = $this->appTitle();
550         return true;
551     }
552
553     function onStartMakeEntryForm($tag, $out, &$form)
554     {
555         if ($tag == $this->tag()) {
556             $form = $this->entryForm($out);
557             return false;
558         }
559
560         return true;
561     }
562
563     /**
564      * Custom HTML output for your special notice; called when a
565      * matching notice turns up in a NoticeListItem.
566      *
567      * All micro-app classes must override this method.
568      *
569      * @param Notice $notice
570      * @param HTMLOutputter $out
571      *
572      * @fixme WARNING WARNING WARNING base plugin stuff below tries to close
573      * a div that this function opens in the BookmarkPlugin child class.
574      * This is probably wrong.
575      */
576     abstract function showNotice($notice, $out);
577
578
579 }