/
codersite
/
plg_content_cs_sendmail
Обзор
Документация
Войти
/
codersite
/
plg_content_cs_sendmail
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
1
CI/CD
Аналитика
Безопасность
master
src/Extension/CsSendmail.php
246 строк
8 KB
Mitriy_Bug
edit readme
08 май 2026, 08:31
08 май 2026, 08:31
20d0eb2
Код
Авторство
О чём код?
<?php namespace CS\Plugin\Content\CsSendmail\Extension; // no direct access defined('_JEXEC') or die; use Exception; use Joomla\CMS\Factory; use Joomla\CMS\Log\Log; use Joomla\CMS\Language\Text; use Joomla\CMS\Mail\MailerFactoryInterface; use Joomla\CMS\Plugin\CMSPlugin; use Joomla\CMS\Router\Route; use Joomla\CMS\Session\Session; use Joomla\CMS\Uri\Uri; use Joomla\Component\Content\Site\Helper\RouteHelper; use Joomla\Component\Fields\Administrator\Helper\FieldsHelper; use Joomla\Event\Event; use Joomla\Event\SubscriberInterface; class CsSendmail extends CMSPlugin implements SubscriberInterface { protected $autoloadLanguage = true; /** * Returns an array of events this subscriber will listen to. * * @return array * @since 5.0 */ public static function getSubscribedEvents(): array { return [ 'onAjaxSendMail' => 'onAjaxSendMail', 'onContentPrepareForm' => 'onContentPrepareForm', ]; } /** * Событие onAjaxSendmail передаёт объект AjaxEvent. * * @param Event $event The event object * * @return void * @throws Exception * @since 5.0 */ public function onAjaxSendMail(Event $event): void { $app = Factory::getApplication(); $inputJson = $app->input->json->getArray(); if (!Session::checkToken()) { $event->setArgument('result', json_encode([ 'success' => false, 'message' => Text::_('PLG_CONTENT_CS_SENDMAIL_INVALID_TOKEN') ])); return; } $idArticle = (int)$inputJson["id"]; if((string)$inputJson["action"] == 'getMessage') { $result = $this->getMessage($idArticle); $event->setArgument('result', $result); } if((string)$inputJson["action"] == 'sendMessage') { $mail = $this->params->get('mail', ''); if ($mail == '{MAIL_DEALER}') { $mail = $this->getTag($idArticle,$this->params->get('mail', '')); if(empty($mail)) { $event->setArgument('result', json_encode([ 'success' => false, 'message' => "Ошибка получения email" ]) ); return; } } $result = $this->sendMailToCustomer($mail); $event->setArgument('result', $result); } } /** * Add button to the toolbar in articles list. * * @param Event $event The event object * * @return void * @throws Exception * @since 5.0 */ public function onContentPrepareForm(Event $event): void { $app = Factory::getApplication(); if (!$app->isClient('administrator')) { return; } $option = $app->getInput()->getCmd('option'); if ($option !== 'com_content') { return; } $view = $app->getInput()->getCmd('view'); $layout = $app->getInput()->getCmd('layout'); if ($view !== 'article' && $layout !== 'edit') { return; } $categoriesVisible = $this->params->get('categories_visible', []); $data = $event->getArguments()['data']; if (!in_array($data->catid, $categoriesVisible)) { return; } Text::script('JYES'); Text::script('JNO'); Text::script('ERROR'); Text::script('PLG_CONTENT_CS_SENDMAIL_MAILTO_SEND'); Text::script('PLG_CONTENT_CS_SENDMAIL_MAILTO_SEND_ERROR'); Text::script('PLG_CONTENT_CS_SENDMAIL_MAILTO_SEND_SUCCESS'); Text::script('PLG_CONTENT_CS_SENDMAIL_SUCCESS'); $doc = $app->getDocument(); $wa = $doc->getWebAssetManager(); $doc->addScriptOptions('plg_content_cs_sendmail', [ 'token' => Session::getFormToken(), 'id' => $data->id ]); $wa->useScript('joomla.dialog'); $wa->registerAndUseScript( 'plg_content_cs_sendmail.script', 'plg_content_cs_sendmail/cs_sendmail.js', [], ['type' => 'module'], ['joomla.dialog'] ); } /** * Формируем сообщение для отправки и подтверждения * * @param int $id ID материала * * @return string * @throws Exception * @since 5.0 */ private function getMessage(int $id): string { $uri = Uri::getInstance(); $scheme = $uri->getScheme(); $host = $uri->getHost(); $link = $scheme.'://'.$host; $app = $this->getApplication(); $subject = $this->getTag($id, $this->params->get('subject', 'Тема письма')); $message = $this->getTag($id,$this->params->get('message', ''),$link); $app->setUserState('plg_cs_sendmail.message', json_encode(['subject'=>$subject,'text'=>$message])); return json_encode([ 'success' => true, 'message' => '<strong>Тема письма:</strong><br><div class="bg-light p-3">'.$subject.'</div><br><br><strong>Текст письма:</strong><br><div class="bg-light p-3">'.$message.'</div>', ]); } /** * Отправка сообщеия на почту * * @param string $email электронная почта * * @return string * @throws Exception * @since 5.0 */ private function sendMailToCustomer(string $email) : string { $app = $this->getApplication(); $message = json_decode($app->getUserState('plg_cs_sendmail.message', ''), true); $subject = $message['subject']; $text = $message['text']; $mailer = Factory::getContainer()->get(MailerFactoryInterface::class)->createMailer(); $sender = array( $this->getApplication()->get('mailfrom'), $this->getApplication()->get('fromname') ); $mailer->setSender($sender); $mailer->setSubject($subject); $mailer->setBody($text); $mailer->addRecipient($email, $this->getApplication()->get('fromname')); $mailer->isHtml(true); $message = $mailer->send(); return json_encode([ 'success' => true, 'message' => $message ]); } /** * Заменяем теги на значения * * @param int $id ID материала * @param string $tag тег, который заменяем * @param string $link id материала для ссылки на него * * @return string * @throws Exception * @since 5.0 */ private function getTag(int $id, string $tag, $link='') : string { $arrayFields = FieldsHelper::getFields('com_content.article', [ 'id' => $id ]); $arrayFieldsClear = []; foreach ($arrayFields as $field) { if(!empty($field->value) && $field->value != "0"){ $arrayFieldsClear[$field->id] = $field->value; } } if ($tag == '{MAIL_DEALER}') { $avtosalonFields = FieldsHelper::getFields('com_content.article', [ 'id' => (int)$arrayFieldsClear[18] ]); foreach ($avtosalonFields as $field) { if(!empty($field->value) && $field->id == 3){ return $field->value; } } } $mailTags = $this->params->get('mail_fields', []); if(!empty($mailTags)) { foreach ($mailTags as $item) { if(empty($arrayFieldsClear[$item->field]) || empty($item->name)) continue; if ($item->name == '{URL_DEALER}'){ $link .= Route::link( 'site', RouteHelper::getArticleRoute($arrayFieldsClear[$item->field], 23), false ); $arrayFieldsClear[$item->field] = "<a href='".$link."' target='_blank'>перейти в карточку автосалона</a>"; $tag = str_replace($item->name, $arrayFieldsClear[$item->field], $tag); continue; } $tag = str_replace($item->name, $arrayFieldsClear[$item->field], $tag); } } return $tag; } }