/var/www/html_fr/wp-content/plugins/fluent-smtp/app/Http/Controllers/SettingsController.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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
<?php

namespace FluentMail\App\Http\Controllers;

use 
Exception;
use 
FluentMail\App\Models\Settings;
use 
FluentMail\Includes\Request\Request;
use 
FluentMail\Includes\Support\Arr;
use 
FluentMail\Includes\Support\ValidationException;
use 
FluentMail\App\Services\Mailer\Providers\Factory;

class 
SettingsController extends Controller
{
    public function 
index(Settings $settings)
    {
        
$this->verify();

        try {
            
$setting $settings->get();

            return 
$this->sendSuccess([
                
'settings' => $setting
            
]);

        } catch (
Exception $e) {
            return 
$this->sendError([
                
'message' => $e->getMessage()
            ], 
$e->getCode());
        }
    }

    public function 
validate(Request $requestSettings $settingsFactory $factory)
    {
        
$this->verify();

        try {
            
$data $request->except(['action''nonce']);

            
$provider $factory->make($data['provider']['key']);

            
$provider->validateBasicInformation($data);

            
$this->sendSuccess();

        } catch (
ValidationException $e) {
            
$this->sendError($e->errors(), $e->getCode());
        }
    }

    public function 
store(Request $requestSettings $settingsFactory $factory)
    {
        
$this->verify();

        
$passWordKeys = ['password''access_key''secret_key''api_key''client_id''client_secret''auth_token''access_token''refresh_token'];

        try {
            
$data $request->except(['action''nonce']);

            
$data wp_unslash($data);

            
$provider $factory->make($data['connection']['provider']);

            
$connection $data['connection'];

            foreach (
$connection as $index => $value) {
                if (
$index == 'sender_email') {
                    
$connection['sender_email'] = sanitize_email($connection['sender_email']);
                }

                if (
in_array($index$passWordKeys)) {
                    if (
$value) {
                        
$connection[$index] = trim($value);
                    }
                    continue;
                }

                if (
is_string($value) && $value) {
                    
$connection[$index] = sanitize_text_field($value);
                }
            }

            
$data['connection'] = $connection;

            
$this->validateConnection($provider$connection);

            
$provider->checkConnection($connection);

            
$data['valid_senders'] = $provider->getValidSenders($connection);

            
$data apply_filters('fluentmail_saving_connection_data'$data$data['connection']['provider']);

            
$settings->store($data);

            return 
$this->sendSuccess([
                
'message'     => __('Settings saved successfully.''fluent-smtp'),
                
'connections' => $settings->getConnections(),
                
'mappings'    => $settings->getMappings(),
                
'misc'        => $settings->getMisc()
            ]);

        } catch (
ValidationException $e) {
            return 
$this->sendError($e->errors(), 422);
        } catch (
Exception $e) {
            return 
$this->sendError([
                
'message' => $e->getMessage()
            ], 
422);
        }
    }

    public function 
storeMiscSettings(Request $requestSettings $settings)
    {
        
$this->verify();

        
$misc $request->get('settings');
        
$settings->updateMiscSettings($misc);
        
$this->sendSuccess([
            
'message' => __('General Settings has been updated''fluent-smtp')
        ]);
    }

    public function 
delete(Request $requestSettings $settings)
    {
        
$this->verify();

        
$settings $settings->delete($request->get('key'));

        return 
$this->sendSuccess($settings);
    }

    public function 
storeGlobals(Request $requestSettings $settings)
    {
        
$this->verify();

        
$settings->saveGlobalSettings(
            
$data $request->except(['action''nonce'])
        );

        return 
$this->sendSuccess([
            
'form'    => $data,
            
'message' => __('Settings saved successfully.''fluent-smtp')
        ]);
    }

    public function 
sendTestEmil(Request $requestSettings $settings)
    {
        
$this->verify();

        try {

            
$this->app->addAction('wp_mail_failed', [$this'onFail']);

            
$data $request->except(['action''nonce']);

            if (!isset(
$data['email'])) {
                return 
$this->sendError([
                    
'email_error' => __('The email field is required.''fluent-smtp')
                ], 
422);
            }

            if (!
defined('FLUENTMAIL_EMAIL_TESTING')) {
                
define('FLUENTMAIL_EMAIL_TESTING'true);
            }

            
$settings->sendTestEmail($data$settings->get());

            return 
$this->sendSuccess([
                
'message' => __('Email delivered successfully.''fluent-smtp')
            ]);

        } catch (
Exception $e) {
            return 
$this->sendError([
                
'message' => $e->getMessage()
            ], 
$e->getCode());
        }
    }

    public function 
onFail($response)
    {
        return 
$this->sendError([
            
'message' => $response->get_error_message(),
            
'errors'  => $response->get_error_data()
        ], 
422);
    }

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

        try {
            
$provider->validateBasicInformation($connection);
        } catch (
ValidationException $e) {
            
$errors $e->errors();
        }

        try {
            
$provider->validateProviderInformation($connection);
        } catch (
ValidationException $e) {
            
$errors array_merge($errors$e->errors());
        }

        if (
$errors) {
            throw new 
ValidationException(esc_html__('Unprocessable Entity''fluent-smtp'), 422null$errors); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped
        
}
    }

    public function 
getConnectionInfo(Request $requestSettings $settingsFactory $factory)
    {
        
$this->verify();

        
$connectionId $request->get('connection_id');
        
$connections $settings->getConnections();

        if (!isset(
$connections[$connectionId]['provider_settings'])) {
            return 
$this->sendSuccess([
                
'info' => __('Sorry no connection found. Please reload the page and try again''fluent-smtp')
            ]);
        }

        
$connection $connections[$connectionId]['provider_settings'];

        
$provider $factory->make($connection['provider']);

        return 
$this->sendSuccess($provider->getConnectionInfo($connection));
    }

    public function 
addNewSenderEmail(Request $requestSettings $settingsFactory $factory)
    {
        
$this->verify();

        
$connectionId $request->get('connection_id');
        
$connections $settings->getConnections();

        if (!isset(
$connections[$connectionId]['provider_settings'])) {
            return 
$this->sendSuccess([
                
'info' => __('Sorry no connection found. Please reload the page and try again''fluent-smtp')
            ]);
        }

        
$connection $connections[$connectionId]['provider_settings'];

        
$provider $factory->make($connection['provider']);
        
$email sanitize_email($request->get('new_sender'));

        if (!
is_email($email)) {
            return 
$this->sendError([
                
'message' => __('Please provide a valid email address''fluent-smtp')
            ]);
        }

        
$result $provider->addNewSenderEmail($connection$email);

        if (
is_wp_error($result)) {
            return 
$this->sendError([
                
'message' => $result->get_error_message()
            ]);
        }

        return 
$this->sendSuccess([
            
'message' => __('Email has been added successfully''fluent-smtp')
        ]);

    }

    public function 
removeSenderEmail(Request $requestSettings $settingsFactory $factory)
    {
        
$this->verify();

        
$connectionId $request->get('connection_id');
        
$connections $settings->getConnections();

        if (!isset(
$connections[$connectionId]['provider_settings'])) {
            return 
$this->sendSuccess([
                
'info' => __('Sorry no connection found. Please reload the page and try again''fluent-smtp')
            ]);
        }

        
$connection $connections[$connectionId]['provider_settings'];

        
$provider $factory->make($connection['provider']);
        
$email sanitize_email($request->get('email'));

        if (!
is_email($email)) {
            return 
$this->sendError([
                
'message' => __('Please provide a valid email address''fluent-smtp')
            ]);
        }

        
$result $provider->removeSenderEmail($connection$email);

        if (
is_wp_error($result)) {
            return 
$this->sendError([
                
'message' => $result->get_error_message()
            ]);
        }

        return 
$this->sendSuccess([
            
'message' => __('Email has been removed successfully''fluent-smtp')
        ]);

    }

    public function 
installPlugin(Request $request)
    {
        
$this->verify();
        
$pluginSlug $request->get('plugin_slug');
        
$plugin = [
            
'name'      => $pluginSlug,
            
'repo-slug' => $pluginSlug,
            
'file'      => $pluginSlug '.php'
        
];

        
$UrlMaps = [
            
'fluentform'   => [
                
'admin_url' => admin_url('admin.php?page=fluent_forms'),
                
'title'     => __('Go to Fluent Forms Dashboard''fluent-smtp')
            ],
            
'fluent-crm'   => [
                
'admin_url' => admin_url('admin.php?page=fluentcrm-admin'),
                
'title'     => __('Go to FluentCRM Dashboard''fluent-smtp')
            ],
            
'ninja-tables' => [
                
'admin_url' => admin_url('admin.php?page=ninja_tables#/'),
                
'title'     => __('Go to Ninja Tables Dashboard''fluent-smtp')
            ]
        ];

        if (!isset(
$UrlMaps[$pluginSlug]) || (defined('DISALLOW_FILE_MODS') && DISALLOW_FILE_MODS)) {
            
$this->sendError([
                
'message' => __('Sorry, You can not install this plugin''fluent-smtp')
            ]);
        }

        try {
            
$this->backgroundInstaller($plugin);
            
$this->send([
                
'message' => __('Plugin has been successfully installed.''fluent-smtp'),
                
'info'    => $UrlMaps[$pluginSlug]
            ]);
        } catch (
\Exception $exception) {
            
$this->sendError([
                
'message' => $exception->getMessage()
            ]);
        }
    }

    private function 
backgroundInstaller($plugin_to_install)
    {
        if (!empty(
$plugin_to_install['repo-slug'])) {
            require_once 
ABSPATH 'wp-admin/includes/file.php';
            require_once 
ABSPATH 'wp-admin/includes/plugin-install.php';
            require_once 
ABSPATH 'wp-admin/includes/class-wp-upgrader.php';
            require_once 
ABSPATH 'wp-admin/includes/plugin.php';

            
WP_Filesystem();

            
$skin = new \Automatic_Upgrader_Skin();
            
$upgrader = new \WP_Upgrader($skin);
            
$installed_plugins array_keys(\get_plugins());
            
$plugin_slug $plugin_to_install['repo-slug'];
            
$plugin_file = isset($plugin_to_install['file']) ? $plugin_to_install['file'] : $plugin_slug '.php';
            
$installed false;
            
$activate false;

            
// See if the plugin is installed already.
            
if (isset($installed_plugins[$plugin_file])) {
                
$installed true;
                
$activate = !is_plugin_active($installed_plugins[$plugin_file]);
            }

            
// Install this thing!
            
if (!$installed) {
                
// Suppress feedback.
                
ob_start();

                try {
                    
$plugin_information plugins_api(
                        
'plugin_information',
                        array(
                            
'slug'   => $plugin_slug,
                            
'fields' => array(
                                
'short_description' => false,
                                
'sections'          => false,
                                
'requires'          => false,
                                
'rating'            => false,
                                
'ratings'           => false,
                                
'downloaded'        => false,
                                
'last_updated'      => false,
                                
'added'             => false,
                                
'tags'              => false,
                                
'homepage'          => false,
                                
'donate_link'       => false,
                                
'author_profile'    => false,
                                
'author'            => false,
                            ),
                        )
                    );

                    if (
is_wp_error($plugin_information)) {
                        throw new 
\Exception(wp_kses_post($plugin_information->get_error_message()));
                    }

                    
$package $plugin_information->download_link;
                    
$download $upgrader->download_package($package);

                    if (
is_wp_error($download)) {
                        throw new 
\Exception(wp_kses_post($download->get_error_message()));
                    }

                    
$working_dir $upgrader->unpack_package($downloadtrue);

                    if (
is_wp_error($working_dir)) {
                        throw new 
\Exception(wp_kses_post($working_dir->get_error_message()));
                    }

                    
$result $upgrader->install_package(
                        array(
                            
'source'                      => $working_dir,
                            
'destination'                 => WP_PLUGIN_DIR,
                            
'clear_destination'           => false,
                            
'abort_if_destination_exists' => false,
                            
'clear_working'               => true,
                            
'hook_extra'                  => array(
                                
'type'   => 'plugin',
                                
'action' => 'install',
                            ),
                        )
                    );

                    if (
is_wp_error($result)) {
                        throw new 
\Exception(wp_kses_post($result->get_error_message()));
                    }

                    
$activate true;

                } catch (
\Exception $e) {
                    throw new 
\Exception(esc_html($e->getMessage()));
                }

                
// Discard feedback.
                
ob_end_clean();
            }

            
wp_clean_plugins_cache();

            
// Activate this thing.
            
if ($activate) {
                try {
                    
$result activate_plugin($installed $installed_plugins[$plugin_file] : $plugin_slug '/' $plugin_file);

                    if (
is_wp_error($result)) {
                        throw new 
\Exception(esc_html($result->get_error_message()));
                    }
                } catch (
\Exception $e) {
                    throw new 
\Exception(esc_html($e->getMessage()));
                }
            }
        }
    }

    public function 
subscribe()
    {
        
$this->verify();
        
$email sanitize_text_field($_REQUEST['email']); // phpcs:ignore WordPress.Security.NonceVerification.Recommended

        
$displayName '';

        if (isset(
$_REQUEST['display_name'])) {
            
$displayName sanitize_text_field($_REQUEST['display_name']);
        }

        if (!
is_email($email)) {
            return 
$this->sendError([
                
'message' => __('Sorry! The provider email is not valid''fluent-smtp')
            ], 
422);
        }

        
$shareEssentials 'no';

        if (
$_REQUEST['share_essentials'] == 'yes') {
            
update_option('_fluentsmtp_sub_update''shared''no');
            
$shareEssentials 'yes';
        } else {
            
update_option('_fluentsmtp_sub_update''yes''no');
        }

        
$this->pushData($email$shareEssentials$displayName);

        return 
$this->sendSuccess([
            
'message' => __('You are subscribed to plugin update and monthly tips''fluent-smtp')
        ]);
    }

    public function 
subscribeDismiss()
    {
        
$this->verify();
        
update_option('_fluentsmtp_dismissed_timestamp'time(), 'no');

        return 
$this->sendSuccess([
            
'message' => 'success'
        
]);
    }

    private function 
pushData($optinEmail$shareEssentials$displayName '')
    {
        
$user get_user_by('ID'get_current_user_id());

        
$url 'https://fluentsmtp.com/wp-admin/?fluentcrm=1&route=contact&hash=6012116c-90d8-42a5-a65b-3649aa34b356';


        if (!
$displayName) {
            
$displayName trim($user->first_name ' ' $user->last_name);
            if (!
$displayName) {
                
$displayName $user->display_name;
            }
        }

        
wp_remote_post($url, [
            
'body' => json_encode([ // phpcs:ignore WordPress.WP.AlternativeFunctions.json_encode_json_encode
                
'full_name'       => $displayName,
                
'email'           => $optinEmail,
                
'source'          => 'smtp',
                
'optin_website'   => site_url(),
                
'share_essential' => $shareEssentials
            
])
        ]);
    }

    public function 
getGmailAuthUrl(Request $request)
    {
        
$this->verify();
        
$connection wp_unslash($request->get('connection'));

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

        if (
Arr::get($connection'key_store') == 'wp_config') {
            if (
defined('FLUENTMAIL_GMAIL_CLIENT_ID')) {
                
$clientId FLUENTMAIL_GMAIL_CLIENT_ID;
            } else {
                return 
$this->sendError([
                    
'client_id' => [
                        
'required' => __('Please define FLUENTMAIL_GMAIL_CLIENT_ID in your wp-config.php file''fluent-smtp')
                    ]
                ]);
            }
            if (
defined('FLUENTMAIL_GMAIL_CLIENT_SECRET')) {
                
$clientSecret FLUENTMAIL_GMAIL_CLIENT_SECRET;
            } else {
                return 
$this->sendError([
                    
'client_secret' => [
                        
'required' => __('Please define FLUENTMAIL_GMAIL_CLIENT_SECRET in your wp-config.php file''fluent-smtp')
                    ]
                ]);
            }
        }

        if (!
$clientId) {
            return 
$this->sendError([
                
'client_id' => [
                    
'required' => __('Please provide application client id''fluent-smtp')
                ]
            ]);
        }

        if (!
$clientSecret) {
            return 
$this->sendError([
                
'client_secret' => [
                    
'required' => __('Please provide application client secret''fluent-smtp')
                ]
            ]);
        }

        
$authUrl add_query_arg([
            
'response_type'          => 'code',
            
'access_type'            => 'offline',
            
'client_id'              => $clientId,
            
'redirect_uri'           => apply_filters('fluentsmtp_gapi_callback''https://fluentsmtp.com/gapi/'),
            
'state'                  => admin_url('options-general.php?page=fluent-mail&gapi=1'),
            
'scope'                  => 'https://mail.google.com/',
            
'approval_prompt'        => 'force',
            
'include_granted_scopes' => 'true'
        
], 'https://accounts.google.com/o/oauth2/auth');

        return 
$this->sendSuccess([
            
'auth_url' => filter_var($authUrlFILTER_SANITIZE_URL)
        ]);
    }

    public function 
getOutlookAuthUrl(Request $request)
    {
        
$this->verify();
        
$connection wp_unslash($request->get('connection'));

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

        
delete_option('_fluentsmtp_intended_outlook_info');

        if (
Arr::get($connection'key_store') == 'wp_config') {
            if (
defined('FLUENTMAIL_OUTLOOK_CLIENT_ID')) {
                
$clientId FLUENTMAIL_OUTLOOK_CLIENT_ID;
            } else {
                return 
$this->sendError([
                    
'client_id' => [
                        
'required' => __('Please define FLUENTMAIL_OUTLOOK_CLIENT_ID in your wp-config.php file''fluent-smtp')
                    ]
                ]);
            }
            if (
defined('FLUENTMAIL_OUTLOOK_CLIENT_SECRET')) {
                
$clientSecret FLUENTMAIL_OUTLOOK_CLIENT_SECRET;
            } else {
                return 
$this->sendError([
                    
'client_secret' => [
                        
'required' => __('Please define FLUENTMAIL_OUTLOOK_CLIENT_SECRET in your wp-config.php file''fluent-smtp')
                    ]
                ]);
            }
        } else {
            
update_option('_fluentsmtp_intended_outlook_info', [
                
'client_id'     => $clientId,
                
'client_secret' => $clientSecret
            
]);
        }

        if (!
$clientId) {
            return 
$this->sendError([
                
'client_id' => [
                    
'required' => __('Please provide application client id''fluent-smtp')
                ]
            ]);
        }

        if (!
$clientSecret) {
            return 
$this->sendError([
                
'client_secret' => [
                    
'required' => __('Please provide application client secret''fluent-smtp')
                ]
            ]);
        }

        return 
$this->sendSuccess([
            
'auth_url' => (new \FluentMail\App\Services\Mailer\Providers\Outlook\API($clientId$clientSecret))->getAuthUrl()
        ]);
    }

    public function 
getNotificationSettings()
    {
        
$settings = (new Settings())->notificationSettings();
        
$this->verify();

        
$settings['telegram_notify_token'] = '';

        return 
$this->sendSuccess([
            
'settings' => $settings
        
]);
    }

    public function 
saveNotificationSettings(Request $request)
    {
        
$this->verify();

        
$settings $request->get('settings', []);

        
$settings Arr::only($settings, ['enabled''notify_email''notify_days']);

        
$settings['notify_email'] = sanitize_text_field($settings['notify_email']);
        
$settings['enabled'] = sanitize_text_field($settings['enabled']);

        
$defaults = [
            
'enabled'      => 'no',
            
'notify_email' => '{site_admin}',
            
'notify_days'  => ['Mon''Tue''Wed''Thu''Fri''Sat''Sun']
        ];

        
$oldSettings = (new Settings())->notificationSettings();
        
$defaults wp_parse_args($defaults$oldSettings);

        
$settings wp_parse_args($settings$defaults);

        
update_option('_fluent_smtp_notify_settings'$settingsfalse);

        return 
$this->sendSuccess([
            
'message' => __('Settings has been updated successfully''fluent-smtp')
        ]);
    }

}