This repository has been archived by the owner on Jun 11, 2019. It is now read-only.
/
Tools.php
363 lines (309 loc) · 11.3 KB
/
Tools.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
<?php
namespace Ecodev\Newsletter;
use DateTime;
use Ecodev\Newsletter\Domain\Model\Email;
use Ecodev\Newsletter\Domain\Model\Newsletter;
use Ecodev\Newsletter\Domain\Repository\EmailRepository;
use Ecodev\Newsletter\Domain\Repository\NewsletterRepository;
use TYPO3\CMS\Core\Database\DatabaseConnection;
use TYPO3\CMS\Core\Log\LogManager;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Extbase\Configuration\BackendConfigurationManager;
use TYPO3\CMS\Extbase\Object\ObjectManager;
/**
* Toolbox for newsletter and dependant extensions.
*/
abstract class Tools
{
private static $configuration = null;
private static $OPEN_SSL_CIPHER = 'aes-256-cbc';
/**
* Get a newsletter-conf-template parameter
*
* @param string $key Parameter key
*
* @return mixed Parameter value
*/
public static function confParam($key)
{
// Look for a config in the module TS first.
static $configTS;
if (!is_array($configTS) && isset($GLOBALS['TYPO3_DB'])) {
$beConfManager = self::getObjectManager()->get(BackendConfigurationManager::class);
$configTS = $beConfManager->getTypoScriptSetup();
$configTS = $configTS['module.']['tx_newsletter.']['config.'];
}
if (isset($configTS[$key])) {
return $configTS[$key];
}
// Else fallback to the extension config.
if (!is_array(self::$configuration)) {
self::$configuration = unserialize($GLOBALS['TYPO3_CONF_VARS']['EXT']['extConf']['newsletter']);
}
return self::$configuration[$key];
}
/**
* Returns a logger for given class
*
* @param string $class
*
* @return \TYPO3\CMS\Core\Log\Logger
*/
public static function getLogger($class)
{
return GeneralUtility::makeInstance(LogManager::class)->getLogger($class);
}
/**
* Create a configured mailer from a newsletter page record.
* This mailer will have both plain and HTML content applied as well as files attached.
*
* @param Newsletter $newsletter The newsletter
* @param int $language
*
* @return Mailer preconfigured mailer for sending
*/
public static function getConfiguredMailer(Newsletter $newsletter, $language = null)
{
// Configure the mailer
$mailer = new Mailer();
$mailer->setNewsletter($newsletter, $language);
// hook for modifying the mailer before finish preconfiguring
if (is_array($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['newsletter']['getConfiguredMailerHook'])) {
foreach ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['newsletter']['getConfiguredMailerHook'] as $_classRef) {
$_procObj = GeneralUtility::getUserObj($_classRef);
$mailer = $_procObj->getConfiguredMailerHook($mailer, $newsletter);
}
}
return $mailer;
}
/**
* Create the spool for all newsletters who need it
*/
public static function createAllSpool()
{
$newsletterRepository = self::getNewsletterRepository();
$newsletters = $newsletterRepository->findAllReadyToSend();
foreach ($newsletters as $newsletter) {
self::createSpool($newsletter);
}
}
/**
* Spool a newsletter page out to the real receivers.
*
* @param Newsletter $newsletter
*/
public static function createSpool(Newsletter $newsletter)
{
// If newsletter is locked because spooling now, or already spooled, then skip
if ($newsletter->getBeginTime()) {
return;
}
$newsletterRepository = self::getNewsletterRepository();
// Lock the newsletter by setting its begin_time
$beginTime = new DateTime();
$newsletter->setBeginTime($beginTime);
$newsletterRepository->update($newsletter);
$emailSpooledCount = 0;
$recipientList = $newsletter->getRecipientList();
$recipientList->init();
$db = self::getDatabaseConnection();
while ($receiver = $recipientList->getRecipient()) {
// Register the recipient
if (GeneralUtility::validEmail($receiver['email'])) {
$db->exec_INSERTquery(
'tx_newsletter_domain_model_email',
[
'pid' => $newsletter->getPid(),
'recipient_address' => $receiver['email'],
'recipient_data' => serialize($receiver),
'newsletter' => $newsletter->getUid(),
]
);
$db->exec_UPDATEquery(
'tx_newsletter_domain_model_email',
'uid = ' . (int) $db->sql_insert_id(),
[
'auth_code' => 'MD5(CONCAT(uid, recipient_address))',
],
['auth_code']
);
++$emailSpooledCount;
}
}
self::getLogger(__CLASS__)->info("Queued $emailSpooledCount emails to be sent for newsletter " . $newsletter->getUid());
// Schedule repeated newsletter if any
$newsletter->scheduleNextNewsletter();
// Unlock the newsletter by setting its end_time
$newsletter->setEndTime(new DateTime());
$newsletterRepository->update($newsletter);
}
/**
* Run the spool for all Newsletters, with a security to avoid parallel sending
*/
public static function runAllSpool()
{
$db = self::getDatabaseConnection();
// Try to detect if a spool is already running
// If there is no records for the last 30 seconds, previous spool session is assumed to have ended.
// If there are newer records, then stop here, and assume the running mailer will take care of it.
$rs = $db->sql_query('SELECT COUNT(uid) FROM tx_newsletter_domain_model_email WHERE begin_time > ' . (time() - 30));
list($num_records) = $db->sql_fetch_row($rs);
if ($num_records != 0) {
return;
}
self::runSpool();
}
/**
* Run the spool for one or all Newsletters
*
* @param Newsletter $limitNewsletter if specified, run spool only for that Newsletter
*/
public static function runSpool(Newsletter $limitNewsletter = null)
{
$emailSentCount = 0;
$mailers = [];
$newsletterRepository = self::getNewsletterRepository();
$emailRepository = self::getObjectManager()->get(EmailRepository::class);
$allUids = $newsletterRepository->findAllNewsletterAndEmailUidToSend($limitNewsletter);
$oldNewsletterUid = null;
foreach ($allUids as $uids) {
$newsletterUid = $uids['newsletter'];
$emailUid = $uids['email'];
/* For the page, this way we can support multiple pages in one spool session */
if ($newsletterUid != $oldNewsletterUid) {
$oldNewsletterUid = $newsletterUid;
$mailers = [];
/** @var Newsletter $newsletter */
$newsletter = $newsletterRepository->findByUid($newsletterUid);
}
// Define the language of email
/** @var Email $email */
$email = $emailRepository->findByUid($emailUid);
$recipientData = $email->getRecipientData();
$language = $recipientData['L'];
// Was a language with this page defined, if not create one
if (!is_object($mailers[$language])) {
$mailers[$language] = self::getConfiguredMailer($newsletter, $language);
}
// Mark it as started sending
$email->setBeginTime(new DateTime());
$emailRepository->update($email);
// Send the email
$mailers[$language]->send($email);
// Mark it as sent already
$email->setEndTime(new DateTime());
$emailRepository->update($email);
++$emailSentCount;
}
// Log numbers
self::getLogger(__CLASS__)->info("Sent $emailSentCount emails");
}
/**
* Returns an base64_encode encrypted string
*
* @param string $data
*
* @return string base64_encode encrypted string
*/
public static function encrypt($data)
{
$iv = openssl_random_pseudo_bytes(self::getInitializationVectorSize());
$encryptedData = openssl_encrypt($data, self::$OPEN_SSL_CIPHER, self::getSecureKey(), 0, $iv);
return base64_encode($iv . $encryptedData);
}
/**
* Returns a decrypted string
*
* @param string $string base64_encode encrypted string
*
* @return string decrypted string
*/
public static function decrypt($string)
{
$string = base64_decode($string, true);
$ivSize = self::getInitializationVectorSize();
$iv = substr($string, 0, $ivSize);
$encryptedData = substr($string, $ivSize);
return trim(openssl_decrypt($encryptedData, self::$OPEN_SSL_CIPHER, self::getSecureKey(), 0, $iv));
}
/**
* Returns the size of the initialization vector
*
* @return int
*/
private static function getInitializationVectorSize()
{
return openssl_cipher_iv_length(self::$OPEN_SSL_CIPHER);
}
/**
* Returns the secure encryption key
*
* @return string
*/
private static function getSecureKey()
{
return hash('sha256', $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'], true);
}
/**
* Return the full user agent string to be used in HTTP headers
*
* @return string
*/
public static function getUserAgent()
{
$userAgent = TYPO3_user_agent . ' Newsletter (https://github.com/Ecodev/newsletter)';
return $userAgent;
}
/**
* Fetch and returns the content at specified URL
*
* @param string $url
*
* @return string
*/
public static function getUrl($url)
{
// Specify User-Agent header if we fetch an URL, but not if it's a file on disk
if (Utility\Uri::isAbsolute($url)) {
$headers = [self::getUserAgent()];
} else {
$headers = null;
}
$report = [];
$content = GeneralUtility::getUrl($url, 0, $headers, $report);
// Throw Exception if content could not be fetched so that it is properly caught in Validator
if ($content === false) {
throw new \Exception(
'Could not fetch "' . $url . '"' . PHP_EOL . 'Error: ' . $report['error'] . PHP_EOL . 'Message: ' . $report['message']
);
}
return $content;
}
/**
* Returns the ObjectManager
*
* @return \TYPO3\CMS\Extbase\Object\ObjectManagerInterface
*/
private static function getObjectManager()
{
return GeneralUtility::makeInstance(ObjectManager::class);
}
/**
* Returns the Newsletter Repository
*
* @return NewsletterRepository
*/
private static function getNewsletterRepository()
{
return self::getObjectManager()->get(NewsletterRepository::class);
}
/**
* Returns the the connection to database
*
* @return DatabaseConnection
*/
public static function getDatabaseConnection()
{
return $GLOBALS['TYPO3_DB'];
}
}