]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/OStatus/actions/ostatussub.php
Properly unlink all old avatars when deleting/uploading a new
[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->avatarUrl(AVATAR_PROFILE_SIZE);
146
147         $this->showEntity($profile,
148                           $profile->profileurl,
149                           $avatarUrl,
150                           $profile->bio);
151         return $ok;
152     }
153
154     function showEntity($entity, $profile, $avatar, $note)
155     {
156         $nickname = $entity->nickname;
157         $fullname = $entity->fullname;
158         $homepage = $entity->homepage;
159         $location = $entity->location;
160
161         $this->elementStart('div', 'entity_profile vcard');
162         $this->element('img', array('src' => $avatar,
163                                     'class' => 'photo avatar entity_depiction',
164                                     'width' => AVATAR_PROFILE_SIZE,
165                                     'height' => AVATAR_PROFILE_SIZE,
166                                     'alt' => $nickname));
167
168         $hasFN = ($fullname !== '') ? 'nickname' : 'fn nickname entity_nickname';
169         $this->elementStart('a', array('href' => $profile,
170                                        'class' => 'url '.$hasFN));
171         $this->raw($nickname);
172         $this->elementEnd('a');
173
174         if (!is_null($fullname)) {
175             $this->elementStart('div', 'fn entity_fn');
176             $this->raw($fullname);
177             $this->elementEnd('div');
178         }
179
180         if (!is_null($location)) {
181             $this->elementStart('div', 'label entity_location');
182             $this->raw($location);
183             $this->elementEnd('div');
184         }
185
186         if (!is_null($homepage)) {
187             $this->elementStart('a', array('href' => $homepage,
188                                            'class' => 'url entity_url'));
189             $this->raw($homepage);
190             $this->elementEnd('a');
191         }
192
193         if (!is_null($note)) {
194             $this->elementStart('div', 'note entity_note');
195             $this->raw($note);
196             $this->elementEnd('div');
197         }
198         $this->elementEnd('div');
199     }
200
201     /**
202      * Redirect on successful remote user subscription
203      */
204     function success()
205     {
206         $cur = common_current_user();
207         $url = common_local_url('subscriptions', array('nickname' => $cur->nickname));
208         common_redirect($url, 303);
209     }
210
211     /**
212      * Pull data for a remote profile and check if it's valid.
213      * Fills out error UI string in $this->error
214      * Fills out $this->oprofile on success.
215      *
216      * @return boolean
217      */
218     function pullRemoteProfile()
219     {
220         $this->profile_uri = $this->trimmed('profile');
221         try {
222             if (Validate::email($this->profile_uri)) {
223                 $this->oprofile = Ostatus_profile::ensureWebfinger($this->profile_uri);
224             } else if (Validate::uri($this->profile_uri)) {
225                 $this->oprofile = Ostatus_profile::ensureProfileURL($this->profile_uri);
226             } else {
227                 // TRANS: Error message in OStatus plugin. Do not translate the domain names example.com
228                 // TRANS: and example.net, as these are official standard domain names for use in examples.
229                 $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.");
230                 common_debug('Invalid address format.', __FILE__);
231                 return false;
232             }
233             return true;
234         } catch (FeedSubBadURLException $e) {
235                 // TRANS: Error message in OStatus plugin. Do not translate the domain names example.com
236                 // TRANS: and example.net, as these are official standard domain names for use in examples.
237             $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.');
238             common_debug('Invalid URL or could not reach server.', __FILE__);
239         } catch (FeedSubBadResponseException $e) {
240             // TRANS: Error text.
241             $this->error = _m('Sorry, we could not reach that feed. Please try that OStatus address again later.');
242             common_debug('Cannot read feed; server returned error.', __FILE__);
243         } catch (FeedSubEmptyException $e) {
244             // TRANS: Error text.
245             $this->error = _m('Sorry, we could not reach that feed. Please try that OStatus address again later.');
246             common_debug('Cannot read feed; server returned an empty page.', __FILE__);
247         } catch (FeedSubBadHTMLException $e) {
248             // TRANS: Error text.
249             $this->error = _m('Sorry, we could not reach that feed. Please try that OStatus address again later.');
250             common_debug('Bad HTML, could not find feed link.', __FILE__);
251         } catch (FeedSubNoFeedException $e) {
252             // TRANS: Error text.
253             $this->error = _m("Sorry, we could not reach that feed. Please try that OStatus address again later.");
254             common_debug('Could not find a feed linked from this URL.', __FILE__);
255         } catch (FeedSubUnrecognizedTypeException $e) {
256             // TRANS: Error text.
257             $this->error = _m("Sorry, we could not reach that feed. Please try that OStatus address again later.");
258             common_debug('Not a recognized feed type.', __FILE__);
259         } catch (Exception $e) {
260             // Any new ones we forgot about
261                 // TRANS: Error message in OStatus plugin. Do not translate the domain names example.com
262                 // TRANS: and example.net, as these are official standard domain names for use in examples.
263             $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.");
264             common_debug(sprintf('Bad feed URL: %s %s', get_class($e), $e->getMessage()), __FILE__);
265         }
266
267         return false;
268     }
269
270     function validateRemoteProfile()
271     {
272         // Send us to the respective subscription form for conf
273         if ($this->oprofile->isGroup()) {
274             $target = common_local_url('ostatusgroup', array(), array('profile' => $this->profile_uri));
275             common_redirect($target, 303);
276         } else if ($this->oprofile->isPeopletag()) {
277             $target = common_local_url('ostatuspeopletag', array(), array('profile' => $this->profile_uri));
278             common_redirect($target, 303);
279         }
280     }
281
282     /**
283      * Attempt to finalize subscription.
284      * validateFeed must have been run first.
285      *
286      * Calls showForm on failure or success on success.
287      */
288     function saveFeed()
289     {
290         // And subscribe the current user to the local profile
291         $user = common_current_user();
292         $local = $this->oprofile->localProfile();
293         if ($user->isSubscribed($local)) {
294             // TRANS: OStatus remote subscription dialog error.
295             $this->showForm(_m('Already subscribed!'));
296         } elseif (Subscription::start($user->getProfile(), $local)) {
297             $this->success();
298         } else {
299             // TRANS: OStatus remote subscription dialog error.
300             $this->showForm(_m('Remote subscription failed!'));
301         }
302     }
303
304     function prepare($args)
305     {
306         parent::prepare($args);
307
308         if (!common_logged_in()) {
309             // XXX: selfURL() didn't work. :<
310             common_set_returnto($_SERVER['REQUEST_URI']);
311             if (Event::handle('RedirectToLogin', array($this, null))) {
312                 common_redirect(common_local_url('login'), 303);
313             }
314             return false;
315         }
316
317         if ($this->pullRemoteProfile()) {
318             $this->validateRemoteProfile();
319         }
320         return true;
321     }
322
323     /**
324      * Handle the submission.
325      */
326     function handle($args)
327     {
328         parent::handle($args);
329         if ($_SERVER['REQUEST_METHOD'] == 'POST') {
330             $this->handlePost();
331         } else {
332             $this->showForm();
333         }
334     }
335
336     /**
337      * Handle posts to this form
338      *
339      * @return void
340      */
341
342     function handlePost()
343     {
344         // CSRF protection
345         $token = $this->trimmed('token');
346         if (!$token || $token != common_session_token()) {
347             // TRANS: Client error displayed when the session token does not match or is not given.
348             $this->showForm(_m('There was a problem with your session token. '.
349                               'Try again, please.'));
350             return;
351         }
352
353         if ($this->oprofile) {
354             if ($this->arg('submit')) {
355                 $this->saveFeed();
356                 return;
357             }
358         }
359         $this->showForm();
360     }
361
362     /**
363      * Show the appropriate form based on our input state.
364      */
365     function showForm($err=null)
366     {
367         if ($err) {
368             $this->error = $err;
369         }
370         if ($this->boolean('ajax')) {
371             $this->startHTML('text/xml;charset=utf-8');
372             $this->elementStart('head');
373             // TRANS: Form title.
374             $this->element('title', null, _m('Subscribe to user'));
375             $this->elementEnd('head');
376             $this->elementStart('body');
377             $this->showContent();
378             $this->elementEnd('body');
379             $this->endHTML();
380         } else {
381             $this->showPage();
382         }
383     }
384
385     /**
386      * Title of the page
387      *
388      * @return string Title of the page
389      */
390
391     function title()
392     {
393         // TRANS: Page title for OStatus remote subscription form.
394         return _m('Confirm');
395     }
396
397     /**
398      * Instructions for use
399      *
400      * @return instructions for use
401      */
402
403     function getInstructions()
404     {
405         // TRANS: Instructions.
406         return _m('You can subscribe to users from other supported sites. Paste their address or profile URI below:');
407     }
408
409     function showPageNotice()
410     {
411         if (!empty($this->error)) {
412             $this->element('p', 'error', $this->error);
413         }
414     }
415
416     /**
417      * Content area of the page
418      *
419      * Shows a form for associating a remote OStatus account with this
420      * StatusNet account.
421      *
422      * @return void
423      */
424     function showContent()
425     {
426         if ($this->oprofile) {
427             $this->showPreviewForm();
428         } else {
429             $this->showInputForm();
430         }
431     }
432
433     function showScripts()
434     {
435         parent::showScripts();
436         $this->autofocus('feedurl');
437     }
438
439     function selfLink()
440     {
441         return common_local_url('ostatussub');
442     }
443
444     /**
445      * Disable the send-notice form at the top of the page.
446      * This is really just a hack for the broken CSS in the Cloudy theme,
447      * I think; copying from other non-notice-navigation pages that do this
448      * as well. There will be plenty of others also broken.
449      *
450      * @fixme fix the cloudy theme
451      * @fixme do this in a more general way
452      */
453     function showNoticeForm() {
454         // nop
455     }
456 }