From 07758334dc465e9a9c232fcc9bc747f8604e6ecc Mon Sep 17 00:00:00 2001
From: Torsten Oppermann <torsten@sgalinski.de>
Date: Fri, 8 Mar 2019 04:34:56 +0100
Subject: [PATCH] [TASK] Working on editing and deletion of mail templates

---
 .../Controller/ConfigurationController.php    | 64 +++++++++++++
 Classes/Controller/MailController.php         |  2 +
 Classes/Service/RegisterService.php           | 91 +++++++++++++++++++
 Resources/Private/Language/de.locallang.xlf   | 17 ++--
 Resources/Private/Language/locallang.xlf      | 28 +++---
 .../Templates/Configuration/Index.html        |  3 +-
 ext_tables.php                                |  2 +-
 7 files changed, 184 insertions(+), 23 deletions(-)

diff --git a/Classes/Controller/ConfigurationController.php b/Classes/Controller/ConfigurationController.php
index 6b14e187..dbd2afa3 100644
--- a/Classes/Controller/ConfigurationController.php
+++ b/Classes/Controller/ConfigurationController.php
@@ -183,4 +183,68 @@ class ConfigurationController extends ActionController {
 			['message' => LocalizationUtility::translate('backend.create_message', 'sg_mail')]
 		);
 	}
+
+	/**
+	 * Edit the template or display errors that occured
+	 *
+	 * @throws StopActionException
+	 * @throws UnsupportedRequestTypeException
+	 * @throws \TYPO3\CMS\Core\Cache\Exception\NoSuchCacheException
+	 * @throws \TYPO3\CMS\Extbase\Mvc\Exception\NoSuchArgumentException
+	 * @throws \TYPO3\CMS\Extbase\Mvc\Exception\InvalidArgumentNameException
+	 */
+	public function editAction() {
+		if (!$this->request->hasArgument('configuration')) {
+			$this->redirect(
+				'index', 'Configuration', NULL,
+				['message' => LocalizationUtility::translate('backend.create_error', 'sg_mail')]
+			);
+		}
+
+		/** @var array $configuration */
+		$configuration = $this->request->getArgument('configuration');
+
+		$templateName = $configuration['templateName'];
+		$extensionKey = $configuration['extensionKey'];
+		$csv = str_replace("\r", '', $configuration['csv']);
+		$subject = $configuration['subject'];
+		$description = $configuration['description'];
+
+		$markersCsv = \explode("\n", $csv);
+		$markers = [];
+
+		foreach ($markersCsv as $markerCsv) {
+			$rowArray = str_getcsv($markerCsv, ';');
+			if (!$rowArray[0]) {
+				continue;
+			}
+			$markers[] = [
+				'identifier' => $rowArray[0],
+				'value' => $rowArray[1],
+				'description' => $rowArray[2]
+			];
+		}
+		$registerService = $this->objectManager->get(RegisterService::class);
+		$registerService->deleteRegisterFile($templateName);
+		$registerService->writeRegisterFile(
+			$templateName, self::DEFAULT_EXTENSION_KEY, $markers, $subject, $description
+		);
+
+		$registerService->clearCaches();
+
+		// store selected template & extension key in the session
+		if (!($this->session instanceof PhpSession)) {
+			$this->session = $this->objectManager->get(PhpSession::class);
+			$this->session->setSessionKey('sg_mail_controller_session');
+		} else {
+			$this->session->setSessionKey('sg_mail_controller_session');
+		}
+		$this->session->setDataByKey('selectedTemplate', $templateName);
+		$this->session->setDataByKey('selectedExtension', self::DEFAULT_EXTENSION_KEY);
+
+		$this->redirect(
+			'index', 'Mail', NULL,
+			['message' => LocalizationUtility::translate('backend.edit_message', 'sg_mail')]
+		);
+	}
 }
diff --git a/Classes/Controller/MailController.php b/Classes/Controller/MailController.php
index 486dee9e..fa07d5ac 100644
--- a/Classes/Controller/MailController.php
+++ b/Classes/Controller/MailController.php
@@ -213,6 +213,8 @@ class MailController extends ActionController {
 		$this->view->assign('languageTemplates', $templates);
 		$this->view->assign('languageLabels', BackendService::getLanguageLabels($languages));
 		$this->view->assign('templates', $registerArray);
+		$registerService = $this->objectManager->get(RegisterService::class);
+		$this->view->assign('isManual', $registerService->isManuallyRegisteredTemplate($parameters['selectedTemplate']));
 
 		$templateDescription = $registerArray[$parameters['selectedExtension']][$parameters['selectedTemplate']]['description'];
 
diff --git a/Classes/Service/RegisterService.php b/Classes/Service/RegisterService.php
index d93951ab..6d1b8935 100644
--- a/Classes/Service/RegisterService.php
+++ b/Classes/Service/RegisterService.php
@@ -30,6 +30,7 @@ use TYPO3\CMS\Core\Cache\Backend\Typo3DatabaseBackend;
 use TYPO3\CMS\Core\Cache\CacheManager;
 use TYPO3\CMS\Core\Cache\Frontend\FrontendInterface;
 use TYPO3\CMS\Core\Cache\Frontend\VariableFrontend;
+use TYPO3\CMS\Core\Database\ConnectionPool;
 use TYPO3\CMS\Core\Utility\ExtensionManagementUtility;
 use TYPO3\CMS\Core\Utility\GeneralUtility;
 use TYPO3\CMS\Extbase\Object\ObjectManager;
@@ -271,6 +272,25 @@ class RegisterService implements \TYPO3\CMS\Core\SingletonInterface {
 		return $registerFile;
 	}
 
+	/**
+	 * WDelete a mail register file
+	 *
+	 * @param string $templateKey
+	 */
+	public function deleteRegisterFile($templateKey): void {
+		$configurationLocation = $this->getRegistrationPath();
+		$registerFolder = GeneralUtility::getFileAbsFileName($configurationLocation);
+		GeneralUtility::mkdir_deep($registerFolder);
+
+		$hashPrefix = md5($GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'] . '|' . $templateKey . '.php');
+		$registerFile = GeneralUtility::getFileAbsFileName(
+			$registerFolder . '/' . $hashPrefix . '_' . $templateKey . '.php'
+		);
+		if (file_exists($registerFile)) {
+			\unlink($registerFile);
+		}
+	}
+
 	/**
 	 * Trims non-allowed characters from the form field marker name
 	 *
@@ -302,4 +322,75 @@ class RegisterService implements \TYPO3\CMS\Core\SingletonInterface {
 		}
 		$GLOBALS['TYPO3_CONF_VARS']['SYS']['caching']['cacheConfigurations'] = $cacheConfigurations;
 	}
+
+	/**
+	 * Delete an email template (database entries and automatic config file)
+	 * works only for manually created templates
+	 *
+	 * @param string $extensionKey
+	 * @param string $templateName
+	 * @param string $filePath
+	 * @return bool
+	 * @throws \TYPO3\CMS\Core\Cache\Exception\NoSuchCacheException
+	 */
+	public function deleteTemplate($extensionKey, $templateName, $filePath = ''): bool {
+		$configurationLocation = $this->getRegistrationPath();
+		$registerFolder = GeneralUtility::getFileAbsFileName($configurationLocation);
+		GeneralUtility::mkdir_deep($registerFolder);
+
+		if ($filePath === '') {
+			$hashPrefix = md5($GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'] . '|' . $templateName . '.php');
+			$filePath = GeneralUtility::getFileAbsFileName(
+				$registerFolder . '/' . $hashPrefix . '_' . $templateName . '.php'
+			);
+		}
+
+		if (file_exists($filePath)) {
+			$success = \unlink($filePath);
+		} else {
+			return FALSE;
+		}
+
+		// delete from register array
+		unset($this->registerArray[$extensionKey][$templateName]);
+
+		// delete from database
+		$queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable(
+			'tx_sgmail_domain_model_template'
+		);
+		$queryBuilder->delete('tx_sgmail_domain_model_template')
+			->where(
+				$queryBuilder->expr()->eq('extension_key', $extensionKey)
+			)
+			->andWhere(
+				$queryBuilder->expr()->eq('template_name', $templateName)
+			)->execute();
+
+		$this->clearCaches();
+
+		return $success;
+	}
+
+	/**
+	 * Check if  a template was manually registered (true) or is delivered by an extension (false)
+	 *
+	 * @param string $templateName
+	 * @return bool
+	 */
+	public function isManuallyRegisteredTemplate($templateName): bool {
+		$configurationLocation = $this->getRegistrationPath();
+		$registerFolder = GeneralUtility::getFileAbsFileName($configurationLocation);
+		GeneralUtility::mkdir_deep($registerFolder);
+
+		$hashPrefix = md5($GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'] . '|' . $templateName . '.php');
+		$filePath = GeneralUtility::getFileAbsFileName(
+			$registerFolder . '/' . $hashPrefix . '_' . $templateName . '.php'
+		);
+
+		if (!file_exists($filePath)) {
+			return FALSE;
+		}
+
+		return TRUE;
+	}
 }
diff --git a/Resources/Private/Language/de.locallang.xlf b/Resources/Private/Language/de.locallang.xlf
index 30f6b0e5..a72b56dc 100644
--- a/Resources/Private/Language/de.locallang.xlf
+++ b/Resources/Private/Language/de.locallang.xlf
@@ -1,6 +1,6 @@
 <?xml version="1.0" encoding="utf-8" standalone="yes" ?>
 <xliff version="1.0">
-	<file source-language="en" target-language="de" datatype="plaintext" original="messages" date="2014-10-16T16:26:21Z">
+	<file source-language="en" target-language="de" datatype="plaintext" original="messages" date="2019-03-08T02:33:28Z">
 		<header>
 			<type>module</type>
 			<description>Language labels for the backend module belonging to extension 'sg_csv_importer'</description>
@@ -115,6 +115,11 @@ Bitte registrieren Sie Ihre Templates in den entsprechenden ext_localconf.php Da
 				<source><![CDATA[Description]]></source>
 				<target><![CDATA[Beschreibung]]></target>
 			</trans-unit>
+			<trans-unit id="backend.edit_message" approved="yes" xml:space="preserve">
+				<source><![CDATA[Mail template was successfully edited,
+]]></source>
+				<target><![CDATA[Die Bearbeitung war erfolgreich.]]></target>
+			</trans-unit>
 			<trans-unit id="backend.email" approved="yes">
 				<source><![CDATA[Email]]></source>
 				<target><![CDATA[E-Mail]]></target>
@@ -131,6 +136,10 @@ Bitte registrieren Sie Ihre Templates in den entsprechenden ext_localconf.php Da
 				<source><![CDATA[The cc addresses are invalid]]></source>
 				<target><![CDATA[Ungültige Kopieempfänger Adressen (cc)]]></target>
 			</trans-unit>
+			<trans-unit id="backend.error_mail_queue" approved="yes">
+				<source><![CDATA[Email could not be sent to %s]]></source>
+				<target><![CDATA[Die E-Mail konnte nicht an %s versendet werden ]]></target>
+			</trans-unit>
 			<trans-unit id="backend.failure_mail" approved="yes">
 				<source><![CDATA[There was an error when sending the preview email. Please check your configuration.]]></source>
 				<target><![CDATA[Ein Fehler ist aufgetreten. Bitte überprüfen Sie die Konfiguration.]]></target>
@@ -355,10 +364,6 @@ Bitte registrieren Sie Ihre Templates in den entsprechenden ext_localconf.php Da
 				<source><![CDATA[Email succesfully sent]]></source>
 				<target><![CDATA[Die E-Mail wurde erfolgreich versendet]]></target>
 			</trans-unit>
-			<trans-unit id="backend.error_mail_queue">
-				<source><![CDATA[Email could not be sent to %s]]></source>
-				<target><![CDATA[Die E-Mail konnte nicht an %s versendet werden ]]></target>
-			</trans-unit>
 			<trans-unit id="backend.template_editor" approved="yes">
 				<source><![CDATA[Template Editor]]></source>
 				<target><![CDATA[Template-Editor]]></target>
@@ -459,4 +464,4 @@ Die Templates declined und approved der Extension sg_comments sind für alle Dom
 			</trans-unit>
 		</body>
 	</file>
-</xliff>
+</xliff>
\ No newline at end of file
diff --git a/Resources/Private/Language/locallang.xlf b/Resources/Private/Language/locallang.xlf
index e7e34092..c9055e59 100644
--- a/Resources/Private/Language/locallang.xlf
+++ b/Resources/Private/Language/locallang.xlf
@@ -1,6 +1,6 @@
 <?xml version="1.0" encoding="utf-8" standalone="yes" ?>
 <xliff version="1.0">
-	<file source-language="en" datatype="plaintext" original="messages" date="2014-10-16T16:26:21Z">
+	<file source-language="en" datatype="plaintext" original="messages" date="2019-03-08T02:33:28Z">
 		<header>
 			<type>module</type>
 			<description>Language labels for the backend module belonging to extension 'sg_csv_importer'</description>
@@ -42,16 +42,6 @@
 			<trans-unit id="backend.cc">
 				<source><![CDATA[CC (Carbon Copy Receiver, comma separated)]]></source>
 			</trans-unit>
-			<trans-unit id="backend.content">
-				<source><![CDATA[Text]]></source>
-			</trans-unit>
-			<trans-unit id="backend.delete_template">
-				<source><![CDATA[Do you really want to reset this template?]]></source>
-			</trans-unit>
-			<trans-unit id="backend.deprecationInfo" xml:space="preserve">
-				<source><![CDATA[Some template configurations have been registered in an old way and won`t work in future versions.
-Please register your configurations in the according ext_localconf.php.]]></source>
-			</trans-unit>
 			<trans-unit id="backend.configuration">
 				<source><![CDATA[Configuration editor]]></source>
 			</trans-unit>
@@ -94,9 +84,17 @@ Please register your configurations in the according ext_localconf.php.]]></sour
 			<trans-unit id="backend.delete_template">
 				<source><![CDATA[Do you really want to reset this template?]]></source>
 			</trans-unit>
+			<trans-unit id="backend.deprecationInfo" xml:space="preserve">
+				<source><![CDATA[Some template configurations have been registered in an old way and won`t work in future versions.
+Please register your configurations in the according ext_localconf.php.]]></source>
+			</trans-unit>
 			<trans-unit id="backend.description">
 				<source><![CDATA[Description]]></source>
 			</trans-unit>
+			<trans-unit id="backend.edit_message" xml:space="preserve">
+				<source><![CDATA[Mail template was successfully edited,
+]]></source>
+			</trans-unit>
 			<trans-unit id="backend.email">
 				<source><![CDATA[Email]]></source>
 			</trans-unit>
@@ -109,6 +107,9 @@ Please register your configurations in the according ext_localconf.php.]]></sour
 			<trans-unit id="backend.error_cc">
 				<source><![CDATA[The cc addresses are invalid]]></source>
 			</trans-unit>
+			<trans-unit id="backend.error_mail_queue">
+				<source><![CDATA[Email could not be sent to %s]]></source>
+			</trans-unit>
 			<trans-unit id="backend.failure_mail">
 				<source><![CDATA[There was an error when sending the preview email. Please check your configuration.]]></source>
 			</trans-unit>
@@ -277,9 +278,6 @@ Please register your configurations in the according ext_localconf.php.]]></sour
 			<trans-unit id="backend.success_mail_queue">
 				<source><![CDATA[Email succesfully sent]]></source>
 			</trans-unit>
-			<trans-unit id="backend.error_mail_queue">
-				<source><![CDATA[Email could not be sent to %s]]></source>
-			</trans-unit>
 			<trans-unit id="backend.template_editor">
 				<source><![CDATA[Template Editor]]></source>
 			</trans-unit>
@@ -349,4 +347,4 @@ The templates declined and approved of the sg_comments extension are blacklisted
 			</trans-unit>
 		</body>
 	</file>
-</xliff>
+</xliff>
\ No newline at end of file
diff --git a/Resources/Private/Templates/Configuration/Index.html b/Resources/Private/Templates/Configuration/Index.html
index c0e7201b..3493a391 100644
--- a/Resources/Private/Templates/Configuration/Index.html
+++ b/Resources/Private/Templates/Configuration/Index.html
@@ -23,9 +23,10 @@
 		</div>
 	</div>
 
-	<f:form action="create" controller="Configuration" method="post" objectName="configuration" object="{configuration}">
+	<f:form action="{f:if(condition: '{editMode}', then: 'edit', else: 'create')}" controller="Configuration" method="post" objectName="configuration" object="{configuration}">
 		<div class="row">
 			<div class="col-xs-12 col-md-10 col-md-offset-1">
+				<f:form.hidden name="extensionKey" value="{selectedExtensionKey}"/>
 				<div class="form-group">
 					<label for="templateName"><f:translate key="backend.create.templateName" /></label>
 					<f:form.textfield class="form-control" property="templateName" id="templateName" required="TRUE" value="{templateName}" />
diff --git a/ext_tables.php b/ext_tables.php
index 46635a10..f0a7284a 100644
--- a/ext_tables.php
+++ b/ext_tables.php
@@ -33,7 +33,7 @@ call_user_func(
 			[
 				'Mail' => 'index, sendTestMail, empty, reset',
 				'Queue' => 'index, sendMail, export',
-				'Configuration' => 'index, create',
+				'Configuration' => 'index, create, edit',
 			],
 			[
 				'access' => 'user,group',
-- 
GitLab