]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/OStatus/actions/ostatussub.php
OStatus: accept webfinger addresses as well as profile URLs in the explicit remote...
[quix0rs-gnu-social.git] / plugins / OStatus / actions / ostatussub.php
1 <?php
2 /*
3  * StatusNet - the distributed open-source microblogging tool
4  * Copyright (C) 2009, StatusNet, 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 /**
21  * @package OStatusPlugin
22  * @maintainer Brion Vibber <brion@status.net>
23  */
24
25 if (!defined('STATUSNET') && !defined('LACONICA')) { exit(1); }
26
27 /**
28  * Key UI methods:
29  *
30  *  showInputForm() - form asking for a remote profile account or URL
31  *                    We end up back here on errors
32  *
33  *  showPreviewForm() - surrounding form for preview-and-confirm
34  *    previewUser() - display profile for a remote user
35  *    previewGroup() - display profile for a remote group
36  *
37  *  successUser() - redirects to subscriptions page on subscribe
38  *  successGroup() - redirects to groups page on join
39  */
40 class OStatusSubAction extends Action
41 {
42     protected $profile_uri; // provided acct: or URI of remote entity
43     protected $oprofile; // Ostatus_profile of remote entity, if valid
44
45     /**
46      * Show the initial form, when we haven't yet been given a valid
47      * remote profile.
48      */
49     function showInputForm()
50     {
51         $user = common_current_user();
52
53         $profile = $user->getProfile();
54
55         $this->elementStart('form', array('method' => 'post',
56                                           'id' => 'form_ostatus_sub',
57                                           'class' => 'form_settings',
58                                           'action' =>
59                                           common_local_url('ostatussub')));
60
61         $this->hidden('token', common_session_token());
62
63         $this->elementStart('fieldset', array('id' => 'settings_feeds'));
64
65         $this->elementStart('ul', 'form_data');
66         $this->elementStart('li');
67         $this->input('profile',
68                      _m('Address or profile URL'),
69                      $this->profile_uri,
70                      _m('Enter the profile URL of a PubSubHubbub-enabled feed'));
71         $this->elementEnd('li');
72         $this->elementEnd('ul');
73
74         $this->submit('validate', _m('Continue'));
75
76         $this->elementEnd('fieldset');
77
78         $this->elementEnd('form');
79     }
80
81     /**
82      * Show the preview-and-confirm form. We've got a valid remote
83      * profile and are ready to poke it!
84      *
85      * This controls the wrapper form; actual profile display will
86      * be in previewUser() or previewGroup() depending on the type.
87      */
88     function showPreviewForm()
89     {
90         if ($this->oprofile->isGroup()) {
91             $ok = $this->previewGroup();
92         } else {
93             $ok = $this->previewUser();
94         }
95         if (!$ok) {
96             // @fixme maybe provide a cancel button or link back?
97             return;
98         }
99
100         $this->elementStart('div', 'entity_actions');
101         $this->elementStart('ul');
102         $this->elementStart('li', 'entity_subscribe');
103         $this->elementStart('form', array('method' => 'post',
104                                           'id' => 'form_ostatus_sub',
105                                           'class' => 'form_remote_authorize',
106                                           'action' =>
107                                           common_local_url('ostatussub')));
108         $this->elementStart('fieldset');
109         $this->hidden('token', common_session_token());
110         $this->hidden('profile', $this->profile_uri);
111         if ($this->oprofile->isGroup()) {
112             $this->submit('submit', _m('Join'), 'submit', null,
113                          _m('Join this group'));
114         } else {
115             $this->submit('submit', _m('Subscribe'), 'submit', null,
116                          _m('Subscribe to this user'));
117         }
118         $this->elementEnd('fieldset');
119         $this->elementEnd('form');
120         $this->elementEnd('li');
121         $this->elementEnd('ul');
122         $this->elementEnd('div');
123     }
124
125     /**
126      * Show a preview for a remote user's profile
127      * @return boolean true if we're ok to try subscribing
128      */
129     function previewUser()
130     {
131         $oprofile = $this->oprofile;
132         $profile = $oprofile->localProfile();
133
134         $cur = common_current_user();
135         if ($cur->isSubscribed($profile)) {
136             $this->element('div', array('class' => 'error'),
137                            _m("You are already subscribed to this user."));
138             $ok = false;
139         } else {
140             $ok = true;
141         }
142
143         $avatar = $profile->getAvatar(AVATAR_PROFILE_SIZE);
144         $avatarUrl = $avatar ? $avatar->displayUrl() : false;
145
146         $this->showEntity($profile,
147                           $profile->profileurl,
148                           $avatarUrl,
149                           $profile->bio);
150         return $ok;
151     }
152
153     /**
154      * Show a preview for a remote group's profile
155      * @return boolean true if we're ok to try joining
156      */
157     function previewGroup()
158     {
159         $oprofile = $this->oprofile;
160         $group = $oprofile->localGroup();
161
162         $cur = common_current_user();
163         if ($cur->isMember($group)) {
164             $this->element('div', array('class' => 'error'),
165                            _m("You are already a member of this group."));
166             $ok = false;
167         } else {
168             $ok = true;
169         }
170
171         $this->showEntity($group,
172                           $group->getProfileUrl(),
173                           $group->homepage_logo,
174                           $group->description);
175         return $ok;
176     }
177
178
179     function showEntity($entity, $profile, $avatar, $note)
180     {
181         $nickname = $entity->nickname;
182         $fullname = $entity->fullname;
183         $homepage = $entity->homepage;
184         $location = $entity->location;
185         
186         if (!$avatar) {
187             $avatar = Avatar::defaultImage(AVATAR_PROFILE_SIZE);
188         }
189
190         $this->elementStart('div', 'entity_profile vcard');
191         $this->elementStart('dl', 'entity_depiction');
192         $this->element('dt', null, _('Photo'));
193         $this->elementStart('dd');
194         $this->element('img', array('src' => $avatar,
195                                     'class' => 'photo avatar',
196                                     'width' => AVATAR_PROFILE_SIZE,
197                                     'height' => AVATAR_PROFILE_SIZE,
198                                     'alt' => $nickname));
199         $this->elementEnd('dd');
200         $this->elementEnd('dl');
201
202         $this->elementStart('dl', 'entity_nickname');
203         $this->element('dt', null, _('Nickname'));
204         $this->elementStart('dd');
205         $hasFN = ($fullname !== '') ? 'nickname' : 'fn nickname';
206         $this->elementStart('a', array('href' => $profile,
207                                        'class' => 'url '.$hasFN));
208         $this->raw($nickname);
209         $this->elementEnd('a');
210         $this->elementEnd('dd');
211         $this->elementEnd('dl');
212
213         if (!is_null($fullname)) {
214             $this->elementStart('dl', 'entity_fn');
215             $this->elementStart('dd');
216             $this->elementStart('span', 'fn');
217             $this->raw($fullname);
218             $this->elementEnd('span');
219             $this->elementEnd('dd');
220             $this->elementEnd('dl');
221         }
222         if (!is_null($location)) {
223             $this->elementStart('dl', 'entity_location');
224             $this->element('dt', null, _('Location'));
225             $this->elementStart('dd', 'label');
226             $this->raw($location);
227             $this->elementEnd('dd');
228             $this->elementEnd('dl');
229         }
230
231         if (!is_null($homepage)) {
232             $this->elementStart('dl', 'entity_url');
233             $this->element('dt', null, _('URL'));
234             $this->elementStart('dd');
235             $this->elementStart('a', array('href' => $homepage,
236                                                 'class' => 'url'));
237             $this->raw($homepage);
238             $this->elementEnd('a');
239             $this->elementEnd('dd');
240             $this->elementEnd('dl');
241         }
242
243         if (!is_null($note)) {
244             $this->elementStart('dl', 'entity_note');
245             $this->element('dt', null, _('Note'));
246             $this->elementStart('dd', 'note');
247             $this->raw($note);
248             $this->elementEnd('dd');
249             $this->elementEnd('dl');
250         }
251         $this->elementEnd('div');
252     }
253
254     /**
255      * Redirect on successful remote user subscription
256      */
257     function successUser()
258     {
259         $cur = common_current_user();
260         $url = common_local_url('subscriptions', array('nickname' => $cur->nickname));
261         common_redirect($url, 303);
262     }
263
264     /**
265      * Redirect on successful remote group join
266      */
267     function successGroup()
268     {
269         $cur = common_current_user();
270         $url = common_local_url('usergroups', array('nickname' => $cur->nickname));
271         common_redirect($url, 303);
272     }
273
274     /**
275      * Pull data for a remote profile and check if it's valid.
276      * Fills out error UI string in $this->error
277      * Fills out $this->oprofile on success.
278      *
279      * @return boolean
280      */
281     function validateFeed()
282     {
283         $profile_uri = trim($this->arg('profile'));
284
285         if ($profile_uri == '') {
286             $this->showForm(_m('Empty remote profile URL!'));
287             return;
288         }
289         $this->profile_uri = $profile_uri;
290
291         try {
292             if (Validate::email($this->profile_uri)) {
293                 $this->oprofile = Ostatus_profile::ensureWebfinger($this->profile_uri);
294             } else if (Validate::uri($this->profile_uri)) {
295                 $this->oprofile = Ostatus_profile::ensureProfile($this->profile_uri);
296             } else {
297                 $this->error = _m("Invalid address format.");
298                 return false;
299             }
300             return true;
301         } catch (FeedSubBadURLException $e) {
302             $this->error = _m('Invalid URL or could not reach server.');
303         } catch (FeedSubBadResponseException $e) {
304             $this->error = _m('Cannot read feed; server returned error.');
305         } catch (FeedSubEmptyException $e) {
306             $this->error = _m('Cannot read feed; server returned an empty page.');
307         } catch (FeedSubBadHTMLException $e) {
308             $this->error = _m('Bad HTML, could not find feed link.');
309         } catch (FeedSubNoFeedException $e) {
310             $this->error = _m('Could not find a feed linked from this URL.');
311         } catch (FeedSubUnrecognizedTypeException $e) {
312             $this->error = _m('Not a recognized feed type.');
313         } catch (FeedSubException $e) {
314             // Any new ones we forgot about
315             $this->error = sprintf(_m('Bad feed URL: %s %s'), get_class($e), $e->getMessage());
316         }
317
318         return false;
319     }
320
321     /**
322      * Attempt to finalize subscription.
323      * validateFeed must have been run first.
324      *
325      * Calls showForm on failure or successUser/successGroup on success.
326      */
327     function saveFeed()
328     {
329         // And subscribe the current user to the local profile
330         $user = common_current_user();
331
332         if ($this->oprofile->isGroup()) {
333             $group = $this->oprofile->localGroup();
334             if ($user->isMember($group)) {
335                 $this->showForm(_m('Already a member!'));
336             } elseif (Group_member::join($this->oprofile->group_id, $user->id)) {
337                 $this->successGroup();
338             } else {
339                 $this->showForm(_m('Remote group join failed!'));
340             }
341         } else {
342             $local = $this->oprofile->localProfile();
343             if ($user->isSubscribed($local)) {
344                 $this->showForm(_m('Already subscribed!'));
345             } elseif ($this->oprofile->subscribeLocalToRemote($user)) {
346                 $this->successUser();
347             } else {
348                 $this->showForm(_m('Remote subscription failed!'));
349             }
350         }
351     }
352
353     function prepare($args)
354     {
355         parent::prepare($args);
356
357         if (!common_logged_in()) {
358             // XXX: selfURL() didn't work. :<
359             common_set_returnto($_SERVER['REQUEST_URI']);
360             if (Event::handle('RedirectToLogin', array($this, null))) {
361                 common_redirect(common_local_url('login'), 303);
362             }
363             return false;
364         }
365
366         $this->profile_uri = $this->arg('profile');
367
368         return true;
369     }
370
371     /**
372      * Handle the submission.
373      */
374     function handle($args)
375     {
376         parent::handle($args);
377         if ($_SERVER['REQUEST_METHOD'] == 'POST') {
378             $this->handlePost();
379         } else {
380             if ($this->arg('profile')) {
381                 $this->validateFeed();
382             }
383             $this->showForm();
384         }
385     }
386
387
388     /**
389      * Handle posts to this form
390      *
391      * @return void
392      */
393
394     function handlePost()
395     {
396         // CSRF protection
397         $token = $this->trimmed('token');
398         if (!$token || $token != common_session_token()) {
399             $this->showForm(_('There was a problem with your session token. '.
400                               'Try again, please.'));
401             return;
402         }
403
404         if ($this->validateFeed()) {
405             if ($this->arg('submit')) {
406                 $this->saveFeed();
407                 return;
408             }
409         }
410         $this->showForm();
411     }
412
413     /**
414      * Show the appropriate form based on our input state.
415      */
416     function showForm($err=null)
417     {
418         if ($err) {
419             $this->error = $err;
420         }
421         if ($this->boolean('ajax')) {
422             header('Content-Type: text/xml;charset=utf-8');
423             $this->xw->startDocument('1.0', 'UTF-8');
424             $this->elementStart('html');
425             $this->elementStart('head');
426             $this->element('title', null, _m('Subscribe to user'));
427             $this->elementEnd('head');
428             $this->elementStart('body');
429             $this->showContent();
430             $this->elementEnd('body');
431             $this->elementEnd('html');
432         } else {
433             $this->showPage();
434         }
435     }
436
437     /**
438      * Title of the page
439      *
440      * @return string Title of the page
441      */
442
443     function title()
444     {
445         return _m('Authorize subscription');
446     }
447
448     /**
449      * Instructions for use
450      *
451      * @return instructions for use
452      */
453
454     function getInstructions()
455     {
456         return _m('You can subscribe to users from other supported sites. Paste their address or profile URI below:');
457     }
458
459     function showPageNotice()
460     {
461         if (!empty($this->error)) {
462             $this->element('p', 'error', $this->error);
463         }
464     }
465
466     /**
467      * Content area of the page
468      *
469      * Shows a form for associating a remote OStatus account with this
470      * StatusNet account.
471      *
472      * @return void
473      */
474
475     function showContent()
476     {
477         if ($this->oprofile) {
478             $this->showPreviewForm();
479         } else {
480             $this->showInputForm();
481         }
482     }
483
484     function showScripts()
485     {
486         parent::showScripts();
487         $this->autofocus('feedurl');
488     }
489 }