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