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