/var/www/html_fr/wp-content/plugins/fluent-smtp/app/Services/Mailer/Providers/Outlook/Handler.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
<?php

namespace FluentMail\App\Services\Mailer\Providers\Outlook;

use 
FluentMail\App\Models\Settings;
use 
FluentMail\Includes\Support\Arr;
use 
FluentMail\App\Services\Mailer\BaseHandler;

class 
Handler extends BaseHandler
{

    public function 
send()
    {
        
$this->phpMailer->Encoding 'base64';

        if (
$this->preSend() && $this->phpMailer->preSend()) {
            return 
$this->postSend();
        }

        return 
$this->handleResponse(new \WP_Error(422__('Something went wrong!''fluent-smtp'), []));
    }

    protected function 
postSend()
    {
        try {
            
$returnResponse $this->sendViaApi();
        } catch (
\Exception $e) {
            
$returnResponse = new \WP_Error(422$e->getMessage(), []);
        }

        
$this->response $returnResponse;

        return 
$this->handleResponse($this->response);
    }

    public function 
setSettings($settings)
    {
        if (
Arr::get($settings'key_store') == 'wp_config') {
            
$settings['client_id'] = defined('FLUENTMAIL_OUTLOOK_CLIENT_ID') ? FLUENTMAIL_OUTLOOK_CLIENT_ID '';
            
$settings['client_secret'] = defined('FLUENTMAIL_OUTLOOK_CLIENT_SECRET') ? FLUENTMAIL_OUTLOOK_CLIENT_SECRET '';
        }

        
$this->settings $settings;

        return 
$this;
    }

    private function 
sendViaApi()
    {
        
$mime chunk_split(base64_encode($this->phpMailer->getSentMIMEMessage()), 76"\n");

        
$data $this->getSetting();

        
$accessToken $this->getAccessToken($data);

        
$api = (new API($data['client_id'], $data['client_secret']));

        
$result $api->sendMime($mime$accessToken);

        if(
is_wp_error($result)) {
            
$errorMessage $result->get_error_message();
            return new 
\WP_Error(422$errorMessage, []);
        } else {
            return array(
                
'RequestId' => $result['request-id'],
            );
        }

    }

    public function 
validateProviderInformation($connection)
    {
        
$errors = [];

        
$keyStoreType $connection['key_store'];

        
$clientId Arr::get($connection'client_id');
        
$clientSecret Arr::get($connection'client_secret');

        if (
$keyStoreType == 'db') {
            if (!
$clientId) {
                
$errors['client_id']['required'] = __('Application Client ID is required.''fluent-smtp');
            }

            if (!
$clientSecret) {
                
$errors['client_secret']['required'] = __('Application Client Secret key is required.''fluent-smtp');
            }
        } else if (
$keyStoreType == 'wp_config') {
            if (!
defined('FLUENTMAIL_OUTLOOK_CLIENT_ID') || !FLUENTMAIL_OUTLOOK_CLIENT_ID) {
                
$errors['client_id']['required'] = __('Please define FLUENTMAIL_OUTLOOK_CLIENT_ID in wp-config.php file.''fluent-smtp');
            } else {
                
$clientId FLUENTMAIL_OUTLOOK_CLIENT_ID;
            }

            if (!
defined('FLUENTMAIL_OUTLOOK_CLIENT_SECRET') || !FLUENTMAIL_OUTLOOK_CLIENT_SECRET) {
                
$errors['client_secret']['required'] = __('Please define FLUENTMAIL_OUTLOOK_CLIENT_SECRET in wp-config.php file.''fluent-smtp');
            } else {
                
$clientSecret FLUENTMAIL_OUTLOOK_CLIENT_SECRET;
            }
        }

        if (
$errors) {
            
$this->throwValidationException($errors);
        }

        
$accessToken Arr::get($connection'access_token');
        
$authToken Arr::get($connection'auth_token');

        if (!
$accessToken && $authToken) {
            
$tokens = (new API($clientId$clientSecret))->generateToken($authToken);
            if (
is_wp_error($tokens)) {
                
$errors['auth_token']['required'] = $tokens->get_error_message();
            } else {
                
add_filter('fluentmail_saving_connection_data', function ($con$provider) use ($connection$tokens) {

                    if (
$provider != 'outlook') {
                        return 
$con;
                    }

                    if (
Arr::get($con'connection.sender_email') != $connection['sender_email']) {
                        return 
$con;
                    }

                    
$con['connection']['refresh_token'] = $tokens['refresh_token'];
                    
$con['connection']['access_token'] = $tokens['access_token'];
                    
$con['connection']['auth_token'] = '';
                    
$con['connection']['expire_stamp'] = time() + $tokens['expires_in'];

                    return 
$con;
                }, 
102);
            }
        } else if (!
$authToken && !$accessToken) {
            
$errors['auth_token']['required'] = __('Please Provide Auth Token.''fluent-smtp');
        }

        if (
$errors) {
            
$this->throwValidationException($errors);
        }
    }

    private function 
saveNewTokens($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();

        (new 
Settings())->updateConnection($senderEmail$existingData);
        return 
fluentMailGetProvider($senderEmailtrue); // we are clearing the static cache here
    
}

    private function 
getAccessToken($config)
    {
        
$accessToken $config['access_token'];
        
// check if expired or will be expired in 300 seconds
        
if ( ($config['expire_stamp'] - 300) < time()) {
            
$fluentAPi = (new API($config['client_id'], $config['client_secret']));

            
$tokens $fluentAPi->sendTokenRequest('refresh_token', [
                
'refresh_token' => $config['refresh_token']
            ]);

            if(
is_wp_error($tokens)) {
                return 
false;
            }

            
$this->saveNewTokens($config$tokens);

            
$accessToken =  $tokens['access_token'];
        }

        return 
$accessToken;
    }

    public function 
getConnectionInfo($connection)
    {
        if (
Arr::get($connection'key_store') == 'wp_config') {
            
$connection['client_id'] = defined('FLUENTMAIL_OUTLOOK_CLIENT_ID') ? FLUENTMAIL_OUTLOOK_CLIENT_ID '';
            
$connection['client_secret'] = defined('FLUENTMAIL_OUTLOOK_CLIENT_SECRET') ? FLUENTMAIL_OUTLOOK_CLIENT_SECRET '';
        }

        
$this->getAccessToken($connection);
        
$info fluentMailgetConnection($connection['sender_email']);
        
$connection $info->getSetting();

        
$extraRow = [
            
'title'   => __('Token Validity''fluent-smtp'),
            
'content' => 'Valid (' intval((($connection['expire_stamp'] - time()) / 60)) . 'm)'
        
];

        if ((
$connection['expire_stamp']) < time()) {
            
$extraRow['content'] = 'Invalid. Please re-authenticate';
        }

        
$connection['extra_rows'] = [$extraRow];

        return [
            
'info' => (string)fluentMail('view')->make('admin.general_connection_info', [
                
'connection' => $connection
            
])
        ];
    }
}