/var/www/html_nl/wp-content/plugins/fluent-smtp/app/Hooks/Handlers/SchedulerHandler.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
<?php

namespace FluentMail\App\Hooks\Handlers;

use 
FluentMail\App\Models\Logger;
use 
FluentMail\App\Models\Settings;
use 
FluentMail\App\Services\NotificationHelper;
use 
FluentMail\Includes\Support\Arr;

class 
SchedulerHandler
{
    protected 
$dailyActionName 'fluentmail_do_daily_scheduled_tasks';

    public function 
register()
    {
        
add_action($this->dailyActionName, array($this'handleScheduledJobs'));
        
add_filter('fluentmail_email_sending_failed', array($this'maybeHandleFallbackConnection'), 104);

        
add_action('fluentsmtp_renew_gmail_token', array($this'renewGmailToken'));

        
add_action('fluentmail_email_sending_failed_no_fallback', array($this'maybeSendNotification'), 103);

    }

    public function 
handleScheduledJobs()
    {
        
$this->deleteOldEmails();
        
$this->sendDailyDigest();
    }

    private function 
deleteOldEmails()
    {
        
$settings fluentMailGetSettings();
        
$logSaveDays intval(Arr::get($settings'misc.log_saved_interval_days'));
        if (
$logSaveDays) {
            (new 
\FluentMail\App\Models\Logger())->deleteLogsOlderThan($logSaveDays);
        }
    }

    public function 
sendDailyDigest()
    {
        
$settings = (new Settings())->notificationSettings();

        if (
$settings['enabled'] != 'yes' || empty($settings['notify_days']) || empty($settings['notify_email'])) {
            return;
        }

        
$currentDay gmdate('D');
        if (!
in_array($currentDay$settings['notify_days'])) {
            return;
        }

        
$sendTo $settings['notify_email'];
        
$sendTo str_replace(['{site_admin}''{admin_email}'], get_option('admin_email'), $sendTo);

        
$sendToArray explode(','$sendTo);

        
$sendToArray array_filter($sendToArray, function ($email) {
            return 
is_email($email);
        });

        if (!
$sendToArray) {
            return 
false;
        }

        
// we can send a summary email
        
$lastDigestSent get_option('_fluentmail_last_email_digest');
        if (
$lastDigestSent) {
            if ((
time() - strtotime($lastDigestSent)) < 72000) {
                return 
false// we don't want to send another email if sent time within 20 hours
            
}
        } else {
            
$lastDigestSent gmdate('Y-m-d'strtotime('-7 days'));
        }

        
// Let's create the stats
        
$startDate gmdate('Y-m-d 00:00:01', (strtotime($lastDigestSent) - 86400));
        
$endDate gmdate('Y-m-d 23:59:59'strtotime('-1 days'));

        
$reportingDays floor((strtotime($endDate) - strtotime($startDate)) / 86400);

        
$loggerModel = new Logger();
        
$sentCount $loggerModel->getTotalCountStat('sent'$startDate$endDate);

        
$sentStats = [
            
'total'           => $sentCount,
            
'subjects'        => [],
            
'unique_subjects' => 0
        
];
        if (
$sentCount) {
            
$sentStats['unique_subjects'] = $loggerModel->getSubjectCountStat('sent'$startDate$endDate);
            
$sentStats['subjects'] = $loggerModel->getSubjectStat('sent'$startDate$endDate10);
        }

        
$failedCount $loggerModel->getTotalCountStat('failed'$startDate$endDate);
        
$failedStats = [
            
'total'           => $sentCount,
            
'subjects'        => [],
            
'unique_subjects' => 0
        
];
        if (
$failedCount) {
            
$failedStats['unique_subjects'] = $loggerModel->getSubjectCountStat('failed'$startDate$endDate);
            
$failedStats['subjects'] = $loggerModel->getSubjectStat('failed'$startDate$endDate);
        }

        
$sentSubTitle sprintf(
            
__('Showing %1$s of %2$s different subject lines sent in the past %3$s''fluent-smtp'),
            
number_format_i18n(count($sentStats['subjects'])),
            
number_format_i18n($sentStats['unique_subjects']),
            (
$reportingDays 2) ? 'day' $reportingDays ' days'
        
);

        
$failedSubTitle sprintf(
            
__('Showing %1$s of %2$s different subject lines failed in the past %3$s''fluent-smtp'),
            
number_format_i18n(count($failedStats['subjects'])),
            
number_format_i18n($failedStats['unique_subjects']),
            (
$reportingDays 2) ? 'day' $reportingDays ' days'
        
);

        
$sentTitle __('Emails Sent''fluent-smtp');
        if (
$sentCount) {
            
$sentTitle .= ' <span style="font-size: 12px; vertical-align: middle;">(' number_format_i18n($sentCount) . ')</span>';
        }
        
$failedTitle __('Email Failures''fluent-smtp');
        if (
$failedCount) {
            
$failedTitle .= ' <span style="font-size: 12px; vertical-align: middle;">(' number_format_i18n($failedCount) . ')</span>';
        }

        
$reportingDate gmdate(get_option('date_format'), strtotime($startDate));

        
$data = [
            
'sent'        => [
                
'total'         => $sentCount,
                
'title'         => $sentTitle,
                
'subtitle'      => $sentSubTitle,
                
'subject_items' => $sentStats['subjects']
            ],
            
'fail'        => [
                
'total'         => $failedCount,
                
'title'         => $failedTitle,
                
'subtitle'      => $failedSubTitle,
                
'subject_items' => $failedStats['subjects']
            ],
            
'date_range'  => $reportingDate,
            
'domain_name' => $this->getDomainName()
        ];

        
$emailBody = (string)fluentMail('view')->make('admin.digest_email'$data);
        
$emailSubject $reportingDate ' email sending stats for ' $this->getDomainName();

        
$headers = array('Content-Type: text/html; charset=UTF-8');

        
update_option('_fluentmail_last_email_digest'gmdate('Y-m-d H:i:s'));

        return 
wp_mail($sendToArray$emailSubject$emailBody$headers);

    }

    private function 
getDomainName()
    {
        
$parts parse_url(site_url());
        
$url $parts['host'] . (isset($parts['path']) ? $parts['path'] : '');
        return 
untrailingslashit($url);
    }

    public function 
maybeHandleFallbackConnection($status$logId$handler$data = [])
    {
        if (
defined('FLUENTMAIL_EMAIL_TESTING')) {
            return 
false;
        }

        
$settings = (new \FluentMail\App\Models\Settings())->getSettings();

        
$fallbackConnectionId \FluentMail\Includes\Support\Arr::get($settings'misc.fallback_connection');

        if (!
$fallbackConnectionId) {
            
do_action('fluentmail_email_sending_failed_no_fallback'$logId$handler$data);
            return 
false;
        }

        
$fallbackConnection \FluentMail\Includes\Support\Arr::get($settings'connections.' $fallbackConnectionId);

        if (!
$fallbackConnection) {
            
do_action('fluentmail_email_sending_failed_no_fallback'$logId$handler$data);
            return 
false;
        }

        
$phpMailer $handler->getPhpMailer();

        
$fallbackSettings $fallbackConnection['provider_settings'];
        
$phpMailer->setFrom($fallbackSettings['sender_email'], $phpMailer->FromName);

        
// Trap the fluentSMTPMail mailer here
        
$phpMailer = new \FluentMail\App\Services\Mailer\FluentPHPMailer($phpMailer);
        return 
$phpMailer->sendViaFallback($logId);
    }

    public function 
renewGmailToken()
    {
        
$settings fluentMailGetSettings();

        if (!
$settings) {
            return;
        }

        
$connections Arr::get($settings'connections', []);

        foreach (
$connections as $connection) {
            if (
Arr::get($connection'provider_settings.provider') != 'gmail') {
                continue;
            }
            
$providerSettings $connection['provider_settings'];
            if ((
$providerSettings['expire_stamp'] - 480) < time() && !empty($providerSettings['refresh_token'])) {
                
$this->callGmailApiForNewToken($connection['provider_settings']);
            }
        }
    }

    public function 
callGmailApiForNewToken($settings)
    {
        if (
Arr::get($settings'key_store') == 'wp_config') {
            
$settings['client_id'] = defined('FLUENTMAIL_GMAIL_CLIENT_ID') ? FLUENTMAIL_GMAIL_CLIENT_ID '';
            
$settings['client_secret'] = defined('FLUENTMAIL_GMAIL_CLIENT_SECRET') ? FLUENTMAIL_GMAIL_CLIENT_SECRET '';
        }

        if (!
class_exists('\FluentSmtpLib\Google\Client')) {
            require_once 
FLUENTMAIL_PLUGIN_PATH 'includes/libs/google-api-client/build/vendor/autoload.php';
        }

        try {
            
$client = new \FluentSmtpLib\Google\Client();
            
$client->setClientId($settings['client_id']);
            
$client->setClientSecret($settings['client_secret']);
            
$client->addScope("https://www.googleapis.com/auth/gmail.compose");
            
$client->setAccessType('offline');
            
$client->setApprovalPrompt('force');

            
$tokens = [
                
'access_token'  => $settings['access_token'],
                
'refresh_token' => $settings['refresh_token'],
                
'expires_in'    => $settings['expire_stamp'] - time()
            ];

            
$client->setAccessToken($tokens);

            
$newTokens $client->refreshToken($tokens['refresh_token']);
            
$result $this->saveNewGmailTokens($settings$newTokens);

            if (!
$result) {
                return new 
\WP_Error('api_error'__('Failed to renew the token''fluent-smtp'));
            }

            return 
true;
        } catch (
\Exception $exception) {
            return new 
\WP_Error('api_error'$exception->getMessage());
        }
    }


    public function 
maybeSendNotification($rowId$handler$logData = [])
    {
        
$channel NotificationHelper::getActiveChannelSettings();

        if (!
$channel) {
            return 
false;
        }

        
$lastNotificationSent get_option('_fsmtp_last_notification_sent');
        if (
$lastNotificationSent && (time() - $lastNotificationSent) < 60) {
            return 
false;
        }

        
update_option('_fsmtp_last_notification_sent'time());

        
$driver $channel['driver'];
        if (
$driver == 'telegram') {
            
$data = [
                
'token_id'      => $channel['token'],
                
'provider'      => $handler->getSetting('provider'),
                
'error_message' => $this->getErrorMessageFromResponse(maybe_unserialize(Arr::get($logData'response')))
            ];

            return 
NotificationHelper::sendFailedNotificationTele($data);
        }

        if (
$driver == 'slack') {
            return 
NotificationHelper::sendSlackMessage(NotificationHelper::formatSlackMessageBlock($handler$logData), $channel['webhook_url'], false);
        }

        if (
$driver == 'discord') {
            return 
NotificationHelper::sendDiscordMessage(NotificationHelper::formatDiscordMessageBlock($handler$logData), $channel['webhook_url'], false);
        }

        return 
false;
    }

    private function 
saveNewGmailTokens($existingData$tokens)
    {
        if (empty(
$tokens['access_token']) || empty($tokens['refresh_token'])) {
            return 
false;
        }

        
$senderEmail $existingData['sender_email'];

        
$existingData['access_token'] = $tokens['access_token'];
        
$existingData['refresh_token'] = $tokens['refresh_token'];
        
$existingData['expire_stamp'] = $tokens['expires_in'] + time();
        
$existingData['expires_in'] = $tokens['expires_in'];

        (new 
Settings())->updateConnection($senderEmail$existingData);
        
fluentMailGetProvider($senderEmailtrue); // we are clearing the static cache here
        
wp_schedule_single_event($existingData['expire_stamp'] - 360'fluentsmtp_renew_gmail_token');
        return 
true;
    }

    private function 
getErrorMessageFromResponse($response)
    {
        if (!
$response || !is_array($response)) {
            return 
'';
        }

        if (!empty(
$response['fallback_response']['message'])) {
            
$message $response['fallback_response']['message'];
        } else {
            
$message Arr::get($response'message');
        }

        if (!
$message) {
            return 
'';
        }

        if (!
is_string($message)) {
            
$message json_encode($message);
        }

        return 
$message;
    }
}