Skip to content

Instantly share code, notes, and snippets.

@eonarik
Last active April 10, 2018 18:06
Show Gist options
  • Save eonarik/e14205babc605be3b3aeb2a102681b9b to your computer and use it in GitHub Desktop.
Save eonarik/e14205babc605be3b3aeb2a102681b9b to your computer and use it in GitHub Desktop.
modx processor indexForm
<?php
class modWebFormsIndexProcessor extends modProcessor{
protected $config = array(
'uploadValidExts' => 'txt,jpg,png,doc,docx,xls,xlsx,pdf,rtf',
'uploadMaxSize' => 5242880,
'uploadFolder' => 'upload/',
);
protected $manager_message_tpl = "";
protected $manager_group_ids = array();
// modCaptcha Extra required. http://modx.com/extras/package/modcaptcha
protected $use_captcha = false;
// Execute subprocessor on success form
protected $use_subprocessor = false;
// For example "site/web/getdata"
protected $subprocessor = '';
protected $subprocessor_namespace = 'modxsite';
protected $success_message = 'Ваше сообщение успешно отправлено';
protected $error_message = 'Не удалось отправить сообщение';
protected $mail_attributes = array();
protected $email_to = '';
protected $attachments = array();
public function initialize(){
if(empty($this->manager_group_ids)){
$this->manager_group_ids = array(
$this->modx->getOption('shop.managers_notify_group', null, 1),
);
}
if($this->modx->getOption('mail_use_smtp') && $this->modx->getOption('mail_smtp_auth')){
$from = $this->modx->getOption('mail_smtp_user');
} else {
$from = $this->modx->getOption('emailsender');
}
$this->mail_attributes = array(
'email_from' => $from,
'email_from_name' => $this->modx->getOption('site_name', null),
'email_subject' => 'Сообщение с сайта "'. $this->modx->getOption('site_name') .'"',
'email_to' => $this->email_to, // optional
);
$this->setProperties(
$this->getInitializeProperties()
);
if($email = mb_strtolower(trim($this->getProperty('email')))){
$this->setProperty('email', $email);
}
if($this->use_captcha){
$this->checkCaptcha();
}
// Выполнеяем проверку данных
if(!$this->validateFields()){
return "Проверьте правильность заполнения формы";
}
if(empty($this->modx->smarty)){
$this->modx->invokeEvent('OnHandleRequest');
}
return parent::initialize() && !$this->hasErrors();
}
public function process(){
$result = null;
if($this->use_subprocessor){
if($this->subprocessor && $this->subprocessor_namespace){
$properties = $this->getProperties();
if(!$response = $this->modx->runProcessor($this->subprocessor,
$properties,
array(
'processors_path' => $this->modx->getObject('modNamespace', $this->subprocessor_namespace)->getCorePath().'processors/',
)
)){
return $this->failure("Не удалось выполнить процессор");
}
// else
if(!$result = $response->getResponse()){
return $this->failure('Error execute request');
}
if($response->isError()){
return $result;
}
}
else{
$this->modx->log(xPDO::LOG_LEVEL_ERROR, '[- '.__CLASS__.' -]. Does not set $this->subprocessor or $this->subprocessor_namespace');
return $this->failure('Error execute request');
}
}
// Отправляем уведомления
if(!$this->sendNotification()){
return $this->failure($this->error_message);
}
if(!$this->use_subprocessor){
$result = $this->success('');
}
return $this->cleanup($result);
}
protected function getInitializeProperties(){
return array(
"manager_group_ids" => $this->manager_group_ids,
"manager_mail_subject" => $this->getManagerMailSubject(),
);
}
protected function getManagerMailSubject(){
$site_name = $this->modx->getOption('site_name');
$subject = "Сообщение с сайта «{$site_name}»";
return $subject;
}
protected function validateFields(){
$fields = $this->getFields();
foreach($fields as $field => $d){
if($d['required']){
if(!$this->getProperty($field)){
$error = !empty($d['error_message']) ? $d['error_message'] : 'Поле заполненно не корректно';
$this->addFieldError($field, $error);
continue;
}
switch ($field){
case 'email':
if(!$$field = filter_var($this->getProperty($field), FILTER_VALIDATE_EMAIL)){
$this->addFieldError($field, 'Укажите корректный емейл');
continue;
}
else{
$this->setProperty($field, $$field);
}
break;
// case 'phone':
// if(!preg_match('/^((8|\+7)[\- ]?)?(\(?\d{3}\)?[\- ]?)?[\d\- ]{7,10}$/uis', $field)){
// $this->addFieldError($field, 'Неправильный формат номера телефона');
// continue;
// }
// break;
default:
}
}
}
if(!empty($_FILES)){
$max_filesize = $this->config['uploadMaxSize'];
$valid_exts = array_map('trim',explode(',',strtolower($this->config['uploadValidExts'])));
$folder = $this->config['uploadFolder'] . $this->modx->user->id .'/';
foreach($_FILES as $key=>$files){
$name = '';
$atts = array();
if(is_array($files['name'])){
$name = $key.'[]';
foreach($files['name'] as $i=>$file){
$arFile = array();
$name = explode('.',$file);
$arFile['ext'] = trim($name[count($name)-1]);
unset($name[count($name)-1]);
$arFile['name'] = implode('.',$name);
$arFile['size'] = $files['size'][$i];
$arFile['type'] = $files['type'][$i];
if($arFile['size'] > $max_filesize){
$this->addFieldError($name, 'Размер файла превышает '. (int)($this->config['uploadMaxSize'] / 1048576) .'мб');
continue;
}
if(!in_array($arFile['ext'],$valid_exts)){
$this->addFieldError($name, 'Недопустимый формат файла '. $file);
continue;
}
$arFile['path'] = $folder . $file;
@mkdir(MODX_BASE_PATH . $folder, 0755, true);
if(!move_uploaded_file($files['tmp_name'][$i], MODX_BASE_PATH . $arFile['path'])){
$this->addFieldError($name, 'Не удалось загрузить файл '. $file);
continue;
}
$attachments[] = $arFile;
}
}else{
// загрузка одиночного файла
}
$this->setProperty($key, $attachments);
}
}
return !$this->hasErrors();
}
protected function checkCaptcha(){
// modCaptcha Extra required. http://modx.com/extras/package/modcaptcha
$result = $this->modx->runSnippet('modcaptcha.check_captcha', array(
"code" => $this->getProperty('captcha'),
));
if($result !== 'true'){
$error = (!empty($result) ? $result : "Неверный проверочный код");
// Надо будет добавить лексиконы в modCaptcha
$this->addFieldError('captcha', $error);
}
return;
}
/*
Example:
$fields = array(
'email' => array(
'required' => true,
'error_message' => 'Fill email',
),
);
*/
protected function getFields(){
$fields = array();
return $fields;
}
/*
Получаем группы, в которые надо добавить пользователя
*/
protected function sendNotification(){
$props = $this->getProperties();
unset($props['pub_action']);
unset($props['action']);
unset($props['actions']);
unset($props['manager_group_ids']);
unset($props['manager_mail_subject']);
// Набиваем данные в шаблонизатор
$this->modx->smarty->assign('properties', $props);
// Отправляем письма менеджерам
return $this->sendManagersEmail();
}
// Отправляем письма менеджерам
protected function sendManagersEmail(){
if($message = $this->getMessage($this->manager_message_tpl)){
if($to = $this->mail_attributes['email_to']){
return $this->sendEmail($message, $to);
} else {
/*
* Получаем менеджеров, кому надо отправить уведомления
*/
$q = $this->modx->newQuery('modUser');
$q->innerJoin('modUserProfile', 'Profile');
$q->innerJoin('modUserGroupMember', 'UserGroupMembers');
$q->where(array(
'active' => 1,
'Profile.blocked' => 0,
'Profile.email:!=' => '',
'UserGroupMembers.user_group:in' => (array)$this->getProperty('manager_group_ids', 1),
));
if($users = $this->modx->getCollection('modUser', $q)){
$sended = true;
foreach($users as $user){
if(!empty($this->attachments)){
if(!$this->sendEmail($message, $user->Profile->email)){
$sended = false;
}
}
else {
if(!$user->sendEmail($message, array(
'subject' => $this->mail_attributes['email_subject'],
))){
$sended = false;
}
}
}
return $sended;
}
$this->error_message = 'Некому отправлять сообщения';
return false;
}
}
$this->error_message = 'Не указан шаблон сообщения';
return false;
}
// Получаем текст письма для уведомления контрагента
protected function getMessage($tpl){
if(strpos($tpl, '.tpl') === false){
return $this->modx->getChunk($tpl, $this->getProperties());
} else {
return $this->modx->smarty->fetch($tpl);
}
}
public function cleanup($result){
return $this->success($this->success_message);
// return $result;
}
protected function sendEmail($message, $to){
$sended = true;
$this->modx->getService('mail', 'mail.modPHPMailer');
$this->modx->mail->reset();
$this->modx->mail->set(modMail::MAIL_BODY, $message);
$this->modx->mail->set(modMail::MAIL_FROM, $this->mail_attributes['email_from']);
$this->modx->mail->set(modMail::MAIL_FROM_NAME, $this->mail_attributes['email_from_name']);
$this->modx->mail->set(modMail::MAIL_SUBJECT, $this->mail_attributes['email_subject']);
$this->modx->mail->setHTML(true);
if(!empty($this->attachments)){
foreach($this->attachments as $a){
$this->modx->mail->mailer->AddAttachment(MODX_BASE_PATH . $a['path'], $a['ext'], 'base64', 'application/octet-stream');
}
}
$this->modx->mail->address('to', $to);
if(!$this->modx->mail->Send()){
$this->modx->log(modX::LOG_LEVEL_ERROR, '['. __CLASS__ .'] send email error: ' . $this->modx->mail->mailer->ErrorInfo);
$this->error_message = $this->modx->mail->mailer->ErrorInfo;
$sended = false;
}
return $sended;
}
}
return 'modWebFormsIndexProcessor';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment