1
0
Fork 0
mirror of https://github.com/Oreolek/ifhub.club.git synced 2024-05-17 00:08:17 +03:00

добавлена экспериментальная поддержка инвайтов

This commit is contained in:
Mzhelskiy Maxim 2008-10-11 14:51:38 +00:00
parent 964139629b
commit 07c1b80e2f
18 changed files with 447 additions and 13 deletions

View file

@ -33,6 +33,13 @@ class ActionRegistration extends Action {
$this->Message_AddErrorSingle('Вы уже зарегистрированы у нас и даже авторизованы!','Упс!');
return Router::Action('error');
}
/**
* Если включены инвайты то перенаправляем на страницу регистрации по инвайтам
*/
if (!$this->User_IsAuthorization() and USER_USE_INVITE and Router::GetActionEvent()!='invite' and !$this->CheckInviteRegister()) {
return Router::Action('registration','invite');
}
$this->SetDefaultEvent('index');
$this->Viewer_AddHtmlTitle('Регистрация на сайте');
}
@ -45,6 +52,7 @@ class ActionRegistration extends Action {
$this->AddEvent('ok','EventOk');
$this->AddEvent('confirm','EventConfirm');
$this->AddEvent('activate','EventActivate');
$this->AddEvent('invite','EventInvite');
}
@ -142,6 +150,17 @@ class ActionRegistration extends Action {
* Создаем персональный блог
*/
$this->Blog_CreatePersonalBlog($oUser);
/**
* Если юзер зарегистрировался по приглашению то обновляем инвайт
*/
if (USER_USE_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);
}
/**
* Если стоит регистрация с активацией то проводим её
*/
@ -225,18 +244,71 @@ class ActionRegistration extends Action {
* Сохраняем юзера
*/
if ($this->User_Update($oUser)) {
$this->DropInviteRegister();
return;
} else {
$this->Message_AddErrorSingle('Возникли технические неполадки при активации, пожалуйста повторите активацию позже.','Внутреняя ошибка');
return Router::Action('error');
}
}
/**
* Обработка кода приглашения при включеном режиме инвайтов
*
*/
protected function EventInvite() {
if (!USER_USE_INVITE) {
$this->Message_AddErrorSingle('Приглашения не доступны','Ошибка');
return Router::Action('error');
}
if (isset($_REQUEST['submit_invite'])) {
/**
* проверяем код приглашения на валидность
*/
if ($this->CheckInviteRegister()) {
$sInviteId=$this->GetInviteRegister();
} else {
$sInviteId=getRequest('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('Неверный код приглашения','Ошибка');
}
}
}
/**
* Путается ли юзер зарегистрироваться с помощью кода приглашения
*
* @return unknown
*/
protected function CheckInviteRegister() {
if ($this->Session_Get('invite_code')) {
return true;
}
return false;
}
protected function GetInviteRegister() {
return $this->Session_Get('invite_code');
}
protected function DropInviteRegister() {
if (USER_USE_INVITE) {
$this->Session_Drop('invite_code');
}
}
/**
* Просто выводит шаблон
*
*/
protected function EventOk() {
protected function EventOk() {
$this->DropInviteRegister();
}
/**
* Просто выводит шаблон

View file

@ -49,7 +49,8 @@ class ActionSettings extends Action {
}
protected function RegisterEvent() {
$this->AddEvent('profile','EventProfile');
$this->AddEvent('profile','EventProfile');
$this->AddEvent('invite','EventInvite');
}
@ -58,6 +59,38 @@ class ActionSettings extends Action {
**********************************************************************************
*/
protected function EventInvite() {
if (!USER_USE_INVITE) {
$this->Message_AddErrorSingle('Приглашения не доступны','Ошибка');
return Router::Action('error');
}
if (!isset($_REQUEST['submit_invite'])) {
return ;
}
if (!func_check(getRequest('invite_mail'),'mail')) {
$this->Message_AddError('Неверный формат e-mail','Ошибка');
return ;
}
$oInvite=$this->User_GenerateInvite($this->oUserCurrent);
$this->Mail_SetAdress(getRequest('invite_mail'));
$this->Mail_SetSubject('Приглашение на регистрацию');
$this->Mail_SetBody('
Пользователь <a href="'.DIR_WEB_ROOT.'/profile/'.$this->oUserCurrent->getLogin().'/">'.$this->oUserCurrent->getLogin().'</a> пригласил вас зарегистрироваться на сайте <a href="'.DIR_WEB_ROOT.'">'.SITE_NAME.'</a><br>
Код приглашения: <b>'.$oInvite->getCode().'</b><br>
Для регистрации вам будет необходимо ввести код приглашения на <a href="'.DIR_WEB_ROOT.'">странице входа</a><br>
<br>
С уважением, администрация сайта <a href="'.DIR_WEB_ROOT.'">'.SITE_NAME.'</a>
');
$this->Mail_setHTML();
$this->Mail_Send();
$this->Message_AddNoticeSingle('Приглашение отправлено');
}
/**
* Выводит форму для редактирования профиля и обрабатывает её
*

View file

@ -0,0 +1,64 @@
<?
/*-------------------------------------------------------
*
* LiveStreet Engine Social Networking
* Copyright © 2008 Mzhelskiy Maxim
*
*--------------------------------------------------------
*
* Official site: www.livestreet.ru
* Contact e-mail: rus.engine@gmail.com
*
* GNU General Public License, version 2:
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
---------------------------------------------------------
*/
/**
* Класс инициализации экшенов.
* Он вызывается всегда перед запуском любого экшена. Может выполнять какие то инициализирующие действия, а так же может помочь при введении инвайтов,
* т.е. перенапрявлять всех неавторизованных юзеров на страницу регистрации по приглашению
*
*/
class Init {
/**
*
*/
protected $oEngine=null;
/**
* Текущий юзер
*
* @var unknown_type
*/
protected $oUserCurrent=null;
/**
* Конструктор
*
*/
public function __construct($oEngine) {
$this->oEngine=$oEngine;
$this->oUserCurrent=$this->User_GetUserCurrent();
}
/**
* Ставим хук на вызов неизвестного метода и считаем что хотели вызвать метод какого либо модуля
*
* @param string $sName
* @param array $aArgs
* @return unknown
*/
public function __call($sName,$aArgs) {
return $this->oEngine->_CallModule($sName,$aArgs);
}
/**
* Логика инициализации
*
*/
public function InitAction() {
if (!$this->oUserCurrent and USER_USE_INVITE and Router::GetAction()!='registration' and Router::GetAction()!='login') {
Router::Action('login');
}
}
}
?>

View file

@ -40,7 +40,7 @@ abstract class Action extends Object {
$this->RegisterEvent();
$this->oEngine=$oEngine;
$this->sCurrentAction=$sAction;
$this->aParams=Router::GetParams();
$this->aParams=Router::GetParams();
}
/**
@ -82,8 +82,7 @@ abstract class Action extends Object {
*
* @return unknown
*/
public function ExecEvent() {
dump($this->aRegisterEvent);
public function ExecEvent() {
$this->sCurrentEvent=Router::GetActionEvent();
if ($this->sCurrentEvent==null) {
$this->sCurrentEvent=$this->GetDefaultEvent();

View file

@ -123,7 +123,15 @@ class Router extends Object {
*
*/
public function ExecAction() {
$sActionClass=$this->DefineActionClass();
$this->DefineActionClass();
/**
* Сначала запускаем инициализирующий экшен
*/
require_once('./classes/actions/Init.class.php');
$oActionInit=new Init($this->oEngine);
$oActionInit->InitAction();
$sActionClass=$this->DefineActionClass();
require_once('./classes/actions/'.$sActionClass.'.class.php');
$this->oAction=new $sActionClass($this->oEngine,self::$sAction);
if ($this->oAction->Init()==='next') {

View file

@ -54,7 +54,7 @@ class Message extends Module {
* @param string $sMsg
* @param string $sTitle
*/
public function AddError($sMsg,$sTitle) {
public function AddError($sMsg,$sTitle=null) {
$this->aMsgError[]=array('msg'=>$sMsg,'title'=>$sTitle);
}
@ -64,7 +64,7 @@ class Message extends Module {
* @param string $sMsg
* @param string $sTitle
*/
public function AddErrorSingle($sMsg,$sTitle) {
public function AddErrorSingle($sMsg,$sTitle=null) {
$this->aMsgError=array();
$this->aMsgError[]=array('msg'=>$sMsg,'title'=>$sTitle);
}
@ -74,7 +74,7 @@ class Message extends Module {
* @param string $sMsg
* @param string $sTitle
*/
public function AddNotice($sMsg,$sTitle) {
public function AddNotice($sMsg,$sTitle=null) {
$this->aMsgNotice[]=array('msg'=>$sMsg,'title'=>$sTitle);
}
@ -84,7 +84,7 @@ class Message extends Module {
* @param string $sMsg
* @param string $sTitle
*/
public function AddNoticeSingle($sMsg,$sTitle) {
public function AddNoticeSingle($sMsg,$sTitle=null) {
$this->aMsgNotice=array();
$this->aMsgNotice[]=array('msg'=>$sMsg,'title'=>$sTitle);
}

View file

@ -91,6 +91,8 @@ class Viewer extends Module {
$this->Assign("DIR_STATIC_ROOT",DIR_STATIC_ROOT);
$this->Assign("SITE_NAME",SITE_NAME);
$this->Assign("DIR_UPLOADS_IMAGES",DIR_UPLOADS_IMAGES);
$this->Assign("USER_USE_INVITE",USER_USE_INVITE);
/**
* Загружаем список блоков
*/

View file

@ -401,5 +401,50 @@ class User extends Module {
}
return $data;
}
/**
* Получает инвайт по его коду
*
* @param unknown_type $sCode
* @param unknown_type $iUsed
* @return unknown
*/
public function GetInviteByCode($sCode,$iUsed=0) {
return $this->oMapper->GetInviteByCode($sCode,$iUsed);
}
/**
* Добавляет новый инвайт
*
* @param UserEntity_Invite $oInvite
* @return unknown
*/
public function AddInvite(UserEntity_Invite $oInvite) {
if ($sId=$this->oMapper->AddInvite($oInvite)) {
$oInvite->setId($sId);
return $oInvite;
}
return false;
}
/**
* Обновляет инвайт
*
* @param UserEntity_Invite $oInvite
* @return unknown
*/
public function UpdateInvite(UserEntity_Invite $oInvite) {
return $this->oMapper->UpdateInvite($oInvite);
}
/**
* Генерирует новый инвайт
*
* @param unknown_type $oUser
* @return unknown
*/
public function GenerateInvite($oUser) {
$oInvite=new UserEntity_Invite();
$oInvite->setCode(func_generator(32));
$oInvite->setDateAdd(date("Y-m-d H:i:s"));
$oInvite->setUserFromId($oUser->getId());
return $this->AddInvite($oInvite);
}
}
?>

View file

@ -0,0 +1,67 @@
<?
/*-------------------------------------------------------
*
* LiveStreet Engine Social Networking
* Copyright © 2008 Mzhelskiy Maxim
*
*--------------------------------------------------------
*
* Official site: www.livestreet.ru
* Contact e-mail: rus.engine@gmail.com
*
* GNU General Public License, version 2:
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
---------------------------------------------------------
*/
class UserEntity_Invite extends Entity
{
public function getId() {
return $this->_aData['invite_id'];
}
public function getCode() {
return $this->_aData['invite_code'];
}
public function getUserFromId() {
return $this->_aData['user_from_id'];
}
public function getUserToId() {
return $this->_aData['user_to_id'];
}
public function getDateAdd() {
return $this->_aData['invite_date_add'];
}
public function getDateUsed() {
return $this->_aData['invite_date_used'];
}
public function getUsed() {
return $this->_aData['invite_used'];
}
public function setId($data) {
$this->_aData['invite_id']=$data;
}
public function setCode($data) {
$this->_aData['invite_code']=$data;
}
public function setUserFromId($data) {
$this->_aData['user_from_id']=$data;
}
public function setUserToId($data) {
$this->_aData['user_to_id']=$data;
}
public function setDateAdd($data) {
$this->_aData['invite_date_add']=$data;
}
public function setDateUsed($data) {
$this->_aData['invite_date_used']=$data;
}
public function setUsed($data) {
$this->_aData['invite_used']=$data;
}
}
?>

View file

@ -397,5 +397,41 @@ class Mapper_User extends Mapper {
}
return $aUsers;
}
public function GetInviteByCode($sCode,$iUsed=0) {
$sql = "SELECT * FROM ".DB_TABLE_INVITE." WHERE invite_code = ? and invite_used = ?d ";
if ($aRow=$this->oDb->selectRow($sql,$sCode,$iUsed)) {
return new UserEntity_Invite($aRow);
}
return null;
}
public function AddInvite(UserEntity_Invite $oInvite) {
$sql = "INSERT INTO ".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;
}
public function UpdateInvite(UserEntity_Invite $oInvite) {
$sql = "UPDATE ".DB_TABLE_INVITE."
SET
user_to_id = ? ,
invite_date_used = ? ,
invite_used =?
WHERE invite_id = ?
";
if ($this->oDb->query($sql,$oInvite->getUserToId(), $oInvite->getDateUsed(), $oInvite->getUsed(), $oInvite->getId())) {
return true;
}
return false;
}
}
?>

View file

@ -103,6 +103,7 @@ define('ACL_CAN_VOTE_USER',-1); // порог рейтинга при котор
*/
define('SITE_NAME','LiveStreet - бесплатный движок социальной сети'); // название сайта
define('USER_USE_ACTIVATION',false); // использовать активацию при регистрации или нет
define('USER_USE_INVITE',false); // использовать режим регистрации по приглашению или нет
define('BLOG_PERSONAL_LIMIT_GOOD',-5); // Рейтинг топика в персональном блоге ниже которого он считается плохим
define('BLOG_COLLECTIVE_LIMIT_GOOD',-3); // рейтинг топика в коллективных блогах ниже которого он считается плохим
define('BLOG_INDEX_LIMIT_GOOD',8); // рейтинг топика выше которого(включительно) он попадает на главную

View file

@ -41,4 +41,5 @@ define('DB_TABLE_TOPIC_CONTENT',DB_PREFIX_TABLE.'topic_content');
define('DB_TABLE_TOPIC_QUESTION_VOTE',DB_PREFIX_TABLE.'topic_question_vote');
define('DB_TABLE_USER_ADMINISTRATOR',DB_PREFIX_TABLE.'user_administrator');
define('DB_TABLE_TOPIC_COMMENT_ONLINE',DB_PREFIX_TABLE.'topic_comment_online');
define('DB_TABLE_INVITE',DB_PREFIX_TABLE.'invite');
?>

View file

@ -102,6 +102,38 @@ ALTER TABLE `prefix_topic_comment_online`
-- новое поле для принудительного вывода топика на главную страницу
ALTER TABLE `prefix_topic` ADD `topic_publish_index` TINYINT( 1 ) NOT NULL DEFAULT '0' AFTER `topic_publish` ;
--
-- Структура таблицы `prefix_invite`
--
CREATE TABLE IF NOT EXISTS `prefix_invite` (
`invite_id` int(11) unsigned NOT NULL auto_increment,
`invite_code` varchar(32) collate utf8_bin NOT NULL,
`user_from_id` int(11) unsigned NOT NULL,
`user_to_id` int(11) unsigned default NULL,
`invite_date_add` datetime NOT NULL,
`invite_date_used` datetime NOT NULL,
`invite_used` tinyint(1) unsigned NOT NULL default '0',
PRIMARY KEY (`invite_id`),
UNIQUE KEY `invite_code` (`invite_code`),
KEY `user_from_id` (`user_from_id`),
KEY `user_to_id` (`user_to_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
--
-- Ограничения внешнего ключа таблицы `prefix_invite`
--
ALTER TABLE `prefix_invite`
ADD CONSTRAINT `prefix_invite_fk` FOREIGN KEY (`user_from_id`) REFERENCES `prefix_user` (`user_id`) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT `prefix_invite_fk1` FOREIGN KEY (`user_to_id`) REFERENCES `prefix_user` (`user_id`) ON DELETE CASCADE ON UPDATE CASCADE;
--
-- ВНИМАНИЕ!!! То что ниже нужно выполнить только после запуска скрипта convert.php !!!! иначе УДАЛЯТСЯ ВСЕ ТОПИКИ!!!!!

View file

@ -27,6 +27,18 @@
<p><input type="submit" name="submit_login" value="войти" /></p>
</form>
{if $USER_USE_INVITE}
<br>
<p><span class="header">Регистрация по приглашению</span><br />
<form action="{$DIR_WEB_ROOT}/registration/invite/" method="POST">
<p><span class="form">Код приглашения: </span> <input type="text" value="" name="invite_code" size="29"> <input type="submit" name="submit_invite" value="проверить код"></p>
</form>
{/if}
</td>
</tr>
</table>

View file

@ -0,0 +1,19 @@
{include file='header.light.tpl'}
{include file='system_message.tpl'}
<table width="100%" border="0" cellspacing="4" cellpadding="4">
<tr>
<td align="left">
<p><span class="header">Регистрация по приглашению</span><br />
<form action="{$DIR_WEB_ROOT}/registration/invite/" method="POST">
<p><span class="form">Код приглашения: </span> <input type="text" value="" name="invite_code" size="29"> <input type="submit" name="submit_invite" value="проверить код"></p>
</form>
</td>
</tr>
</table>
{include file='footer.light.tpl'}

View file

@ -0,0 +1,34 @@
{include file='header.tpl'}
{include file='system_message.tpl'}
<BR>
<table width="100%" border="0" cellspacing="4" cellpadding="4">
<tr>
<td align="left">
<p><span class="header">Управление приглашениями</span>
<form action="{$DIR_WEB_ROOT}/settings/invite/" method="POST" enctype="multipart/form-data">
<label for="invite_mail"><span class="form">Пригласить по e-mail адресу:</span></label><br />
<input style="width: 60%;" type="text" name="invite_mail" tabindex="1" id="invite_mail" value="" size="20" /> <br>
<span class="form_note">На этот e-mail будет высланно приглашение для регистрации</span><br />
<br>
<p class="l-bot"><input type="submit" name="submit_invite" tabindex="6" value="отправить приглашение" /></p>
</form>
<p><span class="txt_small">Может быть, перейти на <a href="{$DIR_WEB_ROOT}/">заглавную страницу</a>?</span><br />
</td>
</tr>
</table>
{include file='footer.tpl'}

View file

@ -65,7 +65,10 @@ var msgNoticeBox=new Roar({
<nobr>У вас нет <A class=hello_exit href="{$DIR_WEB_ROOT}/talk/">новых сообщений</a></nobr><br>
{/if}
Изменить <A class=hello_exit href="{$DIR_WEB_ROOT}/settings/">настройки профиля</a>
Изменить <A class=hello_exit href="{$DIR_WEB_ROOT}/settings/">настройки профиля</a><br>
{if $USER_USE_INVITE}
Управлять <A class=hello_exit href="{$DIR_WEB_ROOT}/settings/invite/">приглашениями</a>
{/if}
{else}
<DIV class=hello>
<form action="{$DIR_WEB_ROOT}/login/" method="POST" id="loginform">

View file

@ -5,7 +5,10 @@
<ul>
{foreach from=$aMsgError item=aMsg}
<li>
<b>{$aMsg.title}</b>: {$aMsg.msg}
{if $aMsg.title!=''}
<b>{$aMsg.title}</b>:
{/if}
{$aMsg.msg}
</li>
{/foreach}
</ul>
@ -19,7 +22,10 @@
<ul>
{foreach from=$aMsgNotice item=aMsg}
<li>
<b>{$aMsg.title}</b>: {$aMsg.msg}
{if $aMsg.title!=''}
<b>{$aMsg.title}</b>:
{/if}
{$aMsg.msg}
</li>
{/foreach}
</ul>