]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/OStatus/actions/ostatussub.php
Handle normalized acct: URIs in ostatussub
[quix0rs-gnu-social.git] / plugins / OStatus / actions / ostatussub.php
1 <?php
2 /*
3  * StatusNet - the distributed open-source microblogging tool
4  * Copyright (C) 2009-2010, 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('GNUSOCIAL') && !defined('STATUSNET')) { 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  *    preview() - display profile for a remote user
35  *
36  *  success() - redirects to subscriptions page on subscribe
37  */
38 class OStatusSubAction extends Action
39 {
40     protected $profile_uri; // provided acct: or URI of remote entity
41     protected $oprofile; // Ostatus_profile of remote entity, if valid
42
43     protected function prepare(array $args=array())
44     {
45         parent::prepare($args);
46
47         if (!common_logged_in()) {
48             // XXX: selfURL() didn't work. :<
49             common_set_returnto($_SERVER['REQUEST_URI']);
50             if (Event::handle('RedirectToLogin', array($this, null))) {
51                 common_redirect(common_local_url('login'), 303);
52             }
53             return false;
54         }
55
56         if ($this->pullRemoteProfile()) {
57             $this->validateRemoteProfile();
58         }
59         return true;
60     }
61
62     /**
63      * Handle the submission.
64      */
65     protected function handle()
66     {
67         parent::handle();
68         if ($_SERVER['REQUEST_METHOD'] == 'POST') {
69             $this->handlePost();
70         } else {
71             $this->showForm();
72         }
73     }
74
75     /**
76      * Show the initial form, when we haven't yet been given a valid
77      * remote profile.
78      */
79     function showInputForm()
80     {
81         $this->elementStart('form', array('method' => 'post',
82                                           'id' => 'form_ostatus_sub',
83                                           'class' => 'form_settings',
84                                           'action' => $this->selfLink()));
85
86         $this->hidden('token', common_session_token());
87
88         $this->elementStart('fieldset', array('id' => 'settings_feeds'));
89
90         $this->elementStart('ul', 'form_data');
91         $this->elementStart('li');
92         $this->input('profile',
93                      // TRANS: Field label for a field that takes an OStatus user address.
94                      _m('Subscribe to'),
95                      $this->profile_uri,
96                      // TRANS: Tooltip for field label "Subscribe to".
97                      _m('OStatus user\'s address, like nickname@example.com or http://example.net/nickname.'));
98         $this->elementEnd('li');
99         $this->elementEnd('ul');
100         // TRANS: Button text.
101         $this->submit('validate', _m('BUTTON','Continue'));
102
103         $this->elementEnd('fieldset');
104
105         $this->elementEnd('form');
106     }
107
108     /**
109      * Show the preview-and-confirm form. We've got a valid remote
110      * profile and are ready to poke it!
111      *
112      * This controls the wrapper form; actual profile display will
113      * be in previewUser() or previewGroup() depending on the type.
114      */
115     function showPreviewForm()
116     {
117         $ok = $this->preview();
118         if (!$ok) {
119             // @todo FIXME maybe provide a cancel button or link back?
120             return;
121         }
122
123         $this->elementStart('div', 'entity_actions');
124         $this->elementStart('ul');
125         $this->elementStart('li', 'entity_subscribe');
126         $this->elementStart('form', array('method' => 'post',
127                                           'id' => 'form_ostatus_sub',
128                                           'class' => 'form_remote_authorize',
129                                           'action' =>
130                                           $this->selfLink()));
131         $this->elementStart('fieldset');
132         $this->hidden('token', common_session_token());
133         $this->hidden('profile', $this->profile_uri);
134         if ($this->oprofile->isGroup()) {
135             // TRANS: Button text.
136             $this->submit('submit', _m('Join'), 'submit', null,
137                          // TRANS: Tooltip for button "Join".
138                          _m('BUTTON','Join this group'));
139         } else {
140             // TRANS: Button text.
141             $this->submit('submit', _m('BUTTON','Confirm'), 'submit', null,
142                          // TRANS: Tooltip for button "Confirm".
143                          _m('Subscribe to this user'));
144         }
145         $this->elementEnd('fieldset');
146         $this->elementEnd('form');
147         $this->elementEnd('li');
148         $this->elementEnd('ul');
149         $this->elementEnd('div');
150     }
151
152     /**
153      * Show a preview for a remote user's profile
154      * @return boolean true if we're ok to try subscribing
155      */
156     function preview()
157     {
158         // Throws NoProfileException on localProfile when remote user's Profile not found
159         $profile = $this->oprofile->localProfile();
160
161         if ($this->scoped->isSubscribed($profile)) {
162             $this->element('div', array('class' => 'error'),
163                            // TRANS: Extra paragraph in remote profile view when already subscribed.
164                            _m('You are already subscribed to this user.'));
165             $ok = false;
166         } else {
167             $ok = true;
168         }
169
170         $avatarUrl = $profile->avatarUrl(AVATAR_PROFILE_SIZE);
171
172         $this->showEntity($profile,
173                           $profile->profileurl,
174                           $avatarUrl,
175                           $profile->bio);
176         return $ok;
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         $this->elementStart('div', 'entity_profile vcard');
187         $this->element('img', array('src' => $avatar,
188                                     'class' => 'photo avatar entity_depiction',
189                                     'width' => AVATAR_PROFILE_SIZE,
190                                     'height' => AVATAR_PROFILE_SIZE,
191                                     'alt' => $nickname));
192
193         $hasFN = ($fullname !== '') ? 'nickname' : 'fn nickname entity_nickname';
194         $this->elementStart('a', array('href' => $profile,
195                                        'class' => 'url '.$hasFN));
196         $this->text($nickname);
197         $this->elementEnd('a');
198
199         if (!is_null($fullname)) {
200             $this->elementStart('div', 'fn entity_fn');
201             $this->text($fullname);
202             $this->elementEnd('div');
203         }
204
205         if (!is_null($location)) {
206             $this->elementStart('div', 'label entity_location');
207             $this->text($location);
208             $this->elementEnd('div');
209         }
210
211         if (!is_null($homepage)) {
212             $this->elementStart('a', array('href' => $homepage,
213                                            'class' => 'url entity_url'));
214             $this->text($homepage);
215             $this->elementEnd('a');
216         }
217
218         if (!is_null($note)) {
219             $this->elementStart('div', 'note entity_note');
220             $this->text($note);
221             $this->elementEnd('div');
222         }
223         $this->elementEnd('div');
224     }
225
226     /**
227      * Redirect on successful remote user subscription
228      */
229     function success()
230     {
231         $url = common_local_url('subscriptions', array('nickname' => $this->scoped->nickname));
232         common_redirect($url, 303);
233     }
234
235     /**
236      * Pull data for a remote profile and check if it's valid.
237      * Fills out error UI string in $this->error
238      * Fills out $this->oprofile on success.
239      *
240      * @return boolean
241      */
242     function pullRemoteProfile()
243     {
244         $validate = new Validate();
245         $this->profile_uri = Discovery::normalize($this->trimmed('profile'));
246         try {
247             if (Discovery::isAcct($this->profile_uri) && $validate->email(mb_substr($this->profile_uri, 5))) {
248                 $this->oprofile = Ostatus_profile::ensureWebfinger($this->profile_uri);
249             } else if ($validate->uri($this->profile_uri)) {
250                 $this->oprofile = Ostatus_profile::ensureProfileURL($this->profile_uri);
251             } else {
252                 // TRANS: Error message in OStatus plugin. Do not translate the domain names example.com
253                 // TRANS: and example.net, as these are official standard domain names for use in examples.
254                 $this->error = _m("Sorry, we could not reach that address. Please make sure that the OStatus address is like nickname@example.com or http://example.net/nickname.");
255                 common_debug('Invalid address format.', __FILE__);
256                 return false;
257             }
258             return true;
259         } catch (FeedSubBadURLException $e) {
260                 // TRANS: Error message in OStatus plugin. Do not translate the domain names example.com
261                 // TRANS: and example.net, as these are official standard domain names for use in examples.
262             $this->error = _m('Sorry, we could not reach that address. Please make sure that the OStatus address is like nickname@example.com or http://example.net/nickname.');
263             common_debug('Invalid URL or could not reach server.', __FILE__);
264         } catch (FeedSubBadResponseException $e) {
265             // TRANS: Error text.
266             $this->error = _m('Sorry, we could not reach that feed. Please try that OStatus address again later.');
267             common_debug('Cannot read feed; server returned error.', __FILE__);
268         } catch (FeedSubEmptyException $e) {
269             // TRANS: Error text.
270             $this->error = _m('Sorry, we could not reach that feed. Please try that OStatus address again later.');
271             common_debug('Cannot read feed; server returned an empty page.', __FILE__);
272         } catch (FeedSubBadHTMLException $e) {
273             // TRANS: Error text.
274             $this->error = _m('Sorry, we could not reach that feed. Please try that OStatus address again later.');
275             common_debug('Bad HTML, could not find feed link.', __FILE__);
276         } catch (FeedSubNoFeedException $e) {
277             // TRANS: Error text.
278             $this->error = _m("Sorry, we could not reach that feed. Please try that OStatus address again later.");
279             common_debug('Could not find a feed linked from this URL.', __FILE__);
280         } catch (FeedSubUnrecognizedTypeException $e) {
281             // TRANS: Error text.
282             $this->error = _m("Sorry, we could not reach that feed. Please try that OStatus address again later.");
283             common_debug('Not a recognized feed type.', __FILE__);
284         } catch (FeedSubNoHubException $e) {
285             // TRANS: Error text.
286             $this->error = _m("Sorry, that feed is not Pubsubhubub enabled.");
287             common_debug('No hub found.', __FILE__);
288         } catch (Exception $e) {
289             // Any new ones we forgot about
290                 // TRANS: Error message in OStatus plugin. Do not translate the domain names example.com
291                 // TRANS: and example.net, as these are official standard domain names for use in examples.
292             $this->error = _m("Sorry, we could not reach that address. Please make sure that the OStatus address is like nickname@example.com or http://example.net/nickname.");
293             common_debug(sprintf('Bad feed URL: %s %s', get_class($e), $e->getMessage()), __FILE__);
294         }
295
296         return false;
297     }
298
299     function validateRemoteProfile()
300     {
301         // Send us to the respective subscription form for conf
302         if ($this->oprofile->isGroup()) {
303             $target = common_local_url('ostatusgroup', array(), array('profile' => $this->profile_uri));
304             common_redirect($target, 303);
305         } else if ($this->oprofile->isPeopletag()) {
306             $target = common_local_url('ostatuspeopletag', array(), array('profile' => $this->profile_uri));
307             common_redirect($target, 303);
308         }
309     }
310
311     /**
312      * Attempt to finalize subscription.
313      * validateFeed must have been run first.
314      *
315      * Calls showForm on failure or success on success.
316      */
317     function saveFeed()
318     {
319         // And subscribe the current user to the local profile
320         $local = $this->oprofile->localProfile();
321         if ($this->scoped->isSubscribed($local)) {
322             // TRANS: OStatus remote subscription dialog error.
323             $this->showForm(_m('Already subscribed!'));
324         } elseif (Subscription::start($this->scoped, $local)) {
325             $this->success();
326         } else {
327             // TRANS: OStatus remote subscription dialog error.
328             $this->showForm(_m('Remote subscription failed!'));
329         }
330     }
331
332     /**
333      * Handle posts to this form
334      *
335      * @return void
336      */
337
338     function handlePost()
339     {
340         // CSRF protection
341         $token = $this->trimmed('token');
342         if (!$token || $token != common_session_token()) {
343             // TRANS: Client error displayed when the session token does not match or is not given.
344             $this->showForm(_m('There was a problem with your session token. '.
345                               'Try again, please.'));
346             return;
347         }
348
349         if ($this->oprofile) {
350             if ($this->arg('submit')) {
351                 $this->saveFeed();
352                 return;
353             }
354         }
355         $this->showForm();
356     }
357
358     /**
359      * Show the appropriate form based on our input state.
360      */
361     function showForm($err=null)
362     {
363         if ($err) {
364             $this->error = $err;
365         }
366         if ($this->boolean('ajax')) {
367             $this->startHTML('text/xml;charset=utf-8');
368             $this->elementStart('head');
369             // TRANS: Form title.
370             $this->element('title', null, _m('Subscribe to user'));
371             $this->elementEnd('head');
372             $this->elementStart('body');
373             $this->showContent();
374             $this->elementEnd('body');
375             $this->endHTML();
376         } else {
377             $this->showPage();
378         }
379     }
380
381     /**
382      * Title of the page
383      *
384      * @return string Title of the page
385      */
386
387     function title()
388     {
389         // TRANS: Page title for OStatus remote subscription form.
390         return _m('Confirm');
391     }
392
393     /**
394      * Instructions for use
395      *
396      * @return instructions for use
397      */
398
399     function getInstructions()
400     {
401         // TRANS: Instructions.
402         return _m('You can subscribe to users from other supported sites. Paste their address or profile URI below:');
403     }
404
405     function showPageNotice()
406     {
407         if (!empty($this->error)) {
408             $this->element('p', 'error', $this->error);
409         }
410     }
411
412     /**
413      * Content area of the page
414      *
415      * Shows a form for associating a remote OStatus account with this
416      * StatusNet account.
417      *
418      * @return void
419      */
420     function showContent()
421     {
422         if ($this->oprofile) {
423             $this->showPreviewForm();
424         } else {
425             $this->showInputForm();
426         }
427     }
428
429     function showScripts()
430     {
431         parent::showScripts();
432         $this->autofocus('feedurl');
433     }
434
435     function selfLink()
436     {
437         return common_local_url('ostatussub');
438     }
439
440     /**
441      * Disable the send-notice form at the top of the page.
442      * This is really just a hack for the broken CSS in the Cloudy theme,
443      * I think; copying from other non-notice-navigation pages that do this
444      * as well. There will be plenty of others also broken.
445      *
446      * @fixme fix the cloudy theme
447      * @fixme do this in a more general way
448      */
449     function showNoticeForm() {
450         // nop
451     }
452 }