PluginProbe ʕ •ᴥ•ʔ
Brevo – Email, SMS, Web Push, Chat, and more. / 3.3.5
Brevo – Email, SMS, Web Push, Chat, and more. v3.3.5
2.9.13 2.9.14 2.9.15 2.9.16 2.9.17 2.9.18 2.9.4 2.9.5 2.9.6 2.9.7 2.9.8 2.9.9 3.0.0 3.0.1 3.0.2 3.0.3 3.0.4 3.0.5 3.0.6 3.0.7 3.0.9 3.1.0 3.1.1 3.1.10 3.1.11 3.1.12 3.1.13 3.1.14 3.1.15 3.1.16 3.1.2 3.1.20 3.1.21 3.1.22 3.1.23 3.1.24 3.1.25 3.1.26 3.1.27 3.1.28 3.1.29 3.1.3 3.1.30 3.1.31 3.1.32 3.1.33 3.1.34 3.1.35 3.1.36 3.1.37 3.1.38 3.1.39 3.1.4 3.1.40 3.1.41 3.1.42 3.1.43 3.1.44 3.1.45 3.1.46 3.1.47 3.1.48 3.1.49 3.1.5 3.1.50 3.1.51 3.1.52 3.1.53 3.1.54 3.1.55 3.1.56 3.1.57 3.1.58 3.1.59 3.1.6 3.1.60 3.1.61 3.1.62 3.1.63 3.1.64 3.1.65 3.1.66 3.1.67 3.1.68 3.1.69 3.1.7 3.1.70 3.1.71 3.1.72 3.1.73 3.1.74 3.1.75 3.1.76 3.1.77 3.1.78 3.1.79 3.1.8 3.1.80 3.1.81 3.1.82 3.1.83 3.1.84 3.1.85 3.1.86 3.1.87 3.1.88 3.1.89 3.1.9 3.1.90 3.1.91 3.1.92 3.1.93 3.1.94 3.1.95 3.1.96 3.1.97 3.1.98 3.2.0 3.2.1 3.2.2 3.2.3 3.2.4 3.2.5 3.2.6 3.2.7 3.2.8 3.2.9 3.3.0 3.3.1 3.3.2 3.3.3 3.3.4 3.3.5 trunk 1.0 1.5 2.0.8 2.9.10 2.9.11 2.9.12
mailin / sendinblue.php
mailin Last commit date
css 1 year ago form 1 year ago img 5 months ago inc 1 week ago js 2 months ago lang 5 months ago model 8 months ago page 1 week ago widget 4 years ago wonderpush-php-lib 2 months ago brevo-frame.html 1 year ago index.php 11 years ago readme.txt 1 week ago screenshot-1.png 2 years ago screenshot-2.png 2 years ago screenshot-3.png 2 years ago screenshot-4.png 2 years ago screenshot-5.png 2 years ago sendinblue.php 1 week ago sw.js 1 year ago wonderpush-worker-loader.min.js 1 year ago wonderpush.min.html 1 year ago
sendinblue.php
1958 lines
1 <?php
2 /**
3 * Plugin Name: Brevo - Email, SMS, Web Push, Chat, and more.
4 * Plugin URI: https://www.brevo.com/?r=wporg
5 * Description: Manage your contact lists, subscription forms and all email and marketing-related topics from your wp panel, within one single plugin
6 * Version: 3.3.5
7 * Author: Brevo
8 * Author URI: https://www.brevo.com/?r=wporg
9 * License: GPLv2 or later
10 *
11 * @package SIB
12 */
13
14 /*
15 This program is free software; you can redistribute it and/or
16 modify it under the terms of the GNU General Public License
17 as published by the Free Software Foundation; either version 2
18 of the License, or (at your option) any later version.
19 This program is distributed in the hope that it will be useful,
20 but WITHOUT ANY WARRANTY; without even the implied warranty of
21 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 GNU General Public License for more details.
23 You should have received a copy of the GNU General Public License
24 along with this program; if not, write to the Free Software
25 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
26 */
27
28 /**
29 * Application entry point. Contains plugin startup class that loads on <i> sendinblue_init </i> action.
30 */
31 if ( ! class_exists( 'Mailin' ) ) {
32 require_once( 'inc/mailin.php' );
33 }
34 if ( ! class_exists( 'SendinblueApiClient' ) ) {
35 require_once( 'inc/SendinblueApiClient.php' );
36 }
37 if ( ! class_exists( 'SendinblueAccount' ) ) {
38 require_once( 'inc/SendinblueAccount.php' );
39 }
40 // For marketing automation.
41 if ( ! class_exists( 'Sendinblue' ) ) {
42 require_once( 'inc/sendinblue.php' );
43 }
44
45 if ( ! class_exists( 'WonderPush\WonderPush' )) {
46 require_once( 'wonderpush-php-lib/init.php' );
47 }
48
49 if ( ! class_exists( 'SIB_Push_Utils' ) ) {
50 require_once( 'inc/push-utils.php' );
51 }
52
53 if ( ! class_exists( 'SIB_Push_Settings' ) ) {
54 require_once( 'inc/push-settings.php' );
55 }
56
57 if ( ! class_exists( 'inc/push-httpclient.php' ) ) {
58 require_once( 'inc/push-httpclient.php' );
59 }
60
61 if ( ! class_exists( 'SIB_Push_API' ) ) {
62 require_once( 'inc/push-api.php' );
63 }
64
65 if ( ! class_exists( 'SIB_Push_Admin' ) ) {
66 require_once( 'inc/push-admin.php' );
67 }
68
69 if ( ! class_exists( 'SIB_Push_Public' ) ) {
70 require_once( 'inc/push-public.php' );
71 }
72
73 if ( ! class_exists( 'SIB_Push_WooCommerce' ) ) {
74 require_once( 'inc/push-woocommerce.php' );
75 }
76
77 if ( ! class_exists( 'SIB_Push_Amp' ) ) {
78 require_once( 'inc/push-amp.php' );
79 }
80
81 if (!function_exists('http_build_url')) {
82 require_once( 'inc/http-build-url.php' );
83 }
84
85 if ( ! class_exists( 'SIB_Manager' ) ) {
86 register_deactivation_hook( __FILE__, array( 'SIB_Manager', 'deactivate' ) );
87 register_activation_hook( __FILE__, array( 'SIB_Manager', 'install' ) );
88 register_uninstall_hook( __FILE__, array( 'SIB_Manager', 'uninstall' ) );
89
90 require_once( 'page/page-home.php' );
91 require_once( 'page/page-form.php' );
92 require_once( 'page/page-push.php' );
93 require_once( 'widget/widget_form.php' );
94 require_once( 'inc/table-forms.php' );
95 require_once( 'inc/sib-api-manager.php' );
96 require_once( 'inc/sib-sms-code.php' );
97 require_once( 'model/model-forms.php' );
98 require_once( 'model/model-users.php' );
99 require_once( 'model/model-lang.php' );
100 require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
101 require_once( ABSPATH . 'wp-admin/includes/class-wp-upgrader.php' );
102 /**
103 * Class SIB_Manager
104 */
105 class SIB_Manager {
106
107 private const ROUTE_METHODS = 'methods';
108 private const ROUTE_CALLBACK = 'callback';
109 private const ROUTE_PATH = 'path';
110 private const PERMISSION_CALLBACK = 'permission_callback';
111 private const API_NAMESPACE = "mailin/v1";
112 private const HTTP_STATUS = 'status';
113
114 /** Main setting option name */
115 const MAIN_OPTION_NAME = 'sib_main_option';
116
117 /** Home setting option name */
118 const HOME_OPTION_NAME = 'sib_home_option';
119
120 /** Access token option name */
121 const ACCESS_TOKEN_OPTION_NAME = 'sib_token_store';
122
123 /** Plugin language notice option name */
124 const LANGUAGE_OPTION_NAME = 'sib_language_notice_option';
125
126 /** Form preview option name */
127 const PREVIEW_OPTION_NAME = 'sib_preview_form';
128
129 const API_KEY_V3_OPTION_NAME = 'sib_api_key_v3';
130
131 const PUSH_SETTINGS_OPTION_NAME = 'sib_push_settings';
132
133 const RECAPTCHA_API_TEMPLATE = 'https://www.google.com/recaptcha/api/siteverify?%s';
134
135 const TURNSTILE_SITE_VERIFY = 'https://challenges.cloudflare.com/turnstile/v0/siteverify';
136
137 /** Installation id option name */
138 const INSTALLATION_ID = 'sib_installation_id';
139 const BREVO_PLUGIN_VERSION = 'brevo_plugin_version';
140
141 const SDK_LOADER_PRODUCTION_URL = "https://cdn.brevo.com/js/sdk-loader.js";
142 const SDK_LOADER_STAGING_URL = "https://cdn.brevo.com/js/sdk-staging-loader.js";
143 const URL_CHECK_STAGING = "staging";
144 const SERVICE_WORKER_FILE_URL = "/js/service-worker.js";
145
146 const SIB_ATTRIBUTE = array(
147 'input' => array(
148 'type' => true,
149 'name' => true,
150 'value' => true,
151 'class' => true,
152 'id' => true,
153 'size' => true,
154 'min' => true,
155 'max' => true,
156 'pattern' => true,
157 'title' => true,
158 'placeholder' => true,
159 'required' => true,
160 ),
161 'p' => array(
162 'align' => true,
163 'id' => true,
164 'class' => true,
165 'dir' => true,
166 'lang' => true,
167 'style' => true,
168 'xml:lang' => true,
169 ),
170 'iframe' => array(
171 'name' => true,
172 'id' => true,
173 'class' => true,
174 'src' => true,
175 'width' => true,
176 'height' => true,
177 'style' => true,
178 'loading' => true,
179 'allow' => true,
180 'allowfullscreen' => true,
181 ),
182 'div' => array(
183 'id' => true,
184 'class' => true,
185 'dir' => true,
186 'lang' => true,
187 'style' => true,
188 'xml:lang' => true,
189 'data-require' => true,
190 'data-sitekey' => true,
191 'data-error-callback' => true,
192 'data-theme' => true,
193 ),
194 'a' => array(
195 'href' => true,
196 'id' => true,
197 'class' => true,
198 'rel' => true,
199 'rev' => true,
200 'name' => true,
201 'target' => true,
202 ),
203 'style' => array(),
204 'script' => array(
205 'src' => true,
206 ),
207 'link' => array(
208 'rel' => true,
209 'href' => true,
210 'type' => true,
211 ),
212 'select' => array(
213 'name' => true,
214 'multiple' => true,
215 'class' => true,
216 'id' => true,
217 'style' => true,
218 'required' => true,
219 ),
220 'option' => array(
221 'value' => true,
222 ),
223 'ul' => array(
224 'class' => true,
225 'style' => true,
226 ),
227 'center' => array(),
228 'download' => array(
229 'valueless' => 'y',
230 )
231 );
232
233 /**
234 * API key
235 *
236 * @var $access_key
237 */
238 public static $access_key;
239
240 /**
241 * Store instance
242 *
243 * @var $instance
244 */
245 public static $instance;
246
247 /**
248 * Plugin directory path value. set in constructor
249 *
250 * @var $plugin_dir
251 */
252 public static $plugin_dir;
253
254 /**
255 * Plugin url. set in constructor
256 *
257 * @var $plugin_url
258 */
259 public static $plugin_url;
260
261 /**
262 * Plugin name. set in constructor
263 *
264 * @var $plugin_name
265 */
266 public static $plugin_name;
267
268 /**
269 * Check if wp_mail is declared
270 *
271 * @var $wp_mail_conflict
272 */
273 static $wp_mail_conflict;
274
275 /**
276 * Class constructor
277 * Sets plugin url and directory and adds hooks to <i>init</i>. <i>admin_menu</i>
278 */
279 function __construct() {
280 // get basic info.
281 self::$plugin_dir = plugin_dir_path( __FILE__ );
282 self::$plugin_url = plugins_url( '', __FILE__ );
283 self::$plugin_name = plugin_basename( __FILE__ );
284
285 self::$wp_mail_conflict = false;
286
287 // api key for sendinblue.
288 $general_settings = get_option( self::MAIN_OPTION_NAME, array() );
289 self::$access_key = isset( $general_settings['access_key'] ) ? $general_settings['access_key'] : '';
290
291 self::$instance = $this;
292 add_action('plugins_loaded', array( &$this, 'brevo_wp_load' ) );
293 add_action( 'upgrader_process_complete', array( &$this, 'my_upgrade_function' ), 10, 2);
294 add_action( 'admin_init', array( &$this, 'admin_init' ), 9999 );
295 add_action( 'admin_menu', array( &$this, 'admin_menu' ), 9999 );
296 add_action('rest_api_init', array($this, 'create_brevo_rest_endpoints'));
297
298 add_action( 'wp_print_scripts', array( &$this, 'frontend_register_scripts' ), 9999 );
299 add_action( 'wp_enqueue_scripts', array( &$this, 'wp_head_ac' ), 999 );
300 add_action( 'wp_dashboard_setup', array( 'SIB_Push_Admin', 'add_dashboard_widget' ), 9999 );
301 add_action( 'admin_init', array( 'SIB_Push_Admin', 'add_post_options' ), 9999 );
302 add_action( 'admin_bar_menu', array( 'SIB_Push_Admin', 'add_admin_bar_menu_item' ), 100);
303
304 // create custom url for form preview.
305 add_filter( 'query_vars', array( &$this, 'sib_query_vars' ) );
306 add_action( 'parse_request', array( &$this, 'sib_parse_request' ) );
307
308 add_action( 'wp_ajax_sib_validate_process', array( 'SIB_Page_Home', 'ajax_validation_process' ) );
309 add_action( 'wp_ajax_sib_validate_ma', array( 'SIB_Page_Home', 'ajax_validate_ma' ) );
310 add_action( 'wp_ajax_sib_activate_email_change', array( 'SIB_Page_Home', 'ajax_activate_email_change' ) );
311 add_action( 'wp_ajax_sib_sender_change', array( 'SIB_Page_Home', 'ajax_sender_change' ) );
312 add_action( 'wp_ajax_sib_send_email', array( 'SIB_Page_Home', 'ajax_send_email' ) );
313 add_action( 'wp_ajax_sib_remove_cache', array( 'SIB_Page_Home', 'ajax_remove_cache' ) );
314 add_action( 'wp_ajax_sib_sync_users', array( 'SIB_Page_Home', 'ajax_sync_users' ) );
315
316 add_action( 'wp_ajax_sib_change_template', array( 'SIB_Page_Form', 'ajax_change_template' ) );
317 add_action( 'wp_ajax_sib_get_lists', array( 'SIB_Page_Form', 'ajax_get_lists' ) );
318 add_action( 'wp_ajax_sib_get_templates', array( 'SIB_Page_Form', 'ajax_get_templates' ) );
319 add_action( 'wp_ajax_sib_get_attributes', array( 'SIB_Page_Form', 'ajax_get_attributes' ) );
320 add_action( 'wp_ajax_sib_update_form_html', array( 'SIB_Page_Form', 'ajax_update_html' ) );
321 add_action( 'wp_ajax_sib_copy_origin_form', array( 'SIB_Page_Form', 'ajax_copy_origin_form' ) );
322
323 add_action( 'wp_ajax_sib_get_country_prefix', array( $this, 'ajax_get_country_prefix' ) );
324 add_action( 'wp_ajax_nopriv_sib_get_country_prefix', array( $this, 'ajax_get_country_prefix' ) );
325
326 add_action( 'init', array( 'SIB_Push_API', 'init' ) );
327 add_action( 'init', array( 'SIB_Push_Public', 'init' ) );
328 // NOTE: deactivate woocommerce
329 // add_action( 'init', array( 'SIB_Push_WooCommerce', 'init' ) );
330
331 add_action( 'init', array( &$this, 'init' ) );
332
333 add_action( 'wp_login', array( &$this, 'sib_wp_login_identify' ), 10, 2 );
334
335 // change sib tables name on prior(2.6.9) versions.
336 SIB_Model_Users::add_prefix();
337 SIB_Forms::add_prefix();
338 SIB_Forms::modify_datatype();
339
340 if ( self::is_api_key_set() ) {
341 add_shortcode( 'sibwp_form', array( &$this, 'sibwp_form_shortcode' ) );
342 // register widget.
343 add_action( 'widgets_init', array( &$this, 'sib_create_widget' ) );
344
345 // create forms tables and create default form.
346 SIB_Forms::createTable();
347 // create users table.
348 SIB_Model_Users::createTable();
349 // add columns for old versions
350 SIB_Forms::alterTable();
351 SIB_Model_Users::add_user_added_date_column();
352 SIB_Model_Users::add_flag_doi_sent();
353 }
354
355 $use_api_version = get_option( 'sib_use_apiv2', '0' );
356 if ( '0' === $use_api_version ) {
357 self::uninstall();
358 update_option( 'sib_use_apiv2', '1' );
359 }
360
361 // Wpml plugin part.
362 if ( ! function_exists( 'is_plugin_active_for_network' ) ) :
363 require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
364 endif;
365 if ( in_array( 'sitepress-multilingual-cms/sitepress.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) || is_plugin_active_for_network( 'sitepress-multilingual-cms/sitepress.php' ) ) {
366 SIB_Forms_Lang::createTable();
367 add_action( 'sib_language_sidebar', array( $this, 'sib_create_language_sidebar' ) );
368 }
369
370 /**
371 * Hook wp_mail to send transactional emails
372 */
373
374 // check if wp_mail function is already declared by others.
375 if ( function_exists( 'wp_mail' ) ) {
376 self::$wp_mail_conflict = true;
377 }
378 $home_settings = get_option( SIB_Manager::HOME_OPTION_NAME, array() );
379
380 if( 'yes' === $home_settings['activate_email'] )
381 {
382 if ( false === self::$wp_mail_conflict ) {
383 /**
384 * Declare wp_mail function for Sendinblue SMTP module
385 *
386 * @param string $to - receiption email.
387 * @param string $subject - subject of email.
388 * @param string $message - message content.
389 * @param string $headers - header of email.
390 * @param array $attachments - attachments.
391 * @return bool
392 */
393 function wp_mail( $to, $subject, $message, $headers = '', $attachments = array() ) {
394 $message = str_replace( 'NF_SIB', '', $message );
395 $message = str_replace( 'WC_SIB', '', $message );
396 try {
397 $sent = SIB_Manager::sib_email( $to, $subject, $message, $headers, $attachments );
398 if ( is_wp_error( $sent ) || ! isset( $sent['code'] ) || 'success' !== $sent['code'] ) {
399 try{
400 return true;
401 }catch( Exception $e ){
402 return false;
403 }
404 }
405 return true;
406 } catch ( Exception $e ) {
407 return false;
408 }
409 }
410 } else {
411 add_action( 'admin_notices', array( &$this, 'wpMailNotices' ) );
412 return;
413 }
414 }
415 }
416
417 /**
418 * Is this wordpress instance connected to the staging environment?
419 * Note: don't forget to manually change mailin/sw.js to put the staging sdk loader
420 * @return bool
421 */
422 static function is_staging() {
423 return false;
424 }
425
426 /**
427 * Add identify tag for login users
428 *
429 * @param string $user_login - user login name.
430 * @param array $user - user.
431 */
432 function sib_wp_login_identify( $user_login, $user ) {
433
434 $userEmail = $user->user_email;
435 $data = array(
436 'email_id' => $userEmail,
437 'name' => $user_login,
438 );
439 SIB_API_Manager::identify_user( $data );
440 }
441
442 /**
443 * Initialize method. called on <i>init</i> action
444 */
445 function init() {
446 // Sign up process.
447 if ( isset( $_POST['sib_form_action'] ) && ( 'subscribe_form_submit' == sanitize_text_field($_POST['sib_form_action']) ) ) {
448 $this->signup_process();
449 }
450 // Subscribe.
451 if ( isset( $_GET['sib_action'] ) && ( 'subscribe' == sanitize_text_field($_GET['sib_action']) ) ) {
452 $code = isset( $_GET['code'] ) ? sanitize_text_field( $_GET['code'] ) : '';
453 $contact_info = SIB_Model_Users::get_data_by_code( $code );
454 $user_added_date = $contact_info['user_added_date'];
455 $current_date = gmdate( 'Y-m-d H:i:s' );
456 $date_diff = strtotime( $current_date ) - strtotime( $user_added_date );
457 if ( $date_diff > 5 ) {
458 SIB_API_Manager::subscribe( $contact_info );
459 } else {
460 $type = 'Bot Event';
461 SIB_API_Manager::template_subscribe( $type );
462 }
463 exit;
464 }
465 // Dismiss language notice.
466 if ( isset( $_GET['dismiss_admin_lang_notice'] ) && '1' == sanitize_text_field($_GET['dismiss_admin_lang_notice']) ) {
467 update_option( SIB_Manager::LANGUAGE_OPTION_NAME, true );
468 wp_safe_redirect( $_SERVER['HTTP_REFERER'] );
469 exit();
470 }
471
472 add_action( 'wp_head', array( &$this, 'install_ma_script' ) );
473 }
474
475 /**
476 * Hook admin_init
477 */
478 function admin_init() {
479 add_action( 'admin_action_sib_setting_subscription', array( 'SIB_Page_Form', 'save_setting_subscription' ) );
480 add_action( 'admin_action_nopriv_sib_setting_subscription', array( 'SIB_Page_Form', 'save_setting_subscription' ) );
481 SIB_Manager::LoadTextDomain();
482 $this->register_scripts();
483 $this->register_styles();
484 }
485
486 /**
487 * Hook admin_menu
488 */
489 function admin_menu() {
490 SIB_Manager::LoadTextDomain();
491 new SIB_Page_Home();
492 if ( SIB_Push_Utils::can_modify_settings() ) {
493 new SIB_Page_Push();
494 }
495 new SIB_Page_Form();
496
497 }
498
499 /**
500 * Register script for admin page
501 */
502 function register_scripts() {
503 wp_register_script( 'sib-bootstrap-js', self::$plugin_url . '/js/bootstrap/js/bootstrap.bundle.min.js', array( 'jquery' ), false );
504 wp_register_script( 'sib-admin-js', self::$plugin_url . '/js/admin.js', array( 'jquery' ), filemtime( self::$plugin_dir . '/js/admin.js' ) );
505 wp_register_script( 'sib-chosen-js', self::$plugin_url . '/js/chosen.jquery.min.js', array( 'jquery' ), false );
506 wp_register_script( 'sib-push-js', self::$plugin_url . '/js/push.bundle.js', array( 'wp-i18n', 'react', 'react-dom' ), filemtime(self::$plugin_dir . '/js/push.bundle.js'), true );
507 wp_register_script('sib-post-editor-js', self::$plugin_url . '/js/post-editor.bundle.js', array( 'jquery', 'wp-i18n' ), filemtime(self::$plugin_dir . '/js/post-editor.bundle.js'));
508 wp_register_script('sib-select2', self::$plugin_url . '/js/select2.full.min.js', array('jquery'), '4.0.13');
509 wp_set_script_translations( 'sib-push-js', 'push', self::$plugin_dir . 'lang' );
510 wp_set_script_translations( 'sib-post-editor-js', 'post-editor', self::$plugin_dir . 'lang' );
511 wp_enqueue_script('jquery-ui-datepicker');
512 wp_enqueue_script('jquery-ui-spinner');
513 }
514
515 /**
516 * Register stylesheet for admin page
517 */
518 function register_styles() {
519 wp_register_style( 'sib-bootstrap-css', self::$plugin_url . '/js/bootstrap/css/bootstrap.css', array(), false, 'all' );
520 wp_register_style( 'sib-fontawesome-css', self::$plugin_url . '/css/fontawesome/css/font-awesome.css', array(), false, 'all' );
521 wp_register_style( 'sib-chosen-css', self::$plugin_url . '/css/chosen.min.css' );
522 wp_register_style( 'sib-admin-css', self::$plugin_url . '/css/admin.css', array(), filemtime( self::$plugin_dir . '/css/admin.css' ), 'all' );
523 wp_register_style('sib-push-admin-css', self::$plugin_url . '/css/push-admin.css', array(), filemtime( self::$plugin_dir . '/css/push-admin.css' ));
524 wp_register_style('sib-select2', self::$plugin_url . '/css/select2.min.css', false, '4.0.13');
525 wp_register_style('sib-font-face', 'https://designsystem.brevo.com/designsystem/component/face/ba05798091ad5d7562c3.css', false, 'ba05798091ad5d7562c3');
526 }
527
528 /**
529 * Registers scripts for frontend
530 */
531 function frontend_register_scripts() {
532
533 }
534
535 /**
536 * Enqueue script on front page
537 */
538 function wp_head_ac() {
539 wp_enqueue_script( 'sib-front-js', self::$plugin_url . '/js/mailin-front.js', array( 'jquery' ), filemtime( self::$plugin_dir . '/js/mailin-front.js' ), false );
540 wp_enqueue_style( 'sib-front-css', self::$plugin_url.'/css/mailin-front.css', array(), array(), 'all');
541 wp_localize_script(
542 'sib-front-js', 'sibErrMsg', array(
543 'invalidMail' => __( 'Please fill out valid email address', 'mailin' ),
544 'requiredField' => __( 'Please fill out required fields', 'mailin' ),
545 'invalidDateFormat' => __( 'Please fill out valid date format', 'mailin' ),
546 'invalidSMSFormat' => __( 'Please fill out valid phone number', 'mailin' ),
547 )
548 );
549 wp_localize_script(
550 'sib-front-js', 'ajax_sib_front_object',
551 array(
552 'ajax_url' => admin_url( 'admin-ajax.php' ),
553 'ajax_nonce' => wp_create_nonce( 'sib_front_ajax_nonce' ),
554 'flag_url' => plugins_url('img/flags/', __FILE__ ),
555 )
556 );
557 }
558
559 /**
560 * Install method is called once install this plugin.
561 * create tables, default option ...
562 */
563 static function install() {
564 $general_settings = get_option( self::MAIN_OPTION_NAME, array() );
565 $access_key = isset( $general_settings['access_key'] ) ? $general_settings['access_key'] : '';
566 if ( '' === $access_key ) {
567 // Default option when activate.
568 $home_settings = array(
569 'activate_email' => 'no',
570 'activate_ma' => 'default',
571 );
572 update_option( self::HOME_OPTION_NAME, $home_settings );
573 }
574
575 self::activate_brevo_connection();
576 }
577
578 /**
579 * Uninstall method is called once uninstall this plugin
580 * delete tables, options that used in plugin
581 */
582 static function uninstall() {
583 $setting = array();
584 update_option( SIB_Manager::MAIN_OPTION_NAME, $setting );
585
586 $home_settings = array(
587 'activate_email' => 'no',
588 'activate_ma' => 'default',
589 );
590 update_option( SIB_Manager::HOME_OPTION_NAME, $home_settings );
591
592 // Delete access_token.
593 $token_settings = array();
594 update_option( SIB_Manager::ACCESS_TOKEN_OPTION_NAME, $token_settings );
595
596 //Deactivate the connection on Brevo
597 self::deactivate_brevo_connection();
598
599 //Then delete the api key in our plugin
600 delete_option(SIB_Manager::API_KEY_V3_OPTION_NAME);
601 // Empty tables.
602 SIB_Model_Users::removeTable();
603 SIB_Forms::removeTable();
604 SIB_Forms_Lang::removeTable();
605
606 // Remove all transient.
607 SIB_API_Manager::remove_transients();
608 }
609
610 static function deactivate_brevo_connection()
611 {
612 $installationId = get_option( SIB_Manager::INSTALLATION_ID );
613 if(!empty($installationId))
614 {
615 $apiClient = new SendinblueApiClient();
616 $params["connection"] = 27;
617 $params["plugin_version"] = SendinblueApiClient::PLUGIN_VERSION;
618 $params["active"] = false;
619 $params["deactivated_at"] = gmdate("Y-m-d\TH:i:s\Z");
620 $apiClient->updateInstallationInfo($installationId, $params);
621 }
622 }
623
624 static function activate_brevo_connection()
625 {
626 $installationId = get_option( SIB_Manager::INSTALLATION_ID );
627 if(!empty($installationId))
628 {
629 $apiClient = new SendinblueApiClient();
630 $params["connection"] = 27;
631 $params["plugin_version"] = SendinblueApiClient::PLUGIN_VERSION;
632 $params["active"] = true;
633 $params["activated_at"] = gmdate("Y-m-d\TH:i:s\Z");
634 $apiClient->updateInstallationInfo($installationId, $params);
635 }
636 }
637
638 /**
639 * Deactivate method is called once deactivate this plugin
640 */
641 static function deactivate() {
642 update_option( SIB_Manager::LANGUAGE_OPTION_NAME, false );
643 self::uninstall_service_worker_script();
644 // Remove sync users option.
645 delete_option( 'sib_sync_users' );
646 // Remove all transient.
647 SIB_API_Manager::remove_transients();
648
649 //Also deactivate the connection on Brevo
650 self::deactivate_brevo_connection();
651 }
652
653 /**
654 * Check if plugin is logged in.
655 *
656 * @param bool $redirect
657 * @return bool
658 */
659 static function is_done_validation($redirect = true) {
660 if (self::is_api_key_set()) {
661 $apiClient = new SendinblueApiClient();
662 $apiClient->getAccount();
663 if ( SendinblueApiClient::RESPONSE_CODE_OK === $apiClient->getLastResponseCode() ) {
664 //This is only for those users who have an active connection but no installation id could be
665 //saved on their shop
666 $installationId = get_option( SIB_Manager::INSTALLATION_ID );
667 if(empty($installationId))
668 {
669 self::fetch_and_save_installation_id();
670 }
671 return true;
672 } elseif (SendinblueApiClient::RESPONSE_CODE_UNAUTHORIZED === $apiClient->getLastResponseCode()) {
673 delete_option(SIB_Manager::API_KEY_V3_OPTION_NAME);
674 }
675 }
676
677 if ($redirect) {
678 self::redirect_to_sib_plugin_homepage();
679 }
680
681 return false;
682 }
683
684 static function redirect_to_sib_plugin_homepage() {
685 wp_safe_redirect(add_query_arg('page', SIB_Page_Home::PAGE_ID, admin_url('admin.php')));
686 }
687
688 /**
689 * @return bool
690 */
691 static function is_api_key_set() {
692 $api_key = get_option(SIB_Manager::API_KEY_V3_OPTION_NAME);
693 return !empty($api_key);
694 }
695
696 static function is_ma_active() {
697 $general_settings = get_option( SIB_Manager::MAIN_OPTION_NAME, array() );
698 $ma_key = isset( $general_settings['ma_key'] ) ? sanitize_text_field($general_settings['ma_key']) : null;
699 if ( $ma_key === null || strlen($ma_key) === 0 ) {
700 return false;
701 }
702 $home_settings = get_option( SIB_Manager::HOME_OPTION_NAME, array() );
703 $activate_ma = isset( $home_settings['activate_ma'] ) ? $home_settings['activate_ma'] : 'default';
704 return 'no' !== $activate_ma;
705 }
706
707 static function fetch_and_save_installation_id()
708 {
709 $apiClient = new SendinblueApiClient();
710
711 $params["partnerName"] = "WORDPRESS";
712 $params["plugin_version"] = SendinblueApiClient::PLUGIN_VERSION;
713 $params["shop_url"] = get_home_url();
714 $params["active"] = true;
715 $params["connection"] = 27;
716 $response = $apiClient->createInstallationInfo($params);
717 if ( $apiClient->getLastResponseCode() === SendinblueApiClient::RESPONSE_CODE_CREATED )
718 {
719 if(!empty($response["id"]))
720 {
721 update_option(SIB_Manager::INSTALLATION_ID, $response["id"]);
722 }
723 }
724 }
725
726 /**
727 * Uninstall service-worker script from plugin
728 * @return void
729 */
730 static function uninstall_service_worker_script()
731 {
732 try {
733 $service_worker_file = __DIR__ . self::SERVICE_WORKER_FILE_URL;
734 if (file_exists($service_worker_file)) {
735 wp_delete_file($service_worker_file);
736 }
737 update_option('sib_service_worker_install_exception', '');
738 } catch (\Throwable $th) {
739 update_option('sib_service_worker_uninstall_exception', $th->getMessage());
740 }
741 }
742
743 /**
744 * Install marketing automation script in header
745 */
746 function install_ma_script() {
747 $push_enabled = SIB_Push_Utils::is_push_sdk_enabled();
748 if ( SIB_Manager::is_ma_active() ) {
749 $init_options = json_encode( SIB_Push_Utils::brevo_init_options() );
750 $script_url = self::is_staging() ? self::SDK_LOADER_STAGING_URL : self::SDK_LOADER_PRODUCTION_URL;
751 $output = <<<EOT
752 <script type="text/javascript" src="{$script_url}" async></script>
753 <script type="text/javascript">
754 window.Brevo = window.Brevo || [];
755 window.Brevo.push(['init', {$init_options}]);
756 </script>
757 EOT;
758 echo $output;
759 } else {
760 self::uninstall_service_worker_script();
761 }
762 if ( $push_enabled ) {
763 $init_options = SIB_Push_Utils::wonderpush_init_options();
764 $script_url = 'https://cdn.by.wonderpush.com/sdk/1.1/wonderpush-loader.min.js';
765 if ($init_options) {
766 $encoded_init_options = json_encode($init_options);
767 $output = <<<EOT
768 <script type="text/javascript" src="{$script_url}" async></script>
769 <script type="text/javascript">
770 window.WonderPush = window.WonderPush || [];
771 window.WonderPush.push(['init', {$encoded_init_options}]);
772 </script>
773 EOT;
774 echo $output;
775 }
776 }
777 }
778
779 /**
780 * Register widget
781 */
782 function sib_create_widget() {
783 register_widget( 'SIB_Widget_Subscribe' );
784 }
785
786 /**
787 * Display form on front page
788 *
789 * @param string $frmID - form ID.
790 * @param string $lang - form language.
791 */
792 function generate_form_box( $frmID = '-1', $lang = '' ) {
793 if ( 'oldForm' == $frmID ) {
794 $frmID = get_option( 'sib_old_form_id' );
795 } elseif ( '' != $lang ) {
796 $trans_id = SIB_Forms_Lang::get_form_ID( $frmID, $lang );
797 if ( null != $trans_id ) {
798 $frmID = $trans_id;
799 }
800 }
801
802 $formData = SIB_Forms::getForm( $frmID );
803
804 if ( empty( $formData ) ) {
805 return;
806 }
807 // Add Google recaptcha
808 if( '0' != $formData['gCaptcha'] && $formData['selectCaptchaType'] != 3) {
809 if( '1' == $formData['gCaptcha'] ) { // For old forms.
810 $formData['html'] = preg_replace( '/([\s\S]*?)<div class="g-recaptcha"[\s\S]*?data-size="invisible"><\/div>/', '$1', $formData['html'] );
811 }
812 if ( '3' == $formData['gCaptcha'] ) // The case of using google recaptcha.
813 {
814 ?>
815 <script type="text/javascript">
816 var onloadSibCallback = function () {
817 jQuery('.g-recaptcha').each(function (index, el) {
818 grecaptcha.render(el, {
819 'sitekey': jQuery(el).attr('data-sitekey')
820 });
821 });
822 };
823 </script>
824 <?php
825 } else { // The case of using google invisible recaptcha.
826 $formData['html'] = str_contains( $formData['html'], 'sib-default-btn' ) ? str_replace(
827 'type="submit"',
828 'type="submit" id="invisible"',
829 $formData['html']
830 ) : $formData['html'];
831 ?>
832 <script type="text/javascript">
833 var gCaptchaSibWidget;
834 var onloadSibCallbackInvisible = function () {
835
836 var element = document.getElementsByClassName('sib-default-btn');
837 var countInvisible = 0;
838 var indexArray = [];
839 jQuery('.sib-default-btn').each(function (index, el) {
840 if ((jQuery(el).attr('id') == "invisible")) {
841 indexArray[countInvisible] = index;
842 countInvisible++
843 }
844 });
845
846 jQuery('.invi-recaptcha').each(function (index, el) {
847 grecaptcha.render(element[indexArray[index]], {
848 'sitekey': jQuery(el).attr('data-sitekey'),
849 'callback': sibVerifyCallback,
850 });
851 });
852 };
853 </script>
854 <?php
855 }
856 ?>
857 <script src="https://www.google.com/recaptcha/api.js?onload=<?php
858 echo esc_attr(
859 $formData['gCaptcha'] == '2' ? 'onloadSibCallbackInvisible' : 'onloadSibCallback'
860 ) ?>&render=explicit" async defer></script>
861 <?php
862 } else if ('0' != $formData['gCaptcha'] && $formData['selectCaptchaType'] == 3) { ?>
863
864 <script src="https://challenges.cloudflare.com/turnstile/v0/api.js"></script>
865
866 <?php } ?>
867
868 <form id="sib_signup_form_<?php echo esc_attr( $frmID ); ?>" method="post" class="sib_signup_form">
869 <div class="sib_loader" style="display:none;"><img
870 src="<?php echo esc_url( includes_url() ); ?>images/spinner.gif" alt="loader"></div>
871 <input type="hidden" name="sib_form_action" value="subscribe_form_submit">
872 <input type="hidden" name="sib_form_id" value="<?php echo esc_attr( $frmID ); ?>">
873 <input type="hidden" name="sib_form_alert_notice" value="<?php echo esc_attr($formData['requiredMsg']); ?>">
874 <input type="hidden" name="sib_form_invalid_email_notice" value="<?php echo esc_attr($formData['invalidMsg']); ?>">
875 <input type="hidden" name="sib_security" value="<?php echo esc_attr( wp_create_nonce( 'sib_front_ajax_nonce' ) ); ?>">
876 <div class="sib_signup_box_inside_<?php echo esc_attr( $frmID ); ?>">
877 <div style="/*display:none*/" class="sib_msg_disp">
878 </div>
879 <?php
880 if (($formData['gCaptcha'] == '2') && false === strpos(
881 $formData['html'],
882 'id="sib_captcha_invisible"'
883 )) { ?>
884 <div id="sib_captcha_invisible" class="invi-recaptcha" data-sitekey="<?php
885 echo esc_attr($formData['gCaptcha_site']); ?>"></div>
886 <?php
887 } ?>
888 <?php
889 // phpcs:ignore
890
891 if (false === strpos($formData['html'], 'class="g-recaptcha"')) {
892 $formData['html'] = str_replace(
893 'id="sib_captcha"',
894 'id="sib_captcha" class="g-recaptcha" data-sitekey="' . $formData['gCaptcha_site'] . '"',
895 $formData['html']
896 );
897 }
898
899 echo wp_kses($formData['html'], SIB_Manager::wordpress_allowed_attributes());
900 ?>
901 </div>
902 </form>
903 <style>
904 <?php
905
906 if ( ! $formData['dependTheme'] ) {
907 // Custom css.
908 $formData['css'] = str_replace( '[form]', 'form#sib_signup_form_' . $frmID, $formData['css'] );
909 echo esc_html($formData['css']);
910 }
911 $msgCss = str_replace( '[form]', 'form#sib_signup_form_' . $frmID, SIB_Forms::getDefaultMessageCss() );
912 echo esc_html($msgCss);
913 ?>
914 </style>
915 <?php
916 }
917
918 /**
919 * Shortcode for sign up form
920 *
921 * @param array $atts - shortcode parameter.
922 * @return string
923 */
924 function sibwp_form_shortcode( $atts ) {
925 $pull_atts = shortcode_atts(
926 array(
927 'id' => 'oldForm', // We will return 'oldForm' for shortcode of old form.
928 ), $atts
929 );
930 $frmID = $pull_atts['id'];
931 $lang = defined( 'ICL_LANGUAGE_CODE' ) ? ICL_LANGUAGE_CODE : '';
932
933 ob_start();
934 $this->generate_form_box( $frmID, $lang );
935
936 $output_string = ob_get_contents();
937 ob_end_clean();
938 return $output_string;
939 }
940
941 /**
942 * Sign up process
943 */
944 function signup_process() {
945 //Handling of backslash added by WP because magic quotes are enabled by default
946 array_walk_recursive( $_POST, function(&$value) {
947 $value = stripslashes($value);
948 });
949
950 if ( empty( $_POST['sib_security'] ) || empty(wp_verify_nonce($_POST['sib_security'], 'sib_front_ajax_nonce'))) {
951 wp_send_json(
952 array(
953 'status' => 'sib_security',
954 'msg' => 'Invalid Token Provided.',
955 )
956 );
957 }
958 $formID = isset( $_POST['sib_form_id'] ) ? sanitize_text_field( $_POST['sib_form_id'] ) : 1;
959 if ( 'oldForm' == $formID ) {
960 $formID = get_option( 'sib_old_form_id' );
961 }
962 $formData = SIB_Forms::getForm( $formID );
963
964 if (!SIB_Manager::is_done_validation(false) || 0 == count($formData)) {
965 wp_send_json(
966 array(
967 'status' => 'failure',
968 'msg' => array("errorMsg" => "Something wrong occurred"),
969 )
970 );
971 }
972 $turnstileCaptcha = false;
973 if ( '0' != $formData['gCaptcha'] && 3 != $formData['selectCaptchaType']) {
974 $turnstileCaptcha = true;
975 if ( ! isset( $_POST['g-recaptcha-response'] ) || empty( $_POST['g-recaptcha-response'] ) ) {
976 wp_send_json(
977 array(
978 'status' => 'gcaptchaEmpty',
979 'msg' => 'Please click on the reCAPTCHA box.',
980 )
981 );
982 }
983 $secret = $formData['gCaptcha_secret'];
984
985 $data = array(
986 'secret' => $secret,
987 'response' => sanitize_text_field( $_POST['g-recaptcha-response'] ),
988 );
989
990 $args = [
991 'method' => 'POST',
992 ];
993
994 try {
995 $data = wp_remote_retrieve_body(wp_remote_request(sprintf(self::RECAPTCHA_API_TEMPLATE, http_build_query($data)), $args));
996 $responseData = json_decode($data);
997 if ( ! $responseData->success ) {
998 wp_send_json(
999 array(
1000 'status' => 'gcaptchaFail',
1001 'msg' => 'Robot verification failed, please try again.',
1002 )
1003 );
1004 }
1005 } catch (Exception $exception) {
1006 wp_send_json(
1007 array(
1008 'status' => 'gcaptchaFail',
1009 'msg' => $exception->getMessage(),
1010 )
1011 );
1012 }
1013 } else if ( '0' != $formData['gCaptcha'] && 3 == $formData['selectCaptchaType'] ) {
1014 $turnstileCaptcha = true;
1015 if ( ! isset( $_POST['cf-turnstile-response'] ) || empty( $_POST['cf-turnstile-response'] ) ) {
1016 wp_send_json(
1017 array(
1018 'status' => 'gcaptchaEmpty',
1019 'msg' => 'Captcha couldnot be verified. Please refresh the page.',
1020 )
1021 );
1022 }
1023 $secret = $formData['cCaptcha_secret'];
1024
1025 $args = [
1026 'method' => 'POST',
1027 ];
1028
1029 try {
1030
1031 $headers = array(
1032 'body' => [
1033 'secret' => $secret,
1034 'response' => sanitize_text_field( $_POST['cf-turnstile-response'] )
1035 ]
1036 );
1037 $verify = wp_remote_post(self::TURNSTILE_SITE_VERIFY, $headers);
1038 $verify = wp_remote_retrieve_body($verify);
1039 $response = json_decode($verify);
1040
1041 if($response->success) {
1042 $results['success'] = $response->success;
1043 } else {
1044 $results['success'] = false;
1045 }
1046
1047 if ( ! $response->success ) {
1048 wp_send_json(
1049 array(
1050 'status' => 'gcaptchaFail',
1051 'msg' => 'Robot verification failed, please try again.',
1052 )
1053 );
1054 }
1055 } catch (Exception $exception) {
1056 wp_send_json(
1057 array(
1058 'status' => 'gcaptchaFail',
1059 'msg' => $exception->getMessage(),
1060 )
1061 );
1062 }
1063 }
1064
1065 $listID = $formData['listID'];
1066 if (empty($listID)) {
1067 $listID = array();
1068 }
1069 $interestingLists = isset( $_POST['interestingLists']) ? array_map( 'sanitize_text_field', $_POST['interestingLists'] ) : array();
1070 $expectedLists = isset( $_POST['listIDs'] ) ? array_map( 'sanitize_text_field', $_POST['listIDs'] ) : array();
1071 if ( empty($interestingLists) )
1072 {
1073 $unlinkedLists = [];
1074 }
1075 else{
1076 $unwantedLists = array_diff( $interestingLists, $expectedLists );
1077 $unlinkedLists = array_diff( $unwantedLists, $listID);
1078 $listID = array_unique(array_merge( $listID, $expectedLists ));
1079 }
1080
1081 $email = isset( $_POST['email'] ) ? sanitize_email( $_POST['email'] ) : '';
1082 if ( ! is_email( $email ) ) {
1083 return;
1084 }
1085
1086 $isDoubleOptin = $formData['isDopt'];
1087 $isOptin = $formData['isOpt'];
1088 $redirectUrlInEmail = $formData['redirectInEmail'];
1089 $redirectUrlInForm = $formData['redirectInForm'];
1090
1091 $info = array();
1092 $attributes = explode( ',', $formData['attributes'] ); // String to array.
1093 if ( isset( $attributes ) && is_array( $attributes ) ) {
1094 foreach ( $_POST as $postAttribute => $postAttributeValue ) {
1095 $correspondingSibAttribute = $this->getCorrespondingSibAttribute($postAttribute, $attributes);
1096 if (!empty($correspondingSibAttribute)) {
1097 $info[$correspondingSibAttribute] = is_array($postAttributeValue)
1098 ? array_map('sanitize_text_field', $postAttributeValue)
1099 : sanitize_text_field($postAttributeValue);
1100
1101 }
1102 }
1103 }
1104 $templateID = $formData['templateID'];
1105
1106 if ( $isDoubleOptin ) {
1107 /*
1108 * Double optin process
1109 * 1. add record to db
1110 * 2. send confirmation email with activate code
1111 */
1112 $result = "success";
1113 // Send a double optin confirm email.
1114 if ( 'success' == $result ) {
1115 // Add a recode with activate code in db.
1116 $activateCode = $this->create_activate_code( $email, $info, $formID, $listID, $redirectUrlInEmail, $unlinkedLists );
1117 SIB_API_Manager::send_comfirm_email( $email, 'double-optin', $templateID, $info, $activateCode );
1118 }
1119 } elseif ( $isOptin ) {
1120 $result = SIB_API_Manager::create_subscriber( $email, $listID, $info, 'confirm', $unlinkedLists );
1121 if ( 'success' == $result ) {
1122 // Send a confirm email.
1123 SIB_API_Manager::send_comfirm_email( $email, 'confirm', $templateID, $info );
1124 }
1125 } else {
1126 $result = SIB_API_Manager::create_subscriber( $email, $listID, $info, 'simple', $unlinkedLists );
1127 }
1128 $msg = array(
1129 'successMsg' => $formData['successMsg'],
1130 'errorMsg' => $formData['errorMsg'],
1131 'existMsg' => $formData['existMsg'],
1132 'invalidMsg' => $formData['invalidMsg'],
1133 );
1134
1135 wp_send_json(
1136 array(
1137 'status' => $result,
1138 'msg' => $msg,
1139 'redirect' => $redirectUrlInForm,
1140 'turnstileCaptcha' => $turnstileCaptcha,
1141 )
1142 );
1143 }
1144
1145 /**
1146 * Create activate code for Double optin
1147 *
1148 * @param string $email - user email.
1149 * @param array $info - info.
1150 * @param string $formID - form ID.
1151 * @param array $listIDs - lists.
1152 * @param string $redirectUrl - redirect url.
1153 * @return string - activate code.
1154 */
1155 function create_activate_code( $email, $info, $formID, $listIDs, $redirectUrl, $unlinkedLists = null ) {
1156 $data = SIB_Model_Users::get_data_by_email( $email, $formID );
1157 $date = gmdate( 'Y-m-d H:i:s' );
1158 if ( $unlinkedLists != null )
1159 {
1160 $info['unlinkedLists'] = $unlinkedLists;
1161 }
1162 if ( false == $data ) {
1163 $uniqid = uniqid();
1164 $data = array(
1165 'email' => $email,
1166 'code' => $uniqid,
1167 'info' => maybe_serialize( $info ),
1168 'frmid' => $formID,
1169 'listIDs' => maybe_serialize( $listIDs ),
1170 'redirectUrl' => $redirectUrl,
1171 'user_added_date' => $date,
1172 'doi_sent' => 0,
1173 );
1174 SIB_Model_Users::add_record( $data );
1175 } else {
1176 $update_data = array(
1177 'id' => $data['id'],
1178 'email' => $email,
1179 'info' => maybe_serialize( $info ),
1180 );
1181 SIB_Model_Users::update_element( $update_data );
1182 $uniqid = $data['code'];
1183 }
1184 return $uniqid;
1185 }
1186
1187 /**
1188 * Use Sendinblue SMTP to send all emails
1189 *
1190 * @param string $to - reception email.
1191 * @param string $subject - subject of email.
1192 * @param string $message - message of email.
1193 * @param string $headers - header of email.
1194 * @param array $attachments - attachments.
1195 */
1196 static function wp_mail_native( $to, $subject, $message, $headers = '', $attachments = array() ) {
1197 $result = require self::$plugin_dir . '/inc/function.wp_mail.php';
1198 return $result;
1199 }
1200
1201 /**
1202 * To send the transactional email via Sendinblue
1203 * hook wp_mail
1204 *
1205 * @param string $to - reception email.
1206 * @param string $subject - subject of email.
1207 * @param string $message - message of email.
1208 * @param string $headers - header of email.
1209 * @param array $attachments - attachments
1210 * @param array $tags - tag.
1211 * @param string $from_name - sender name.
1212 * @param string $from_email - sender email.
1213 * @return mixed|WP_Error
1214 */
1215 static function sib_email( $to, $subject, $message, $headers = '', $attachments = array(), $tags = array(), $from_name = '', $from_email = '' ) {
1216 $data = [];
1217 // Compact the input, apply the filters, and extract them back out.
1218 extract( apply_filters( 'wp_mail', compact( 'to', 'subject', 'message', 'headers', 'attachments' ) ) );
1219
1220 if ( !empty( $attachments ) && ! is_array( $attachments ) ) {
1221 $attachments = explode( "\n", str_replace( "\r\n", "\n", $attachments ) );
1222 }
1223
1224 // From email and name.
1225 $home_settings = get_option( SIB_Manager::HOME_OPTION_NAME );
1226 if ( isset( $home_settings['sender'] ) ) {
1227 $from_name = $home_settings['from_name'];
1228 $from_email = $home_settings['from_email'];
1229 } else {
1230 $from_email = trim( get_bloginfo( 'admin_email' ) );
1231 $from_name = trim( get_bloginfo( 'name' ) );
1232 }
1233
1234 //Set additional address fields as empty
1235 $bcc = array();
1236 $cc = array();
1237 $reply_to = array();
1238 if ( ! is_array( $to ) ) {
1239 $to = explode( ',', $to );
1240 }
1241
1242 $from_email = apply_filters( 'wp_mail_from', $from_email );
1243 $from_name = apply_filters( 'wp_mail_from_name', $from_name );
1244
1245 if ( !empty( $headers ) ) {
1246 if( is_array( $headers ) ){
1247 foreach ($headers as $key => $val) {
1248 if( stripos($val, "Content-Type: text/html") !== false ) {
1249 unset( $headers[$key] );
1250 }
1251 }
1252 $headers = array_values( $headers );
1253 if( count( $headers ) == 1 && $headers[0] == '' ) {
1254 unset( $headers[0] );
1255 }
1256 }
1257 if( is_string( $headers ) ){
1258 $headers = str_replace("Content-Type: text/html", "", $headers);
1259 }
1260 if( !empty( $headers ) ){
1261 $data['headers'] = $headers;
1262 }
1263 if ( ! is_array( $headers ) ) {
1264 // Explode the headers out, so this function can take both.
1265 // string headers and an array of headers.
1266 $tempheaders = explode( "\n", str_replace( "\r\n", "\n", $headers ) );
1267 } else {
1268 $tempheaders = $headers;
1269 }
1270 $headers = array();
1271 // If it's actually got contents.
1272 if ( ! empty( $tempheaders ) ) {
1273 // Iterate through the raw headers.
1274 foreach ( (array) $tempheaders as $header ) {
1275 if ( strpos( $header, ':' ) === false ) {
1276 if ( false !== stripos( $header, 'boundary=' ) ) {
1277 $parts = preg_split( '/boundary=/i', trim( $header ) );
1278 $boundary = trim( str_replace( array( "'", '"' ), '', $parts[1] ) );
1279 }
1280 continue;
1281 }
1282 // Explode them out.
1283 list($name, $content) = explode( ':', trim( $header ), 2 );
1284
1285 // Cleanup crew.
1286 $name = trim( $name );
1287 $content = trim( $content );
1288
1289 switch ( strtolower( $name ) ) {
1290 case 'content-type':
1291 $headers[ trim( $name ) ] = trim( $content );
1292 break;
1293 case 'x-mailin-tag':
1294 $headers[ trim( $name ) ] = trim( $content );
1295 break;
1296 case 'from':
1297 if ( strpos( $content, '<' ) !== false ) {
1298 // So... making my life hard again?
1299 $from_name = substr( $content, 0, strpos( $content, '<' ) - 1 );
1300 $from_name = str_replace( '"', '', $from_name );
1301 $from_name = trim( $from_name );
1302
1303 $from_email = substr( $content, strpos( $content, '<' ) + 1 );
1304 $from_email = str_replace( '>', '', $from_email );
1305 $from_email = trim( $from_email );
1306 } else {
1307 $from_name = '';
1308 $from_email = trim( $content );
1309 }
1310 break;
1311
1312 case 'cc':
1313 $cc = array_merge( (array) $cc, explode( ',', $content ) );
1314 break;
1315
1316 case 'bcc':
1317 $bcc = array_merge( (array) $bcc, explode( ',', $content ) );
1318 break;
1319
1320 case 'reply-to':
1321 $reply_to = array_merge( (array) $reply_to, explode( ',', $content ) );
1322 break;
1323 default:
1324 break;
1325 }
1326 }
1327 }
1328 }
1329
1330 // Set destination addresses, using appropriate methods for handling addresses.
1331 $address_headers = compact('to', 'cc', 'bcc', 'reply_to');
1332 $processed_address_fields = self::processAddressFields($address_headers);
1333 $data = array_merge($data, $processed_address_fields);
1334 // Attachments.
1335 $attachment_content = array();
1336 if ( ! empty( $attachments ) ) {
1337 foreach ( $attachments as $attachment ) {
1338 if ( !empty( $attachment ) ) {
1339 $content = self::getAttachmentStruct( $attachment );
1340 if ( ! is_wp_error( $content ) ) {
1341 array_push( $attachment_content, $content );
1342 }
1343 }
1344 }
1345 if ( !empty( $attachment_content ) ) {
1346 $data["attachment"] = $attachment_content;
1347 }
1348 }
1349
1350 // Common transformations for the HTML part.
1351 // If it is text/plain, New line break found.
1352 if ( strpos( $message, '</table>' ) === false && strpos( $message, '</div>' ) === false ) {
1353 if ( strpos( $message, "\n" ) !== false ) {
1354 if ( is_array( $message ) ) {
1355 foreach ( $message as &$value ) {
1356 $value['content'] = preg_replace( '#<(https?://[^*]+)>#', '$1', $value['content'] );
1357 $value['content'] = nl2br( $value['content'] );
1358 }
1359 } else {
1360 $message = preg_replace( '#<(https?://[^*]+)>#', '$1', $message );
1361 $message = nl2br( $message );
1362 }
1363 }
1364 }
1365 // Sending...
1366 $data['sender'] = ['email' => $from_email, 'name' => $from_name ];
1367 $data['subject'] = $subject;
1368 $data['htmlContent'] = $message;
1369
1370 try {
1371 $sent = SIB_API_Manager::send_email( $data );
1372 return $sent;
1373 } catch ( Exception $e ) {
1374 return new WP_Error( $e->getMessage() );
1375 }
1376 }
1377
1378 /**
1379 * @param array $address_fields
1380 * @return array
1381 */
1382 private static function processAddressFields($address_fields)
1383 {
1384 $data = [
1385 'to' => [],
1386 'cc' => [],
1387 'bcc' => [],
1388 'replyTo' => [],
1389 ];
1390
1391 $address_fields['reply_to'] = is_array($address_fields['reply_to'])
1392 && count($address_fields['reply_to']) > 1 ? $address_fields['reply_to'][0] : $address_fields['reply_to'];
1393 foreach ($address_fields as $address_header => $addresses) {
1394 if (empty($addresses)) {
1395 continue;
1396 }
1397
1398 foreach ((array) $addresses as $address) {
1399 // Break $recipient into name and address parts if in the format "Foo <bar@baz.com>".
1400 if (preg_match('/(.*)<(.+)>/', $address, $matches)) {
1401 if (count($matches) == 3) {
1402 $address = preg_replace('/\s+/', '', $matches[2]); //strip whitespaces
1403 }
1404 }
1405
1406 switch ($address_header) {
1407 case 'to':
1408 $data['to'][] = ['email' => $address];
1409 break;
1410 case 'cc':
1411 $data['cc'][] = ['email' => $address];
1412 break;
1413 case 'bcc':
1414 $data['bcc'][] = ['email' => $address];
1415 break;
1416 case 'reply_to':
1417 $data['replyTo']['email'] = $address;
1418 break;
1419 }
1420 }
1421 }
1422 return $data;
1423 }
1424
1425 /**
1426 * @param string $path - attachment file path
1427 * @return array|WP_Error
1428 */
1429 static function getAttachmentStruct( $path ) {
1430
1431 $struct = array();
1432
1433 try {
1434
1435 if ( ! @is_file( $path ) ) {
1436 throw new Exception( $path . ' is not a valid file.' );
1437 }
1438
1439 $filename = basename( $path );
1440
1441 if ( ! function_exists( 'get_magic_quotes' ) ) {
1442 /**
1443 * @return bool
1444 */
1445 function get_magic_quotes() {
1446 return false;
1447 }
1448 }
1449 if ( ! function_exists( 'set_magic_quotes' ) ) {
1450 /**
1451 * @param $value
1452 * @return bool
1453 */
1454 function set_magic_quotes( $value ) {
1455 return true;
1456 }
1457 }
1458
1459 $isMagicQuotesSupported = version_compare( PHP_VERSION, '5.3.0', '<' )
1460 && function_exists( 'get_magic_quotes_runtime' )
1461 && function_exists( 'set_magic_quotes_runtime' );
1462
1463 if ( $isMagicQuotesSupported ) {
1464 // Escape linters check.
1465 $getMagicQuotesRuntimeFunc = 'get_magic_quotes_runtime';
1466 $setMagicQuotesRuntimeFunc = 'set_magic_quotes_runtime';
1467
1468 // Save magic quotes value.
1469 $magicQuotes = $getMagicQuotesRuntimeFunc();
1470 $setMagicQuotesRuntimeFunc (0);
1471 }
1472
1473 $file_buffer = file_get_contents( $path );
1474 $file_buffer = base64_encode($file_buffer);
1475
1476 if ( $isMagicQuotesSupported ) {
1477 // Restore magic quotes value.
1478 $setMagicQuotesRuntimeFunc($magicQuotes);
1479 }
1480
1481 $struct["name"] = $filename;
1482 $struct["content"] = $file_buffer;
1483
1484 } catch ( Exception $e ) {
1485 return new WP_Error( 'Error creating the attachment structure: ' . $e->getMessage() );
1486 }
1487
1488 return $struct;
1489 }
1490
1491 /**
1492 * Create custom page for form preview
1493 *
1494 * @param array $query_vars - query.
1495 * @return array
1496 */
1497 function sib_query_vars( $query_vars ) {
1498 $query_vars[] = 'sib_form';
1499 return $query_vars;
1500 }
1501
1502 /**
1503 * Parse request
1504 *
1505 * @param mixed $wp - object.
1506 */
1507 function sib_parse_request( &$wp ) {
1508 if ( array_key_exists( 'sib_form', $wp->query_vars ) ) {
1509 include 'inc/sib-form-preview.php';
1510 exit();
1511 }
1512 }
1513
1514 /**
1515 * Load Text domain.
1516 */
1517 static function LoadTextDomain() {
1518 // Load lang file.
1519 $i18n_file_name = 'mailin';
1520 $locale = apply_filters( 'plugin_locale', get_locale(), $i18n_file_name );
1521 // $locale = 'fr_FR';
1522 $filename = plugin_dir_path( __FILE__ ) . '/lang/' . $i18n_file_name . '-' . $locale . '.mo';
1523 load_textdomain( 'mailin', $filename );
1524 }
1525
1526 /**
1527 * Notice the language is difference than site's language
1528 */
1529 static function language_admin_notice() {
1530 if ( ! get_option( SIB_Manager::LANGUAGE_OPTION_NAME ) ) {
1531 $lang_prefix = substr( get_bloginfo( 'language' ), 0, 2 );
1532 $lang = self::getLanguageName( $lang_prefix );
1533 $class = 'error';
1534 $message = sprintf( 'Please note that your Brevo account is in %s, but Brevo WordPress plugin is only available in English / French for now. Sorry for inconvenience.', $lang );
1535 if ( 'en' !== $lang_prefix && 'fr' !== $lang_prefix ) {
1536 // phpcs:ignore
1537 echo ( "<div class=\"$class\" style='margin-left: 2px;margin-bottom: 4px;'> <p>$message<a class='' href='?dismiss_admin_lang_notice=1'> No problem...</a></p></div>" );
1538 }
1539 }
1540 }
1541
1542 /**
1543 * Notice wp_mail is not possible
1544 */
1545 static function wpMailNotices() {
1546 if ( self::$wp_mail_conflict ) {
1547 echo ( '<div class="error"><p>' . __( 'You cannot use Brevo SMTP now because wp_mail has been declared by another process or plugin. ', 'mailin' ) . '</p></div>' );
1548 }
1549 }
1550
1551 /**
1552 * Names of languages.
1553 *
1554 * @param string $prefix - language.
1555 * @return mixed
1556 */
1557 public static function getLanguageName( $prefix = 'en' ) {
1558 $lang = array();
1559 $lang['de'] = 'Deutsch';
1560 $lang['en'] = 'English';
1561 $lang['zh'] = '中文';
1562 $lang['ru'] = 'Русский';
1563 $lang['fi'] = 'suomi';
1564 $lang['fr'] = 'Français';
1565 $lang['nl'] = 'Nederlands';
1566 $lang['sv'] = 'Svenska';
1567 $lang['it'] = 'Italiano';
1568 $lang['ro'] = 'Română';
1569 $lang['hu'] = 'Magyar';
1570 $lang['ja'] = '日本語';
1571 $lang['es'] = 'Español';
1572 $lang['vi'] = 'Tiếng Việt';
1573 $lang['ar'] = 'العربية';
1574 $lang['pt'] = 'Português';
1575 $lang['pb'] = 'Português do Brasil';
1576 $lang['pl'] = 'Polski';
1577 $lang['gl'] = 'galego';
1578 $lang['tr'] = 'Turkish';
1579 $lang['et'] = 'Eesti';
1580 $lang['hr'] = 'Hrvatski';
1581 $lang['eu'] = 'Euskera';
1582 $lang['el'] = 'Ελληνικά';
1583 $lang['ua'] = 'Українська';
1584 $lang['ko'] = '한국어';
1585
1586 return $lang[ $prefix ];
1587 }
1588
1589 /**
1590 * Create language sidebar for wpml plugin.
1591 */
1592 public function sib_create_language_sidebar() {
1593 $languages = apply_filters( 'wpml_active_languages', array() );
1594 $page = isset( $_GET['page'] ) ? sanitize_text_field( $_GET['page'] ) : '';
1595 $action = isset( $_GET['action'] ) ? sanitize_text_field( $_GET['action'] ) : '';
1596 $frmID = isset( $_GET['id'] ) ? sanitize_text_field( $_GET['id'] ) : '';
1597 $pID = isset( $_GET['pid'] ) ? sanitize_text_field( $_GET['pid'] ) : '';
1598 $parent = true;
1599 if ( '' !== $frmID && '' !== $pID ) {
1600 $lang = SIB_Forms_Lang::get_lang( $frmID, $pID );
1601 $parent = false;
1602 } else {
1603 $lang = ICL_LANGUAGE_CODE;
1604 if ( '' !== $frmID && '' === $pID ) {
1605 $pID = $frmID;
1606
1607 }
1608 }
1609
1610 if ( 'sib_page_form' === $page && 'edit' === $action ) {
1611 ?>
1612 <div class="panel panel-default text-left box-border-box sib-small-content">
1613 <div class="panel-heading"><strong><?php esc_attr_e( 'About Brevo', 'mailin' ); ?></strong></div>
1614 <div class="panel-body">
1615 <p>
1616 <label for='sib_form_language'><?php esc_attr_e( 'Language of this form:', 'mailin' ); ?> </label>
1617 <select id="sib_form_lang" name="sib_form_lang" data-selected="">
1618 <?php
1619 foreach ( $languages as $language ) {
1620 $selected = (isset($language['code']) && ($language['code'] == $lang)) ? 'selected' : '';
1621 if ( isset($language['code']) && $language['code'] == $lang && true === $parent ) {
1622 $option_text = '<option value="" ' . $selected . '>' . $language['native_name'] . '</option>';
1623 } else {
1624 $exist = SIB_Forms_Lang::get_form_ID( $pID, $language['language_code'] );
1625
1626 if ( null === $exist ) {
1627 continue;
1628 } else {
1629 $option_text = ( 'selected' === $selected ) ?
1630 sprintf( '<option value="" selected>%s</option>', esc_html( $language['native_name'] ) ) :
1631 sprintf( '<option value="%s" %s>%s</option>',
1632 esc_url( add_query_arg( array(
1633 'page' => sanitize_text_field( $_REQUEST['page'] ),
1634 'action' => 'edit',
1635 'pid' => absint( $pID ),
1636 'lang' => sanitize_text_field( $language['language_code'] )
1637 ) ) ),
1638 $selected,
1639 esc_html( $language['native_name'] )
1640 );
1641 }
1642 }
1643 echo $option_text ;
1644 }
1645 ?>
1646 </select>
1647 </p>
1648 <div class="sib_form_translate">
1649 <p>
1650 <label><?php esc_attr_e( 'Translate this form', 'mailin' ); ?></label>
1651 </p>
1652 <table aria-describedby="wpml-language-table" class="sib_form_trans_table" style="border: 1px solid #8cceea;">
1653 <tr>
1654 <?php
1655 foreach ( $languages as $language ) {
1656 if ( isset($language['code']) && $language['code'] == $lang ) {
1657 continue;
1658 }
1659 ?>
1660 <th style="text-align: center;"><img
1661 src="<?php echo esc_url( $language['country_flag_url'] ); ?>" alt="Flag of <?php echo esc_attr( $language['translated_name'] ); ?>"></th>
1662 <?php
1663 }
1664 ?>
1665 </tr>
1666 <tr style="background-color: #EFF8FC;">
1667 <?php
1668 foreach ( $languages as $language ) {
1669 if ( isset($language['code']) && $language['code'] == $lang ) {
1670 continue;
1671 }
1672 if ( '' === $pID ) {
1673 $img_src = plugins_url( 'img/add_translation_disabled.png', __FILE__ );
1674 $td = '<img src="' . $img_src . '" style="margin:2px;">';
1675 } else {
1676 $exist = SIB_Forms_Lang::get_form_ID( $pID, $language['language_code'] );
1677
1678 if ( null === $exist ) {
1679 $img_src = plugins_url( 'img/add_translation.png', __FILE__ );
1680
1681 $href = sprintf( '<a class="sib-form-redirect" href="?page=%s&action=%s&pid=%s&lang=%s" style="width: 20px; text-align: center;padding: 2px 1px;">', esc_attr( $_REQUEST['page'] ), 'edit', absint( $pID ), $language['language_code'] );
1682 $td = $href . '<img src="' . $img_src . '" style="margin:2px;"></a>';
1683 } else {
1684 $img_src = plugins_url( 'img/edit_translation.png', __FILE__ );
1685 $href = sprintf( '<a class="sib-form-redirect" href="%s" style="width: 20px; text-align: center;padding: 2px 1px;">', esc_url( add_query_arg( array(
1686 'page' => sanitize_text_field( $_REQUEST['page'] ),
1687 'action' => 'edit',
1688 'id' => absint( $exist ),
1689 'pid' => absint( $pID ),
1690 'lang' => sanitize_text_field( $language['language_code'] )
1691 ) ) ) );
1692 $td = $href . '<img src="' . $img_src . '" style="margin:2px;"></a>';
1693 }
1694 }
1695 ?>
1696 <td style="text-align: center;"><?php echo wp_kses($td, wp_kses_allowed_html('post')); ?></td>
1697 <?php
1698 }
1699 ?>
1700 </tr>
1701 </table>
1702 </div>
1703 <?php if ( isset( $_GET['pid'] ) ) { ?>
1704 <div class="sib-form-duplicate">
1705 <button class="btn btn-default sib-duplicate-btn"><?php esc_attr_e( 'Copy content from origin form', 'mailin' ); ?></button>
1706 <span class="sib-spin"><i
1707 class="fa fa-circle-o-notch fa-spin fa-lg"></i>&nbsp;&nbsp;</span>
1708 <i title="<?php echo esc_attr_e( 'Copy content from origin form', 'mailin' ); ?>"
1709 data-container="body" data-toggle="popover" data-placement="left"
1710 data-content="<?php echo esc_attr_e( 'You can copy contents from origin form. You need to translate the contents by this language.', 'mailin' ); ?>"
1711 data-html="true" class="fa fa-question-circle popover-help-form"></i>
1712 </div>
1713 <?php } ?>
1714 </div>
1715 </div>
1716 <?php
1717 }
1718 }
1719
1720 public function ajax_get_country_prefix() {
1721 check_ajax_referer( 'sib_front_ajax_nonce', 'security' );
1722 $sms_manager = new SIB_SMS_Code();
1723 $country_list = $sms_manager->get_sms_code_list();
1724 $country_list_html = '';
1725 foreach ( $country_list as $item => $value ) {
1726 $flg_url = plugins_url( 'img/flags/', __FILE__ ).strtolower($item).'.png';
1727 $item_html = '<li class="sib-country-prefix" data-country-code="'.$item.'" data-dial-code="'.$value["code"].'"><div class="sib-flag-box"><div class="sib-flag '.$item.'" style="background-image: url('.$flg_url.')"></div><span>'.$value['name'].'</span><span class="sib-dial-code">+'.$value['code'].'</span></div></li>';
1728 $country_list_html .= $item_html;
1729 }
1730 wp_send_json($country_list_html);
1731 }
1732
1733 /**
1734 * @param string $postAttribute
1735 * @param array $sibAttributes
1736 * @return null|string the corresponding sib attribute or null if not found
1737 */
1738 private function getCorrespondingSibAttribute($postAttribute, $sibAttributes)
1739 {
1740 $normalizedPostAttribute = strtoupper(sanitize_text_field($postAttribute));
1741 foreach ($sibAttributes as $sibAttribute) {
1742 if ($normalizedPostAttribute == strtoupper($sibAttribute)) {
1743 return $sibAttribute;
1744 }
1745 }
1746
1747 return null;
1748 }
1749
1750 public function my_upgrade_function() {
1751 $current_plugin_path_name = plugin_basename( __FILE__ );
1752 activate_plugin( $current_plugin_path_name );
1753 }
1754
1755 public function brevo_wp_load()
1756 {
1757 $installationId = get_option( SIB_Manager::INSTALLATION_ID );
1758 $pluginVersion = get_option( SIB_Manager::BREVO_PLUGIN_VERSION );
1759 if(!empty($installationId) && (empty($pluginVersion) || $pluginVersion != SendinblueApiClient::PLUGIN_VERSION))
1760 {
1761 $apiClient = new SendinblueApiClient();
1762 $params["connection"] = 27;
1763 $params["plugin_version"] = SendinblueApiClient::PLUGIN_VERSION;
1764 $params["shop_version"] = get_bloginfo('version');
1765 $apiClient->updateInstallationInfo($installationId, $params);;
1766 if ( $apiClient->getLastResponseCode() === SendinblueApiClient::RESPONSE_CODE_NO_CONTENT )
1767 {
1768 update_option(SIB_Manager::BREVO_PLUGIN_VERSION, SendinblueApiClient::PLUGIN_VERSION);
1769 }
1770 }
1771 }
1772
1773 public static function wordpress_allowed_attributes()
1774 {
1775 global $allowedposttags, $allowedtags, $allowedentitynames;
1776 $attributes = [$allowedposttags, $allowedtags, $allowedentitynames, self::SIB_ATTRIBUTE];
1777 $attributes = call_user_func_array("array_merge", $attributes);
1778
1779 add_filter( 'safe_style_css', function($css_attr) {
1780 array_push($css_attr, 'display');
1781 return $css_attr;
1782 });
1783
1784 return $attributes;
1785 }
1786
1787 static function create_brevo_rest_endpoints()
1788 {
1789 $authenticated_routes = array(
1790 array(
1791 self::ROUTE_PATH => '/mailin_disconnect',
1792 self::ROUTE_METHODS => 'DELETE',
1793 self::ROUTE_CALLBACK => function ($request) {
1794 return self::mailin_disconnect($request);
1795 }
1796 )
1797 );
1798
1799 $routes = array(
1800 array(
1801 self::ROUTE_PATH => '/testconnection',
1802 self::ROUTE_METHODS => 'GET',
1803 self::ROUTE_CALLBACK => function ($request) {
1804 return self::mailin_testconnection($request);
1805 },
1806 self::PERMISSION_CALLBACK => '__return_true',
1807 )
1808 );
1809
1810 foreach ($routes as $route) {
1811 self::register_route($route);
1812 }
1813
1814 foreach ($authenticated_routes as $route) {
1815 self::register_route_authenticated($route);
1816 }
1817 }
1818
1819 private static function register_route(array $route)
1820 {
1821 $arguments = array(
1822 self::ROUTE_METHODS => $route[self::ROUTE_METHODS],
1823 self::ROUTE_CALLBACK => $route[self::ROUTE_CALLBACK],
1824 self::PERMISSION_CALLBACK => $route[self::PERMISSION_CALLBACK]
1825 );
1826
1827 register_rest_route(
1828 self::API_NAMESPACE,
1829 $route[self::ROUTE_PATH],
1830 $arguments
1831 );
1832 }
1833
1834 private static function register_route_authenticated(array $route) {
1835 $path = $route[self::ROUTE_PATH];
1836 $methods = $route[self::ROUTE_METHODS];
1837 $callback = $route[self::ROUTE_CALLBACK];
1838
1839 if(empty($path)) {
1840 return;
1841 }
1842
1843 $arguments = array(
1844 self::ROUTE_METHODS => $methods,
1845 self::ROUTE_CALLBACK => $callback,
1846 self::PERMISSION_CALLBACK => array(self::class, 'validate_auth')
1847 );
1848
1849 register_rest_route(self::API_NAMESPACE, $path, $arguments);
1850 }
1851
1852 public static function validate_auth()
1853 {
1854 nocache_headers();
1855
1856 $user_connection_id = $_GET['id'] ?? '';
1857
1858 if (!empty($user_connection_id)) {
1859 $installationId = get_option( SIB_Manager::INSTALLATION_ID );
1860
1861 if ($user_connection_id != $installationId) {
1862 return new WP_Error(
1863 'rest_forbidden',
1864 __('You are not authorized to complete this request.',"mailin"),
1865 array(
1866 self::HTTP_STATUS => 401
1867 )
1868 );
1869 } else {
1870 return true;
1871 }
1872 } else {
1873 return new WP_Error(
1874 'rest_forbidden',
1875 __('You are not authorized to complete this request.',"mailin"),
1876 array(
1877 self::HTTP_STATUS => 401
1878 )
1879 );
1880 }
1881 }
1882
1883 private static function mailin_disconnect($request) {
1884 $request = $request->get_params();
1885 $user_connection_id = isset($request['id']) ? $request['id'] : '';
1886 if (!empty($user_connection_id)) {
1887 $installationId = get_option( SIB_Manager::INSTALLATION_ID );
1888
1889 if ($user_connection_id === $installationId) {
1890 self::delete_connection();
1891 } else {
1892 return new WP_REST_Response(
1893 array(
1894 'message' => "user_connection_id not found"
1895 ), 404);
1896 }
1897 }
1898 }
1899
1900 private static function mailin_testconnection($request) {
1901 $request = $request->get_params();
1902 $uc_id = isset($request['id']) ? $request['id'] : '';
1903 if (empty($uc_id)) {
1904 return new WP_REST_Response(array('success' => false), 404);
1905 }
1906 $installationId = get_option(SIB_Manager::INSTALLATION_ID);
1907 if ($installationId !== $uc_id) {
1908 return new WP_REST_Response(array('success' => false), 403);
1909 }
1910 $haveApiKey = get_option(SIB_Manager::API_KEY_V3_OPTION_NAME, false);
1911 if ( false === $haveApiKey ) {
1912 return new WP_REST_Response(array('success' => false), 404);
1913 }
1914
1915 return new WP_REST_Response(array('success' => true), 200);
1916 }
1917
1918 private static function delete_connection()
1919 {
1920 $setting = array();
1921 update_option( self::MAIN_OPTION_NAME, $setting );
1922 delete_option(self::API_KEY_V3_OPTION_NAME);
1923
1924 $home_settings = array(
1925 'activate_email' => 'no',
1926 'activate_ma' => 'default',
1927 );
1928 update_option( self::HOME_OPTION_NAME, $home_settings );
1929
1930 // remove sync users option.
1931 delete_option( 'sib_sync_users' );
1932 // remove all transients.
1933 SIB_API_Manager::remove_transients();
1934
1935 // remove all forms.
1936 SIB_Forms::removeAllForms();
1937 SIB_Forms_Lang::remove_all_trans();
1938 delete_option(SIB_Manager::INSTALLATION_ID);
1939 }
1940 }
1941
1942 add_action( 'sendinblue_init', 'sendinblue_init' );
1943 add_filter( 'widget_text', 'do_shortcode' );
1944 add_action( 'save_post', array( 'SIB_Push_Admin', 'on_save_post' ), 1, 3 );
1945 add_action( 'transition_post_status', array( 'SIB_Push_Admin', 'on_transition_post_status' ), 10, 3 );
1946
1947
1948 /**
1949 * Plugin entry point Process.
1950 */
1951 function sendinblue_init() {
1952 SIB_Manager::LoadTextDomain();
1953 new SIB_Manager();
1954 }
1955
1956 do_action( 'sendinblue_init' );
1957 }
1958