]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/OStatus/actions/ostatussub.php
Merge branch 'master' into testing
[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                 // TRANS: OStatus remote group subscription dialog error.
336                 $this->showForm(_m('Already a member!'));
337                 return;
338             }
339             if (Event::handle('StartJoinGroup', array($group, $user))) {
340                 $ok = Group_member::join($this->oprofile->group_id, $user->id);
341                 if ($ok) {
342                     Event::handle('EndJoinGroup', array($group, $user));
343                     $this->successGroup();
344                 } else {
345                     // TRANS: OStatus remote group subscription dialog error.
346                     $this->showForm(_m('Remote group join failed!'));
347                 }
348             } else {
349                 // TRANS: OStatus remote group subscription dialog error.
350                 $this->showForm(_m('Remote group join aborted!'));
351             }
352         } else {
353             $local = $this->oprofile->localProfile();
354             if ($user->isSubscribed($local)) {
355                 // TRANS: OStatus remote subscription dialog error.
356                 $this->showForm(_m('Already subscribed!'));
357             } elseif ($this->oprofile->subscribeLocalToRemote($user)) {
358                 $this->successUser();
359             } else {
360                 // TRANS: OStatus remote subscription dialog error.
361                 $this->showForm(_m('Remote subscription failed!'));
362             }
363         }
364     }
365
366     function prepare($args)
367     {
368         parent::prepare($args);
369
370         if (!common_logged_in()) {
371             // XXX: selfURL() didn't work. :<
372             common_set_returnto($_SERVER['REQUEST_URI']);
373             if (Event::handle('RedirectToLogin', array($this, null))) {
374                 common_redirect(common_local_url('login'), 303);
375             }
376             return false;
377         }
378
379         $this->profile_uri = $this->arg('profile');
380
381         return true;
382     }
383
384     /**
385      * Handle the submission.
386      */
387     function handle($args)
388     {
389         parent::handle($args);
390         if ($_SERVER['REQUEST_METHOD'] == 'POST') {
391             $this->handlePost();
392         } else {
393             if ($this->arg('profile')) {
394                 $this->validateFeed();
395             }
396             $this->showForm();
397         }
398     }
399
400
401     /**
402      * Handle posts to this form
403      *
404      * @return void
405      */
406
407     function handlePost()
408     {
409         // CSRF protection
410         $token = $this->trimmed('token');
411         if (!$token || $token != common_session_token()) {
412             $this->showForm(_('There was a problem with your session token. '.
413                               'Try again, please.'));
414             return;
415         }
416
417         if ($this->validateFeed()) {
418             if ($this->arg('submit')) {
419                 $this->saveFeed();
420                 return;
421             }
422         }
423         $this->showForm();
424     }
425
426     /**
427      * Show the appropriate form based on our input state.
428      */
429     function showForm($err=null)
430     {
431         if ($err) {
432             $this->error = $err;
433         }
434         if ($this->boolean('ajax')) {
435             header('Content-Type: text/xml;charset=utf-8');
436             $this->xw->startDocument('1.0', 'UTF-8');
437             $this->elementStart('html');
438             $this->elementStart('head');
439             $this->element('title', null, _m('Subscribe to user'));
440             $this->elementEnd('head');
441             $this->elementStart('body');
442             $this->showContent();
443             $this->elementEnd('body');
444             $this->elementEnd('html');
445         } else {
446             $this->showPage();
447         }
448     }
449
450     /**
451      * Title of the page
452      *
453      * @return string Title of the page
454      */
455
456     function title()
457     {
458         // TRANS: Page title for OStatus remote subscription form
459         return _m('Authorize subscription');
460     }
461
462     /**
463      * Instructions for use
464      *
465      * @return instructions for use
466      */
467
468     function getInstructions()
469     {
470         return _m('You can subscribe to users from other supported sites. Paste their address or profile URI below:');
471     }
472
473     function showPageNotice()
474     {
475         if (!empty($this->error)) {
476             $this->element('p', 'error', $this->error);
477         }
478     }
479
480     /**
481      * Content area of the page
482      *
483      * Shows a form for associating a remote OStatus account with this
484      * StatusNet account.
485      *
486      * @return void
487      */
488
489     function showContent()
490     {
491         if ($this->oprofile) {
492             $this->showPreviewForm();
493         } else {
494             $this->showInputForm();
495         }
496     }
497
498     function showScripts()
499     {
500         parent::showScripts();
501         $this->autofocus('feedurl');
502     }
503 }