Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /**
- * ActionMain.class.php
- * @author: Roman Revin <xgismox@gmail.com>
- * @date : 02.07.13
- */
- class PluginSocialauthlite_ActionMain extends ActionPlugin
- {
- public function Init()
- {
- }
- protected function RegisterEvent()
- {
- $this->AddEventPreg('/^admin/i', '/^$/i', 'EventAdmin');
- $this->AddEventPreg('/^registration/i', '/^$/i', 'EventRegistration');
- $this->AddEventPreg('/^vkontakte_adapter/i', '/^$/i', 'EventVkontakte_adapter');
- }
- public function EventAdmin()
- {
- $this->oUserCurrent = $this->User_GetUserCurrent();
- if (!$this->oUserCurrent or !$this->oUserCurrent->isAdministrator()) {
- return $this->EventNotFound();
- }
- $this->Viewer_AddBlock('right', 'faq', array('plugin' => 'socialauthlite'));
- $can_save = true;
- $file_social_settings_storage = Config::Get('plugin.socialauthlite.file_social_settings_storage');
- if (empty($file_social_settings_storage)) {
- $this->Message_AddError($this->Lang_Get('plugin.socialauthlite.error_file_social_settings_storage_not_found'));
- $can_save = false;
- } elseif (!file_exists($file_social_settings_storage)) {
- $fp = fopen($file_social_settings_storage, 'a+');
- fwrite($fp, file_get_contents($file_social_settings_storage . '.dist'));
- fclose($fp);
- if (!file_exists($file_social_settings_storage)) {
- $this->Message_AddError(
- $this->Lang_Get('plugin.socialauthlite.error_file_social_settings_storage_not_created')
- );
- $can_save = false;
- } else {
- Router::Location(Router::GetPath('socialauth/admin'));
- }
- }
- if (!is_readable($file_social_settings_storage)) {
- $this->Message_AddError(
- $this->Lang_Get('plugin.socialauthlite.error_file_social_settings_storage_not_readable')
- );
- $can_save = false;
- } elseif (!is_writable($file_social_settings_storage)) {
- $this->Message_AddError(
- $this->Lang_Get('plugin.socialauthlite.error_file_social_settings_storage_not_writable')
- );
- $can_save = false;
- }
- if (isset($_POST['c'])) {
- $config = $_POST['c'];
- file_put_contents($file_social_settings_storage, json_encode($config));
- $this->Message_AddNotice($this->Lang_Get('plugin.socialauthlite.success_settings_save'), null, true);
- Router::Location(Router::GetPath('socialauth/admin'));
- }
- $this->Viewer_Assign('can_save', $can_save);
- $this->Viewer_Assign('plugin_config', Config::Get('plugin.socialauthlite.networks'));
- $this->Viewer_SetHtmlTitle($this->Lang_Get('plugin.socialauthlite.admin_title_raw'));
- $this->SetTemplateAction('admin');
- }
- public function EventVkontakte_adapter()
- {
- $error = htmlspecialchars(substr(getRequestStr('error_description', null, 'get'), 0, 100));
- if (!empty($error)) {
- return $this->error($error, 'VK Error');
- }
- $code = getRequestStr('code', null, 'get');
- if (empty($code)) {
- return $this->error(
- $this->Lang_Get('plugin.socialauthlite.vk_code_empty'),
- $this->Lang_Get('attention')
- );
- }
- $q = array(
- 'client_id' => Config::Get('plugin.socialauthlite.networks.vkontakte.app_id'),
- 'client_secret' => Config::Get('plugin.socialauthlite.networks.vkontakte.app_secret'),
- 'code' => $code,
- 'redirect_uri' => Config::Get('plugin.socialauthlite.networks.vkontakte.redirect_uri'),
- );
- $url = 'https://oauth.vk.com/access_token?' . http_build_query($q);
- $response = $this->curl_send($url);
- if (empty($response)) {
- return $this->error($this->Lang_Get('system_error'), $this->Lang_Get('attention'));
- }
- if (isset($response->error)) {
- return $this->error($response->error_description, 'VK Error');
- }
- /** @var PluginSitemap_ModuleUser_EntityUser $oUser */
- if ($oUser = $this->PluginSocialauthlite_Oauth_GetUserByVkontakteID($response->user_id)) {
- if ($oUser->GetUserActivate() === '0') {
- $this->Message_AddErrorSingle(
- $this->Lang_Get(
- 'user_not_activated',
- array('reactivation_path' => Router::GetPath('login') . 'reactivation')
- ),
- null,
- true
- );
- } else {
- $this->User_Authorization($oUser);
- }
- ?>
- <script>
- window.opener.location.reload();
- window.close();
- </script>
- <?
- } else {
- $_SESSION['vk-oauth-response'] = (array)$response;
- if (!empty($response->email)) {
- $_REQUEST['mail'] = $response->email;
- }
- $url = 'https://api.vk.com/method/getProfiles?v=5.21&uid=' . $response->user_id . '&fields=screen_name,photo_200,city,bdate,sex&access_token=' . $response->access_token;
- $response = $this->curl_send($url);
- $_REQUEST['login'] = $response->response[0]->screen_name;
- $_REQUEST['name'] = $response->response[0]->first_name . ' ' . $response->response[0]->last_name;
- $iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($response->response[0]));
- $result = array();
- foreach ($iterator as $key => $value) {
- for ($i = $iterator->getDepth() - 1; $i >= 0; $i--){
- $key = $iterator->getSubIterator($i)->key() . '_' . $key;
- }
- $result[$key] = $iterator->current();
- }
- foreach ($result as $key => $value) {
- setcookie($key, $value, time()+3600, '/');
- }
- $this->SetTemplateAction('approve_fields');
- return;
- }
- $this->SetTemplate(false);
- }
- private function curl_send($url)
- {
- ob_start();
- $ch = curl_init($url);
- curl_exec($ch);
- curl_close($ch);
- return json_decode(ob_get_clean());
- }
- public function EventRegistration()
- {
- /** отключаем капчу */
- $old_captcha_value = Config::Get('module.user.captcha_use_registration');
- Config::Set('module.user.captcha_use_registration', false);
- $login = getRequestStr('login', null, 'post');
- $email = getRequestStr('mail', null, 'post');
- $name = getRequestStr('name', null, 'post');
- $password = func_generator(12);
- /**
- * Устанавливаем формат Ajax ответа
- */
- $this->Viewer_SetResponseAjax('json');
- /**
- * Создаем объект пользователя и устанавливаем сценарий валидации
- */
- /** @var ModuleUser_EntityUser $oUser */
- $oUser = Engine::GetEntity('ModuleUser_EntityUser');
- $oUser->_setValidateScenario('registration');
- /**
- * Заполняем поля (данные)
- */
- $oUser->setLogin($login);
- $oUser->setMail($email);
- $oUser->setProfileName($name);
- $oUser->setPassword($password);
- $oUser->setPasswordConfirm($password);
- $oUser->setDateRegister(date("Y-m-d H:i:s"));
- $oUser->setIpRegister(func_getIp());
- /**
- * Если используется активация, то генерим код активации
- */
- if (Config::Get('general.reg.activation')) {
- $oUser->setActivate(0);
- $oUser->setActivateKey(md5(func_generator() . time()));
- } else {
- $oUser->setActivate(1);
- $oUser->setActivateKey(null);
- }
- $this->Hook_Run('registration_validate_before', array('oUser' => $oUser));
- /**
- * Запускаем валидацию
- */
- if ($oUser->_Validate()) {
- $this->Hook_Run('registration_validate_after', array('oUser' => $oUser));
- $oUser->setPassword(md5($password));
- if ($this->User_Add($oUser)) {
- $this->Hook_Run('registration_after', array('oUser' => $oUser));
- /**
- * Подписываем пользователя на дефолтные события в ленте активности
- */
- $this->Stream_switchUserEventDefaultTypes($oUser->getId());
- /** Создаем OAuth сущность */
- if (isset($_SESSION['vk-oauth-response'])) {
- $oOAuth = $this->create_oauth_entity(
- 'vk',
- $_SESSION['vk-oauth-response']['user_id'],
- $oUser->getId(),
- $_SESSION['vk-oauth-response']['access_token'],
- time() + $_SESSION['vk-oauth-response']['expires_in']
- );
- $this->PluginSocialauthlite_Oauth_AddOAuth($oOAuth);
- }
- /**
- * Если стоит регистрация с активацией то проводим её
- */
- if (Config::Get('general.reg.activation')) {
- /**
- * Отправляем на мыло письмо о подтверждении регистрации
- */
- $this->Notify_SendRegistrationActivate($oUser, $password);
- $this->Viewer_AssignAjax('sUrlRedirect', Router::GetPath('registration') . 'confirm/');
- } else {
- $this->Notify_SendRegistration($oUser, $password);
- $oUser = $this->User_GetUserById($oUser->getId());
- /**
- * Сразу авторизуем
- */
- $this->User_Authorization($oUser, false);
- /**
- * Определяем URL для редиректа после авторизации
- */
- $sUrl = Config::Get('module.user.redirect_after_registration');
- if (getRequestStr('return-path', null, 'get')) {
- $sUrl = getRequestStr('return-path', null, 'get');
- }
- $this->Viewer_AssignAjax('sUrlRedirect', $sUrl ? $sUrl : Config::Get('path.root.web'));
- $this->Message_AddNoticeSingle($this->Lang_Get('registration_ok'), null, true);
- }
- } else {
- $this->Message_AddErrorSingle($this->Lang_Get('system_error'), true);
- return Config::Get('path.root.web');
- }
- } else {
- /**
- * Получаем ошибки
- */
- $this->Viewer_AssignAjax('aErrors', $oUser->_getValidateErrors());
- }
- /** возвращаем капчу */
- Config::Set('module.user.captcha_use_registration', $old_captcha_value);
- }
- private function create_oauth_entity($social_type, $social_user_id, $user_id, $token, $expire = 0)
- {
- /** @var PluginSocialauthlite_ModuleOauth_EntityOauth $Oauth */
- $oOAuth = Engine::GetEntity('PluginSocialauthlite_Oauth_Oauth');
- $oOAuth
- ->SetDateReceived(date('Y-m-d H:i:s'))
- ->SetDateExpire(date('Y-m-d H:i:s', $expire))
- ->SetToken($token)
- ->SetSocialID($social_user_id)
- ->SetSocialType($social_type)
- ->SetUserID($user_id);
- return $oOAuth;
- }
- private function error($message, $title = null)
- {
- $this->Message_AddErrorSingle($message, $title);
- return Router::Action('error');
- }
- }
Add Comment
Please, Sign In to add comment