Guest User

Livestreet Plugin

a guest
Jun 22nd, 2014
319
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 9.95 KB | None | 0 0
  1. <?php
  2. /**
  3. * ActionMain.class.php
  4. * @author: Roman Revin <xgismox@gmail.com>
  5. * @date : 02.07.13
  6. */
  7.  
  8. class PluginSocialauthlite_ActionMain extends ActionPlugin
  9. {
  10.  
  11. public function Init()
  12. {
  13. }
  14.  
  15. protected function RegisterEvent()
  16. {
  17. $this->AddEventPreg('/^admin/i', '/^$/i', 'EventAdmin');
  18. $this->AddEventPreg('/^registration/i', '/^$/i', 'EventRegistration');
  19. $this->AddEventPreg('/^vkontakte_adapter/i', '/^$/i', 'EventVkontakte_adapter');
  20. }
  21.  
  22. public function EventAdmin()
  23. {
  24. $this->oUserCurrent = $this->User_GetUserCurrent();
  25. if (!$this->oUserCurrent or !$this->oUserCurrent->isAdministrator()) {
  26. return $this->EventNotFound();
  27. }
  28.  
  29. $this->Viewer_AddBlock('right', 'faq', array('plugin' => 'socialauthlite'));
  30.  
  31. $can_save = true;
  32.  
  33. $file_social_settings_storage = Config::Get('plugin.socialauthlite.file_social_settings_storage');
  34. if (empty($file_social_settings_storage)) {
  35. $this->Message_AddError($this->Lang_Get('plugin.socialauthlite.error_file_social_settings_storage_not_found'));
  36. $can_save = false;
  37. } elseif (!file_exists($file_social_settings_storage)) {
  38. $fp = fopen($file_social_settings_storage, 'a+');
  39. fwrite($fp, file_get_contents($file_social_settings_storage . '.dist'));
  40. fclose($fp);
  41. if (!file_exists($file_social_settings_storage)) {
  42. $this->Message_AddError(
  43. $this->Lang_Get('plugin.socialauthlite.error_file_social_settings_storage_not_created')
  44. );
  45. $can_save = false;
  46. } else {
  47. Router::Location(Router::GetPath('socialauth/admin'));
  48. }
  49. }
  50.  
  51. if (!is_readable($file_social_settings_storage)) {
  52. $this->Message_AddError(
  53. $this->Lang_Get('plugin.socialauthlite.error_file_social_settings_storage_not_readable')
  54. );
  55. $can_save = false;
  56. } elseif (!is_writable($file_social_settings_storage)) {
  57. $this->Message_AddError(
  58. $this->Lang_Get('plugin.socialauthlite.error_file_social_settings_storage_not_writable')
  59. );
  60. $can_save = false;
  61. }
  62.  
  63. if (isset($_POST['c'])) {
  64. $config = $_POST['c'];
  65. file_put_contents($file_social_settings_storage, json_encode($config));
  66. $this->Message_AddNotice($this->Lang_Get('plugin.socialauthlite.success_settings_save'), null, true);
  67. Router::Location(Router::GetPath('socialauth/admin'));
  68. }
  69.  
  70. $this->Viewer_Assign('can_save', $can_save);
  71. $this->Viewer_Assign('plugin_config', Config::Get('plugin.socialauthlite.networks'));
  72.  
  73. $this->Viewer_SetHtmlTitle($this->Lang_Get('plugin.socialauthlite.admin_title_raw'));
  74.  
  75. $this->SetTemplateAction('admin');
  76. }
  77.  
  78. public function EventVkontakte_adapter()
  79. {
  80. $error = htmlspecialchars(substr(getRequestStr('error_description', null, 'get'), 0, 100));
  81. if (!empty($error)) {
  82. return $this->error($error, 'VK Error');
  83. }
  84.  
  85. $code = getRequestStr('code', null, 'get');
  86. if (empty($code)) {
  87. return $this->error(
  88. $this->Lang_Get('plugin.socialauthlite.vk_code_empty'),
  89. $this->Lang_Get('attention')
  90. );
  91. }
  92.  
  93. $q = array(
  94. 'client_id' => Config::Get('plugin.socialauthlite.networks.vkontakte.app_id'),
  95. 'client_secret' => Config::Get('plugin.socialauthlite.networks.vkontakte.app_secret'),
  96. 'code' => $code,
  97. 'redirect_uri' => Config::Get('plugin.socialauthlite.networks.vkontakte.redirect_uri'),
  98. );
  99. $url = 'https://oauth.vk.com/access_token?' . http_build_query($q);
  100.  
  101. $response = $this->curl_send($url);
  102. if (empty($response)) {
  103. return $this->error($this->Lang_Get('system_error'), $this->Lang_Get('attention'));
  104. }
  105.  
  106. if (isset($response->error)) {
  107. return $this->error($response->error_description, 'VK Error');
  108. }
  109.  
  110. /** @var PluginSitemap_ModuleUser_EntityUser $oUser */
  111. if ($oUser = $this->PluginSocialauthlite_Oauth_GetUserByVkontakteID($response->user_id)) {
  112. if ($oUser->GetUserActivate() === '0') {
  113. $this->Message_AddErrorSingle(
  114. $this->Lang_Get(
  115. 'user_not_activated',
  116. array('reactivation_path' => Router::GetPath('login') . 'reactivation')
  117. ),
  118. null,
  119. true
  120. );
  121. } else {
  122. $this->User_Authorization($oUser);
  123. }
  124. ?>
  125. <script>
  126. window.opener.location.reload();
  127. window.close();
  128. </script>
  129. <?
  130. } else {
  131. $_SESSION['vk-oauth-response'] = (array)$response;
  132. if (!empty($response->email)) {
  133. $_REQUEST['mail'] = $response->email;
  134. }
  135.  
  136. $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;
  137. $response = $this->curl_send($url);
  138.  
  139. $_REQUEST['login'] = $response->response[0]->screen_name;
  140. $_REQUEST['name'] = $response->response[0]->first_name . ' ' . $response->response[0]->last_name;
  141.  
  142. $iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($response->response[0]));
  143. $result = array();
  144.  
  145. foreach ($iterator as $key => $value) {
  146. for ($i = $iterator->getDepth() - 1; $i >= 0; $i--){
  147. $key = $iterator->getSubIterator($i)->key() . '_' . $key;
  148. }
  149. $result[$key] = $iterator->current();
  150. }
  151. foreach ($result as $key => $value) {
  152. setcookie($key, $value, time()+3600, '/');
  153. }
  154.  
  155. $this->SetTemplateAction('approve_fields');
  156. return;
  157. }
  158.  
  159. $this->SetTemplate(false);
  160. }
  161.  
  162. private function curl_send($url)
  163. {
  164. ob_start();
  165. $ch = curl_init($url);
  166. curl_exec($ch);
  167. curl_close($ch);
  168. return json_decode(ob_get_clean());
  169. }
  170.  
  171. public function EventRegistration()
  172. {
  173. /** отключаем капчу */
  174. $old_captcha_value = Config::Get('module.user.captcha_use_registration');
  175. Config::Set('module.user.captcha_use_registration', false);
  176.  
  177. $login = getRequestStr('login', null, 'post');
  178. $email = getRequestStr('mail', null, 'post');
  179. $name = getRequestStr('name', null, 'post');
  180. $password = func_generator(12);
  181.  
  182. /**
  183. * Устанавливаем формат Ajax ответа
  184. */
  185. $this->Viewer_SetResponseAjax('json');
  186. /**
  187. * Создаем объект пользователя и устанавливаем сценарий валидации
  188. */
  189. /** @var ModuleUser_EntityUser $oUser */
  190. $oUser = Engine::GetEntity('ModuleUser_EntityUser');
  191. $oUser->_setValidateScenario('registration');
  192. /**
  193. * Заполняем поля (данные)
  194. */
  195. $oUser->setLogin($login);
  196. $oUser->setMail($email);
  197. $oUser->setProfileName($name);
  198. $oUser->setPassword($password);
  199. $oUser->setPasswordConfirm($password);
  200. $oUser->setDateRegister(date("Y-m-d H:i:s"));
  201. $oUser->setIpRegister(func_getIp());
  202. /**
  203. * Если используется активация, то генерим код активации
  204. */
  205. if (Config::Get('general.reg.activation')) {
  206. $oUser->setActivate(0);
  207. $oUser->setActivateKey(md5(func_generator() . time()));
  208. } else {
  209. $oUser->setActivate(1);
  210. $oUser->setActivateKey(null);
  211. }
  212. $this->Hook_Run('registration_validate_before', array('oUser' => $oUser));
  213. /**
  214. * Запускаем валидацию
  215. */
  216. if ($oUser->_Validate()) {
  217. $this->Hook_Run('registration_validate_after', array('oUser' => $oUser));
  218. $oUser->setPassword(md5($password));
  219. if ($this->User_Add($oUser)) {
  220. $this->Hook_Run('registration_after', array('oUser' => $oUser));
  221. /**
  222. * Подписываем пользователя на дефолтные события в ленте активности
  223. */
  224. $this->Stream_switchUserEventDefaultTypes($oUser->getId());
  225. /** Создаем OAuth сущность */
  226. if (isset($_SESSION['vk-oauth-response'])) {
  227. $oOAuth = $this->create_oauth_entity(
  228. 'vk',
  229. $_SESSION['vk-oauth-response']['user_id'],
  230. $oUser->getId(),
  231. $_SESSION['vk-oauth-response']['access_token'],
  232. time() + $_SESSION['vk-oauth-response']['expires_in']
  233. );
  234. $this->PluginSocialauthlite_Oauth_AddOAuth($oOAuth);
  235. }
  236. /**
  237. * Если стоит регистрация с активацией то проводим её
  238. */
  239. if (Config::Get('general.reg.activation')) {
  240. /**
  241. * Отправляем на мыло письмо о подтверждении регистрации
  242. */
  243. $this->Notify_SendRegistrationActivate($oUser, $password);
  244. $this->Viewer_AssignAjax('sUrlRedirect', Router::GetPath('registration') . 'confirm/');
  245. } else {
  246. $this->Notify_SendRegistration($oUser, $password);
  247. $oUser = $this->User_GetUserById($oUser->getId());
  248. /**
  249. * Сразу авторизуем
  250. */
  251. $this->User_Authorization($oUser, false);
  252. /**
  253. * Определяем URL для редиректа после авторизации
  254. */
  255. $sUrl = Config::Get('module.user.redirect_after_registration');
  256. if (getRequestStr('return-path', null, 'get')) {
  257. $sUrl = getRequestStr('return-path', null, 'get');
  258. }
  259. $this->Viewer_AssignAjax('sUrlRedirect', $sUrl ? $sUrl : Config::Get('path.root.web'));
  260. $this->Message_AddNoticeSingle($this->Lang_Get('registration_ok'), null, true);
  261. }
  262. } else {
  263. $this->Message_AddErrorSingle($this->Lang_Get('system_error'), true);
  264. return Config::Get('path.root.web');
  265. }
  266. } else {
  267. /**
  268. * Получаем ошибки
  269. */
  270. $this->Viewer_AssignAjax('aErrors', $oUser->_getValidateErrors());
  271. }
  272.  
  273. /** возвращаем капчу */
  274. Config::Set('module.user.captcha_use_registration', $old_captcha_value);
  275. }
  276.  
  277. private function create_oauth_entity($social_type, $social_user_id, $user_id, $token, $expire = 0)
  278. {
  279. /** @var PluginSocialauthlite_ModuleOauth_EntityOauth $Oauth */
  280. $oOAuth = Engine::GetEntity('PluginSocialauthlite_Oauth_Oauth');
  281. $oOAuth
  282. ->SetDateReceived(date('Y-m-d H:i:s'))
  283. ->SetDateExpire(date('Y-m-d H:i:s', $expire))
  284. ->SetToken($token)
  285. ->SetSocialID($social_user_id)
  286. ->SetSocialType($social_type)
  287. ->SetUserID($user_id);
  288.  
  289. return $oOAuth;
  290. }
  291.  
  292. private function error($message, $title = null)
  293. {
  294. $this->Message_AddErrorSingle($message, $title);
  295. return Router::Action('error');
  296. }
  297. }
Add Comment
Please, Sign In to add comment