Skip to content

Commit

Permalink
notifications
Browse files Browse the repository at this point in the history
  • Loading branch information
cia1 committed Aug 29, 2018
1 parent 9189d97 commit 922ea91
Show file tree
Hide file tree
Showing 10 changed files with 70 additions and 64 deletions.
1 change: 0 additions & 1 deletion www/controller/user.php
Expand Up @@ -97,7 +97,6 @@ public function actionRegisterSubmit($data) {
if(!$data['captcha'] || (int)$data['captcha']!==$_SESSION['captcha']) {
core::error(LNGCaptcha.' '.LNGwroteWrong);
}
core::import('model/user');
if(core::config('_core','emailRequired')===false) $user=core::user()->model();
else {
core::import('model/user');
Expand Down
2 changes: 1 addition & 1 deletion www/core/model.php
Expand Up @@ -8,7 +8,7 @@ class model extends validator {
protected $db; //экземпляр класса базы данных (может быть отличным от заданного по умолчанию)
protected $_multiLanguage=false; //если true, то будут выполнены запросы для всех языков
protected $_languageDb; //true - мультиязычная таблица, array - мультиязычные поля, false - не мультиязычная таблица
private $_bool=array(); //список булевых полей (для корректного преобразования)
protected $_bool=array(); //список булевых полей (для корректного преобразования)

public function __construct($table=null,$db='db') {
if($table) $this->_table=$table; else $this->_table=$_GET['corePath'][0];
Expand Down
8 changes: 4 additions & 4 deletions www/core/validator.php
Expand Up @@ -85,8 +85,8 @@ protected function validateDate($attribute,$setting) {

protected function validateEmail($attribute,$setting) {
$value=$this->_data[$attribute];
if(filter_var($this->_data[$attribute],FILTER_VALIDATE_EMAIL)) {
core::error(sprintf(LNGFieldHasBeEMail,$options[1]));
if(filter_var($value,FILTER_VALIDATE_EMAIL)===false) {
core::error(sprintf(LNGFieldHasBeEMail,$setting[1]));
return false;
}
return true;
Expand All @@ -112,7 +112,7 @@ protected function validateHtml($attribute,$setting) {
}

protected function validateImage($attribute,$setting) {
//settings[]: 'minWidth','minHeight','maxWidth','maxHeight'
//setting[]: 'minWidth','minHeight','maxWidth','maxHeight'
core::import('core/picture');
$value=&$this->_data[$attribute];
if(is_array($value) && !$setting[2] && !$setting['size']) {
Expand Down Expand Up @@ -163,7 +163,7 @@ protected function validteRegular($attribute,$setting) {
$value=$this->_data[$attribute];
if($value) {
if(!preg_match('%'.$setting[3].'%',$value)) {
core::error(sprintf(LNGFieldIllegalValue,$options[1]));
core::error(sprintf(LNGFieldIllegalValue,$setting[1]));
return false;
}
}
Expand Down
24 changes: 13 additions & 11 deletions www/model/form.php
Expand Up @@ -74,11 +74,10 @@ public function execute($id,$data) {
$f=core::path().'data/'.$this->form['script'].'Before.php';
if(file_exists($f)) if(!include($f)) return false; //false расценивается как неудача.
}
//Стандартная валидация полей формы
$model=core::model();
$model->set($data);

//Подготовка данных для валидации
$db->query('SELECT id,title_'._LANG.',htmlType,data_'._LANG.',required FROM frmField WHERE formId='.$id.' ORDER BY sort');
$this->field=$validate=array();
$this->field=$rule=array();
while($item=$db->fetch()) {
$fldName=$item[0];
$value=$data[$fldName];
Expand Down Expand Up @@ -106,11 +105,14 @@ public function execute($id,$data) {
}
}
$this->field[]=array('id'=>$fldName,'title'=>$item[1],'required'=>(bool)$item[4],'htmlType'=>$item[2]);
if($item[2]!='file') $validate[$fldName]=array($type,$item[1],(bool)$item[4]);
if($item[2]!='file') $rule[$fldName]=array($type,$item[1],(bool)$item[4]);
}
$model->set($data);
if(!$model->validate($validate)) return false;
unset($validate);

core::import('core/validator');
$validator=new validator();
$validator->set($data);
if($validator->validate($rule)===false) return false;
unset($rule);

$cfg=core::config();
if($this->form['email']=='cfg') {
Expand Down Expand Up @@ -144,10 +146,10 @@ public function execute($id,$data) {
//Отправить уведомление
if($this->form['notification'] && core::moduleExists('notification')) {
core::import('model/notification');
$transport=notification::instance($this->form['notification']['transport']);
$transport=notification::instance($this->form['notification']['transport'],$this->form['notification']['userId']);
if($transport!==null) {
$transport->send($this->form['notification']['userId'],'Получено сообщение с формы "'.$this->form['title'].'"');
}
$transport->send('Получено сообщение с формы "'.$this->form['title'].'"');
}
}
return true;
}
Expand Down
65 changes: 37 additions & 28 deletions www/model/notification.php
@@ -1,28 +1,5 @@
<?php abstract class notification {

//Должна возвращать название метода отправки уведомления, с учётом мультиязычности
abstract public function title();
//Должна возвращать true, если метод доставки доступен (настроен) для пользователя
abstract public function available();

abstract public function send($userId,$message);

public $userId;
private $_setting;

//Возвращает имя транспорта для группы для текущего пользователя.
public static function userTransportName($group) {
$notification=core::user()->model()->attribute('notification');
return (isset($notification[$group])===false ? null : $notification[$group]);
}

//Возвращает экземпляр класса транспорта для указанной группы или null, если для этой группы уведомления отключены
public static function userTransport($group) {
$notification=core::user()->model()->attribute('notification');
if(isset($notification[$group])===false) return null;
return notification::instance($notification[$group]);
}

//Возвращает массив notification для пользователя $userId
public static function transportList($userId,$available=null) {
$cfg=core::config('notification');
Expand All @@ -33,8 +10,7 @@ public static function transportList($userId,$available=null) {
if($item['status']===false) continue;
$class='notification'.ucfirst($attribute);
core::import('model/'.$class);
$class=new $class(false);
$class->userId=$userId;
$class=new $class($userId);
if($available!==null && $class->available()!=$available) continue;
$transport[]=$class;
}
Expand Down Expand Up @@ -66,17 +42,49 @@ public static function groupList($userId=null) {
return $group;
}

public static function sendIfCan($userId,$group,$message) {
$transport=self::userTransport($userId,$group);
if($transport===null) return null;
return $transport->send($message);
}

//Возвращает экземпляр класса транспорта для указанной группы или null, если для этой группы уведомления отключены
public static function userTransport($userId,$group) {
if($userId===core::userId()) $notification=core::user()->model()->attribute('notification');
else {
core::import('model/user');
$notification=new modelUser();
$notification->id=$userId;
$notification=$notification->attribute('notification');
}
if(isset($notification[$group])===false) return null;
return notification::instance($notification[$group],$userId);
}

//Возвращает класс транспорта, создавая его по ИД
public static function instance($id,$available=true) {
public static function instance($id,$userId,$available=true) {
$transport='notification'.ucfirst(core::translit($id));
if(file_exists(core::path().'model/'.$transport.'.php')===false) return null;
core::import('model/'.$transport);
$transport=new $transport();
$transport=new $transport($userId);
if($transport->status===false) return null;
if($available!==null) if($transport->available()!==$available) return null;
return $transport;
}




//Должна возвращать название метода отправки уведомления, с учётом мультиязычности
abstract public function title();
//Должна возвращать true, если метод доставки доступен (настроен) для пользователя
abstract public function available();

abstract public function send($message);

public $userId; //получатель уведомления
private $_setting;

public function __construct($userId=null) {
if($userId===null) $this->userId=core::userId(); else $this->userId=(int)$userId;
}
Expand All @@ -100,7 +108,8 @@ protected static function userAttribute($userId,$attribute='notification') {
if($userId==core::userId()) $user=core::user()->model();
else {
core::import('model/user');
$user=new modelUser($userId);
$user=new modelUser();
$user->id=$userId;
}
return $user->attribute($attribute);
}
Expand Down
7 changes: 3 additions & 4 deletions www/model/notificationEmail.php
Expand Up @@ -8,12 +8,11 @@ public function available() {
return true;
}

public function send($userId,$message) {
public function send($message) {
core::import('core/email');
$email=new email();
$user=core::user();
if($userId==core::user()) $recepient=$user->email;
else $recepient=core::db()->fetchValue('SELECT email FROM user WHERE id='.(int)$userId);
if($this->userId==core::userId()) $recepient=core::user()->email;
else $recepient=core::db()->fetchValue('SELECT email FROM user WHERE id='.(int)$this->userId);
if(!$recepient) return false;
if($user->email) {
$fromEmail=$user->email;
Expand Down
12 changes: 6 additions & 6 deletions www/model/notificationInner.php
Expand Up @@ -9,16 +9,16 @@ public function available() {
return true;
}

public function send($userId,$message) {
$user=core::user();
public function send($message) {
$db=core::db();
if($userId==$user->id) $recepient=array($user->id,$user->login);
$user=core::user();
if($this->userId==$user->id) $recepient=array($this->userId,$user->login);
else {
$login=$db->fetchValue('SELECT login FROM user WHERE id='.(int)$userId);
$login=$db->fetchValue('SELECT login FROM user WHERE id='.(int)$this->userId);
if(!$login) return false;
$recepient=array((int)$userId,$login);
$recepient=array((int)$this->userId,$login);
}
if($this->userId==$user->id) $sender=array($user->id,$user->login);
if($user->group) $sender=array($user->id,$user->login);
else $sender=array($this->defaultUserId,$this->defaultUserLogin);
if(!$sender[0] || !$sender[1]) return false;
return $db->insert('userMessage',array(
Expand Down
8 changes: 4 additions & 4 deletions www/model/notificationViber.php
Expand Up @@ -10,15 +10,15 @@ public function available() {
return false;
}

public function send($userId,$message) {
$userId=(int)$userId;
public function send($message) {
core::import('model/user');
if($userId===core::userId()) $user=core::user()->model();
if($this->userId===core::userId()) $user=core::user()->model();
else {
$user=new modelUser();
$user->id=$userId;
$user->id=$this->userId;
}
$recipient=$user->attribute('viber');
unset($user);
if(!$recipient || strlen($recipient)!==24) return false;

core::import('model/request');
Expand Down
5 changes: 1 addition & 4 deletions www/model/user.php
Expand Up @@ -148,10 +148,7 @@ public function message($user2Id=null,$user2Login=null,$message) {
//Уведомления
if(core::moduleExists('notification')) {
core::import('model/notification');
$transport=notification::userTransport('privateMessage');
if($transport!==null) {
$transport->send($user2['id'],'<p>'.sprintf(LNGYouGotNewMessageOnSite,$_SERVER['HTTP_HOST'].core::url()).'</p><hr />'.$message);
}
notification::sendIfCan($user2['id'],'privateMessage','<p>'.sprintf(LNGYouGotNewMessageOnSite,$_SERVER['HTTP_HOST'].core::url()).'</p><hr />'.$message);
}
return true;
}
Expand Down
2 changes: 1 addition & 1 deletion www/widget/notificationSettingForm.php
Expand Up @@ -27,8 +27,8 @@ public function __invoke() {
if(!$available) return false;
$form=core::form('notification');
core::language('notification');
array_unshift($available,array(false,LNGDisabled));
foreach($group as $g=>$item) {
array_unshift($available,array(false,LNGDisabled));
$form->radio($g,$item['title'],$available,$item['transport']);
}
$form->submit();
Expand Down

0 comments on commit 922ea91

Please sign in to comment.