mirror of
https://github.com/Oreolek/ifhub.club.git
synced 2024-05-21 18:28:17 +03:00
Обновление системы инвайтов. Теперь приглашать на сайт можно и в открытом режиме по реферельной ссылке.
This commit is contained in:
parent
1243fa5618
commit
2a329f7748
|
@ -33,6 +33,14 @@ class ActionAuth extends Action
|
|||
*/
|
||||
public function Init()
|
||||
{
|
||||
/**
|
||||
* Если включены инвайты то перенаправляем на страницу регистрации по инвайтам
|
||||
*/
|
||||
if (!$this->User_IsAuthorization() and Config::Get('general.reg.invite') and in_array(Router::GetActionEvent(),
|
||||
array('register', 'ajax-register')) and !$this->CheckInviteRegister()
|
||||
) {
|
||||
return Router::Action('auth', 'invite');
|
||||
}
|
||||
/**
|
||||
* Устанавливаем дефолтный евент
|
||||
*/
|
||||
|
@ -56,6 +64,8 @@ class ActionAuth extends Action
|
|||
$this->AddEvent('register-confirm', 'EventRegisterConfirm');
|
||||
$this->AddEvent('activate', 'EventActivate');
|
||||
$this->AddEvent('reactivation', 'EventReactivation');
|
||||
$this->AddEvent('invite', 'EventInvite');
|
||||
$this->AddEventPreg('/^referal$/i', '/^[\w\-\_]{1,200}$/i', 'EventReferal');
|
||||
|
||||
$this->AddEvent('ajax-login', 'EventAjaxLogin');
|
||||
$this->AddEvent('ajax-password-reset', 'EventAjaxPasswordReset');
|
||||
|
@ -147,7 +157,7 @@ class ActionAuth extends Action
|
|||
/**
|
||||
* Если уже авторизирован
|
||||
*/
|
||||
if ($this->User_GetUserCurrent()) {
|
||||
if ($this->User_IsAuthorization()) {
|
||||
Router::Location(Router::GetPath('/'));
|
||||
}
|
||||
$this->Viewer_AddHtmlTitle($this->Lang_Get('auth.login.title'));
|
||||
|
@ -160,7 +170,9 @@ class ActionAuth extends Action
|
|||
protected function EventLogout()
|
||||
{
|
||||
$this->Security_ValidateSendForm();
|
||||
$this->User_Logout();
|
||||
if ($this->User_GetUserCurrent()) {
|
||||
$this->User_Logout();
|
||||
}
|
||||
Router::LocationAction('/');
|
||||
}
|
||||
|
||||
|
@ -202,6 +214,9 @@ class ActionAuth extends Action
|
|||
*/
|
||||
protected function EventPasswordReset()
|
||||
{
|
||||
if ($this->User_IsAuthorization()) {
|
||||
Router::LocationAction('/');
|
||||
}
|
||||
$this->SetTemplateAction('reset');
|
||||
/**
|
||||
* Устанавливаем title страницы
|
||||
|
@ -353,6 +368,12 @@ class ActionAuth extends Action
|
|||
* Подписываем пользователя на дефолтные события в ленте активности
|
||||
*/
|
||||
$this->Stream_switchUserEventDefaultTypes($oUser->getId());
|
||||
/**
|
||||
* Если юзер зарегистрировался по приглашению то обновляем инвайт
|
||||
*/
|
||||
if ($sCode = $this->GetInviteRegister()) {
|
||||
$this->Invite_UseCode($sCode, $oUser);
|
||||
}
|
||||
/**
|
||||
* Если стоит регистрация с активацией то проводим её
|
||||
*/
|
||||
|
@ -369,6 +390,7 @@ class ActionAuth extends Action
|
|||
* Сразу авторизуем
|
||||
*/
|
||||
$this->User_Authorization($oUser, false);
|
||||
$this->DropInviteRegister();
|
||||
/**
|
||||
* Определяем URL для редиректа после авторизации
|
||||
*/
|
||||
|
@ -397,7 +419,30 @@ class ActionAuth extends Action
|
|||
*/
|
||||
protected function EventRegister()
|
||||
{
|
||||
if ($this->User_IsAuthorization()) {
|
||||
Router::LocationAction('/');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Обработка реферального кода
|
||||
*/
|
||||
protected function EventReferal()
|
||||
{
|
||||
if ($this->User_IsAuthorization()) {
|
||||
Router::LocationAction('/');
|
||||
}
|
||||
/**
|
||||
* Смотрим наличие реферального кода и сохраняем его в сессию
|
||||
*/
|
||||
if ($sCode = $this->GetParam(0)) {
|
||||
if ($iType = $this->Invite_GetInviteTypeByCode($sCode)) {
|
||||
if (!Config::Get('general.reg.invite') or $iType != ModuleInvite::INVITE_TYPE_REFERAL) {
|
||||
$this->Session_Set('invite_code', $sCode);
|
||||
}
|
||||
}
|
||||
}
|
||||
Router::LocationAction('auth/register');
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -405,6 +450,9 @@ class ActionAuth extends Action
|
|||
*/
|
||||
protected function EventActivate()
|
||||
{
|
||||
if ($this->User_IsAuthorization()) {
|
||||
Router::LocationAction('/');
|
||||
}
|
||||
$bError = false;
|
||||
/**
|
||||
* Проверяет передан ли код активации
|
||||
|
@ -445,6 +493,7 @@ class ActionAuth extends Action
|
|||
*/
|
||||
if ($this->User_Update($oUser)) {
|
||||
$this->User_Authorization($oUser, false);
|
||||
$this->DropInviteRegister();
|
||||
return;
|
||||
} else {
|
||||
$this->Message_AddErrorSingle($this->Lang_Get('system_error'));
|
||||
|
@ -457,8 +506,8 @@ class ActionAuth extends Action
|
|||
*/
|
||||
protected function EventReactivation()
|
||||
{
|
||||
if ($this->User_GetUserCurrent()) {
|
||||
Router::Location(Router::GetPath('/'));
|
||||
if ($this->User_IsAuthorization()) {
|
||||
Router::LocationAction('/');
|
||||
}
|
||||
|
||||
$this->Viewer_AddHtmlTitle($this->Lang_Get('auth.reactivation.title'));
|
||||
|
@ -496,4 +545,54 @@ class ActionAuth extends Action
|
|||
{
|
||||
$this->SetTemplateAction('confirm');
|
||||
}
|
||||
|
||||
protected function EventInvite()
|
||||
{
|
||||
if ($this->User_IsAuthorization()) {
|
||||
Router::LocationAction('/');
|
||||
}
|
||||
$this->SetTemplateAction('invite');
|
||||
|
||||
if (isPost('submit_invite')) {
|
||||
/**
|
||||
* Проверяем валидность кода
|
||||
*/
|
||||
if ($this->Invite_CheckCode(getRequestStr('invite_code'), ModuleInvite::INVITE_TYPE_CODE)) {
|
||||
Router::Location($this->Invite_GetReferalLink(null, getRequestStr('invite_code')));
|
||||
} else {
|
||||
$this->Message_AddError($this->Lang_Get('auth.invite.alerts.error_code'), $this->Lang_Get('error'));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Пытается ли юзер зарегистрироваться с помощью кода приглашения
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
protected function CheckInviteRegister()
|
||||
{
|
||||
if ($this->GetInviteRegister()) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Вожвращает код приглашения из сессии
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function GetInviteRegister()
|
||||
{
|
||||
return $this->Session_Get('invite_code');
|
||||
}
|
||||
|
||||
/**
|
||||
* Удаляет код приглашения из сессии
|
||||
*/
|
||||
protected function DropInviteRegister()
|
||||
{
|
||||
$this->Session_Drop('invite_code');
|
||||
}
|
||||
}
|
|
@ -1,230 +0,0 @@
|
|||
<?php
|
||||
/*
|
||||
* LiveStreet CMS
|
||||
* Copyright © 2013 OOO "ЛС-СОФТ"
|
||||
*
|
||||
* ------------------------------------------------------
|
||||
*
|
||||
* Official site: www.livestreetcms.com
|
||||
* Contact e-mail: office@livestreetcms.com
|
||||
*
|
||||
* GNU General Public License, version 2:
|
||||
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
|
||||
*
|
||||
* ------------------------------------------------------
|
||||
*
|
||||
* @link http://www.livestreetcms.com
|
||||
* @copyright 2013 OOO "ЛС-СОФТ"
|
||||
* @author Maxim Mzhelskiy <rus.engine@gmail.com>
|
||||
*
|
||||
*/
|
||||
|
||||
/**
|
||||
* Обрабатывые авторизацию
|
||||
*
|
||||
* @package application.actions
|
||||
* @since 1.0
|
||||
*/
|
||||
class ActionLogin extends Action
|
||||
{
|
||||
/**
|
||||
* Инициализация
|
||||
*
|
||||
*/
|
||||
public function Init()
|
||||
{
|
||||
/**
|
||||
* Устанавливаем дефолтный евент
|
||||
*/
|
||||
$this->SetDefaultEvent('index');
|
||||
/**
|
||||
* Отключаем отображение статистики выполнения
|
||||
*/
|
||||
Router::SetIsShowStats(false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Регистрируем евенты
|
||||
*
|
||||
*/
|
||||
protected function RegisterEvent()
|
||||
{
|
||||
$this->AddEvent('index', 'EventLogin');
|
||||
$this->AddEvent('exit', 'EventExit');
|
||||
$this->AddEvent('reset', 'EventReset');
|
||||
|
||||
$this->AddEvent('ajax-login', 'EventAjaxLogin');
|
||||
$this->AddEvent('ajax-reset', 'EventAjaxReset');
|
||||
}
|
||||
|
||||
/**
|
||||
* Ajax авторизация
|
||||
*/
|
||||
protected function EventAjaxLogin()
|
||||
{
|
||||
/**
|
||||
* Устанвливаем формат Ajax ответа
|
||||
*/
|
||||
$this->Viewer_SetResponseAjax('json');
|
||||
/**
|
||||
* Логин и пароль являются строками?
|
||||
*/
|
||||
if (!is_string(getRequest('login')) or !is_string(getRequest('password'))) {
|
||||
$this->Message_AddErrorSingle($this->Lang_Get('system_error'));
|
||||
return;
|
||||
}
|
||||
/**
|
||||
* Проверяем есть ли такой юзер по логину
|
||||
*/
|
||||
if ((func_check(getRequest('login'),
|
||||
'mail') and $oUser = $this->User_GetUserByMail(getRequest('login'))) or $oUser = $this->User_GetUserByLogin(getRequest('login'))
|
||||
) {
|
||||
/**
|
||||
* Выбираем сценарий валидации
|
||||
*/
|
||||
$oUser->_setValidateScenario('signIn');
|
||||
/**
|
||||
* Заполняем поля (данные)
|
||||
*/
|
||||
$oUser->setCaptcha(getRequestStr('captcha'));
|
||||
/**
|
||||
* Запускаем валидацию
|
||||
*/
|
||||
if ($oUser->_Validate()) {
|
||||
/**
|
||||
* Сверяем хеши паролей и проверяем активен ли юзер
|
||||
*/
|
||||
|
||||
if ($oUser->getPassword() == func_encrypt(getRequest('password'))) {
|
||||
if (!$oUser->getActivate()) {
|
||||
$this->Message_AddErrorSingle($this->Lang_Get('auth.login.notices.error_not_activated',
|
||||
array('reactivation_path' => Router::GetPath('registration') . 'reactivation')));
|
||||
return;
|
||||
}
|
||||
$bRemember = getRequest('remember', false) ? true : false;
|
||||
/**
|
||||
* Убиваем каптчу
|
||||
*/
|
||||
unset($_SESSION['captcha_keystring_user_auth']);
|
||||
/**
|
||||
* Авторизуем
|
||||
*/
|
||||
$this->User_Authorization($oUser, $bRemember);
|
||||
/**
|
||||
* Определяем редирект
|
||||
*/
|
||||
$sUrl = Config::Get('module.user.redirect_after_login');
|
||||
if (getRequestStr('return-path')) {
|
||||
$sUrl = getRequestStr('return-path');
|
||||
}
|
||||
$this->Viewer_AssignAjax('sUrlRedirect', $sUrl ? $sUrl : Router::GetPath('/'));
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
/**
|
||||
* Получаем ошибки
|
||||
*/
|
||||
$this->Viewer_AssignAjax('aErrors', $oUser->_getValidateErrors());
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
$this->Message_AddErrorSingle($this->Lang_Get('auth.login.notices.error_login'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Обрабатываем процесс залогинивания
|
||||
* По факту только отображение шаблона, дальше вступает в дело Ajax
|
||||
*
|
||||
*/
|
||||
protected function EventLogin()
|
||||
{
|
||||
/**
|
||||
* Если уже авторизирован
|
||||
*/
|
||||
if ($this->User_GetUserCurrent()) {
|
||||
Router::Location(Router::GetPath('/'));
|
||||
}
|
||||
$this->Viewer_AddHtmlTitle($this->Lang_Get('auth.login.title'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Обрабатываем процесс разлогинивания
|
||||
*
|
||||
*/
|
||||
protected function EventExit()
|
||||
{
|
||||
$this->Security_ValidateSendForm();
|
||||
$this->User_Logout();
|
||||
Router::Location(Router::GetPath('/'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Ajax запрос на восстановление пароля
|
||||
*/
|
||||
protected function EventAjaxReset()
|
||||
{
|
||||
/**
|
||||
* Устанвливаем формат Ajax ответа
|
||||
*/
|
||||
$this->Viewer_SetResponseAjax('json');
|
||||
/**
|
||||
* Пользователь с таким емайлом существует?
|
||||
*/
|
||||
if ((func_check(getRequestStr('mail'), 'mail') and $oUser = $this->User_GetUserByMail(getRequestStr('mail')))) {
|
||||
/**
|
||||
* Формируем и отправляем ссылку на смену пароля
|
||||
*/
|
||||
$oReminder = Engine::GetEntity('User_Reminder');
|
||||
$oReminder->setCode(func_generator(32));
|
||||
$oReminder->setDateAdd(date("Y-m-d H:i:s"));
|
||||
$oReminder->setDateExpire(date("Y-m-d H:i:s", time() + 60 * 60 * 24 * 7));
|
||||
$oReminder->setDateUsed(null);
|
||||
$oReminder->setIsUsed(0);
|
||||
$oReminder->setUserId($oUser->getId());
|
||||
if ($this->User_AddReminder($oReminder)) {
|
||||
$this->Message_AddNotice($this->Lang_Get('auth.reset.notices.success_send_link'));
|
||||
$this->Notify_SendReminderCode($oUser, $oReminder);
|
||||
return;
|
||||
}
|
||||
}
|
||||
$this->Message_AddError($this->Lang_Get('auth.notices.error_bad_email'), $this->Lang_Get('error'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Обработка напоминания пароля, подтверждение смены пароля
|
||||
*
|
||||
*/
|
||||
protected function EventReset()
|
||||
{
|
||||
/**
|
||||
* Устанавливаем title страницы
|
||||
*/
|
||||
$this->Viewer_AddHtmlTitle($this->Lang_Get('auth.reset.title'));
|
||||
/**
|
||||
* Проверка кода на восстановление пароля и генерация нового пароля
|
||||
*/
|
||||
if (func_check($this->GetParam(0), 'md5')) {
|
||||
/**
|
||||
* Проверка кода подтверждения
|
||||
*/
|
||||
if ($oReminder = $this->User_GetReminderByCode($this->GetParam(0))) {
|
||||
if (!$oReminder->getIsUsed() and strtotime($oReminder->getDateExpire()) > time() and $oUser = $this->User_GetUserById($oReminder->getUserId())) {
|
||||
$sNewPassword = func_generator(7);
|
||||
$oUser->setPassword(func_encrypt($sNewPassword));
|
||||
if ($this->User_Update($oUser)) {
|
||||
$oReminder->setDateUsed(date("Y-m-d H:i:s"));
|
||||
$oReminder->setIsUsed(1);
|
||||
$this->User_UpdateReminder($oReminder);
|
||||
$this->Notify_SendReminderPassword($oUser, $sNewPassword);
|
||||
$this->SetTemplateAction('reset_confirm');
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
$this->Message_AddErrorSingle($this->Lang_Get('auth.reset.alerts.error_bad_code'),
|
||||
$this->Lang_Get('error'));
|
||||
return Router::Action('error');
|
||||
}
|
||||
}
|
||||
}
|
|
@ -501,20 +501,15 @@ class ActionProfile extends Action
|
|||
$aUsersFriend = $this->User_GetUsersFriend($this->oUserProfile->getId(), 1,
|
||||
Config::Get('module.user.friend_on_profile'));
|
||||
/**
|
||||
* Если активен режим инвайтов, то прогружаем дополнительную информацию
|
||||
* Получаем список тех кого пригласил юзер
|
||||
*/
|
||||
if (Config::Get('general.reg.invite')) {
|
||||
/**
|
||||
* Получаем список тех кого пригласил юзер
|
||||
*/
|
||||
$aUsersInvite = $this->User_GetUsersInvite($this->oUserProfile->getId());
|
||||
$this->Viewer_Assign('usersInvited', $aUsersInvite);
|
||||
/**
|
||||
* Получаем того юзера, кто пригласил текущего
|
||||
*/
|
||||
$oUserInviteFrom = $this->User_GetUserInviteFrom($this->oUserProfile->getId());
|
||||
$this->Viewer_Assign('invitedByUser', $oUserInviteFrom);
|
||||
}
|
||||
$aUsersInvite = $this->Invite_GetUsersInvite($this->oUserProfile->getId());
|
||||
$this->Viewer_Assign('usersInvited', $aUsersInvite);
|
||||
/**
|
||||
* Получаем того юзера, кто пригласил текущего
|
||||
*/
|
||||
$oUserInviteFrom = $this->Invite_GetUserInviteFrom($this->oUserProfile->getId());
|
||||
$this->Viewer_Assign('invitedByUser', $oUserInviteFrom);
|
||||
/**
|
||||
* Получаем список юзеров блога
|
||||
*/
|
||||
|
|
|
@ -1,420 +0,0 @@
|
|||
<?php
|
||||
/*
|
||||
* LiveStreet CMS
|
||||
* Copyright © 2013 OOO "ЛС-СОФТ"
|
||||
*
|
||||
* ------------------------------------------------------
|
||||
*
|
||||
* Official site: www.livestreetcms.com
|
||||
* Contact e-mail: office@livestreetcms.com
|
||||
*
|
||||
* GNU General Public License, version 2:
|
||||
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
|
||||
*
|
||||
* ------------------------------------------------------
|
||||
*
|
||||
* @link http://www.livestreetcms.com
|
||||
* @copyright 2013 OOO "ЛС-СОФТ"
|
||||
* @author Maxim Mzhelskiy <rus.engine@gmail.com>
|
||||
*
|
||||
*/
|
||||
|
||||
/**
|
||||
* Экшен обработки регистрации
|
||||
*
|
||||
* @package application.actions
|
||||
* @since 1.0
|
||||
*/
|
||||
class ActionRegistration extends Action
|
||||
{
|
||||
/**
|
||||
* Инициализация
|
||||
*
|
||||
*/
|
||||
public function Init()
|
||||
{
|
||||
/**
|
||||
* Проверяем аторизован ли юзер
|
||||
*/
|
||||
if ($this->User_IsAuthorization()) {
|
||||
$this->Message_AddErrorSingle($this->Lang_Get('auth.registration.notices.already_registered'),
|
||||
$this->Lang_Get('attention'));
|
||||
return Router::Action('error');
|
||||
}
|
||||
/**
|
||||
* Если включены инвайты то перенаправляем на страницу регистрации по инвайтам
|
||||
*/
|
||||
if (!$this->User_IsAuthorization() and Config::Get('general.reg.invite') and !in_array(Router::GetActionEvent(),
|
||||
array('invite', 'activate', 'reactivation', 'confirm')) and !$this->CheckInviteRegister()
|
||||
) {
|
||||
return Router::Action('registration', 'invite');
|
||||
}
|
||||
$this->SetDefaultEvent('index');
|
||||
/**
|
||||
* Устанавливаем title страницы
|
||||
*/
|
||||
$this->Viewer_AddHtmlTitle($this->Lang_Get('auth.registration.title'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Регистрируем евенты
|
||||
*
|
||||
*/
|
||||
protected function RegisterEvent()
|
||||
{
|
||||
$this->AddEvent('index', 'EventIndex');
|
||||
$this->AddEvent('confirm', 'EventConfirm');
|
||||
$this->AddEvent('activate', 'EventActivate');
|
||||
$this->AddEvent('invite', 'EventInvite');
|
||||
$this->AddEvent('reactivation', 'EventReactivation');
|
||||
|
||||
$this->AddEvent('ajax-validate-fields', 'EventAjaxValidateFields');
|
||||
$this->AddEvent('ajax-registration', 'EventAjaxRegistration');
|
||||
$this->AddEvent('ajax-reactivation', 'EventAjaxReactivation');
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**********************************************************************************
|
||||
************************ РЕАЛИЗАЦИЯ ЭКШЕНА ***************************************
|
||||
**********************************************************************************
|
||||
*/
|
||||
|
||||
/**
|
||||
* Ajax валидация форму регистрации
|
||||
*/
|
||||
protected function EventAjaxValidateFields()
|
||||
{
|
||||
/**
|
||||
* Устанавливаем формат Ajax ответа
|
||||
*/
|
||||
$this->Viewer_SetResponseAjax('json');
|
||||
/**
|
||||
* Создаем объект пользователя и устанавливаем сценарий валидации
|
||||
*/
|
||||
$oUser = Engine::GetEntity('ModuleUser_EntityUser');
|
||||
$oUser->_setValidateScenario('registration');
|
||||
/**
|
||||
* Пробегаем по переданным полям/значениям и валидируем их каждое в отдельности
|
||||
*/
|
||||
$aFields = getRequest('fields');
|
||||
if (is_array($aFields)) {
|
||||
foreach ($aFields as $aField) {
|
||||
if (isset($aField['field']) and isset($aField['value'])) {
|
||||
$this->Hook_Run('registration_validate_field', array('aField' => &$aField, 'oUser' => $oUser));
|
||||
|
||||
$sField = $aField['field'];
|
||||
$sValue = $aField['value'];
|
||||
/**
|
||||
* Список полей для валидации
|
||||
*/
|
||||
switch ($sField) {
|
||||
case 'login':
|
||||
$oUser->setLogin($sValue);
|
||||
break;
|
||||
case 'mail':
|
||||
$oUser->setMail($sValue);
|
||||
break;
|
||||
case 'captcha':
|
||||
$oUser->setCaptcha($sValue);
|
||||
break;
|
||||
case 'password':
|
||||
$oUser->setPassword($sValue);
|
||||
break;
|
||||
case 'password_confirm':
|
||||
$oUser->setPasswordConfirm($sValue);
|
||||
$oUser->setPassword(isset($aField['params']['password']) ? $aField['params']['password'] : null);
|
||||
break;
|
||||
default:
|
||||
continue;
|
||||
break;
|
||||
}
|
||||
/**
|
||||
* Валидируем поле
|
||||
*/
|
||||
$oUser->_Validate(array($sField), false);
|
||||
}
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Возникли ошибки?
|
||||
*/
|
||||
if ($oUser->_hasValidateErrors()) {
|
||||
/**
|
||||
* Получаем ошибки
|
||||
*/
|
||||
$this->Viewer_AssignAjax('aErrors', $oUser->_getValidateErrors());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Обработка Ajax регистрации
|
||||
*/
|
||||
protected function EventAjaxRegistration()
|
||||
{
|
||||
/**
|
||||
* Устанавливаем формат Ajax ответа
|
||||
*/
|
||||
$this->Viewer_SetResponseAjax('json');
|
||||
/**
|
||||
* Создаем объект пользователя и устанавливаем сценарий валидации
|
||||
*/
|
||||
$oUser = Engine::GetEntity('ModuleUser_EntityUser');
|
||||
$oUser->_setValidateScenario('registration');
|
||||
/**
|
||||
* Заполняем поля (данные)
|
||||
*/
|
||||
$oUser->setLogin(getRequestStr('login'));
|
||||
$oUser->setMail(getRequestStr('mail'));
|
||||
$oUser->setPassword(getRequestStr('password'));
|
||||
$oUser->setPasswordConfirm(getRequestStr('password_confirm'));
|
||||
$oUser->setCaptcha(getRequestStr('captcha'));
|
||||
$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(func_encrypt($oUser->getPassword()));
|
||||
if ($this->User_Add($oUser)) {
|
||||
$this->Hook_Run('registration_after', array('oUser' => $oUser));
|
||||
/**
|
||||
* Убиваем каптчу
|
||||
*/
|
||||
unset($_SESSION['captcha_keystring_user_signup']);
|
||||
/**
|
||||
* Подписываем пользователя на дефолтные события в ленте активности
|
||||
*/
|
||||
$this->Stream_switchUserEventDefaultTypes($oUser->getId());
|
||||
/**
|
||||
* Если юзер зарегистрировался по приглашению то обновляем инвайт
|
||||
*/
|
||||
if (Config::Get('general.reg.invite') and $oInvite = $this->User_GetInviteByCode($this->GetInviteRegister())) {
|
||||
$oInvite->setUserToId($oUser->getId());
|
||||
$oInvite->setDateUsed(date("Y-m-d H:i:s"));
|
||||
$oInvite->setUsed(1);
|
||||
$this->User_UpdateInvite($oInvite);
|
||||
}
|
||||
/**
|
||||
* Если стоит регистрация с активацией то проводим её
|
||||
*/
|
||||
if (Config::Get('general.reg.activation')) {
|
||||
/**
|
||||
* Отправляем на мыло письмо о подтверждении регистрации
|
||||
*/
|
||||
$this->Notify_SendRegistrationActivate($oUser, getRequestStr('password'));
|
||||
$this->Viewer_AssignAjax('sUrlRedirect', Router::GetPath('registration') . 'confirm/');
|
||||
} else {
|
||||
$this->Notify_SendRegistration($oUser, getRequestStr('password'));
|
||||
$oUser = $this->User_GetUserById($oUser->getId());
|
||||
/**
|
||||
* Сразу авторизуем
|
||||
*/
|
||||
$this->User_Authorization($oUser, false);
|
||||
$this->DropInviteRegister();
|
||||
/**
|
||||
* Определяем URL для редиректа после авторизации
|
||||
*/
|
||||
$sUrl = Config::Get('module.user.redirect_after_registration');
|
||||
if (getRequestStr('return-path')) {
|
||||
$sUrl = getRequestStr('return-path');
|
||||
}
|
||||
$this->Viewer_AssignAjax('sUrlRedirect', $sUrl ? $sUrl : Router::GetPath('/'));
|
||||
$this->Message_AddNoticeSingle($this->Lang_Get('auth.registration.notices.success'));
|
||||
}
|
||||
} else {
|
||||
$this->Message_AddErrorSingle($this->Lang_Get('system_error'));
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
/**
|
||||
* Получаем ошибки
|
||||
*/
|
||||
$this->Viewer_AssignAjax('aErrors', $oUser->_getValidateErrors());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Показывает страничку регистрации
|
||||
* Просто вывод шаблона
|
||||
*/
|
||||
protected function EventIndex()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Обрабатывает активацию аккаунта
|
||||
*/
|
||||
protected function EventActivate()
|
||||
{
|
||||
$bError = false;
|
||||
/**
|
||||
* Проверяет передан ли код активации
|
||||
*/
|
||||
$sActivateKey = $this->GetParam(0);
|
||||
if (!func_check($sActivateKey, 'md5')) {
|
||||
$bError = true;
|
||||
}
|
||||
/**
|
||||
* Проверяет верный ли код активации
|
||||
*/
|
||||
if (!($oUser = $this->User_GetUserByActivateKey($sActivateKey))) {
|
||||
$bError = true;
|
||||
}
|
||||
/**
|
||||
*
|
||||
*/
|
||||
if ($oUser and $oUser->getActivate()) {
|
||||
$this->Message_AddErrorSingle($this->Lang_Get('auth.registration.notices.error_reactivate'),
|
||||
$this->Lang_Get('error'));
|
||||
return Router::Action('error');
|
||||
}
|
||||
/**
|
||||
* Если что то не то
|
||||
*/
|
||||
if ($bError) {
|
||||
$this->Message_AddErrorSingle($this->Lang_Get('auth.registration.notices.error_code'),
|
||||
$this->Lang_Get('error'));
|
||||
return Router::Action('error');
|
||||
}
|
||||
/**
|
||||
* Активируем
|
||||
*/
|
||||
$oUser->setActivate(1);
|
||||
$oUser->setDateActivate(date("Y-m-d H:i:s"));
|
||||
/**
|
||||
* Сохраняем юзера
|
||||
*/
|
||||
if ($this->User_Update($oUser)) {
|
||||
$this->DropInviteRegister();
|
||||
$this->User_Authorization($oUser, false);
|
||||
return;
|
||||
} else {
|
||||
$this->Message_AddErrorSingle($this->Lang_Get('system_error'));
|
||||
return Router::Action('error');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Повторный запрос активации
|
||||
*/
|
||||
protected function EventReactivation()
|
||||
{
|
||||
if ($this->User_GetUserCurrent()) {
|
||||
Router::Location(Router::GetPath('/'));
|
||||
}
|
||||
|
||||
$this->Viewer_AddHtmlTitle($this->Lang_Get('auth.reactivation.title'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Ajax повторной активации
|
||||
*/
|
||||
protected function EventAjaxReactivation()
|
||||
{
|
||||
$this->Viewer_SetResponseAjax('json');
|
||||
|
||||
if ((func_check(getRequestStr('mail'), 'mail') and $oUser = $this->User_GetUserByMail(getRequestStr('mail')))) {
|
||||
if ($oUser->getActivate()) {
|
||||
$this->Message_AddErrorSingle($this->Lang_Get('auth.registration.notices.error_reactivate'));
|
||||
return;
|
||||
} else {
|
||||
$oUser->setActivateKey(md5(func_generator() . time()));
|
||||
if ($this->User_Update($oUser)) {
|
||||
$this->Message_AddNotice($this->Lang_Get('auth.reactivation.notices.success'));
|
||||
$this->Notify_SendReactivationCode($oUser);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$this->Message_AddErrorSingle($this->Lang_Get('auth.notices.error_bad_email'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Обработка кода приглашения при включеном режиме инвайтов
|
||||
*
|
||||
*/
|
||||
protected function EventInvite()
|
||||
{
|
||||
if (!Config::Get('general.reg.invite')) {
|
||||
return parent::EventNotFound();
|
||||
}
|
||||
/**
|
||||
* Обработка отправки формы с кодом приглашения
|
||||
*/
|
||||
if (isPost('submit_invite')) {
|
||||
/**
|
||||
* проверяем код приглашения на валидность
|
||||
*/
|
||||
if ($this->CheckInviteRegister()) {
|
||||
$sInviteId = $this->GetInviteRegister();
|
||||
} else {
|
||||
$sInviteId = getRequestStr('invite_code');
|
||||
}
|
||||
$oInvate = $this->User_GetInviteByCode($sInviteId);
|
||||
if ($oInvate) {
|
||||
if (!$this->CheckInviteRegister()) {
|
||||
$this->Session_Set('invite_code', $oInvate->getCode());
|
||||
}
|
||||
return Router::Action('registration');
|
||||
} else {
|
||||
$this->Message_AddError($this->Lang_Get('auth.invite.alerts.error_code'), $this->Lang_Get('error'));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Пытается ли юзер зарегистрироваться с помощью кода приглашения
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
protected function CheckInviteRegister()
|
||||
{
|
||||
if ($this->Session_Get('invite_code')) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Вожвращает код приглашения из сессии
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function GetInviteRegister()
|
||||
{
|
||||
return $this->Session_Get('invite_code');
|
||||
}
|
||||
|
||||
/**
|
||||
* Удаляет код приглашения из сессии
|
||||
*/
|
||||
protected function DropInviteRegister()
|
||||
{
|
||||
if (Config::Get('general.reg.invite')) {
|
||||
$this->Session_Drop('invite_code');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Просто выводит шаблон для подтверждения регистрации
|
||||
*
|
||||
*/
|
||||
protected function EventConfirm()
|
||||
{
|
||||
}
|
||||
}
|
|
@ -215,10 +215,10 @@ class ActionSettings extends Action
|
|||
$oViewer = $this->Viewer_GetLocalViewer();
|
||||
|
||||
$oViewer->Assign('image', getRequestStr('path'), true);
|
||||
$oViewer->Assign('originalWidth', (int) getRequest('original_width'), true);
|
||||
$oViewer->Assign('originalHeight', (int) getRequest('original_height'), true);
|
||||
$oViewer->Assign('width', (int) getRequest('width'), true);
|
||||
$oViewer->Assign('height', (int) getRequest('height'), true);
|
||||
$oViewer->Assign('originalWidth', (int)getRequest('original_width'), true);
|
||||
$oViewer->Assign('originalHeight', (int)getRequest('original_height'), true);
|
||||
$oViewer->Assign('width', (int)getRequest('width'), true);
|
||||
$oViewer->Assign('height', (int)getRequest('height'), true);
|
||||
|
||||
$this->Viewer_AssignAjax('sText', $oViewer->Fetch("component@user.modal.crop-photo"));
|
||||
}
|
||||
|
@ -233,10 +233,10 @@ class ActionSettings extends Action
|
|||
$oViewer = $this->Viewer_GetLocalViewer();
|
||||
|
||||
$oViewer->Assign('image', getRequestStr('path'), true);
|
||||
$oViewer->Assign('originalWidth', (int) getRequest('original_width'), true);
|
||||
$oViewer->Assign('originalHeight', (int) getRequest('original_height'), true);
|
||||
$oViewer->Assign('width', (int) getRequest('width'), true);
|
||||
$oViewer->Assign('height', (int) getRequest('height'), true);
|
||||
$oViewer->Assign('originalWidth', (int)getRequest('original_width'), true);
|
||||
$oViewer->Assign('originalHeight', (int)getRequest('original_height'), true);
|
||||
$oViewer->Assign('width', (int)getRequest('width'), true);
|
||||
$oViewer->Assign('height', (int)getRequest('height'), true);
|
||||
$oViewer->Assign('usePreview', true, true);
|
||||
|
||||
$this->Viewer_AssignAjax('sText', $oViewer->Fetch("component@user.modal.crop-avatar"));
|
||||
|
@ -367,16 +367,12 @@ class ActionSettings extends Action
|
|||
*/
|
||||
protected function EventInvite()
|
||||
{
|
||||
/**
|
||||
* Только при активном режиме инвайтов
|
||||
*/
|
||||
if (!Config::Get('general.reg.invite')) {
|
||||
return parent::EventNotFound();
|
||||
}
|
||||
|
||||
$this->sMenuItemSelect = 'invite';
|
||||
$this->sMenuSubItemSelect = '';
|
||||
$this->sMenuSubItemSelect = 'invite';
|
||||
$this->Viewer_AddHtmlTitle($this->Lang_Get('user.settings.nav.invites'));
|
||||
|
||||
$this->Viewer_Assign('iCountInviteAvailable', $this->Invite_GetCountInviteAvailable($this->oUserCurrent));
|
||||
$this->Viewer_Assign('iCountInviteUsed', $this->Invite_GetCountInviteUsed($this->oUserCurrent->getId()));
|
||||
$this->Viewer_Assign('sReferalLink', $this->Invite_GetReferalLink($this->oUserCurrent));
|
||||
/**
|
||||
* Если отправили форму
|
||||
*/
|
||||
|
@ -389,32 +385,40 @@ class ActionSettings extends Action
|
|||
*/
|
||||
if (!$this->ACL_CanSendInvite($this->oUserCurrent)) {
|
||||
$this->Message_AddErrorSingle($this->Rbac_GetMsgLast());
|
||||
$bError = true;
|
||||
return;
|
||||
}
|
||||
/**
|
||||
* Емайл корректен?
|
||||
*/
|
||||
if (!func_check(getRequestStr('invite_mail'), 'mail')) {
|
||||
$this->Message_AddError($this->Lang_Get('fields.email.notices.error'), $this->Lang_Get('error'));
|
||||
$bError = true;
|
||||
if (!$this->Validate_Validate('email', getRequestStr('invite_mail'))) {
|
||||
$this->Message_AddError($this->Validate_GetErrorLast());
|
||||
return;
|
||||
}
|
||||
|
||||
if (Config::Get('general.reg.invite')) {
|
||||
if (!($oInvite = $this->Invite_GenerateInvite($this->oUserCurrent))) {
|
||||
return $this->EventErrorDebug();
|
||||
}
|
||||
$sRefCode = $oInvite->getCode();
|
||||
} else {
|
||||
if (!($sRefCode = $this->Invite_GetReferalCode($this->oUserCurrent))) {
|
||||
return $this->EventErrorDebug();
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Запускаем выполнение хуков
|
||||
*/
|
||||
$this->Hook_Run('settings_invate_send_before', array('oUser' => $this->oUserCurrent));
|
||||
/**
|
||||
* Если нет ошибок, то отправляем инвайт
|
||||
*/
|
||||
if (!$bError) {
|
||||
$oInvite = $this->User_GenerateInvite($this->oUserCurrent);
|
||||
$this->Notify_SendInvite($this->oUserCurrent, getRequestStr('invite_mail'), $oInvite);
|
||||
/**
|
||||
* Запускаем выполнение хуков
|
||||
*/
|
||||
$this->Hook_Run('settings_invite_send_before', array('oUser' => $this->oUserCurrent, 'sRefCode' => $sRefCode));
|
||||
|
||||
$this->Notify_SendInvite($this->oUserCurrent, getRequestStr('invite_mail'), $sRefCode);
|
||||
$this->Message_AddNoticeSingle($this->Lang_Get('user.settings.invites.notices.success'));
|
||||
$this->Hook_Run('settings_invate_send_after', array('oUser' => $this->oUserCurrent));
|
||||
$this->Hook_Run('settings_invite_send_after', array('oUser' => $this->oUserCurrent, 'sRefCode' => $sRefCode));
|
||||
}
|
||||
}
|
||||
|
||||
$this->Viewer_Assign('iCountInviteAvailable', $this->User_GetCountInviteAvailable($this->oUserCurrent));
|
||||
$this->Viewer_Assign('iCountInviteUsed', $this->User_GetCountInviteUsed($this->oUserCurrent->getId()));
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
|
@ -363,15 +363,19 @@ class ModuleACL extends Module
|
|||
public function CanSendInvite($oUser)
|
||||
{
|
||||
$that = $this; // fix for PHP < 5.4
|
||||
return $this->Rbac_IsAllowUser($oUser, 'vote_user', array(
|
||||
return $this->Rbac_IsAllowUser($oUser, 'create_invite', array(
|
||||
'callback' => function ($oUser, $aParams) use ($that) {
|
||||
if (!$oUser) {
|
||||
return false;
|
||||
}
|
||||
if (!Config::Get('general.reg.invite')) {
|
||||
// разрешаем приглашения всем, когда сайт открыт
|
||||
return true;
|
||||
}
|
||||
if ($oUser->isAdministrator()) {
|
||||
return true;
|
||||
}
|
||||
if ($that->User_GetCountInviteAvailable($oUser) == 0) {
|
||||
if ($that->Invite_GetCountInviteAvailable($oUser) == 0) {
|
||||
return $that->Lang_Get('user.settings.invites.available_no');
|
||||
}
|
||||
return true;
|
||||
|
|
257
application/classes/modules/invite/Invite.class.php
Normal file
257
application/classes/modules/invite/Invite.class.php
Normal file
|
@ -0,0 +1,257 @@
|
|||
<?php
|
||||
/*
|
||||
* LiveStreet CMS
|
||||
* Copyright © 2013 OOO "ЛС-СОФТ"
|
||||
*
|
||||
* ------------------------------------------------------
|
||||
*
|
||||
* Official site: www.livestreetcms.com
|
||||
* Contact e-mail: office@livestreetcms.com
|
||||
*
|
||||
* GNU General Public License, version 2:
|
||||
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
|
||||
*
|
||||
* ------------------------------------------------------
|
||||
*
|
||||
* @link http://www.livestreetcms.com
|
||||
* @copyright 2013 OOO "ЛС-СОФТ"
|
||||
* @author Maxim Mzhelskiy <rus.engine@gmail.com>
|
||||
*
|
||||
*/
|
||||
|
||||
/**
|
||||
* Модуль управления инвайтами
|
||||
*
|
||||
* @package application.modules.invite
|
||||
* @since 2.0
|
||||
*/
|
||||
class ModuleInvite extends ModuleORM
|
||||
{
|
||||
/**
|
||||
* Тип реферального инвайта, когда пользователь приглашает по своему реферальному коду
|
||||
*/
|
||||
const INVITE_TYPE_REFERAL = 1;
|
||||
/**
|
||||
* Тип инвайта по сгенерированному коду, когда пользователь генерирует для приглашения отдельный код (доступен в закрытом режиме сайта)
|
||||
*/
|
||||
const INVITE_TYPE_CODE = 2;
|
||||
|
||||
/**
|
||||
* Генерирует новый код инвайта
|
||||
*
|
||||
* @param int $iUserId
|
||||
* @param string|null $sCode
|
||||
* @param int $iCountAllowUse
|
||||
* @param int|string|null $sDateExpired
|
||||
* @return bool|ModuleInvite_EntityCode
|
||||
*/
|
||||
public function GenerateInvite($iUserId, $sCode = null, $iCountAllowUse = 1, $sDateExpired = null)
|
||||
{
|
||||
$iUserId = is_scalar($iUserId) ? (int)$iUserId : $iUserId->getId();
|
||||
$sDateExpired = is_int($sDateExpired) ? date('Y-m-d H:i:s', time() + $sDateExpired) : $sDateExpired;
|
||||
|
||||
$oInviteCode = Engine::GetEntity('ModuleInvite_EntityCode');
|
||||
$oInviteCode->setUserId($iUserId);
|
||||
$oInviteCode->setCode(is_null($sCode) ? $this->GenerateRandomCode() : $sCode);
|
||||
$oInviteCode->setCountAllowUse($iCountAllowUse);
|
||||
$oInviteCode->setDateExpired($sDateExpired);
|
||||
$oInviteCode->setActive(1);
|
||||
if ($oInviteCode->Add()) {
|
||||
return $oInviteCode;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Фиксирует факт использования кода инвайта
|
||||
*
|
||||
* @param string $sCode
|
||||
* @param int $iUserId
|
||||
* @return bool
|
||||
*/
|
||||
public function UseCode($sCode, $iUserId)
|
||||
{
|
||||
$iUserId = is_scalar($iUserId) ? (int)$iUserId : $iUserId->getId();
|
||||
$iType = $this->GetInviteTypeByCode($sCode);
|
||||
|
||||
$oUse = Engine::GetEntity('ModuleInvite_EntityUse');
|
||||
$oUse->setType($iType);
|
||||
$oUse->setToUserId($iUserId);
|
||||
|
||||
if ($iType == self::INVITE_TYPE_CODE) {
|
||||
$oCode = $this->GetCodeByCode($sCode);
|
||||
$oCode->setCountUse($oCode->getCountUse() + 1);
|
||||
$oCode->Update();
|
||||
|
||||
$oUse->setCodeId($oCode->getId());
|
||||
$oUse->setFromUserId($oCode->getUserId());
|
||||
} elseif ($iType == self::INVITE_TYPE_REFERAL) {
|
||||
$oUser = $this->User_GetUserByReferalCode($sCode);
|
||||
$oUse->setFromUserId($oUser->getId());
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
return $oUse->Add();
|
||||
}
|
||||
|
||||
/**
|
||||
* Проверяет корректность кода инвайта с учетом его типа
|
||||
*
|
||||
* @param string $sCode
|
||||
* @param int $iType Тип инвайта, смотри self::INVITE_TYPE_*
|
||||
* @return bool
|
||||
*/
|
||||
public function CheckCode($sCode, $iType = self::INVITE_TYPE_CODE)
|
||||
{
|
||||
if ($iType == self::INVITE_TYPE_CODE) {
|
||||
if ($oCode = $this->GetCodeByCode($sCode)) {
|
||||
if ($oCode->getActive()
|
||||
and $oCode->getCountUse() < $oCode->getCountAllowUse()
|
||||
and (!$oCode->getDateExpired() or strtotime($oCode->getDateExpired()) < time())
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
} elseif ($iType == self::INVITE_TYPE_REFERAL) {
|
||||
if ($oUser = $this->User_GetUserByReferalCode($sCode)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Возвращает тип инвайта по его коду
|
||||
*
|
||||
* @param string $sCode
|
||||
* @return bool|int
|
||||
*/
|
||||
public function GetInviteTypeByCode($sCode)
|
||||
{
|
||||
/**
|
||||
* Приоритет отдаем сгенерированному коду
|
||||
*/
|
||||
if ($this->CheckCode($sCode, self::INVITE_TYPE_CODE)) {
|
||||
return self::INVITE_TYPE_CODE;
|
||||
}
|
||||
if ($this->CheckCode($sCode, self::INVITE_TYPE_REFERAL)) {
|
||||
return self::INVITE_TYPE_REFERAL;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Возвращает персональный реферальный код пользователя
|
||||
*
|
||||
* @param ModuleUser_EntityUser $oUser
|
||||
* @return string|null
|
||||
*/
|
||||
public function GetReferalCode($oUser)
|
||||
{
|
||||
if (is_scalar($oUser)) {
|
||||
$oUser = $this->User_GetUserById($oUser);
|
||||
}
|
||||
if (is_object($oUser)) {
|
||||
return $oUser->getReferalCode();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Возвращает полную ссылку с реферальным кодом
|
||||
*
|
||||
* @param ModuleUser_EntityUser $oUser
|
||||
* @param string|null $sCode
|
||||
* @return null|string
|
||||
*/
|
||||
public function GetReferalLink($oUser, $sCode = null)
|
||||
{
|
||||
if ($sCode or $sCode = $this->GetReferalCode($oUser)) {
|
||||
return Router::GetPath('auth/referal') . urlencode($sCode) . '/';
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Генерирует случайный код
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function GenerateRandomCode()
|
||||
{
|
||||
return func_generator(10);
|
||||
}
|
||||
|
||||
/**
|
||||
* Возвращает количество доступных инвайтов для пользователя в данный момент
|
||||
*
|
||||
* @param ModuleUser_EntityUser $oUser
|
||||
* @return int
|
||||
*/
|
||||
public function GetCountInviteAvailable($oUser)
|
||||
{
|
||||
if (is_scalar($oUser)) {
|
||||
$oUser = $this->User_GetUserById($oUser);
|
||||
}
|
||||
/**
|
||||
* Период в днях, за который выдаем инвайты
|
||||
*/
|
||||
$sDay = 7;
|
||||
/**
|
||||
* Количество выданных инвайтов за эти дни
|
||||
*/
|
||||
$iCountUsed = $this->GetCountFromCodeByFilter(array(
|
||||
'user_id' => $oUser->getId(),
|
||||
'date_create >' => date("Y-m-d 00:00:00", mktime(0, 0, 0, date("m"), date("d") - $sDay, date("Y")))
|
||||
));
|
||||
/**
|
||||
* Доступное число инвайтов период = рейтингу пользователя
|
||||
*/
|
||||
$iCountAllAvailable = round($oUser->getRating());
|
||||
$iCountAllAvailable = $iCountAllAvailable < 0 ? 0 : $iCountAllAvailable;
|
||||
$iCountAvailable = $iCountAllAvailable - $iCountUsed;
|
||||
$iCountAvailable = $iCountAvailable < 0 ? 0 : $iCountAvailable;
|
||||
return $iCountAvailable;
|
||||
}
|
||||
|
||||
/**
|
||||
* Возвращает количество приглашенных пользователей (число использованных инвайтов)
|
||||
*
|
||||
* @param int $iUserId
|
||||
* @return int
|
||||
*/
|
||||
public function GetCountInviteUsed($iUserId)
|
||||
{
|
||||
$iUserId = is_scalar($iUserId) ? (int)$iUserId : $iUserId->getId();
|
||||
|
||||
return $this->GetCountFromUseByFilter(array('from_user_id' => $iUserId));
|
||||
}
|
||||
|
||||
/**
|
||||
* Возвращает пользователя, который пригласил текущего
|
||||
*
|
||||
* @param $iUserId
|
||||
* @return ModuleUser_EntityUser|null
|
||||
*/
|
||||
public function GetUserInviteFrom($iUserId)
|
||||
{
|
||||
if ($oUse = $this->GetUseByToUserId($iUserId) and $iUserFrom = $oUse->getFromUserId()) {
|
||||
return $this->User_GetUserById($iUserFrom);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Возвращает список приглашенных пользователей
|
||||
*
|
||||
* @param int $iUserId
|
||||
* @return array
|
||||
*/
|
||||
public function GetUsersInvite($iUserId)
|
||||
{
|
||||
if ($aUseItems = $this->GetUseItemsByFilter(array('from_user_id' => $iUserId, '#index-from' => 'to_user_id', '#limit' => 100))) {
|
||||
return $this->User_GetUsersAdditionalData(array_keys($aUseItems));
|
||||
}
|
||||
return array();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,39 @@
|
|||
<?php
|
||||
/*
|
||||
* LiveStreet CMS
|
||||
* Copyright © 2013 OOO "ЛС-СОФТ"
|
||||
*
|
||||
* ------------------------------------------------------
|
||||
*
|
||||
* Official site: www.livestreetcms.com
|
||||
* Contact e-mail: office@livestreetcms.com
|
||||
*
|
||||
* GNU General Public License, version 2:
|
||||
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
|
||||
*
|
||||
* ------------------------------------------------------
|
||||
*
|
||||
* @link http://www.livestreetcms.com
|
||||
* @copyright 2013 OOO "ЛС-СОФТ"
|
||||
* @author Maxim Mzhelskiy <rus.engine@gmail.com>
|
||||
*
|
||||
*/
|
||||
|
||||
/**
|
||||
* Сущность инвайта
|
||||
*
|
||||
* @package application.modules.invite
|
||||
* @since 2.0
|
||||
*/
|
||||
class ModuleInvite_EntityCode extends EntityORM
|
||||
{
|
||||
protected function beforeSave()
|
||||
{
|
||||
if ($bResult = parent::beforeSave()) {
|
||||
if ($this->_isNew()) {
|
||||
$this->setDateCreate(date("Y-m-d H:i:s"));
|
||||
}
|
||||
}
|
||||
return $bResult;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,39 @@
|
|||
<?php
|
||||
/*
|
||||
* LiveStreet CMS
|
||||
* Copyright © 2013 OOO "ЛС-СОФТ"
|
||||
*
|
||||
* ------------------------------------------------------
|
||||
*
|
||||
* Official site: www.livestreetcms.com
|
||||
* Contact e-mail: office@livestreetcms.com
|
||||
*
|
||||
* GNU General Public License, version 2:
|
||||
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
|
||||
*
|
||||
* ------------------------------------------------------
|
||||
*
|
||||
* @link http://www.livestreetcms.com
|
||||
* @copyright 2013 OOO "ЛС-СОФТ"
|
||||
* @author Maxim Mzhelskiy <rus.engine@gmail.com>
|
||||
*
|
||||
*/
|
||||
|
||||
/**
|
||||
* Сущность факта использования инвайта
|
||||
*
|
||||
* @package application.modules.invite
|
||||
* @since 2.0
|
||||
*/
|
||||
class ModuleInvite_EntityUse extends EntityORM
|
||||
{
|
||||
protected function beforeSave()
|
||||
{
|
||||
if ($bResult = parent::beforeSave()) {
|
||||
if ($this->_isNew()) {
|
||||
$this->setDateCreate(date("Y-m-d H:i:s"));
|
||||
}
|
||||
}
|
||||
return $bResult;
|
||||
}
|
||||
}
|
|
@ -243,9 +243,9 @@ class ModuleNotify extends Module
|
|||
*
|
||||
* @param ModuleUser_EntityUser $oUserFrom Пароль пользователя, который отправляет инвайт
|
||||
* @param string $sMailTo Емайл на который отправляем инвайт
|
||||
* @param ModuleUser_EntityInvite $oInvite Объект инвайта
|
||||
* @param string $sRefCode Код приглашения
|
||||
*/
|
||||
public function SendInvite(ModuleUser_EntityUser $oUserFrom, $sMailTo, ModuleUser_EntityInvite $oInvite)
|
||||
public function SendInvite(ModuleUser_EntityUser $oUserFrom, $sMailTo, $sRefCode)
|
||||
{
|
||||
$this->Send(
|
||||
$sMailTo,
|
||||
|
@ -254,7 +254,8 @@ class ModuleNotify extends Module
|
|||
array(
|
||||
'sMailTo' => $sMailTo,
|
||||
'oUserFrom' => $oUserFrom,
|
||||
'oInvite' => $oInvite,
|
||||
'sRefCode' => $sRefCode,
|
||||
'sRefLink' => $this->Invite_GetReferalLink($oUserFrom, $sRefCode),
|
||||
)
|
||||
);
|
||||
}
|
||||
|
|
|
@ -463,6 +463,9 @@ class ModuleUser extends Module
|
|||
*/
|
||||
public function Add(ModuleUser_EntityUser $oUser)
|
||||
{
|
||||
if (is_null($oUser->getReferalCode())) {
|
||||
$oUser->setReferalCode(md5((string)$oUser->getMail() . func_generator(32)));
|
||||
}
|
||||
if ($sId = $this->oMapper->Add($oUser)) {
|
||||
$oUser->setId($sId);
|
||||
//чистим зависимые кеши
|
||||
|
@ -516,6 +519,18 @@ class ModuleUser extends Module
|
|||
return $this->GetUserById($id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Получить юзера по реферальному коду
|
||||
*
|
||||
* @param string $sCode Реферальный код
|
||||
* @return ModuleUser_EntityUser|null
|
||||
*/
|
||||
public function GetUserByReferalCode($sCode)
|
||||
{
|
||||
$id = $this->oMapper->GetUserByReferalCode($sCode);
|
||||
return $this->GetUserById($id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Получить юзера по логину
|
||||
*
|
||||
|
@ -1123,135 +1138,6 @@ class ModuleUser extends Module
|
|||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Получает инвайт по его коду
|
||||
*
|
||||
* @param string $sCode Код инвайта
|
||||
* @param int $iUsed Флаг испольщования инвайта
|
||||
* @return ModuleUser_EntityInvite|null
|
||||
*/
|
||||
public function GetInviteByCode($sCode, $iUsed = 0)
|
||||
{
|
||||
return $this->oMapper->GetInviteByCode($sCode, $iUsed);
|
||||
}
|
||||
|
||||
/**
|
||||
* Добавляет новый инвайт
|
||||
*
|
||||
* @param ModuleUser_EntityInvite $oInvite Объект инвайта
|
||||
* @return ModuleUser_EntityInvite|bool
|
||||
*/
|
||||
public function AddInvite(ModuleUser_EntityInvite $oInvite)
|
||||
{
|
||||
if ($sId = $this->oMapper->AddInvite($oInvite)) {
|
||||
$oInvite->setId($sId);
|
||||
return $oInvite;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Обновляет инвайт
|
||||
*
|
||||
* @param ModuleUser_EntityInvite $oInvite бъект инвайта
|
||||
* @return bool
|
||||
*/
|
||||
public function UpdateInvite(ModuleUser_EntityInvite $oInvite)
|
||||
{
|
||||
//чистим зависимые кеши
|
||||
$this->Cache_Clean(Zend_Cache::CLEANING_MODE_MATCHING_TAG,
|
||||
array("invate_new_to_{$oInvite->getUserToId()}", "invate_new_from_{$oInvite->getUserFromId()}"));
|
||||
return $this->oMapper->UpdateInvite($oInvite);
|
||||
}
|
||||
|
||||
/**
|
||||
* Генерирует новый инвайт
|
||||
*
|
||||
* @param ModuleUser_EntityUser $oUser Объект пользователя
|
||||
* @return ModuleUser_EntityInvite|bool
|
||||
*/
|
||||
public function GenerateInvite($oUser)
|
||||
{
|
||||
$oInvite = Engine::GetEntity('User_Invite');
|
||||
$oInvite->setCode(func_generator(32));
|
||||
$oInvite->setDateAdd(date("Y-m-d H:i:s"));
|
||||
$oInvite->setUserFromId($oUser->getId());
|
||||
return $this->AddInvite($oInvite);
|
||||
}
|
||||
|
||||
/**
|
||||
* Получает число использованых приглашений юзером за определенную дату
|
||||
*
|
||||
* @param int $sUserIdFrom ID пользователя
|
||||
* @param string $sDate Дата
|
||||
* @return int
|
||||
*/
|
||||
public function GetCountInviteUsedByDate($sUserIdFrom, $sDate)
|
||||
{
|
||||
return $this->oMapper->GetCountInviteUsedByDate($sUserIdFrom, $sDate);
|
||||
}
|
||||
|
||||
/**
|
||||
* Получает полное число использованных приглашений юзера
|
||||
*
|
||||
* @param int $sUserIdFrom ID пользователя
|
||||
* @return int
|
||||
*/
|
||||
public function GetCountInviteUsed($sUserIdFrom)
|
||||
{
|
||||
return $this->oMapper->GetCountInviteUsed($sUserIdFrom);
|
||||
}
|
||||
|
||||
/**
|
||||
* Получаем число доступных приглашений для юзера
|
||||
*
|
||||
* @param ModuleUser_EntityUser $oUserFrom Объект пользователя
|
||||
* @return int
|
||||
*/
|
||||
public function GetCountInviteAvailable(ModuleUser_EntityUser $oUserFrom)
|
||||
{
|
||||
$sDay = 7;
|
||||
$iCountUsed = $this->GetCountInviteUsedByDate($oUserFrom->getId(),
|
||||
date("Y-m-d 00:00:00", mktime(0, 0, 0, date("m"), date("d") - $sDay, date("Y"))));
|
||||
$iCountAllAvailable = round($oUserFrom->getRating());
|
||||
$iCountAllAvailable = $iCountAllAvailable < 0 ? 0 : $iCountAllAvailable;
|
||||
$iCountAvailable = $iCountAllAvailable - $iCountUsed;
|
||||
$iCountAvailable = $iCountAvailable < 0 ? 0 : $iCountAvailable;
|
||||
return $iCountAvailable;
|
||||
}
|
||||
|
||||
/**
|
||||
* Получает список приглашенных юзеров
|
||||
*
|
||||
* @param int $sUserId ID пользователя
|
||||
* @return array
|
||||
*/
|
||||
public function GetUsersInvite($sUserId)
|
||||
{
|
||||
if (false === ($data = $this->Cache_Get("users_invite_{$sUserId}"))) {
|
||||
$data = $this->oMapper->GetUsersInvite($sUserId);
|
||||
$this->Cache_Set($data, "users_invite_{$sUserId}", array("invate_new_from_{$sUserId}"), 60 * 60 * 24 * 1);
|
||||
}
|
||||
$data = $this->GetUsersAdditionalData($data);
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Получает юзера который пригласил
|
||||
*
|
||||
* @param int $sUserIdTo ID пользователя
|
||||
* @return ModuleUser_EntityUser|null
|
||||
*/
|
||||
public function GetUserInviteFrom($sUserIdTo)
|
||||
{
|
||||
if (false === ($id = $this->Cache_Get("user_invite_from_{$sUserIdTo}"))) {
|
||||
$id = $this->oMapper->GetUserInviteFrom($sUserIdTo);
|
||||
$this->Cache_Set($id, "user_invite_from_{$sUserIdTo}", array("invate_new_to_{$sUserIdTo}"),
|
||||
60 * 60 * 24 * 1);
|
||||
}
|
||||
return $this->GetUserById($id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Добавляем воспоминание(восстановление) пароля
|
||||
*
|
||||
|
|
|
@ -1,170 +0,0 @@
|
|||
<?php
|
||||
/*
|
||||
* LiveStreet CMS
|
||||
* Copyright © 2013 OOO "ЛС-СОФТ"
|
||||
*
|
||||
* ------------------------------------------------------
|
||||
*
|
||||
* Official site: www.livestreetcms.com
|
||||
* Contact e-mail: office@livestreetcms.com
|
||||
*
|
||||
* GNU General Public License, version 2:
|
||||
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
|
||||
*
|
||||
* ------------------------------------------------------
|
||||
*
|
||||
* @link http://www.livestreetcms.com
|
||||
* @copyright 2013 OOO "ЛС-СОФТ"
|
||||
* @author Maxim Mzhelskiy <rus.engine@gmail.com>
|
||||
*
|
||||
*/
|
||||
|
||||
/**
|
||||
* Сущность инвайта(приглашения)
|
||||
*
|
||||
* @package application.modules.user
|
||||
* @since 1.0
|
||||
*/
|
||||
class ModuleUser_EntityInvite extends Entity
|
||||
{
|
||||
/**
|
||||
* Возвращает ID инвайта
|
||||
*
|
||||
* @return int|null
|
||||
*/
|
||||
public function getId()
|
||||
{
|
||||
return $this->_getDataOne('invite_id');
|
||||
}
|
||||
|
||||
/**
|
||||
* Возвращает код инвайта
|
||||
*
|
||||
* @return string|null
|
||||
*/
|
||||
public function getCode()
|
||||
{
|
||||
return $this->_getDataOne('invite_code');
|
||||
}
|
||||
|
||||
/**
|
||||
* Возвращает ID пользователя, который отправляет инвайт
|
||||
*
|
||||
* @return int|null
|
||||
*/
|
||||
public function getUserFromId()
|
||||
{
|
||||
return $this->_getDataOne('user_from_id');
|
||||
}
|
||||
|
||||
/**
|
||||
* Возвращает ID пользователя, которому отправляем инвайт
|
||||
*
|
||||
* @return int|null
|
||||
*/
|
||||
public function getUserToId()
|
||||
{
|
||||
return $this->_getDataOne('user_to_id');
|
||||
}
|
||||
|
||||
/**
|
||||
* Возвращает дату выдачи инвайта
|
||||
*
|
||||
* @return string|null
|
||||
*/
|
||||
public function getDateAdd()
|
||||
{
|
||||
return $this->_getDataOne('invite_date_add');
|
||||
}
|
||||
|
||||
/**
|
||||
* Возвращает дату использования инвайта
|
||||
*
|
||||
* @return string|null
|
||||
*/
|
||||
public function getDateUsed()
|
||||
{
|
||||
return $this->_getDataOne('invite_date_used');
|
||||
}
|
||||
|
||||
/**
|
||||
* Возвращает статус использованости инвайта
|
||||
*
|
||||
* @return int|null
|
||||
*/
|
||||
public function getUsed()
|
||||
{
|
||||
return $this->_getDataOne('invite_used');
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Устанавливает ID инвайта
|
||||
*
|
||||
* @param int $data
|
||||
*/
|
||||
public function setId($data)
|
||||
{
|
||||
$this->_aData['invite_id'] = $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Устанавливает код инвайта
|
||||
*
|
||||
* @param string $data
|
||||
*/
|
||||
public function setCode($data)
|
||||
{
|
||||
$this->_aData['invite_code'] = $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Устанавливает ID пользователя, который отправляет инвайт
|
||||
*
|
||||
* @param int $data
|
||||
*/
|
||||
public function setUserFromId($data)
|
||||
{
|
||||
$this->_aData['user_from_id'] = $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Устанавливает ID пользователя, которому отправляем инвайт
|
||||
*
|
||||
* @param int $data
|
||||
*/
|
||||
public function setUserToId($data)
|
||||
{
|
||||
$this->_aData['user_to_id'] = $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Устанавливает дату выдачи инвайта
|
||||
*
|
||||
* @param string $data
|
||||
*/
|
||||
public function setDateAdd($data)
|
||||
{
|
||||
$this->_aData['invite_date_add'] = $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Устанавливает дату использования инвайта
|
||||
*
|
||||
* @param string $data
|
||||
*/
|
||||
public function setDateUsed($data)
|
||||
{
|
||||
$this->_aData['invite_date_used'] = $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Устанавливает статус использованости инвайта
|
||||
*
|
||||
* @param int $data
|
||||
*/
|
||||
public function setUsed($data)
|
||||
{
|
||||
$this->_aData['invite_used'] = $data;
|
||||
}
|
||||
}
|
|
@ -240,6 +240,16 @@ class ModuleUser_EntityUser extends Entity
|
|||
return $this->_getDataOne('user_activate_key');
|
||||
}
|
||||
|
||||
/**
|
||||
* Возвращает реферальный код
|
||||
*
|
||||
* @return string|null
|
||||
*/
|
||||
public function getReferalCode()
|
||||
{
|
||||
return $this->_getDataOne('user_referal_code');
|
||||
}
|
||||
|
||||
/**
|
||||
* Возвращает имя
|
||||
*
|
||||
|
@ -733,6 +743,16 @@ class ModuleUser_EntityUser extends Entity
|
|||
$this->_aData['user_activate_key'] = $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Устанавливает реферальный код
|
||||
*
|
||||
* @param string $data
|
||||
*/
|
||||
public function setReferalCode($data)
|
||||
{
|
||||
$this->_aData['user_referal_code'] = $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Устанавливает имя
|
||||
*
|
||||
|
|
|
@ -42,12 +42,13 @@ class ModuleUser_MapperUser extends Mapper
|
|||
user_date_register,
|
||||
user_ip_register,
|
||||
user_activate,
|
||||
user_activate_key
|
||||
user_activate_key,
|
||||
user_referal_code
|
||||
)
|
||||
VALUES(?, ?, ?, ?, ?, ?, ?)
|
||||
VALUES(?, ?, ?, ?, ?, ?, ?, ?)
|
||||
";
|
||||
if ($iId = $this->oDb->query($sql, $oUser->getLogin(), $oUser->getPassword(), $oUser->getMail(),
|
||||
$oUser->getDateRegister(), $oUser->getIpRegister(), $oUser->getActivate(), $oUser->getActivateKey())
|
||||
$oUser->getDateRegister(), $oUser->getIpRegister(), $oUser->getActivate(), $oUser->getActivateKey(), $oUser->getReferalCode())
|
||||
) {
|
||||
return $iId;
|
||||
}
|
||||
|
@ -73,6 +74,7 @@ class ModuleUser_MapperUser extends Mapper
|
|||
user_count_vote = ? ,
|
||||
user_activate = ? ,
|
||||
user_activate_key = ? ,
|
||||
user_referal_code = ? ,
|
||||
user_profile_name = ? ,
|
||||
user_profile_sex = ? ,
|
||||
user_profile_country = ? ,
|
||||
|
@ -100,6 +102,7 @@ class ModuleUser_MapperUser extends Mapper
|
|||
$oUser->getCountVote(),
|
||||
$oUser->getActivate(),
|
||||
$oUser->getActivateKey(),
|
||||
$oUser->getReferalCode(),
|
||||
$oUser->getProfileName(),
|
||||
$oUser->getProfileSex(),
|
||||
$oUser->getProfileCountry(),
|
||||
|
@ -337,6 +340,25 @@ class ModuleUser_MapperUser extends Mapper
|
|||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Получить юзера по реферальному коду
|
||||
*
|
||||
* @param string $sCode Код
|
||||
* @return int|null
|
||||
*/
|
||||
public function GetUserByReferalCode($sCode)
|
||||
{
|
||||
$sql = "SELECT
|
||||
u.user_id
|
||||
FROM
|
||||
" . Config::Get('db.table.user') . " as u
|
||||
WHERE u.user_referal_code = ? ";
|
||||
if ($aRow = $this->oDb->selectRow($sql, $sCode)) {
|
||||
return $aRow['user_id'];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Получить юзера по логину
|
||||
*
|
||||
|
@ -715,139 +737,6 @@ class ModuleUser_MapperUser extends Mapper
|
|||
return $aUsers;
|
||||
}
|
||||
|
||||
/**
|
||||
* Получает инвайт по его коду
|
||||
*
|
||||
* @param string $sCode Код инвайта
|
||||
* @param int $iUsed Флаг испольщования инвайта
|
||||
* @return ModuleUser_EntityInvite|null
|
||||
*/
|
||||
public function GetInviteByCode($sCode, $iUsed = 0)
|
||||
{
|
||||
$sql = "SELECT * FROM " . Config::Get('db.table.invite') . " WHERE invite_code = ? and invite_used = ?d ";
|
||||
if ($aRow = $this->oDb->selectRow($sql, $sCode, $iUsed)) {
|
||||
return Engine::GetEntity('User_Invite', $aRow);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Добавляет новый инвайт
|
||||
*
|
||||
* @param ModuleUser_EntityInvite $oInvite Объект инвайта
|
||||
* @return int|bool
|
||||
*/
|
||||
public function AddInvite(ModuleUser_EntityInvite $oInvite)
|
||||
{
|
||||
$sql = "INSERT INTO " . Config::Get('db.table.invite') . "
|
||||
(invite_code,
|
||||
user_from_id,
|
||||
invite_date_add
|
||||
)
|
||||
VALUES(?, ?, ?)
|
||||
";
|
||||
if ($iId = $this->oDb->query($sql, $oInvite->getCode(), $oInvite->getUserFromId(), $oInvite->getDateAdd())) {
|
||||
return $iId;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Обновляет инвайт
|
||||
*
|
||||
* @param ModuleUser_EntityInvite $oInvite бъект инвайта
|
||||
* @return bool
|
||||
*/
|
||||
public function UpdateInvite(ModuleUser_EntityInvite $oInvite)
|
||||
{
|
||||
$sql = "UPDATE " . Config::Get('db.table.invite') . "
|
||||
SET
|
||||
user_to_id = ? ,
|
||||
invite_date_used = ? ,
|
||||
invite_used =?
|
||||
WHERE invite_id = ?
|
||||
";
|
||||
$res = $this->oDb->query($sql, $oInvite->getUserToId(), $oInvite->getDateUsed(), $oInvite->getUsed(),
|
||||
$oInvite->getId());
|
||||
return $this->IsSuccessful($res);
|
||||
}
|
||||
|
||||
/**
|
||||
* Получает число использованых приглашений юзером за определенную дату
|
||||
*
|
||||
* @param int $sUserIdFrom ID пользователя
|
||||
* @param string $sDate Дата
|
||||
* @return int
|
||||
*/
|
||||
public function GetCountInviteUsedByDate($sUserIdFrom, $sDate)
|
||||
{
|
||||
$sql = "SELECT count(invite_id) as count FROM " . Config::Get('db.table.invite') . " WHERE user_from_id = ?d and invite_date_add >= ? ";
|
||||
if ($aRow = $this->oDb->selectRow($sql, $sUserIdFrom, $sDate)) {
|
||||
return $aRow['count'];
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Получает полное число использованных приглашений юзера
|
||||
*
|
||||
* @param int $sUserIdFrom ID пользователя
|
||||
* @return int
|
||||
*/
|
||||
public function GetCountInviteUsed($sUserIdFrom)
|
||||
{
|
||||
$sql = "SELECT count(invite_id) as count FROM " . Config::Get('db.table.invite') . " WHERE user_from_id = ?d";
|
||||
if ($aRow = $this->oDb->selectRow($sql, $sUserIdFrom)) {
|
||||
return $aRow['count'];
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Получает список приглашенных юзеров
|
||||
*
|
||||
* @param int $sUserId ID пользователя
|
||||
* @return array
|
||||
*/
|
||||
public function GetUsersInvite($sUserId)
|
||||
{
|
||||
$sql = "SELECT
|
||||
i.user_to_id
|
||||
FROM
|
||||
" . Config::Get('db.table.invite') . " as i
|
||||
WHERE
|
||||
i.user_from_id = ?d ";
|
||||
$aUsers = array();
|
||||
if ($aRows = $this->oDb->select($sql, $sUserId)) {
|
||||
foreach ($aRows as $aUser) {
|
||||
$aUsers[] = $aUser['user_to_id'];
|
||||
}
|
||||
}
|
||||
return $aUsers;
|
||||
}
|
||||
|
||||
/**
|
||||
* Получает юзера который пригласил
|
||||
*
|
||||
* @param int $sUserIdTo ID пользователя
|
||||
* @return int|null
|
||||
*/
|
||||
public function GetUserInviteFrom($sUserIdTo)
|
||||
{
|
||||
$sql = "SELECT
|
||||
i.user_from_id
|
||||
FROM
|
||||
" . Config::Get('db.table.invite') . " as i
|
||||
WHERE
|
||||
i.user_to_id = ?d
|
||||
LIMIT 0,1;
|
||||
";
|
||||
if ($aRow = $this->oDb->selectRow($sql, $sUserIdTo)) {
|
||||
return $aRow['user_from_id'];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Добавляем воспоминание(восстановление) пароля
|
||||
*
|
||||
|
|
|
@ -321,7 +321,8 @@ $config['db']['table']['talk_blacklist'] = '___db.table.prefix___talk_blacklist'
|
|||
$config['db']['table']['friend'] = '___db.table.prefix___friend';
|
||||
$config['db']['table']['topic_content'] = '___db.table.prefix___topic_content';
|
||||
$config['db']['table']['comment_online'] = '___db.table.prefix___comment_online';
|
||||
$config['db']['table']['invite'] = '___db.table.prefix___invite';
|
||||
$config['db']['table']['invite_code'] = '___db.table.prefix___invite_code';
|
||||
$config['db']['table']['invite_use'] = '___db.table.prefix___invite_use';
|
||||
$config['db']['table']['page'] = '___db.table.prefix___page';
|
||||
$config['db']['table']['reminder'] = '___db.table.prefix___reminder';
|
||||
$config['db']['table']['session'] = '___db.table.prefix___session';
|
||||
|
|
|
@ -115,28 +115,26 @@
|
|||
*}
|
||||
{$items = []}
|
||||
|
||||
{if Config::Get('general.reg.invite')}
|
||||
{* Кто пригласил пользователя *}
|
||||
{if $smarty.local.invitedByUser}
|
||||
{$items[] = [
|
||||
'label' => {lang name='user.profile.activity.invited_by'},
|
||||
'content' => "<a href=\"{$invitedByUser->getUserWebPath()}\">{$invitedByUser->getDisplayName()}</a>"
|
||||
]}
|
||||
{/if}
|
||||
{* Кто пригласил пользователя *}
|
||||
{if $smarty.local.invitedByUser}
|
||||
{$items[] = [
|
||||
'label' => {lang name='user.profile.activity.invited_by'},
|
||||
'content' => "<a href=\"{$invitedByUser->getUserWebPath()}\">{$invitedByUser->getDisplayName()}</a>"
|
||||
]}
|
||||
{/if}
|
||||
|
||||
{* Приглашенные пользователем *}
|
||||
{if $smarty.local.usersInvited}
|
||||
{$users = []}
|
||||
{* Приглашенные пользователем *}
|
||||
{if $smarty.local.usersInvited}
|
||||
{$users = ''}
|
||||
|
||||
{foreach $smarty.local.usersInvited as $userInvited}
|
||||
{$users = $users|cat:"<a href=\"{$userInvited->getUserWebPath()}\">{$userInvited->getDisplayName()}</a> "}
|
||||
{/foreach}
|
||||
{foreach $smarty.local.usersInvited as $userInvited}
|
||||
{$users = $users|cat:"<a href=\"{$userInvited->getUserWebPath()}\">{$userInvited->getDisplayName()}</a> "}
|
||||
{/foreach}
|
||||
|
||||
{$items[] = [
|
||||
'label' => {lang name='user.profile.activity.invited'},
|
||||
'content' => $users
|
||||
]}
|
||||
{/if}
|
||||
{$items[] = [
|
||||
'label' => {lang name='user.profile.activity.invited'},
|
||||
'content' => $users
|
||||
]}
|
||||
{/if}
|
||||
|
||||
{* Блоги созданные пользователем *}
|
||||
|
|
|
@ -2,16 +2,21 @@
|
|||
* Управление инвайтами
|
||||
*}
|
||||
|
||||
<small class="note mb-20">
|
||||
<div class="note mb-20">
|
||||
{lang name='user.settings.invites.note'}
|
||||
</small>
|
||||
</div>
|
||||
|
||||
{hook run='settings_invite_begin'}
|
||||
|
||||
<form action="" method="POST" enctype="multipart/form-data">
|
||||
{hook run='form_settings_invite_begin'}
|
||||
|
||||
<p>
|
||||
{if Config::Get('general.reg.invite')}
|
||||
|
||||
{else}
|
||||
|
||||
{/if}
|
||||
|
||||
<p>
|
||||
{if Config::Get('general.reg.invite')}
|
||||
{lang name='user.settings.invites.available'}:
|
||||
<strong>
|
||||
{if $oUserCurrent->isAdministrator()}
|
||||
|
@ -19,24 +24,36 @@
|
|||
{else}
|
||||
{$iCountInviteAvailable}
|
||||
{/if}
|
||||
</strong><br />
|
||||
</strong>
|
||||
{else}
|
||||
{if $sReferalLink}
|
||||
{lang name='user.settings.invites.referal_link'}:<br/>
|
||||
<strong>{$sReferalLink|escape}</strong>
|
||||
{/if}
|
||||
|
||||
{lang name='user.settings.invites.used'}: <strong>{$iCountInviteUsed}</strong>
|
||||
</p>
|
||||
{/if}
|
||||
<br />
|
||||
|
||||
{* E-mail *}
|
||||
{component 'field' template='text'
|
||||
name = 'invite_mail'
|
||||
note = {lang name='user.settings.invites.fields.email.note'}
|
||||
label = {lang name='user.settings.invites.fields.email.label'}}
|
||||
{lang name='user.settings.invites.used'}: <strong>{($iCountInviteUsed) ? $iCountInviteUsed : {lang name='user.settings.invites.used_empty'}}</strong>
|
||||
</p>
|
||||
|
||||
<form action="" method="POST" enctype="multipart/form-data">
|
||||
{hook run='form_settings_invite_begin'}
|
||||
|
||||
{* E-mail *}
|
||||
{component 'field' template='text'
|
||||
name = 'invite_mail'
|
||||
placeholder = 'e-mail'
|
||||
note = {lang name='user.settings.invites.fields.email.note'}
|
||||
label = {lang name='user.settings.invites.fields.email.label'}}
|
||||
|
||||
{hook run='form_settings_invite_end'}
|
||||
|
||||
{* Скрытые поля *}
|
||||
{component 'field' template='hidden.security-key'}
|
||||
{* Скрытые поля *}
|
||||
{component 'field' template='hidden.security-key'}
|
||||
|
||||
{* Кнопки *}
|
||||
{component 'button' name='submit_invite' mods='primary' text={lang name='user.settings.invites.fields.submit.text'}}
|
||||
{* Кнопки *}
|
||||
{component 'button' name='submit_invite' mods='primary' text={lang name='user.settings.invites.fields.submit.text'}}
|
||||
</form>
|
||||
|
||||
{hook run='settings_invite_end'}
|
|
@ -661,11 +661,9 @@ return array(
|
|||
'subject' => 'Приглашение на регистрацию',
|
||||
'text' =>
|
||||
'Пользователь <a href="%%user_url%%">%%user_name%%</a>
|
||||
пригласил вас зарегистрироваться на сайте <a href="%%website_url%%">%%website_name%%</a>
|
||||
пригласил вас зарегистрироваться на сайте %%website_name%%
|
||||
<br><br>
|
||||
Код приглашения: <b>%%invite_code%%</b>
|
||||
<br><br>
|
||||
Для регистрации вам будет необходимо ввести код приглашения на <a href="%%login_url%%">странице входа</a>'
|
||||
Для регистрации пройдите по ссылке: <a href="%%ref_link%%">%%ref_link%%</a>.'
|
||||
),
|
||||
// Повторная активация
|
||||
'reactivation' => array(
|
||||
|
@ -1398,14 +1396,16 @@ return array(
|
|||
),
|
||||
// Инвайты
|
||||
'invites' => array(
|
||||
'note' => 'Вы можете пригласить на сайт своих друзей и знакомых, для этого просто укажите их e-mail и нажмите кнопку',
|
||||
'available' => 'Доступно',
|
||||
'note' => 'Вы можете пригласить на сайт своих друзей и знакомых, для этого просто укажите их e-mail и нажмите кнопку.',
|
||||
'available' => 'Доступно приглашений',
|
||||
'available_no' => 'У вас пока нет доступных инвайтов',
|
||||
'used' => 'Использовано',
|
||||
'used' => 'Приглашено пользователей',
|
||||
'used_empty' => 'нет',
|
||||
'referal_link' => 'Ваша персональная реферальная ссылка',
|
||||
'many' => 'много',
|
||||
'fields' => array(
|
||||
'email' => array(
|
||||
'label' => 'Пригласить по e-mail адресу',
|
||||
'label' => 'Пригласить пользователя',
|
||||
'note' => 'На этот e-mail будет выслано приглашение для регистрации',
|
||||
),
|
||||
'submit' => array(
|
||||
|
|
|
@ -10,7 +10,8 @@
|
|||
'user_name' => $oUserFrom->getDisplayName(),
|
||||
'website_url' => Router::GetPath('/'),
|
||||
'website_name' => Config::Get('view.name'),
|
||||
'invite_code' => $oInvite->getCode(),
|
||||
'invite_code' => $sRefCode,
|
||||
'ref_link' => $sRefLink,
|
||||
'login_url' => {router page='auth/login'}
|
||||
]}
|
||||
{/block}
|
|
@ -10,5 +10,5 @@
|
|||
[ 'url' => "{router page='settings'}profile/", 'text' => {lang name='user.settings.nav.profile'}, 'name' => 'profile' ],
|
||||
[ 'url' => "{router page='settings'}account/", 'text' => {lang name='user.settings.nav.account'}, 'name' => 'account' ],
|
||||
[ 'url' => "{router page='settings'}tuning/", 'text' => {lang name='user.settings.nav.tuning'}, 'name' => 'tuning' ],
|
||||
[ 'url' => "{router page='settings'}invite/", 'text' => {lang name='user.settings.nav.invites'}, 'name' => 'invite', 'is_enabled' => Config::Get('general.reg.invite') ]
|
||||
[ 'url' => "{router page='settings'}invite/", 'text' => {lang name='user.settings.nav.invites'}, 'name' => 'invite' ]
|
||||
]}
|
|
@ -523,18 +523,18 @@ class InstallStepUpdateVersion extends InstallStep
|
|||
/**
|
||||
* Получаем текущий список админов
|
||||
*/
|
||||
$aUserAdmin=array();
|
||||
$aUserAdmin = array();
|
||||
if ($this->dbCheckTable("prefix_user_administrator")) {
|
||||
if ($aAdmins = $this->dbSelect("SELECT * FROM prefix_user_administrator ")) {
|
||||
foreach ($aAdmins as $aRow) {
|
||||
$aUserAdmin[]=$aRow['user_id'];
|
||||
$aUserAdmin[] = $aRow['user_id'];
|
||||
}
|
||||
}
|
||||
}
|
||||
$iPage = 1;
|
||||
$iLimitCount = 50;
|
||||
$iLimitStart = 0;
|
||||
while ($aUsers = $this->dbSelect("SELECT * FROM prefix_user WHERE (user_profile_foto <> '' and user_profile_foto IS NOT NULL) or (user_profile_avatar <> '' and user_profile_avatar IS NOT NULL) LIMIT {$iLimitStart},{$iLimitCount}")) {
|
||||
while ($aUsers = $this->dbSelect("SELECT * FROM prefix_user LIMIT {$iLimitStart},{$iLimitCount}")) {
|
||||
$iPage++;
|
||||
$iLimitStart = ($iPage - 1) * $iLimitCount;
|
||||
|
||||
|
@ -643,12 +643,20 @@ class InstallStepUpdateVersion extends InstallStep
|
|||
$sTzName = $this->convertTzOffsetToName($aUser['user_settings_timezone']);
|
||||
}
|
||||
|
||||
/**
|
||||
* Реферальный код
|
||||
*/
|
||||
$sReferalCode = $aUser['user_referal_code'];
|
||||
if (!$sReferalCode) {
|
||||
$sReferalCode = md5($aUser['user_id'] . '_' . mt_rand());
|
||||
}
|
||||
|
||||
/**
|
||||
* Админы
|
||||
*/
|
||||
$isAdmin=0;
|
||||
if (in_array($aUser['user_id'],$aUserAdmin) or $aUser['user_admin']) {
|
||||
$isAdmin=1;
|
||||
$isAdmin = 0;
|
||||
if (in_array($aUser['user_id'], $aUserAdmin) or $aUser['user_admin']) {
|
||||
$isAdmin = 1;
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -656,7 +664,7 @@ class InstallStepUpdateVersion extends InstallStep
|
|||
*/
|
||||
$sAvatar = mysqli_escape_string($this->rDbLink, $sAvatar);
|
||||
$sPhoto = mysqli_escape_string($this->rDbLink, $sPhoto);
|
||||
$this->dbQuery("UPDATE prefix_user SET user_admin = '{$isAdmin}' , user_settings_timezone = " . ($sTzName ? "'{$sTzName}'" : 'null') . " , user_profile_avatar = '{$sAvatar}', user_profile_foto = '{$sPhoto}' WHERE user_id ='{$aUser['user_id']}'");
|
||||
$this->dbQuery("UPDATE prefix_user SET user_admin = '{$isAdmin}' , user_referal_code = '{$sReferalCode}' , user_settings_timezone = " . ($sTzName ? "'{$sTzName}'" : 'null') . " , user_profile_avatar = '{$sAvatar}', user_profile_foto = '{$sPhoto}' WHERE user_id ='{$aUser['user_id']}'");
|
||||
|
||||
/**
|
||||
* Удаляем таблицы
|
||||
|
|
|
@ -839,3 +839,33 @@ ALTER TABLE `prefix_poll` ADD `is_guest_allow` TINYINT(1) NOT NULL DEFAULT '0' A
|
|||
ALTER TABLE `prefix_poll_vote` ADD `guest_key` VARCHAR(32) NULL AFTER `user_id`, ADD `ip` VARCHAR(40) NOT NULL AFTER `guest_key`, ADD INDEX (`guest_key`) ;
|
||||
ALTER TABLE `prefix_poll_vote` ADD INDEX(`ip`);
|
||||
ALTER TABLE `prefix_poll_vote` CHANGE `user_id` `user_id` INT(11) NULL DEFAULT NULL;
|
||||
|
||||
-- 27.02.2015
|
||||
DROP TABLE `prefix_invite`;
|
||||
ALTER TABLE `prefix_user` ADD `user_referal_code` VARCHAR(32) NULL DEFAULT NULL AFTER `user_activate_key`, ADD INDEX (`user_referal_code`) ;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `prefix_invite_code` (
|
||||
`id` int(11) NOT NULL,
|
||||
`user_id` int(11) DEFAULT NULL,
|
||||
`code` varchar(32) NOT NULL,
|
||||
`date_create` datetime NOT NULL,
|
||||
`date_expired` datetime DEFAULT NULL,
|
||||
`count_allow_use` int(11) NOT NULL DEFAULT '1',
|
||||
`count_use` int(11) NOT NULL DEFAULT '0',
|
||||
`active` tinyint(1) NOT NULL DEFAULT '1'
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `prefix_invite_use` (
|
||||
`id` int(11) NOT NULL,
|
||||
`type` tinyint(4) NOT NULL DEFAULT '1',
|
||||
`code_id` int(11) DEFAULT NULL,
|
||||
`from_user_id` int(11) DEFAULT NULL,
|
||||
`to_user_id` int(11) NOT NULL,
|
||||
`date_create` datetime NOT NULL
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
|
||||
|
||||
ALTER TABLE `prefix_invite_code`
|
||||
ADD PRIMARY KEY (`id`), ADD KEY `code` (`code`), ADD KEY `count_allow_use` (`count_allow_use`), ADD KEY `count_use` (`count_use`), ADD KEY `active` (`active`), ADD KEY `date_create` (`date_create`), ADD KEY `user_id` (`user_id`);
|
||||
|
||||
ALTER TABLE `prefix_invite_use`
|
||||
ADD PRIMARY KEY (`id`), ADD KEY `type` (`type`), ADD KEY `code_id` (`code_id`), ADD KEY `from_user_id` (`from_user_id`), ADD KEY `to_user_id` (`to_user_id`);
|
||||
|
|
|
@ -1 +1 @@
|
|||
Subproject commit 660b4d87b929734b10014a8e386f22070e67ee96
|
||||
Subproject commit 31b4cc4c82732f7029c90955dc0ee6213948d1f3
|
Loading…
Reference in a new issue