facebookfinishlogin.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619
  1. <?php
  2. /**
  3. * StatusNet, the distributed open-source microblogging tool
  4. *
  5. * Login or register a local user based on a Facebook user
  6. *
  7. * PHP version 5
  8. *
  9. * LICENCE: This program is free software: you can redistribute it and/or modify
  10. * it under the terms of the GNU Affero General Public License as published by
  11. * the Free Software Foundation, either version 3 of the License, or
  12. * (at your option) any later version.
  13. *
  14. * This program is distributed in the hope that it will be useful,
  15. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. * GNU Affero General Public License for more details.
  18. *
  19. * You should have received a copy of the GNU Affero General Public License
  20. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  21. *
  22. * @category Plugin
  23. * @package StatusNet
  24. * @author Zach Copley <zach@status.net>
  25. * @copyright 2010-2011 StatusNet, Inc.
  26. * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
  27. * @link http://status.net/
  28. */
  29. if (!defined('STATUSNET')) {
  30. exit(1);
  31. }
  32. class FacebookfinishloginAction extends Action
  33. {
  34. private $fbuid = null; // Facebook user ID
  35. private $fbuser = null; // Facebook user object (JSON)
  36. private $accessToken = null; // Access token provided by Facebook JS API
  37. function prepare($args) {
  38. parent::prepare($args);
  39. // Check cookie for a valid access_token
  40. if (isset($_COOKIE['fb_access_token'])) {
  41. $this->accessToken = $_COOKIE['fb_access_token'];
  42. }
  43. if (empty($this->accessToken)) {
  44. $this->clientError(_m("Unable to authenticate you with Facebook."));
  45. }
  46. $graphUrl = 'https://graph.facebook.com/me?access_token=' . urlencode($this->accessToken);
  47. $this->fbuser = json_decode(file_get_contents($graphUrl));
  48. if (empty($this->fbuser)) {
  49. // log badness
  50. list($proxy, $ip) = common_client_ip();
  51. common_log(
  52. LOG_WARNING,
  53. sprintf(
  54. 'Failed Facebook authentication attempt, proxy = %s, ip = %s.',
  55. $proxy,
  56. $ip
  57. ),
  58. __FILE__
  59. );
  60. $this->clientError(
  61. // TRANS: Client error displayed when trying to connect to Facebook while not logged in.
  62. _m('You must be logged into Facebook to register a local account using Facebook.')
  63. );
  64. }
  65. $this->fbuid = $this->fbuser->id;
  66. // OKAY, all is well... proceed to register
  67. return true;
  68. }
  69. function handle($args)
  70. {
  71. parent::handle($args);
  72. if (common_is_real_login()) {
  73. // This will throw a client exception if the user already
  74. // has some sort of foreign_link to Facebook.
  75. $this->checkForExistingLink();
  76. // Possibly reconnect an existing account
  77. $this->connectUser();
  78. } else if ($_SERVER['REQUEST_METHOD'] == 'POST') {
  79. $this->handlePost();
  80. } else {
  81. $this->tryLogin();
  82. }
  83. }
  84. function checkForExistingLink() {
  85. // User is already logged in, are her accounts already linked?
  86. $flink = Foreign_link::getByForeignID($this->fbuid, FACEBOOK_SERVICE);
  87. if (!empty($flink)) {
  88. // User already has a linked Facebook account and shouldn't be here!
  89. $this->clientError(
  90. // TRANS: Client error displayed when trying to connect to a Facebook account that is already linked
  91. // TRANS: in the same StatusNet site.
  92. _m('There is already a local account linked with that Facebook account.')
  93. );
  94. }
  95. $cur = common_current_user();
  96. $flink = Foreign_link::getByUserID($cur->id, FACEBOOK_SERVICE);
  97. if (!empty($flink)) {
  98. // There's already a local user linked to this Facebook account.
  99. $this->clientError(
  100. // TRANS: Client error displayed when trying to connect to a Facebook account that is already linked
  101. // TRANS: in the same StatusNet site.
  102. _m('There is already a local account linked with that Facebook account.')
  103. );
  104. }
  105. }
  106. function handlePost()
  107. {
  108. $token = $this->trimmed('token');
  109. // CSRF protection
  110. if (!$token || $token != common_session_token()) {
  111. $this->showForm(
  112. // TRANS: Client error displayed when the session token does not match or is not given.
  113. _m('There was a problem with your session token. Try again, please.')
  114. );
  115. return;
  116. }
  117. if ($this->arg('create')) {
  118. if (!$this->boolean('license')) {
  119. $this->showForm(
  120. // TRANS: Form validation error displayed when user has not agreed to the license.
  121. _m('You cannot register if you do not agree to the license.'),
  122. $this->trimmed('newname')
  123. );
  124. return;
  125. }
  126. // We has a valid Facebook session and the Facebook user has
  127. // agreed to the SN license, so create a new user
  128. $this->createNewUser();
  129. } else if ($this->arg('connect')) {
  130. $this->connectNewUser();
  131. } else {
  132. $this->showForm(
  133. // TRANS: Form validation error displayed when an unhandled error occurs.
  134. _m('An unknown error has occured.'),
  135. $this->trimmed('newname')
  136. );
  137. }
  138. }
  139. function showPageNotice()
  140. {
  141. if ($this->error) {
  142. $this->element('div', array('class' => 'error'), $this->error);
  143. } else {
  144. $this->element(
  145. 'div', 'instructions',
  146. sprintf(
  147. // TRANS: Form instructions for connecting to Facebook.
  148. // TRANS: %s is the site name.
  149. _m('This is the first time you have logged into %s so we must connect your Facebook to a local account. You can either create a new local account, or connect with an existing local account.'),
  150. common_config('site', 'name')
  151. )
  152. );
  153. }
  154. }
  155. function title()
  156. {
  157. // TRANS: Page title.
  158. return _m('Facebook Setup');
  159. }
  160. function showForm($error=null, $username=null)
  161. {
  162. $this->error = $error;
  163. $this->username = $username;
  164. $this->showPage();
  165. }
  166. function showPage()
  167. {
  168. parent::showPage();
  169. }
  170. /**
  171. * @todo FIXME: Much of this duplicates core code, which is very fragile.
  172. * Should probably be replaced with an extensible mini version of
  173. * the core registration form.
  174. */
  175. function showContent()
  176. {
  177. if (!empty($this->message_text)) {
  178. $this->element('p', null, $this->message);
  179. return;
  180. }
  181. $this->elementStart('form', array('method' => 'post',
  182. 'id' => 'form_settings_facebook_connect',
  183. 'class' => 'form_settings',
  184. 'action' => common_local_url('facebookfinishlogin')));
  185. $this->elementStart('fieldset', array('id' => 'settings_facebook_connect_options'));
  186. // TRANS: Fieldset legend.
  187. $this->element('legend', null, _m('Connection options'));
  188. $this->elementStart('ul', 'form_data');
  189. $this->elementStart('li');
  190. $this->element('input', array('type' => 'checkbox',
  191. 'id' => 'license',
  192. 'class' => 'checkbox',
  193. 'name' => 'license',
  194. 'value' => 'true'));
  195. $this->elementStart('label', array('class' => 'checkbox', 'for' => 'license'));
  196. // TRANS: %s is the name of the license used by the user for their status updates.
  197. $message = _m('My text and files are available under %s ' .
  198. 'except this private data: password, ' .
  199. 'email address, IM address, and phone number.');
  200. $link = '<a href="' .
  201. htmlspecialchars(common_config('license', 'url')) .
  202. '">' .
  203. htmlspecialchars(common_config('license', 'title')) .
  204. '</a>';
  205. $this->raw(sprintf(htmlspecialchars($message), $link));
  206. $this->elementEnd('label');
  207. $this->elementEnd('li');
  208. $this->elementEnd('ul');
  209. $this->elementStart('fieldset');
  210. $this->hidden('token', common_session_token());
  211. $this->element('legend', null,
  212. // TRANS: Fieldset legend.
  213. _m('Create new account'));
  214. $this->element('p', null,
  215. // TRANS: Form instructions.
  216. _m('Create a new user with this nickname.'));
  217. $this->elementStart('ul', 'form_data');
  218. // Hook point for captcha etc
  219. Event::handle('StartRegistrationFormData', array($this));
  220. $this->elementStart('li');
  221. // TRANS: Field label.
  222. $this->input('newname', _m('New nickname'),
  223. ($this->username) ? $this->username : '',
  224. // TRANS: Field title.
  225. _m('1-64 lowercase letters or numbers, no punctuation or spaces.'));
  226. $this->elementEnd('li');
  227. // Hook point for captcha etc
  228. Event::handle('EndRegistrationFormData', array($this));
  229. $this->elementEnd('ul');
  230. // TRANS: Submit button to create a new account.
  231. $this->submit('create', _m('BUTTON','Create'));
  232. $this->elementEnd('fieldset');
  233. $this->elementStart('fieldset');
  234. $this->element('legend', null,
  235. // TRANS: Fieldset legend.
  236. _m('Connect existing account'));
  237. $this->element('p', null,
  238. // TRANS: Form instructions.
  239. _m('If you already have an account, login with your username and password to connect it to your Facebook.'));
  240. $this->elementStart('ul', 'form_data');
  241. $this->elementStart('li');
  242. // TRANS: Field label.
  243. $this->input('nickname', _m('Existing nickname'));
  244. $this->elementEnd('li');
  245. $this->elementStart('li');
  246. // TRANS: Field label.
  247. $this->password('password', _m('Password'));
  248. $this->elementEnd('li');
  249. $this->elementEnd('ul');
  250. // TRANS: Submit button to connect a Facebook account to an existing StatusNet account.
  251. $this->submit('connect', _m('BUTTON','Connect'));
  252. $this->elementEnd('fieldset');
  253. $this->elementEnd('fieldset');
  254. $this->elementEnd('form');
  255. }
  256. function message($msg)
  257. {
  258. $this->message_text = $msg;
  259. $this->showPage();
  260. }
  261. function createNewUser()
  262. {
  263. if (!Event::handle('StartRegistrationTry', array($this))) {
  264. return;
  265. }
  266. if (common_config('site', 'closed')) {
  267. // TRANS: Client error trying to register with registrations not allowed.
  268. $this->clientError(_m('Registration not allowed.'));
  269. }
  270. $invite = null;
  271. if (common_config('site', 'inviteonly')) {
  272. $code = $_SESSION['invitecode'];
  273. if (empty($code)) {
  274. // TRANS: Client error trying to register with registrations 'invite only'.
  275. $this->clientError(_m('Registration not allowed.'));
  276. }
  277. $invite = Invitation::getKV($code);
  278. if (empty($invite)) {
  279. // TRANS: Client error trying to register with an invalid invitation code.
  280. $this->clientError(_m('Not a valid invitation code.'));
  281. }
  282. }
  283. try {
  284. $nickname = Nickname::normalize($this->trimmed('newname'), true);
  285. } catch (NicknameException $e) {
  286. $this->showForm($e->getMessage());
  287. return;
  288. }
  289. $args = array(
  290. 'nickname' => $nickname,
  291. 'fullname' => $this->fbuser->name,
  292. 'homepage' => $this->fbuser->website,
  293. 'location' => $this->fbuser->location->name
  294. );
  295. // It's possible that the email address is already in our
  296. // DB. It's a unique key, so we need to check
  297. if ($this->isNewEmail($this->fbuser->email)) {
  298. $args['email'] = $this->fbuser->email;
  299. if (isset($this->fuser->verified) && $this->fuser->verified == true) {
  300. $args['email_confirmed'] = true;
  301. }
  302. }
  303. if (!empty($invite)) {
  304. $args['code'] = $invite->code;
  305. }
  306. $user = User::register($args);
  307. $result = $this->flinkUser($user->id, $this->fbuid);
  308. if (!$result) {
  309. // TRANS: Server error displayed when connecting to Facebook fails.
  310. $this->serverError(_m('Error connecting user to Facebook.'));
  311. }
  312. // Add a Foreign_user record
  313. Facebookclient::addFacebookUser($this->fbuser);
  314. $this->setAvatar($user);
  315. common_set_user($user);
  316. common_real_login(true);
  317. common_log(
  318. LOG_INFO,
  319. sprintf(
  320. 'Registered new user %s (%d) from Facebook user %s, (fbuid %d)',
  321. $user->nickname,
  322. $user->id,
  323. $this->fbuser->name,
  324. $this->fbuid
  325. ),
  326. __FILE__
  327. );
  328. Event::handle('EndRegistrationTry', array($this));
  329. $this->goHome($user->nickname);
  330. }
  331. /*
  332. * Attempt to download the user's Facebook picture and create a
  333. * StatusNet avatar for the new user.
  334. */
  335. function setAvatar($user)
  336. {
  337. try {
  338. $picUrl = sprintf(
  339. 'http://graph.facebook.com/%d/picture?type=large',
  340. $this->fbuser->id
  341. );
  342. // fetch the picture from Facebook
  343. $client = new HTTPClient();
  344. // fetch the actual picture
  345. $response = $client->get($picUrl);
  346. if ($response->isOk()) {
  347. // seems to always be jpeg, but not sure
  348. $tmpname = "facebook-avatar-tmp-" . common_random_hexstr(4);
  349. $ok = file_put_contents(
  350. Avatar::path($tmpname),
  351. $response->getBody()
  352. );
  353. if (!$ok) {
  354. common_log(LOG_WARNING, 'Couldn\'t save tmp Facebook avatar: ' . $tmpname, __FILE__);
  355. } else {
  356. // save it as an avatar
  357. $imagefile = new ImageFile(null, Avatar::path($tmpname));
  358. $filename = Avatar::filename($user->id, image_type_to_extension($imagefile->preferredType()),
  359. 180, common_timestamp());
  360. // Previous docs said 180 is the "biggest img we get from Facebook"
  361. $imagefile->resizeTo(Avatar::path($filename, array('width'=>180, 'height'=>180)));
  362. // No need to keep the temporary file around...
  363. @unlink(Avatar::path($tmpname));
  364. $profile = $user->getProfile();
  365. if ($profile->setOriginal($filename)) {
  366. common_log(
  367. LOG_INFO,
  368. sprintf(
  369. 'Saved avatar for %s (%d) from Facebook picture for '
  370. . '%s (fbuid %d), filename = %s',
  371. $user->nickname,
  372. $user->id,
  373. $this->fbuser->name,
  374. $this->fbuid,
  375. $filename
  376. ),
  377. __FILE__
  378. );
  379. // clean up tmp file
  380. }
  381. }
  382. }
  383. } catch (Exception $e) {
  384. common_log(LOG_WARNING, 'Couldn\'t save Facebook avatar: ' . $e->getMessage(), __FILE__);
  385. // error isn't fatal, continue
  386. }
  387. }
  388. function connectNewUser()
  389. {
  390. $nickname = $this->trimmed('nickname');
  391. $password = $this->trimmed('password');
  392. if (!common_check_user($nickname, $password)) {
  393. // TRANS: Form validation error displayed when username/password combination is incorrect.
  394. $this->showForm(_m('Invalid username or password.'));
  395. return;
  396. }
  397. $user = User::getKV('nickname', $nickname);
  398. $this->tryLinkUser($user);
  399. common_set_user($user);
  400. common_real_login(true);
  401. // clear out the stupid cookie
  402. setcookie('fb_access_token', '', time() - 3600); // one hour ago
  403. $this->goHome($user->nickname);
  404. }
  405. function connectUser()
  406. {
  407. $user = common_current_user();
  408. $this->tryLinkUser($user);
  409. // clear out the stupid cookie
  410. setcookie('fb_access_token', '', time() - 3600); // one hour ago
  411. common_redirect(common_local_url('facebookfinishlogin'), 303);
  412. }
  413. function tryLinkUser($user)
  414. {
  415. $result = $this->flinkUser($user->id, $this->fbuid);
  416. if (empty($result)) {
  417. // TRANS: Server error displayed when connecting to Facebook fails.
  418. $this->serverError(_m('Error connecting user to Facebook.'));
  419. }
  420. }
  421. function tryLogin()
  422. {
  423. try {
  424. $flink = Foreign_link::getByForeignID($this->fbuid, FACEBOOK_SERVICE);
  425. $user = $flink->getUser();
  426. common_log(
  427. LOG_INFO,
  428. sprintf(
  429. 'Logged in Facebook user %s as user %d (%s)',
  430. $this->fbuid,
  431. $user->nickname,
  432. $user->id
  433. ),
  434. __FILE__
  435. );
  436. common_set_user($user);
  437. common_real_login(true);
  438. // clear out the stupid cookie
  439. setcookie('fb_access_token', '', time() - 3600); // one hour ago
  440. $this->goHome($user->nickname);
  441. } catch (NoResultException $e) {
  442. $this->showForm(null, $this->bestNewNickname());
  443. }
  444. }
  445. function goHome($nickname)
  446. {
  447. $url = common_get_returnto();
  448. if ($url) {
  449. // We don't have to return to it again
  450. common_set_returnto(null);
  451. } else {
  452. $url = common_local_url('all',
  453. array('nickname' =>
  454. $nickname));
  455. }
  456. common_redirect($url, 303);
  457. }
  458. function flinkUser($user_id, $fbuid)
  459. {
  460. $flink = new Foreign_link();
  461. $flink->user_id = $user_id;
  462. $flink->foreign_id = $fbuid;
  463. $flink->service = FACEBOOK_SERVICE;
  464. $flink->credentials = $this->accessToken;
  465. $flink->created = common_sql_now();
  466. $flink_id = $flink->insert();
  467. return $flink_id;
  468. }
  469. function bestNewNickname()
  470. {
  471. try {
  472. $nickname = Nickname::normalize($this->fbuser->username, true);
  473. return $nickname;
  474. } catch (NicknameException $e) {
  475. // Failed to normalize nickname, but let's try the full name
  476. }
  477. try {
  478. $nickname = Nickname::normalize($this->fbuser->name, true);
  479. return $nickname;
  480. } catch (NicknameException $e) {
  481. // Any more ideas? Nope.
  482. }
  483. return null;
  484. }
  485. /*
  486. * Do we already have a user record with this email?
  487. * (emails have to be unique but they can change)
  488. *
  489. * @param string $email the email address to check
  490. *
  491. * @return boolean result
  492. */
  493. function isNewEmail($email)
  494. {
  495. // we shouldn't have to validate the format
  496. $result = User::getKV('email', $email);
  497. if (empty($result)) {
  498. return true;
  499. }
  500. return false;
  501. }
  502. }