facebook.inc.php 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. <?php
  2. /**
  3. * Licence: GPL
  4. * Please contact CBlue regarding any licences issues.
  5. * Author: noel@cblue.be
  6. * Copyright: CBlue SPRL, 20XX.
  7. *
  8. * External login module : FACEBOOK
  9. *
  10. * This files provides the facebookConnect() and facebook_get_url functions
  11. * Please edit the facebook.conf.php file to adapt it to your fb application parameter
  12. */
  13. require_once __DIR__.'/../../inc/global.inc.php';
  14. require_once __DIR__.'/facebook.init.php';
  15. require_once __DIR__.'/functions.inc.php';
  16. /**
  17. * This function connect to facebook and retrieves the user info
  18. * If user does not exist in chamilo, it creates it and logs in
  19. * If user already exists, it updates his info.
  20. */
  21. function facebookConnect()
  22. {
  23. $fb = new \Facebook\Facebook([
  24. 'app_id' => $GLOBALS['facebook_config']['appId'],
  25. 'app_secret' => $GLOBALS['facebook_config']['secret'],
  26. 'default_graph_version' => 'v2.2',
  27. ]);
  28. $helper = $fb->getRedirectLoginHelper();
  29. try {
  30. $accessToken = $helper->getAccessToken();
  31. } catch (Facebook\Exceptions\FacebookResponseException $e) {
  32. Display::addFlash(
  33. Display::return_message('Facebook Graph returned an error: '.$e->getMessage(), 'error')
  34. );
  35. header('Location: '.api_get_path(WEB_PATH));
  36. exit;
  37. } catch (Facebook\Exceptions\FacebookSDKException $e) {
  38. Display::addFlash(
  39. Display::return_message('Facebook SDK returned an error: '.$e->getMessage(), 'error')
  40. );
  41. header('Location: '.api_get_path(WEB_PATH));
  42. exit;
  43. }
  44. if (!isset($accessToken)) {
  45. if (!$helper->getError()) {
  46. return;
  47. }
  48. if (isset($_GET['loginFailed'])) {
  49. return;
  50. }
  51. $error = implode('<br>', [
  52. 'Error: '.$helper->getError(),
  53. 'Error Code: '.$helper->getErrorCode(),
  54. 'Error Reason: '.$helper->getErrorReason(),
  55. 'Error Description: '.$helper->getErrorDescription(),
  56. ]);
  57. Display::addFlash(
  58. Display::return_message($error, 'error', false)
  59. );
  60. header('Location: '.api_get_path(WEB_PATH));
  61. exit;
  62. }
  63. $oAuth2Client = $fb->getOAuth2Client();
  64. $tokenMetadata = $oAuth2Client->debugToken($accessToken);
  65. $tokenMetadata->validateAppId($GLOBALS['facebook_config']['appId']);
  66. $tokenMetadata->validateExpiration();
  67. if (!$accessToken->isLongLived()) {
  68. try {
  69. $accessToken = $oAuth2Client->getLongLivedAccessToken($accessToken);
  70. } catch (Facebook\Exceptions\FacebookSDKException $e) {
  71. Display::addFlash(
  72. Display::return_message('Error getting long-lived access token: '.$e->getMessage(), 'error')
  73. );
  74. header('Location: '.api_get_path(WEB_PATH));
  75. exit;
  76. }
  77. }
  78. try {
  79. $response = $fb->get('/me?fields=id,first_name,last_name,locale,email', $accessToken->getValue());
  80. } catch (Facebook\Exceptions\FacebookResponseException $e) {
  81. Display::addFlash(
  82. Display::return_message('Graph returned an error: '.$e->getMessage(), 'error')
  83. );
  84. header('Location: '.api_get_path(WEB_PATH));
  85. exit;
  86. } catch (Facebook\Exceptions\FacebookSDKException $e) {
  87. Display::addFlash(
  88. Display::return_message('Facebook SDK returned an error: '.$e->getMessage(), 'error')
  89. );
  90. header('Location: '.api_get_path(WEB_PATH));
  91. exit;
  92. }
  93. $user = $response->getGraphUser();
  94. $language = facebookPluginGetLanguage($user['locale']);
  95. if (!$language) {
  96. $language = 'en_US';
  97. }
  98. $u = [
  99. 'firstname' => $user->getFirstName(),
  100. 'lastname' => $user->getLastName(),
  101. 'status' => STUDENT,
  102. 'email' => $user->getEmail(),
  103. 'username' => changeToValidChamiloLogin($user->getEmail()),
  104. 'language' => $language,
  105. 'password' => 'facebook',
  106. 'auth_source' => 'facebook',
  107. 'extra' => [],
  108. ];
  109. $chamiloUinfo = api_get_user_info_from_email($user->getEmail());
  110. $_user['uidReset'] = true;
  111. $_user['language'] = $language;
  112. if ($chamiloUinfo === false) {
  113. // We have to create the user
  114. $chamilo_uid = external_add_user($u);
  115. if ($chamilo_uid === false) {
  116. Display::addFlash(
  117. Display::return_message(get_lang('UserNotRegistered'), 'error')
  118. );
  119. header('Location: '.api_get_path(WEB_PATH));
  120. exit;
  121. }
  122. $_user['user_id'] = $chamilo_uid;
  123. $_SESSION['_user'] = $_user;
  124. header('Location: '.api_get_path(WEB_PATH));
  125. exit();
  126. }
  127. // User already exists, update info and login
  128. $chamilo_uid = $chamiloUinfo['user_id'];
  129. $u['user_id'] = $chamilo_uid;
  130. external_update_user($u);
  131. $_user['user_id'] = $chamilo_uid;
  132. $_SESSION['_user'] = $_user;
  133. header('Location: '.api_get_path(WEB_PATH));
  134. exit();
  135. }
  136. /**
  137. * Get facebook login url for the platform.
  138. *
  139. * @return string
  140. */
  141. function facebookGetLoginUrl()
  142. {
  143. $fb = new \Facebook\Facebook([
  144. 'app_id' => $GLOBALS['facebook_config']['appId'],
  145. 'app_secret' => $GLOBALS['facebook_config']['secret'],
  146. 'default_graph_version' => 'v2.2',
  147. ]);
  148. $helper = $fb->getRedirectLoginHelper();
  149. $loginUrl = $helper->getLoginUrl(api_get_path(WEB_PATH).'?action=fbconnect', [
  150. 'email',
  151. ]);
  152. return $loginUrl;
  153. }
  154. /**
  155. * Return a valid Chamilo login
  156. * Chamilo login only use characters lettres, des chiffres et les signes _ . -.
  157. *
  158. * @param $in_txt
  159. *
  160. * @return mixed
  161. */
  162. function changeToValidChamiloLogin($in_txt)
  163. {
  164. return preg_replace("/[^a-zA-Z1-9_\-.]/", "_", $in_txt);
  165. }
  166. /**
  167. * Get user language.
  168. *
  169. * @param string $language
  170. *
  171. * @return bool
  172. */
  173. function facebookPluginGetLanguage($language = 'en_US')
  174. {
  175. $language = substr($language, 0, 2);
  176. $sqlResult = Database::query(
  177. "SELECT english_name FROM ".
  178. Database::get_main_table(TABLE_MAIN_LANGUAGE).
  179. " WHERE available = 1 AND isocode = '$language'"
  180. );
  181. if (Database::num_rows($sqlResult)) {
  182. $result = Database::fetch_array($sqlResult);
  183. return $result['english_name'];
  184. }
  185. return false;
  186. }