Skip to content

Instantly share code, notes, and snippets.

@AgelxNash
Last active April 17, 2019 12:21
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save AgelxNash/7336644 to your computer and use it in GitHub Desktop.
Save AgelxNash/7336644 to your computer and use it in GitHub Desktop.
Плагин для MODX Evolution отправляющий уведомление на почту указанную в документе при сохранении этого же документа (имеется проверка на заполненность обязательного поля во время сохранения). Помимо этого плагин сохраняет в ТВ параметр статус отправки письма. И если все хорошо, то при повторном редактировании письмо не отправляется. Но для этого…
<?php
/**
* MailNotify
*
* Отправка уведомлений на почту пользователю при публикации документа
*
* @license GNU General Public License (GPL), http://www.gnu.org/copyleft/gpl.html
* @author Agel_Nash <Agel_Nash@xaker.ru>
* @version 0.1
*
* @internal @properties &fieldmail=Поле с email;text;longtitle &tpl=Чанк с шаблоном письма;text;notifyMail &fieldreply=Поле с ответом;text;content &modresource=Путь к библиотеке modResource;text;assets/lib/modxAPI &replyto=Email для ответа;text;typodin@gmail.com &ishtml=HTML письмо?;list;true,false;true &from=Почта отправителя;text;modx@agel-nash.ru &fromname=Имя отправителя;text;Зальцман &subject=Тема письма;text;Есть ответ на ваш вопрос &tvsend=Имя TV параметра со статусом отправки;text;send &template=ID шаблона;text;20
* @internal @events OnDocFormSave,OnDocPublished
*
*/
if(!defined('MODX_BASE_PATH')){die('What are you doing? Get out of here!');}
new mailNotify($modx, $modx->Event->params, $modx->Event->name);
class mailNotify{
/** @var DocumentParser */
protected $_modx = null;
/** @var array */
protected $_config = array();
/**
* @var string
*/
protected $_event = '';
/**
* @var null|modResource
*/
protected $_DOC = null;
public function __construct(DocumentParser $modx, array $config = array(), $event){
$idName = null;
$this->_modx = $modx;
switch($event){
case 'OnDocPublished':{
$idName = 'docid';
break;
}
case 'OnDocFormSave':{
$idName = 'id';
break;
}
}
if(!empty($idName) && $this->_validateCFG($idName, $config)){
if($this->_config['template'] == $this->_DOC->get('template')){
$send = $this->_DOC->get($this->_config['tvsend']);
if(empty($send) && $this->_DOC->get('published')){
$this->send();
}else{
$this->warning("Письмо уже отправлялось или документ еще не опубликован", 'Документ '.$this->_DOC->getID());
}
}
}else{
if($this->unpublish()){
$this->warning("Параметры плагина не прошли валидацию или он был запущен на неизвестном событии", (string)$event);
}
}
}
protected function unpublish(){
$out = true;
if($this->_DOC instanceof modResource && $this->_DOC->getID()){
if($this->_config['template'] == $this->_DOC->get('template')){
$this->_DOC->set('published', 0);
$this->_DOC->set('pub_date', 0);
$this->_DOC->save(false, true);
}else{
$out = false;
}
}
return $out;
}
protected function _validateCFG($idName='id', array $config = array()){
$flag = true;
$tpl = null;
if(isset($config['modresource']) && is_scalar($config['modresource'])){
$path = MODX_BASE_PATH . trim($config['modresource'], '/') . "/modResource.php";
if(file_exists($path) && is_readable($path)){
include_once($path);
}
}
if(!class_exists("modResource")){
$flag = false;
$this->error('Не удалось обнаружить библиотеку modResource');
}
if($flag && isset($config[$idName]) && is_scalar($config[$idName]) && (int)$config[$idName]>0){
$this->_DOC = new modResource($this->_modx);
$this->_DOC->edit((int)$config[$idName]);
}
if(!($this->_DOC instanceof modResource && $this->_DOC->getID())){
if($flag){
$this->error('Не удалось открыть на редактирование документ с указаным ID');
}
$flag = false;
}
if($flag && isset($config['tvsend']) && is_scalar($config['tvsend'])){
$this->_config['tvsend'] = $config['tvsend'];
}else{
if($flag){
$this->error("Не указан TV параметр в котором хранится статус отправки писем");
}
$flag = false;
}
if($flag && isset($config['template']) && (int)$config['template']>=0){
$this->_config['template'] = (int)$config['template'];
$flag = ($this->_config['template'] == $this->_DOC->get('template'));
}else{
if($flag){
$this->error('Не корректно задан ID шаблона при публикации которого стоит производить отправку писем');
}
$flag = false;
}
if($flag && isset($config['tpl']) && is_scalar($config['tpl'])){
$tpl = $this->_modx->getChunk($config['tpl']);
$this->_config['tpl'] = $config['tpl'];
}
if($flag && empty($tpl)){
if($flag){
$this->error('Шаблон для писем не существует или пустой');
}
$flag = false;
}
if($flag && isset($config['fieldreply']) && is_scalar($config['fieldreply']) && $this->_DOC->get($config['fieldreply']) != ''){
$this->_config['fieldreply'] = $config['fieldreply'];
}else{
if($flag){
$this->error('Поле с ответом указано некорректно или ответ пустой', 'Документ '.$this->_DOC->getID());
}
$flag = false;
}
if($flag && isset($config['fieldmail']) && is_scalar($config['fieldmail']) && $this->_DOC->get($config['fieldmail']) != ''){
$this->_config['fieldmail'] = $config['fieldmail'];
}else{
if($flag){
$this->error('Поле с email указано не корректно или в указаном поле ничего не написано', 'Документ '.$this->_DOC->getID());
}
$flag = false;
}
if($flag && !empty($config['subject']) && is_scalar($config['subject'])){
$this->_config['subject'] = $config['subject'];
}else{
if($flag){
$this->error('Не указана тема письма');
}
$flag = false;
}
//@TODO: имя TV параметра в котором хранить состояние отправки письма
if($flag && isset($config['replyto']) && $this->_DOC->emailValidate($config['replyto'])){
$this->_config['replyTo'] = $config['replyto'];
}
if(isset($config['ishtml'])){
$this->_config['ishtml'] = ($config['ishtml']=='false' ? false : true);
}else{
$this->_config['ishtml'] = true;
}
if($flag && isset($config['from']) && $this->_DOC->emailValidate($config['from'])){
$this->_config['from'] = $config['from'];
}else{
$this->_config['from'] = $this->_modx->config['emailsender'];
}
if(!empty($config['fromname'])){
$this->_config['fromname'] = $config['fromname'];
}else{
$this->_config['fromname'] = $this->_modx->config['site_name'];
}
return $flag;
}
public function info($message, $title=''){
$this->_sendLogEvent(1, $message, $title);
}
public function warning($message, $title=''){
$this->_sendLogEvent(2, $message, $title);
}
public function error($message, $title=''){
$this->_sendLogEvent(3, $message, $title);
}
protected function _sendLogEvent($type, $message, $title=''){
$title = "mailNotify" . (!empty($title) ? ' - '.$title : '');
$this->_modx->logEvent(0, $type, $message, $title);
}
public function send(){
$flag = false;
include_once MODX_MANAGER_PATH . "includes/controls/class.phpmailer.php";
$mail = new PHPMailer();
$mail->IsMail();
$mail->CharSet = $this->_modx->config['modx_charset'];
$mail->IsHTML($this->_config['ishtml']);
$mail->From = $this->_config['from'];
$mail->FromName = $this->_config['fromname'];
$mail->Subject = $this->_config['subject'];
$data = $this->_DOC->toArray();
$data['id'] = $this->_DOC->getID();
$data['url'] = $this->_modx->makeUrl($data['id'],'','','full');
$mail->Body = $this->_modx->parseChunk($this->_config['tpl'], $data, '[+', '+]');
$toMail = $this->_DOC->get($this->_config['fieldmail']);
$mail->AddAddress($toMail);
if(!empty($this->_config['replyTo'])) $mail->AddReplyTo($this->_config['replyTo']);
if(!$mail->send()){
$this->unpublish();
$this->error("<pre>{$mail->ErrorInfo}</pre>", "Письмо не отправлено");
}else{
$flag = true;
$this->info("Отправлено уведомление об ответе на почту", $toMail);
$this->_DOC->set($this->_config['tvsend'], 1)->save();
}
return $flag;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment