Skip to content
Snippets Groups Projects
MailController.php 12.6 KiB
Newer Older
namespace SGalinski\SgMail\Controller;

/***************************************************************
 *  Copyright notice
 *
 *  (c) sgalinski Internet Services (https://www.sgalinski.de)
 *
 *  All rights reserved
 *
 *  This script is part of the TYPO3 project. The TYPO3 project is
 *  free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  The GNU General Public License can be found at
 *  http://www.gnu.org/copyleft/gpl.html.
 *
 *  This script is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  This copyright notice MUST APPEAR in all copies of the script!
 ***************************************************************/
use SGalinski\SgMail\Domain\Model\Template;
use SGalinski\SgMail\Service\MailTemplateService;
use SGalinski\SgMail\Session\PhpSession;
use TYPO3\CMS\Backend\Template\Components\DocHeaderComponent;
use TYPO3\CMS\Backend\Utility\BackendUtility;
use TYPO3\CMS\Core\Messaging\FlashMessage;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Core\Utility\VersionNumberUtility;
use TYPO3\CMS\Extbase\Mvc\Controller\ActionController;
use TYPO3\CMS\Extbase\Object\ObjectManager;
use TYPO3\CMS\Extbase\Utility\LocalizationUtility;

/**
 * Controller for the mail templating service module
 */
class MailController extends ActionController {
	/**
	 * DocHeaderComponent
	 *
	 * @var DocHeaderComponent
	 */
	protected $docHeaderComponent;

	/**
	 * @var \TYPO3\CMS\Lang\Domain\Repository\LanguageRepository
	 * @inject
	 */
	protected $languageRepository;
	/**
	 * @var \SGalinski\SgMail\Domain\Repository\TemplateRepository
	 * @inject
	 */
	protected $templateRepository;
	 * @var \SGalinski\SgMail\Session\PhpSession
	 */
	protected $session;

	 * Show template Selection and enable content input + mail preview
Fabian Galinski's avatar
Fabian Galinski committed
	 *
	 * @throws \InvalidArgumentException
	 * @throws \UnexpectedValueException
	 * @throws \TYPO3\CMS\Extbase\Mvc\Exception\StopActionException
	 * @throws \TYPO3\CMS\Extbase\Mvc\Exception\UnsupportedRequestTypeException
	 * @throws \BadFunctionCallException
	 * @throws \TYPO3\CMS\Core\Cache\Exception\NoSuchCacheException
	public function indexAction(array $parameters = []) {
		$pid = (int) GeneralUtility::_GP('id');
		if (!($this->session instanceof PhpSession)) {
Torsten Oppermann's avatar
Torsten Oppermann committed
			$this->session = $this->objectManager->get(PhpSession::class);
			$this->session->setSessionKey('sg_mail_controller_session');
		}
		$registerArray = MailTemplateService::getRegisterArray();
		$extensionConfiguration = unserialize($GLOBALS['TYPO3_CONF_VARS']['EXT']['extConf']['sg_mail']);
		if (isset($extensionConfiguration['excludeTemplates']) && $extensionConfiguration['excludeTemplates'] !== '') {
			$excludedTemplates = GeneralUtility::trimExplode(',', $extensionConfiguration['excludeTemplates'], TRUE);
			if ($excludedTemplates && count($excludedTemplates)) {
				foreach ($excludedTemplates as $excludedTemplate) {
					list($extensionKey, $templateName) = GeneralUtility::trimExplode('.', $excludedTemplate);
					if ($extensionKey && $templateName && isset($registerArray[$extensionKey][$templateName])) {
						unset($registerArray[$extensionKey][$templateName]);
					}
				}
			}
		}
		$removeExtensionKeys = [];
		foreach ($registerArray as $extensionKey => $extensionTemplates) {
			if (count($extensionTemplates) === 0) {
				$removeExtensionKeys[] = $extensionKey;
			}
		}
		foreach ($removeExtensionKeys as $extensionKey) {
			unset($registerArray[$extensionKey]);
		}
		reset($registerArray);

		// if no extensions are registered, redirect to empty action
		if (empty($registerArray)) {
			$this->redirect('empty');
		}

		if ($parameters['selectedTemplate'] === NULL || $parameters['selectedTemplate'] === '') {
			$parameters['selectedExtension'] = key($registerArray);
			$parameters['selectedTemplate'] = key($registerArray[$parameters['selectedExtension']]);
		$languages = BackendService::getLanguages();
		$templatesFromDb = BackendService::getSelectedTemplates(
			$parameters['selectedExtension'], $parameters['selectedTemplate'], $languages,
		// if no templates are in the db, get the default from the files
		$templates = [];
		$subject = $registerArray[$parameters['selectedExtension']][$parameters['selectedTemplate']]['subject'];
		foreach ($templatesFromDb as $key => $template) {
			if ($template === NULL) {
				$defaultTemplatePath = $registerArray[$parameters['selectedExtension']][$parameters['selectedTemplate']]['templatePath'];
				$defaultTemplateFile = $defaultTemplatePath . $key . '.' . 'template.html';
				$fallbackTemplateFile = $defaultTemplatePath . 'template.html';

				$templateFromFile = new Template();
				$templateFromFile->setLanguage($key);
				$templates[$key] = $templateFromFile;
				if (file_exists($defaultTemplateFile)) {
					$templateFromFile->setContent(file_get_contents($defaultTemplateFile));
					$templateFromFile->setSubject($subject);
					// set subject from register array
					$templateFromFile->setSubject(LocalizationUtility::translate($subject, $this->extensionName));

					if (file_exists($fallbackTemplateFile)) {
						$templateFromFile->setContent(file_get_contents($fallbackTemplateFile));
					}
				}
			} else {
				$templates[$key] = $template;
				$template->setIsOverwritten(TRUE);
		// calculating optimal column width for the view
		$templateCount = count($templates);
		if ($templateCount % 2 === 0 && $templateCount <= 4) {
			$colspace = 6;
		} elseif ($templateCount === 1) {
			$colspace = 12;
		$this->view->assign('colspace', $colspace);
		$this->view->assign('languageTemplates', $templates);
		$this->view->assign('languageLabels', BackendService::getLanguageLabels($languages));
		$this->view->assign('templates', $registerArray);
		$templateDescription = $registerArray[$parameters['selectedExtension']][$parameters['selectedTemplate']]['description'];
		if (is_array($templateDescription)) {
			if ($languages[0]['isocode']) {
				$templateDescription = $templateDescription[$languages[0]['isocode']];
			}
		} else {
			$templateDescription = LocalizationUtility::translate(
				$templateDescription, $parameters['selectedExtension']
			);
		}
		// create doc header component
		$pageUid = (int) GeneralUtility::_GP('id');
		$pageInfo = BackendUtility::readPageAccess($pageUid, $GLOBALS['BE_USER']->getPagePermsClause(1));

		if ($pageInfo && (int) $pageInfo['is_siteroot'] === 1) {

			$this->view->assign('templateDescription', $templateDescription);
			$this->view->assign(
				'selectedTemplate', $registerArray[$parameters['selectedExtension']][$parameters['selectedTemplate']]
			);
			$this->view->assign('selectedTemplateKey', $parameters['selectedTemplate']);
			$this->view->assign('selectedExtensionKey', $parameters['selectedExtension']);
		} else {
			$this->view->assign('pages', BackendService::getPages());
		$this->docHeaderComponent = GeneralUtility::makeInstance(DocHeaderComponent::class);
		$this->docHeaderComponent->setMetaInformation($pageInfo);
		BackendService::makeButtons($this->docHeaderComponent, $this->request);

		$this->view->assign('docHeader', $this->docHeaderComponent->docHeaderContent());
		$this->view->assign('typo3Version', VersionNumberUtility::convertVersionNumberToInteger(TYPO3_version));
		$this->view->assign('beUserMail', $GLOBALS['BE_USER']->user['email']);

		// get the default language label and pass it to the view
		$languageService = $GLOBALS['LANG'];
		$pageTsConfig = BackendUtility::getPagesTSconfig($pageUid);
		if (VersionNumberUtility::convertVersionNumberToInteger(TYPO3_version) >= 8000000) {
			$defaultLanguageLabel = $languageService->sL(
				'LLL:EXT:lang/Resources/Private/Language/locallang_mod_web_list.xlf:defaultLanguage'
			);
		} else {
			$defaultLanguageLabel = $languageService->sL(
				'lll:EXT:lang/locallang_mod_web_list.xlf:defaultLanguage'
			);
		}

		if (isset($pageTsConfig['mod.']['SHARED.']['defaultLanguageLabel'])) {
			$defaultLanguageLabel = $pageTsConfig['mod.']['SHARED.']['defaultLanguageLabel'];
		}

		$this->view->assign('defaultLanguageLabel', $defaultLanguageLabel);
	/**
	 * send a test email to a given address
	 * redirect to index action
	 *
	 * @throws \InvalidArgumentException
	 * @throws \TYPO3\CMS\Extbase\Persistence\Exception\IllegalObjectTypeException
	 * @throws \TYPO3\CMS\Extbase\Mvc\Exception\StopActionException
	 * @throws \TYPO3\CMS\Extbase\Mvc\Exception\UnsupportedRequestTypeException
	 * @throws \TYPO3\CMS\Extbase\Persistence\Exception\UnknownObjectException
	 * @throws \BadFunctionCallException
	 * @throws \TYPO3\CMS\Core\Cache\Exception\NoSuchCacheException
	public function sendTestMailAction(array $parameters = []) {
		foreach ((array) $parameters['templates'] as $parameter) {
			$ccAddresses = GeneralUtility::trimExplode(',', $parameter['cc']);
			if (count($ccAddresses) > 0) {

				foreach ($ccAddresses as $ccAddress) {
					if (!filter_var($ccAddress, FILTER_VALIDATE_EMAIL) && trim($ccAddress) !== '') {
						$message = LocalizationUtility::translate('backend.error_cc', 'sg_mail');
						$this->addFlashMessage($message, '', FlashMessage::WARNING);

						$arguments = $this->request->getArguments();
						$this->redirect('index', NULL, NULL, $arguments);
					}
				}
			}

			$bccAddresses = GeneralUtility::trimExplode(',', $parameter['bcc']);
			if (count($bccAddresses) > 0) {
				foreach ($bccAddresses as $bccAddress) {
					if (!filter_var($bccAddress, FILTER_VALIDATE_EMAIL) && trim($bccAddress) !== '') {
						$message = LocalizationUtility::translate('backend.error_bcc', 'sg_mail');
						$this->addFlashMessage($message, '', FlashMessage::WARNING);

						$arguments = $this->request->getArguments();
						$this->redirect('index', NULL, NULL, $arguments);
					}
				}
			}
		}

		foreach ((array) $parameters['templates'] as $key => $template) {
			BackendService::saveTemplate(
				(int) GeneralUtility::_GP('id'), $parameters['selectedExtension'], $parameters['selectedTemplate'],
				$key, $template
			);
		$message = LocalizationUtility::translate('backend.success', 'sg_mail');
		$this->addFlashMessage($message, '', FlashMessage::OK);

		if (!filter_var($parameters['emailAddress'], FILTER_VALIDATE_EMAIL)) {
			$arguments = $this->request->getArguments();
			$this->redirect('index', NULL, NULL, $arguments);
		}

		$objectManager = GeneralUtility::makeInstance(ObjectManager::class);
		/** @var \SGalinski\SgMail\Service\MailTemplateService $mailTemplateService */
		$mailTemplateService = $objectManager->get(
			MailTemplateService::class, $parameters['selectedTemplate'], $parameters['selectedExtension']
		);
		$mailIsSend = FALSE;
		foreach ((array) $parameters['templates'] as $key => $template) {
			$mailTemplateService->setLanguage($key);
			$mailTemplateService->setToAddresses($parameters['emailAddress']);
			$mailTemplateService->setFromAddress($template['fromMail']);
			$mailTemplateService->setTemplateName($parameters['selectedTemplate']);
			$mailTemplateService->setExtensionKey($parameters['selectedExtension']);
			$mailIsSend = $mailTemplateService->sendEmail(TRUE);
			$message = LocalizationUtility::translate('backend.success_mail', 'sg_mail');
			$this->addFlashMessage($message, '', FlashMessage::OK);
		} else {
			$message = LocalizationUtility::translate('backend.failure_mail', 'sg_mail');
			$this->addFlashMessage($message, '', FlashMessage::ERROR);
		}
		$arguments = $this->request->getArguments();
		$this->redirect('index', NULL, NULL, $arguments);
	}
	 * show a notice when no extension is registered
	 * reset template values to default state for a specific language (delete from db)
	 * @param string $template
	 * @param string $extensionKey
	 * @throws \InvalidArgumentException
	 * @throws \TYPO3\CMS\Extbase\Mvc\Exception\StopActionException
	 * @throws \TYPO3\CMS\Extbase\Mvc\Exception\UnsupportedRequestTypeException
	public function resetAction($template, $extensionKey) {
		$this->templateRepository->deleteTemplate($extensionKey, $template);
		$message = LocalizationUtility::translate('backend.template_reset', 'sg_mail');
		$this->addFlashMessage($message, '', FlashMessage::OK);

		$arguments = $this->request->getArguments();
		$this->redirect('index', NULL, NULL, $arguments);
	}