PluginProbe ʕ •ᴥ•ʔ
Brevo – Email, SMS, Web Push, Chat, and more. / 3.1.83
Brevo – Email, SMS, Web Push, Chat, and more. v3.1.83
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 2 years ago form 4 years ago img 2 years ago inc 1 year ago js 2 years ago lang 2 years ago model 2 years ago page 2 years ago widget 4 years ago index.php 11 years ago readme.txt 1 year 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 year ago
sendinblue.php
1703 lines
1 <?php
2 /**
3 * Plugin Name: Newsletter, SMTP, Email marketing and Subscribe forms by Brevo
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.1.83
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( 'SIB_Manager' ) ) {
46 register_deactivation_hook( __FILE__, array( 'SIB_Manager', 'deactivate' ) );
47 register_activation_hook( __FILE__, array( 'SIB_Manager', 'install' ) );
48 register_uninstall_hook( __FILE__, array( 'SIB_Manager', 'uninstall' ) );
49
50 require_once( 'page/page-home.php' );
51 require_once( 'page/page-form.php' );
52 require_once( 'page/page-statistics.php' );
53 require_once( 'page/page-scenarios.php' );
54 require_once( 'widget/widget_form.php' );
55 require_once( 'inc/table-forms.php' );
56 require_once( 'inc/sib-api-manager.php' );
57 require_once( 'inc/sib-sms-code.php' );
58 require_once( 'model/model-forms.php' );
59 require_once( 'model/model-users.php' );
60 require_once( 'model/model-lang.php' );
61 require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
62 require_once( ABSPATH . 'wp-admin/includes/class-wp-upgrader.php' );
63 /**
64 * Class SIB_Manager
65 */
66 class SIB_Manager {
67
68 /** Main setting option name */
69 const MAIN_OPTION_NAME = 'sib_main_option';
70
71 /** Home setting option name */
72 const HOME_OPTION_NAME = 'sib_home_option';
73
74 /** Access token option name */
75 const ACCESS_TOKEN_OPTION_NAME = 'sib_token_store';
76
77 /** Plugin language notice option name */
78 const LANGUAGE_OPTION_NAME = 'sib_language_notice_option';
79
80 /** Form preview option name */
81 const PREVIEW_OPTION_NAME = 'sib_preview_form';
82
83 const API_KEY_V3_OPTION_NAME = 'sib_api_key_v3';
84
85 const RECAPTCHA_API_TEMPLATE = 'https://www.google.com/recaptcha/api/siteverify?%s';
86
87 const TURNSTILE_SITE_VERIFY = 'https://challenges.cloudflare.com/turnstile/v0/siteverify';
88
89 /** Installation id option name */
90 const INSTALLATION_ID = 'sib_installation_id';
91
92 /*Pushowl Url */
93 const PUSHOWL_STAGING_URL = "https://cdn-staging.pushowl.com/latest/sdks/service-worker.js";
94 const PUSHOWL_PRODUCTION_URL = "https://cdn.pushowl.com/latest/sdks/service-worker.js";
95 const URL_CHECK_STAGING = "staging";
96 const SERVICE_WORKER_FILE_URL = "/js/service-worker.js";
97
98 const SIB_ATTRIBUTE = array(
99 'input' => array(
100 'type' => true,
101 'name' => true,
102 'value' => true,
103 'class' => true,
104 'id' => true,
105 'size' => true,
106 'min' => true,
107 'max' => true,
108 'pattern' => true,
109 'title' => true,
110 'placeholder' => true,
111 'required' => true,
112 ),
113 'p' => array(
114 'align' => true,
115 'id' => true,
116 'class' => true,
117 'dir' => true,
118 'lang' => true,
119 'style' => true,
120 'xml:lang' => true,
121 ),
122 'iframe' => array(
123 'name' => true,
124 'id' => true,
125 'class' => true,
126 'src' => true,
127 'width' => true,
128 'height' => true,
129 'style' => true,
130 'loading' => true,
131 'allow' => true,
132 'allowfullscreen' => true,
133 ),
134 'div' => array(
135 'id' => true,
136 'class' => true,
137 'dir' => true,
138 'lang' => true,
139 'style' => true,
140 'xml:lang' => true,
141 'data-require' => true,
142 'data-sitekey' => true,
143 'data-error-callback' => true,
144 'data-theme' => true,
145 ),
146 'a' => array(
147 'href' => true,
148 'id' => true,
149 'class' => true,
150 'rel' => true,
151 'rev' => true,
152 'name' => true,
153 'target' => true,
154 ),
155 'style' => array(),
156 'script' => array(
157 'src' => true,
158 ),
159 'link' => array(
160 'rel' => true,
161 'href' => true,
162 'type' => true,
163 ),
164 'select' => array(
165 'name' => true,
166 'class' => true,
167 'id' => true,
168 'style' => true,
169 'required' => true,
170 ),
171 'option' => array(
172 'value' => true,
173 ),
174 'ul' => array(
175 'class' => true,
176 'style' => true,
177 ),
178 'center' => array(),
179 'download' => array(
180 'valueless' => 'y',
181 )
182 );
183
184 /**
185 * API key
186 *
187 * @var $access_key
188 */
189 public static $access_key;
190
191 /**
192 * Store instance
193 *
194 * @var $instance
195 */
196 public static $instance;
197
198 /**
199 * Plugin directory path value. set in constructor
200 *
201 * @var $plugin_dir
202 */
203 public static $plugin_dir;
204
205 /**
206 * Plugin url. set in constructor
207 *
208 * @var $plugin_url
209 */
210 public static $plugin_url;
211
212 /**
213 * Plugin name. set in constructor
214 *
215 * @var $plugin_name
216 */
217 public static $plugin_name;
218
219 /**
220 * Check if wp_mail is declared
221 *
222 * @var $wp_mail_conflict
223 */
224 static $wp_mail_conflict;
225
226 /**
227 * Class constructor
228 * Sets plugin url and directory and adds hooks to <i>init</i>. <i>admin_menu</i>
229 */
230 function __construct() {
231 // get basic info.
232 self::$plugin_dir = plugin_dir_path( __FILE__ );
233 self::$plugin_url = plugins_url( '', __FILE__ );
234 self::$plugin_name = plugin_basename( __FILE__ );
235
236 self::$wp_mail_conflict = false;
237
238 // api key for sendinblue.
239 $general_settings = get_option( self::MAIN_OPTION_NAME, array() );
240 self::$access_key = isset( $general_settings['access_key'] ) ? $general_settings['access_key'] : '';
241
242 self::$instance = $this;
243 add_action( 'upgrader_process_complete', array( &$this, 'my_upgrade_function' ), 10, 2);
244 add_action( 'admin_init', array( &$this, 'admin_init' ), 9999 );
245 add_action( 'admin_menu', array( &$this, 'admin_menu' ), 9999 );
246
247 add_action( 'wp_print_scripts', array( &$this, 'frontend_register_scripts' ), 9999 );
248 add_action( 'wp_enqueue_scripts', array( &$this, 'wp_head_ac' ), 999 );
249
250 // create custom url for form preview.
251 add_filter( 'query_vars', array( &$this, 'sib_query_vars' ) );
252 add_action( 'parse_request', array( &$this, 'sib_parse_request' ) );
253
254 add_action( 'wp_ajax_sib_validate_process', array( 'SIB_Page_Home', 'ajax_validation_process' ) );
255 add_action( 'wp_ajax_sib_validate_ma', array( 'SIB_Page_Home', 'ajax_validate_ma' ) );
256 add_action( 'wp_ajax_sib_activate_email_change', array( 'SIB_Page_Home', 'ajax_activate_email_change' ) );
257 add_action( 'wp_ajax_sib_sender_change', array( 'SIB_Page_Home', 'ajax_sender_change' ) );
258 add_action( 'wp_ajax_sib_send_email', array( 'SIB_Page_Home', 'ajax_send_email' ) );
259 add_action( 'wp_ajax_sib_remove_cache', array( 'SIB_Page_Home', 'ajax_remove_cache' ) );
260 add_action( 'wp_ajax_sib_sync_users', array( 'SIB_Page_Home', 'ajax_sync_users' ) );
261
262 add_action( 'wp_ajax_sib_change_template', array( 'SIB_Page_Form', 'ajax_change_template' ) );
263 add_action( 'wp_ajax_sib_get_lists', array( 'SIB_Page_Form', 'ajax_get_lists' ) );
264 add_action( 'wp_ajax_sib_get_templates', array( 'SIB_Page_Form', 'ajax_get_templates' ) );
265 add_action( 'wp_ajax_sib_get_attributes', array( 'SIB_Page_Form', 'ajax_get_attributes' ) );
266 add_action( 'wp_ajax_sib_update_form_html', array( 'SIB_Page_Form', 'ajax_update_html' ) );
267 add_action( 'wp_ajax_sib_copy_origin_form', array( 'SIB_Page_Form', 'ajax_copy_origin_form' ) );
268
269 add_action( 'wp_ajax_sib_get_country_prefix', array( $this, 'ajax_get_country_prefix' ) );
270 add_action( 'wp_ajax_nopriv_sib_get_country_prefix', array( $this, 'ajax_get_country_prefix' ) );
271
272 add_action( 'init', array( &$this, 'init' ) );
273
274 add_action( 'wp_login', array( &$this, 'sib_wp_login_identify' ), 10, 2 );
275
276 // change sib tables name on prior(2.6.9) versions.
277 SIB_Model_Users::add_prefix();
278 SIB_Forms::add_prefix();
279 SIB_Forms::modify_datatype();
280
281 if ( self::is_api_key_set() ) {
282 add_shortcode( 'sibwp_form', array( &$this, 'sibwp_form_shortcode' ) );
283 // register widget.
284 add_action( 'widgets_init', array( &$this, 'sib_create_widget' ) );
285
286 // create forms tables and create default form.
287 SIB_Forms::createTable();
288 // create users table.
289 SIB_Model_Users::createTable();
290 // add columns for old versions
291 SIB_Forms::alterTable();
292 SIB_Model_Users::add_user_added_date_column();
293 }
294
295 $use_api_version = get_option( 'sib_use_apiv2', '0' );
296 if ( '0' === $use_api_version ) {
297 self::uninstall();
298 update_option( 'sib_use_apiv2', '1' );
299 }
300
301 // Wpml plugin part.
302 if ( ! function_exists( 'is_plugin_active_for_network' ) ) :
303 require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
304 endif;
305 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' ) ) {
306 SIB_Forms_Lang::createTable();
307 add_action( 'sib_language_sidebar', array( $this, 'sib_create_language_sidebar' ) );
308 }
309
310 /**
311 * Hook wp_mail to send transactional emails
312 */
313
314 // check if wp_mail function is already declared by others.
315 if ( function_exists( 'wp_mail' ) ) {
316 self::$wp_mail_conflict = true;
317 }
318 $home_settings = get_option( SIB_Manager::HOME_OPTION_NAME, array() );
319
320 if( 'yes' === $home_settings['activate_email'] )
321 {
322 if ( false === self::$wp_mail_conflict ) {
323 /**
324 * Declare wp_mail function for Sendinblue SMTP module
325 *
326 * @param string $to - receiption email.
327 * @param string $subject - subject of email.
328 * @param string $message - message content.
329 * @param string $headers - header of email.
330 * @param array $attachments - attachments.
331 * @return bool
332 */
333 function wp_mail( $to, $subject, $message, $headers = '', $attachments = array() ) {
334 $message = str_replace( 'NF_SIB', '', $message );
335 $message = str_replace( 'WC_SIB', '', $message );
336 try {
337 $sent = SIB_Manager::sib_email( $to, $subject, $message, $headers, $attachments );
338 if ( is_wp_error( $sent ) || ! isset( $sent['code'] ) || 'success' !== $sent['code'] ) {
339 try{
340 return true;
341 }catch( Exception $e ){
342 return false;
343 }
344 }
345 return true;
346 } catch ( Exception $e ) {
347 return false;
348 }
349 }
350 } else {
351 add_action( 'admin_notices', array( &$this, 'wpMailNotices' ) );
352 return;
353 }
354 }
355 }
356
357 /**
358 * Add identify tag for login users
359 *
360 * @param string $user_login - user login name.
361 * @param array $user - user.
362 */
363 function sib_wp_login_identify( $user_login, $user ) {
364
365 $userEmail = $user->user_email;
366 $data = array(
367 'email_id' => $userEmail,
368 'name' => $user_login,
369 );
370 SIB_API_Manager::identify_user( $data );
371 }
372
373 /**
374 * Initialize method. called on <i>init</i> action
375 */
376 function init() {
377 // Sign up process.
378 if ( isset( $_POST['sib_form_action'] ) && ( 'subscribe_form_submit' == sanitize_text_field($_POST['sib_form_action']) ) ) {
379 $this->signup_process();
380 }
381 // Subscribe.
382 if ( isset( $_GET['sib_action'] ) && ( 'subscribe' == sanitize_text_field($_GET['sib_action']) ) ) {
383 $code = isset( $_GET['code'] ) ? sanitize_text_field( $_GET['code'] ) : '';
384 $contact_info = SIB_Model_Users::get_data_by_code( $code );
385 $user_added_date = $contact_info['user_added_date'];
386 $current_date = gmdate( 'Y-m-d H:i:s' );
387 $date_diff = strtotime( $current_date ) - strtotime( $user_added_date );
388 if ( $date_diff > 5 ) {
389 SIB_API_Manager::subscribe( $contact_info );
390 } else {
391 $type = 'Bot Event';
392 SIB_API_Manager::template_subscribe( $type );
393 }
394 exit;
395 }
396 // Dismiss language notice.
397 if ( isset( $_GET['dismiss_admin_lang_notice'] ) && '1' == sanitize_text_field($_GET['dismiss_admin_lang_notice']) ) {
398 update_option( SIB_Manager::LANGUAGE_OPTION_NAME, true );
399 wp_safe_redirect( $_SERVER['HTTP_REFERER'] );
400 exit();
401 }
402
403 add_action( 'wp_head', array( &$this, 'install_ma_script' ) );
404 }
405
406 /**
407 * Hook admin_init
408 */
409 function admin_init() {
410 add_action( 'admin_action_sib_setting_subscription', array( 'SIB_Page_Form', 'save_setting_subscription' ) );
411 add_action( 'admin_action_nopriv_sib_setting_subscription', array( 'SIB_Page_Form', 'save_setting_subscription' ) );
412 SIB_Manager::LoadTextDomain();
413 $this->register_scripts();
414 $this->register_styles();
415 }
416
417 /**
418 * Hook admin_menu
419 */
420 function admin_menu() {
421 SIB_Manager::LoadTextDomain();
422 new SIB_Page_Home();
423 new SIB_Page_Form();
424 new SIB_Page_Statistics();
425 $home_settings = get_option( SIB_Manager::HOME_OPTION_NAME );
426 if ( isset( $home_settings['activate_ma'] ) && 'yes' == $home_settings['activate_ma'] ) {
427 new SIB_Page_Scenarios();
428 }
429
430 }
431
432 /**
433 * Register script for admin page
434 */
435 function register_scripts() {
436 wp_register_script( 'sib-bootstrap-js', self::$plugin_url . '/js/bootstrap/js/bootstrap.bundle.min.js', array( 'jquery' ), false );
437 wp_register_script( 'sib-admin-js', self::$plugin_url . '/js/admin.js', array( 'jquery' ), filemtime( self::$plugin_dir . '/js/admin.js' ) );
438 wp_register_script( 'sib-chosen-js', self::$plugin_url . '/js/chosen.jquery.min.js', array( 'jquery' ), false );
439 wp_enqueue_script('jquery-ui-datepicker');
440 wp_enqueue_script('jquery-ui-spinner');
441 }
442
443 /**
444 * Register stylesheet for admin page
445 */
446 function register_styles() {
447 wp_register_style( 'sib-bootstrap-css', self::$plugin_url . '/js/bootstrap/css/bootstrap.css', array(), false, 'all' );
448 wp_register_style( 'sib-fontawesome-css', self::$plugin_url . '/css/fontawesome/css/font-awesome.css', array(), false, 'all' );
449 wp_register_style( 'sib-chosen-css', self::$plugin_url . '/css/chosen.min.css' );
450 wp_register_style( 'sib-admin-css', self::$plugin_url . '/css/admin.css', array(), filemtime( self::$plugin_dir . '/css/admin.css' ), 'all' );
451 }
452
453 /**
454 * Registers scripts for frontend
455 */
456 function frontend_register_scripts() {
457
458 }
459
460 /**
461 * Enqueue script on front page
462 */
463 function wp_head_ac() {
464 wp_enqueue_script( 'sib-front-js', self::$plugin_url . '/js/mailin-front.js', array( 'jquery' ), filemtime( self::$plugin_dir . '/js/mailin-front.js' ), false );
465 wp_enqueue_style( 'sib-front-css', self::$plugin_url.'/css/mailin-front.css', array(), array(), 'all');
466 wp_localize_script(
467 'sib-front-js', 'sibErrMsg', array(
468 'invalidMail' => __( 'Please fill out valid email address', 'mailin' ),
469 'requiredField' => __( 'Please fill out required fields', 'mailin' ),
470 'invalidDateFormat' => __( 'Please fill out valid date format', 'mailin' ),
471 'invalidSMSFormat' => __( 'Please fill out valid phone number', 'mailin' ),
472 )
473 );
474 wp_localize_script(
475 'sib-front-js', 'ajax_sib_front_object',
476 array(
477 'ajax_url' => admin_url( 'admin-ajax.php' ),
478 'ajax_nonce' => wp_create_nonce( 'sib_front_ajax_nonce' ),
479 'flag_url' => plugins_url('img/flags/', __FILE__ ),
480 )
481 );
482 }
483
484 /**
485 * Install method is called once install this plugin.
486 * create tables, default option ...
487 */
488 static function install() {
489 $general_settings = get_option( self::MAIN_OPTION_NAME, array() );
490 $access_key = isset( $general_settings['access_key'] ) ? $general_settings['access_key'] : '';
491 if ( '' === $access_key ) {
492 // Default option when activate.
493 $home_settings = array(
494 'activate_email' => 'no',
495 'activate_ma' => 'no',
496 );
497 update_option( self::HOME_OPTION_NAME, $home_settings );
498 }
499
500 self::activate_brevo_connection();
501 }
502
503 /**
504 * Uninstall method is called once uninstall this plugin
505 * delete tables, options that used in plugin
506 */
507 static function uninstall() {
508 $setting = array();
509 update_option( SIB_Manager::MAIN_OPTION_NAME, $setting );
510
511 $home_settings = array(
512 'activate_email' => 'no',
513 'activate_ma' => 'no',
514 );
515 update_option( SIB_Manager::HOME_OPTION_NAME, $home_settings );
516
517 // Delete access_token.
518 $token_settings = array();
519 update_option( SIB_Manager::ACCESS_TOKEN_OPTION_NAME, $token_settings );
520
521 //Deactivate the connection on Brevo
522 self::deactivate_brevo_connection();
523
524 //Then delete the api key in our plugin
525 delete_option(SIB_Manager::API_KEY_V3_OPTION_NAME);
526 // Empty tables.
527 SIB_Model_Users::removeTable();
528 SIB_Forms::removeTable();
529 SIB_Forms_Lang::removeTable();
530
531 // Remove all transient.
532 SIB_API_Manager::remove_transients();
533 }
534
535 static function deactivate_brevo_connection()
536 {
537 $installationId = get_option( SIB_Manager::INSTALLATION_ID );
538 if(!empty($installationId))
539 {
540 $apiClient = new SendinblueApiClient();
541 $params["active"] = false;
542 $params["deactivated_at"] = gmdate("Y-m-d\TH:i:s\Z");
543 $apiClient->updateInstallationInfo($installationId, $params);
544 }
545 }
546
547 static function activate_brevo_connection()
548 {
549 $installationId = get_option( SIB_Manager::INSTALLATION_ID );
550 if(!empty($installationId))
551 {
552 $apiClient = new SendinblueApiClient();
553 $params["active"] = true;
554 $params["activated_at"] = gmdate("Y-m-d\TH:i:s\Z");
555 $apiClient->updateInstallationInfo($installationId, $params);
556 }
557 }
558
559 /**
560 * Deactivate method is called once deactivate this plugin
561 */
562 static function deactivate() {
563 update_option( SIB_Manager::LANGUAGE_OPTION_NAME, false );
564 // Remove service worker file.
565 self::uninstall_service_worker_script();
566 // Remove sync users option.
567 delete_option( 'sib_sync_users' );
568 // Remove all transient.
569 SIB_API_Manager::remove_transients();
570
571 //Also deactivate the connection on Brevo
572 self::deactivate_brevo_connection();
573 }
574
575 /**
576 * Check if plugin is logged in.
577 *
578 * @param bool $redirect
579 * @return bool
580 */
581 static function is_done_validation($redirect = true) {
582 if (self::is_api_key_set()) {
583 $apiClient = new SendinblueApiClient();
584 $apiClient->getAccount();
585 if ( SendinblueApiClient::RESPONSE_CODE_OK === $apiClient->getLastResponseCode() ) {
586 //This is only for those users who have an active connection but no installation id could be
587 //saved on their shop
588 $installationId = get_option( SIB_Manager::INSTALLATION_ID );
589 if(empty($installationId))
590 {
591 self::fetch_and_save_installation_id();
592 }
593 return true;
594 } elseif (SendinblueApiClient::RESPONSE_CODE_UNAUTHORIZED === $apiClient->getLastResponseCode()) {
595 delete_option(SIB_Manager::API_KEY_V3_OPTION_NAME);
596 }
597 }
598
599 if ($redirect) {
600 self::redirect_to_sib_plugin_homepage();
601 }
602
603 return false;
604 }
605
606 static function redirect_to_sib_plugin_homepage() {
607 wp_safe_redirect(add_query_arg('page', SIB_Page_Home::PAGE_ID, admin_url('admin.php')));
608 }
609
610 /**
611 * @return bool
612 */
613 static function is_api_key_set() {
614 $api_key = get_option(SIB_Manager::API_KEY_V3_OPTION_NAME);
615 return !empty($api_key);
616 }
617
618 static function fetch_and_save_installation_id()
619 {
620 $apiClient = new SendinblueApiClient();
621
622 $params["partnerName"] = "WORDPRESS";
623 $params["plugin_version"] = SendinblueApiClient::PLUGIN_VERSION;
624 $params["shop_url"] = get_home_url();
625 $params["active"] = true;
626 $response = $apiClient->createInstallationInfo($params);
627 if ( $apiClient->getLastResponseCode() === SendinblueApiClient::RESPONSE_CODE_CREATED )
628 {
629 if(!empty($response["id"]))
630 {
631 update_option(SIB_Manager::INSTALLATION_ID, $response["id"]);
632 }
633 }
634 }
635
636 /**
637 * Install service-worker script in plugin for push notifications
638 * @return void
639 */
640 static function install_service_worker_script($service_worker)
641 {
642 try {
643 $site_url = get_site_url();
644 $service_worker_file = str_contains($site_url, self::URL_CHECK_STAGING)
645 ? self::PUSHOWL_STAGING_URL
646 : self::PUSHOWL_PRODUCTION_URL;
647 $js_content = "importScripts('" . $service_worker_file . "');";
648 $service_worker_script = fopen($service_worker, "wb");
649 fwrite($service_worker_script, $js_content);
650 fclose($service_worker_script);
651 } catch (\Throwable $th) {
652 update_option('sib_service_worker_install_exception', $th->getMessage());
653 }
654 }
655
656 /**
657 * Uninstall service-worker script from plugin
658 * @return void
659 */
660 static function uninstall_service_worker_script()
661 {
662 try {
663 $service_worker_file = __DIR__ . self::SERVICE_WORKER_FILE_URL;
664 if (file_exists($service_worker_file)) {
665 wp_delete_file($service_worker_file);
666 }
667 update_option('sib_service_worker_install_exception', '');
668 } catch (\Throwable $th) {
669 update_option('sib_service_worker_uninstall_exception', $th->getMessage());
670 }
671 }
672
673 /**
674 * Install marketing automation script in header
675 */
676 function install_ma_script() {
677 $home_settings = get_option( SIB_Manager::HOME_OPTION_NAME, array() );
678 if ( isset( $home_settings['activate_ma'] ) && 'yes' == $home_settings['activate_ma'] ) {
679 $general_settings = get_option( SIB_Manager::MAIN_OPTION_NAME, array() );
680 $service_worker = __DIR__ . self::SERVICE_WORKER_FILE_URL;
681 if ( ! file_exists($service_worker)) {
682 self::install_service_worker_script($service_worker);
683 }
684 $ma_email = '';
685 $current_user = wp_get_current_user();
686 if ( $current_user instanceof WP_User ) {
687 $ma_email = $current_user->user_email;
688 }
689 $ma_key = sanitize_text_field($general_settings['ma_key']);
690 $output = '<script type="text/javascript">
691 (function() {
692 window.sib ={equeue:[],client_key:"'. $ma_key .'"};/* OPTIONAL: email for identify request*/
693 window.sib.email_id = "'. sanitize_email($ma_email) .'";
694 window.sendinblue = {}; for (var j = [\'track\', \'identify\', \'trackLink\', \'page\'], i = 0; i < j.length; i++) { (function(k) { window.sendinblue[k] = function() { var arg = Array.prototype.slice.call(arguments); (window.sib[k] || function() { var t = {}; t[k] = arg; window.sib.equeue.push(t);})(arg[0], arg[1], arg[2]);};})(j[i]);}var n = document.createElement("script"),i = document.getElementsByTagName("script")[0]; n.type = "text/javascript", n.id = "sendinblue-js", n.async = !0, n.src = "https://sibautomation.com/sa.js?plugin=wordpress&key=" + window.sib.client_key, i.parentNode.insertBefore(n, i), window.sendinblue.page();})();
695 </script>';
696 echo html_entity_decode($output);
697 } else {
698 self::uninstall_service_worker_script();
699 }
700
701 }
702
703 /**
704 * Register widget
705 */
706 function sib_create_widget() {
707 register_widget( 'SIB_Widget_Subscribe' );
708 }
709
710 /**
711 * Display form on front page
712 *
713 * @param string $frmID - form ID.
714 * @param string $lang - form language.
715 */
716 function generate_form_box( $frmID = '-1', $lang = '' ) {
717 if ( 'oldForm' == $frmID ) {
718 $frmID = get_option( 'sib_old_form_id' );
719 } elseif ( '' != $lang ) {
720 $trans_id = SIB_Forms_Lang::get_form_ID( $frmID, $lang );
721 if ( null != $trans_id ) {
722 $frmID = $trans_id;
723 }
724 }
725
726 $formData = SIB_Forms::getForm( $frmID );
727
728 if ( empty( $formData ) ) {
729 return;
730 }
731 // Add Google recaptcha
732 if( '0' != $formData['gCaptcha'] && $formData['selectCaptchaType'] != 3) {
733 if( '1' == $formData['gCaptcha'] ) { // For old forms.
734 $formData['html'] = preg_replace( '/([\s\S]*?)<div class="g-recaptcha"[\s\S]*?data-size="invisible"><\/div>/', '$1', $formData['html'] );
735 }
736 if ( '3' == $formData['gCaptcha'] ) // The case of using google recaptcha.
737 {
738 ?>
739 <script type="text/javascript">
740 var onloadSibCallback = function () {
741 jQuery('.g-recaptcha').each(function (index, el) {
742 grecaptcha.render(el, {
743 'sitekey': jQuery(el).attr('data-sitekey')
744 });
745 });
746 };
747 </script>
748 <?php
749 } else { // The case of using google invisible recaptcha.
750 $formData['html'] = str_contains( $formData['html'], 'sib-default-btn' ) ? str_replace(
751 'type="submit"',
752 'type="submit" id="invisible"',
753 $formData['html']
754 ) : $formData['html'];
755 ?>
756 <script type="text/javascript">
757 var gCaptchaSibWidget;
758 var onloadSibCallbackInvisible = function () {
759
760 var element = document.getElementsByClassName('sib-default-btn');
761 var countInvisible = 0;
762 var indexArray = [];
763 jQuery('.sib-default-btn').each(function (index, el) {
764 if ((jQuery(el).attr('id') == "invisible")) {
765 indexArray[countInvisible] = index;
766 countInvisible++
767 }
768 });
769
770 jQuery('.invi-recaptcha').each(function (index, el) {
771 grecaptcha.render(element[indexArray[index]], {
772 'sitekey': jQuery(el).attr('data-sitekey'),
773 'callback': sibVerifyCallback,
774 });
775 });
776 };
777 </script>
778 <?php
779 }
780 ?>
781 <script src="https://www.google.com/recaptcha/api.js?onload=<?php
782 echo esc_attr(
783 $formData['gCaptcha'] == '2' ? 'onloadSibCallbackInvisible' : 'onloadSibCallback'
784 ) ?>&render=explicit" async defer></script>
785 <?php
786 } else if ('0' != $formData['gCaptcha'] && $formData['selectCaptchaType'] == 3) { ?>
787
788 <script src="https://challenges.cloudflare.com/turnstile/v0/api.js"></script>
789
790 <?php } ?>
791
792 <form id="sib_signup_form_<?php echo esc_attr( $frmID ); ?>" method="post" class="sib_signup_form">
793 <div class="sib_loader" style="display:none;"><img
794 src="<?php echo esc_url( includes_url() ); ?>images/spinner.gif" alt="loader"></div>
795 <input type="hidden" name="sib_form_action" value="subscribe_form_submit">
796 <input type="hidden" name="sib_form_id" value="<?php echo esc_attr( $frmID ); ?>">
797 <input type="hidden" name="sib_form_alert_notice" value="<?php echo esc_attr($formData['requiredMsg']); ?>">
798 <input type="hidden" name="sib_form_invalid_email_notice" value="<?php echo esc_attr($formData['invalidMsg']); ?>">
799 <input type="hidden" name="sib_security" value="<?php echo esc_attr( wp_create_nonce( 'sib_front_ajax_nonce' ) ); ?>">
800 <div class="sib_signup_box_inside_<?php echo esc_attr( $frmID ); ?>">
801 <div style="/*display:none*/" class="sib_msg_disp">
802 </div>
803 <?php
804 if (($formData['gCaptcha'] == '2') && false === strpos(
805 $formData['html'],
806 'id="sib_captcha_invisible"'
807 )) { ?>
808 <div id="sib_captcha_invisible" class="invi-recaptcha" data-sitekey="<?php
809 echo esc_attr($formData['gCaptcha_site']); ?>"></div>
810 <?php
811 } ?>
812 <?php
813 // phpcs:ignore
814
815 if (false === strpos($formData['html'], 'class="g-recaptcha"')) {
816 $formData['html'] = str_replace(
817 'id="sib_captcha"',
818 'id="sib_captcha" class="g-recaptcha" data-sitekey="' . $formData['gCaptcha_site'] . '"',
819 $formData['html']
820 );
821 }
822
823 echo wp_kses($formData['html'], SIB_Manager::wordpress_allowed_attributes());
824 ?>
825 </div>
826 </form>
827 <style>
828 <?php
829
830 if ( ! $formData['dependTheme'] ) {
831 // Custom css.
832 $formData['css'] = str_replace( '[form]', 'form#sib_signup_form_' . $frmID, $formData['css'] );
833 echo esc_html($formData['css']);
834 }
835 $msgCss = str_replace( '[form]', 'form#sib_signup_form_' . $frmID, SIB_Forms::getDefaultMessageCss() );
836 echo esc_html($msgCss);
837 ?>
838 </style>
839 <?php
840 }
841
842 /**
843 * Shortcode for sign up form
844 *
845 * @param array $atts - shortcode parameter.
846 * @return string
847 */
848 function sibwp_form_shortcode( $atts ) {
849 $pull_atts = shortcode_atts(
850 array(
851 'id' => 'oldForm', // We will return 'oldForm' for shortcode of old form.
852 ), $atts
853 );
854 $frmID = $pull_atts['id'];
855 $lang = defined( 'ICL_LANGUAGE_CODE' ) ? ICL_LANGUAGE_CODE : '';
856
857 ob_start();
858 $this->generate_form_box( $frmID, $lang );
859
860 $output_string = ob_get_contents();
861 ob_end_clean();
862 return $output_string;
863 }
864
865 /**
866 * Sign up process
867 */
868 function signup_process() {
869 //Handling of backslash added by WP because magic quotes are enabled by default
870 array_walk_recursive( $_POST, function(&$value) {
871 $value = stripslashes($value);
872 });
873
874 if ( empty( $_POST['sib_security'] ) || empty(wp_verify_nonce($_POST['sib_security'], 'sib_front_ajax_nonce'))) {
875 wp_send_json(
876 array(
877 'status' => 'sib_security',
878 'msg' => 'Invalid Token Provided.',
879 )
880 );
881 }
882 $formID = isset( $_POST['sib_form_id'] ) ? sanitize_text_field( $_POST['sib_form_id'] ) : 1;
883 if ( 'oldForm' == $formID ) {
884 $formID = get_option( 'sib_old_form_id' );
885 }
886 $formData = SIB_Forms::getForm( $formID );
887
888 if (!SIB_Manager::is_done_validation(false) || 0 == count($formData)) {
889 wp_send_json(
890 array(
891 'status' => 'failure',
892 'msg' => array("errorMsg" => "Something wrong occurred"),
893 )
894 );
895 }
896 $turnstileCaptcha = false;
897 if ( '0' != $formData['gCaptcha'] && 3 != $formData['selectCaptchaType']) {
898 $turnstileCaptcha = true;
899 if ( ! isset( $_POST['g-recaptcha-response'] ) || empty( $_POST['g-recaptcha-response'] ) ) {
900 wp_send_json(
901 array(
902 'status' => 'gcaptchaEmpty',
903 'msg' => 'Please click on the reCAPTCHA box.',
904 )
905 );
906 }
907 $secret = $formData['gCaptcha_secret'];
908
909 $data = array(
910 'secret' => $secret,
911 'response' => sanitize_text_field( $_POST['g-recaptcha-response'] ),
912 );
913
914 $args = [
915 'method' => 'POST',
916 ];
917
918 try {
919 $data = wp_remote_retrieve_body(wp_remote_request(sprintf(self::RECAPTCHA_API_TEMPLATE, http_build_query($data)), $args));
920 $responseData = json_decode($data);
921 if ( ! $responseData->success ) {
922 wp_send_json(
923 array(
924 'status' => 'gcaptchaFail',
925 'msg' => 'Robot verification failed, please try again.',
926 )
927 );
928 }
929 } catch (Exception $exception) {
930 wp_send_json(
931 array(
932 'status' => 'gcaptchaFail',
933 'msg' => $exception->getMessage(),
934 )
935 );
936 }
937 } else if ( '0' != $formData['gCaptcha'] && 3 == $formData['selectCaptchaType'] ) {
938 $turnstileCaptcha = true;
939 if ( ! isset( $_POST['cf-turnstile-response'] ) || empty( $_POST['cf-turnstile-response'] ) ) {
940 wp_send_json(
941 array(
942 'status' => 'gcaptchaEmpty',
943 'msg' => 'Captcha couldnot be verified. Please refresh the page.',
944 )
945 );
946 }
947 $secret = $formData['cCaptcha_secret'];
948
949 $args = [
950 'method' => 'POST',
951 ];
952
953 try {
954
955 $headers = array(
956 'body' => [
957 'secret' => $secret,
958 'response' => sanitize_text_field( $_POST['cf-turnstile-response'] )
959 ]
960 );
961 $verify = wp_remote_post(self::TURNSTILE_SITE_VERIFY, $headers);
962 $verify = wp_remote_retrieve_body($verify);
963 $response = json_decode($verify);
964
965 if($response->success) {
966 $results['success'] = $response->success;
967 } else {
968 $results['success'] = false;
969 }
970
971 if ( ! $response->success ) {
972 wp_send_json(
973 array(
974 'status' => 'gcaptchaFail',
975 'msg' => 'Robot verification failed, please try again.',
976 )
977 );
978 }
979 } catch (Exception $exception) {
980 wp_send_json(
981 array(
982 'status' => 'gcaptchaFail',
983 'msg' => $exception->getMessage(),
984 )
985 );
986 }
987 }
988
989 $listID = $formData['listID'];
990 if (empty($listID)) {
991 $listID = array();
992 }
993 $interestingLists = isset( $_POST['interestingLists']) ? array_map( 'sanitize_text_field', $_POST['interestingLists'] ) : array();
994 $expectedLists = isset( $_POST['listIDs'] ) ? array_map( 'sanitize_text_field', $_POST['listIDs'] ) : array();
995 if ( empty($interestingLists) )
996 {
997 $unlinkedLists = [];
998 }
999 else{
1000 $unwantedLists = array_diff( $interestingLists, $expectedLists );
1001 $unlinkedLists = array_diff( $unwantedLists, $listID);
1002 $listID = array_unique(array_merge( $listID, $expectedLists ));
1003 }
1004
1005 $email = isset( $_POST['email'] ) ? sanitize_email( $_POST['email'] ) : '';
1006 if ( ! is_email( $email ) ) {
1007 return;
1008 }
1009
1010 $isDoubleOptin = $formData['isDopt'];
1011 $isOptin = $formData['isOpt'];
1012 $redirectUrlInEmail = $formData['redirectInEmail'];
1013 $redirectUrlInForm = $formData['redirectInForm'];
1014
1015 $info = array();
1016 $attributes = explode( ',', $formData['attributes'] ); // String to array.
1017 if ( isset( $attributes ) && is_array( $attributes ) ) {
1018 foreach ( $_POST as $postAttribute => $postAttributeValue ) {
1019 $correspondingSibAttribute = $this->getCorrespondingSibAttribute($postAttribute, $attributes);
1020 if (!empty($correspondingSibAttribute)) {
1021 $info[ $correspondingSibAttribute ] = sanitize_text_field( $postAttributeValue );
1022 }
1023 }
1024 }
1025 $templateID = $formData['templateID'];
1026
1027 if ( $isDoubleOptin ) {
1028 /*
1029 * Double optin process
1030 * 1. add record to db
1031 * 2. send confirmation email with activate code
1032 */
1033 $result = "success";
1034 // Send a double optin confirm email.
1035 if ( 'success' == $result ) {
1036 // Add a recode with activate code in db.
1037 $activateCode = $this->create_activate_code( $email, $info, $formID, $listID, $redirectUrlInEmail, $unlinkedLists );
1038 SIB_API_Manager::send_comfirm_email( $email, 'double-optin', $templateID, $info, $activateCode );
1039 }
1040 } elseif ( $isOptin ) {
1041 $result = SIB_API_Manager::create_subscriber( $email, $listID, $info, 'confirm', $unlinkedLists );
1042 if ( 'success' == $result ) {
1043 // Send a confirm email.
1044 SIB_API_Manager::send_comfirm_email( $email, 'confirm', $templateID, $info );
1045 }
1046 } else {
1047 $result = SIB_API_Manager::create_subscriber( $email, $listID, $info, 'simple', $unlinkedLists );
1048 }
1049 $msg = array(
1050 'successMsg' => $formData['successMsg'],
1051 'errorMsg' => $formData['errorMsg'],
1052 'existMsg' => $formData['existMsg'],
1053 'invalidMsg' => $formData['invalidMsg'],
1054 );
1055
1056 wp_send_json(
1057 array(
1058 'status' => $result,
1059 'msg' => $msg,
1060 'redirect' => $redirectUrlInForm,
1061 'turnstileCaptcha' => $turnstileCaptcha,
1062 )
1063 );
1064 }
1065
1066 /**
1067 * Create activate code for Double optin
1068 *
1069 * @param string $email - user email.
1070 * @param array $info - info.
1071 * @param string $formID - form ID.
1072 * @param array $listIDs - lists.
1073 * @param string $redirectUrl - redirect url.
1074 * @return string - activate code.
1075 */
1076 function create_activate_code( $email, $info, $formID, $listIDs, $redirectUrl, $unlinkedLists = null ) {
1077 $data = SIB_Model_Users::get_data_by_email( $email, $formID );
1078 $date = gmdate( 'Y-m-d H:i:s' );
1079 if ( $unlinkedLists != null )
1080 {
1081 $info['unlinkedLists'] = $unlinkedLists;
1082 }
1083 if ( false == $data ) {
1084 $uniqid = uniqid();
1085 $data = array(
1086 'email' => $email,
1087 'code' => $uniqid,
1088 'info' => maybe_serialize( $info ),
1089 'frmid' => $formID,
1090 'listIDs' => maybe_serialize( $listIDs ),
1091 'redirectUrl' => $redirectUrl,
1092 'user_added_date' => $date,
1093 );
1094 SIB_Model_Users::add_record( $data );
1095 } else {
1096 $update_data = array(
1097 'id' => $data['id'],
1098 'email' => $email,
1099 'info' => maybe_serialize( $info ),
1100 );
1101 SIB_Model_Users::update_element( $update_data );
1102 $uniqid = $data['code'];
1103 }
1104 return $uniqid;
1105 }
1106
1107 /**
1108 * Use Sendinblue SMTP to send all emails
1109 *
1110 * @param string $to - reception email.
1111 * @param string $subject - subject of email.
1112 * @param string $message - message of email.
1113 * @param string $headers - header of email.
1114 * @param array $attachments - attachments.
1115 */
1116 static function wp_mail_native( $to, $subject, $message, $headers = '', $attachments = array() ) {
1117 $result = require self::$plugin_dir . '/inc/function.wp_mail.php';
1118 return $result;
1119 }
1120
1121 /**
1122 * To send the transactional email via Sendinblue
1123 * hook wp_mail
1124 *
1125 * @param string $to - reception email.
1126 * @param string $subject - subject of email.
1127 * @param string $message - message of email.
1128 * @param string $headers - header of email.
1129 * @param array $attachments - attachments
1130 * @param array $tags - tag.
1131 * @param string $from_name - sender name.
1132 * @param string $from_email - sender email.
1133 * @return mixed|WP_Error
1134 */
1135 static function sib_email( $to, $subject, $message, $headers = '', $attachments = array(), $tags = array(), $from_name = '', $from_email = '' ) {
1136 $data = [];
1137 // Compact the input, apply the filters, and extract them back out.
1138 extract( apply_filters( 'wp_mail', compact( 'to', 'subject', 'message', 'headers', 'attachments' ) ) );
1139
1140 if ( !empty( $attachments ) && ! is_array( $attachments ) ) {
1141 $attachments = explode( "\n", str_replace( "\r\n", "\n", $attachments ) );
1142 }
1143
1144 // From email and name.
1145 $home_settings = get_option( SIB_Manager::HOME_OPTION_NAME );
1146 if ( isset( $home_settings['sender'] ) ) {
1147 $from_name = $home_settings['from_name'];
1148 $from_email = $home_settings['from_email'];
1149 } else {
1150 $from_email = trim( get_bloginfo( 'admin_email' ) );
1151 $from_name = trim( get_bloginfo( 'name' ) );
1152 }
1153
1154 //Set additional address fields as empty
1155 $bcc = array();
1156 $cc = array();
1157 $reply_to = array();
1158 if ( ! is_array( $to ) ) {
1159 $to = explode( ',', $to );
1160 }
1161
1162 $from_email = apply_filters( 'wp_mail_from', $from_email );
1163 $from_name = apply_filters( 'wp_mail_from_name', $from_name );
1164
1165 if ( !empty( $headers ) ) {
1166 if( is_array( $headers ) ){
1167 foreach ($headers as $key => $val) {
1168 if( stripos($val, "Content-Type: text/html") !== false ) {
1169 unset( $headers[$key] );
1170 }
1171 }
1172 $headers = array_values( $headers );
1173 if( count( $headers ) == 1 && $headers[0] == '' ) {
1174 unset( $headers[0] );
1175 }
1176 }
1177 if( is_string( $headers ) ){
1178 $headers = str_replace("Content-Type: text/html", "", $headers);
1179 }
1180 if( !empty( $headers ) ){
1181 $data['headers'] = $headers;
1182 }
1183 if ( ! is_array( $headers ) ) {
1184 // Explode the headers out, so this function can take both.
1185 // string headers and an array of headers.
1186 $tempheaders = explode( "\n", str_replace( "\r\n", "\n", $headers ) );
1187 } else {
1188 $tempheaders = $headers;
1189 }
1190 $headers = array();
1191 // If it's actually got contents.
1192 if ( ! empty( $tempheaders ) ) {
1193 // Iterate through the raw headers.
1194 foreach ( (array) $tempheaders as $header ) {
1195 if ( strpos( $header, ':' ) === false ) {
1196 if ( false !== stripos( $header, 'boundary=' ) ) {
1197 $parts = preg_split( '/boundary=/i', trim( $header ) );
1198 $boundary = trim( str_replace( array( "'", '"' ), '', $parts[1] ) );
1199 }
1200 continue;
1201 }
1202 // Explode them out.
1203 list($name, $content) = explode( ':', trim( $header ), 2 );
1204
1205 // Cleanup crew.
1206 $name = trim( $name );
1207 $content = trim( $content );
1208
1209 switch ( strtolower( $name ) ) {
1210 case 'content-type':
1211 $headers[ trim( $name ) ] = trim( $content );
1212 break;
1213 case 'x-mailin-tag':
1214 $headers[ trim( $name ) ] = trim( $content );
1215 break;
1216 case 'from':
1217 if ( strpos( $content, '<' ) !== false ) {
1218 // So... making my life hard again?
1219 $from_name = substr( $content, 0, strpos( $content, '<' ) - 1 );
1220 $from_name = str_replace( '"', '', $from_name );
1221 $from_name = trim( $from_name );
1222
1223 $from_email = substr( $content, strpos( $content, '<' ) + 1 );
1224 $from_email = str_replace( '>', '', $from_email );
1225 $from_email = trim( $from_email );
1226 } else {
1227 $from_name = '';
1228 $from_email = trim( $content );
1229 }
1230 break;
1231
1232 case 'cc':
1233 $cc = array_merge( (array) $cc, explode( ',', $content ) );
1234 break;
1235
1236 case 'bcc':
1237 $bcc = array_merge( (array) $bcc, explode( ',', $content ) );
1238 break;
1239
1240 case 'reply-to':
1241 $reply_to = array_merge( (array) $reply_to, explode( ',', $content ) );
1242 break;
1243 default:
1244 break;
1245 }
1246 }
1247 }
1248 }
1249
1250 // Set destination addresses, using appropriate methods for handling addresses.
1251 $address_headers = compact('to', 'cc', 'bcc', 'reply_to');
1252 $processed_address_fields = self::processAddressFields($address_headers);
1253 $data = array_merge($data, $processed_address_fields);
1254 // Attachments.
1255 $attachment_content = array();
1256 if ( ! empty( $attachments ) ) {
1257 foreach ( $attachments as $attachment ) {
1258 if ( !empty( $attachment ) ) {
1259 $content = self::getAttachmentStruct( $attachment );
1260 if ( ! is_wp_error( $content ) ) {
1261 array_push( $attachment_content, $content );
1262 }
1263 }
1264 }
1265 if ( !empty( $attachment_content ) ) {
1266 $data["attachment"] = $attachment_content;
1267 }
1268 }
1269
1270 // Common transformations for the HTML part.
1271 // If it is text/plain, New line break found.
1272 if ( strpos( $message, '</table>' ) === false && strpos( $message, '</div>' ) === false ) {
1273 if ( strpos( $message, "\n" ) !== false ) {
1274 if ( is_array( $message ) ) {
1275 foreach ( $message as &$value ) {
1276 $value['content'] = preg_replace( '#<(https?://[^*]+)>#', '$1', $value['content'] );
1277 $value['content'] = nl2br( $value['content'] );
1278 }
1279 } else {
1280 $message = preg_replace( '#<(https?://[^*]+)>#', '$1', $message );
1281 $message = nl2br( $message );
1282 }
1283 }
1284 }
1285 // Sending...
1286 $data['sender'] = ['email' => $from_email, 'name' => $from_name ];
1287 $data['subject'] = $subject;
1288 $data['htmlContent'] = $message;
1289
1290 try {
1291 $sent = SIB_API_Manager::send_email( $data );
1292 return $sent;
1293 } catch ( Exception $e ) {
1294 return new WP_Error( $e->getMessage() );
1295 }
1296 }
1297
1298 /**
1299 * @param array $address_fields
1300 * @return array
1301 */
1302 private static function processAddressFields($address_fields)
1303 {
1304 $data = [
1305 'to' => [],
1306 'cc' => [],
1307 'bcc' => [],
1308 'replyTo' => [],
1309 ];
1310
1311 $address_fields['reply_to'] = is_array($address_fields['reply_to'])
1312 && count($address_fields['reply_to']) > 1 ? $address_fields['reply_to'][0] : $address_fields['reply_to'];
1313 foreach ($address_fields as $address_header => $addresses) {
1314 if (empty($addresses)) {
1315 continue;
1316 }
1317
1318 foreach ((array) $addresses as $address) {
1319 // Break $recipient into name and address parts if in the format "Foo <bar@baz.com>".
1320 if (preg_match('/(.*)<(.+)>/', $address, $matches)) {
1321 if (count($matches) == 3) {
1322 $address = preg_replace('/\s+/', '', $matches[2]); //strip whitespaces
1323 }
1324 }
1325
1326 switch ($address_header) {
1327 case 'to':
1328 $data['to'][] = ['email' => $address];
1329 break;
1330 case 'cc':
1331 $data['cc'][] = ['email' => $address];
1332 break;
1333 case 'bcc':
1334 $data['bcc'][] = ['email' => $address];
1335 break;
1336 case 'reply_to':
1337 $data['replyTo']['email'] = $address;
1338 break;
1339 }
1340 }
1341 }
1342 return $data;
1343 }
1344
1345 /**
1346 * @param string $path - attachment file path
1347 * @return array|WP_Error
1348 */
1349 static function getAttachmentStruct( $path ) {
1350
1351 $struct = array();
1352
1353 try {
1354
1355 if ( ! @is_file( $path ) ) {
1356 throw new Exception( $path . ' is not a valid file.' );
1357 }
1358
1359 $filename = basename( $path );
1360
1361 if ( ! function_exists( 'get_magic_quotes' ) ) {
1362 /**
1363 * @return bool
1364 */
1365 function get_magic_quotes() {
1366 return false;
1367 }
1368 }
1369 if ( ! function_exists( 'set_magic_quotes' ) ) {
1370 /**
1371 * @param $value
1372 * @return bool
1373 */
1374 function set_magic_quotes( $value ) {
1375 return true;
1376 }
1377 }
1378
1379 $isMagicQuotesSupported = version_compare( PHP_VERSION, '5.3.0', '<' )
1380 && function_exists( 'get_magic_quotes_runtime' )
1381 && function_exists( 'set_magic_quotes_runtime' );
1382
1383 if ( $isMagicQuotesSupported ) {
1384 // Escape linters check.
1385 $getMagicQuotesRuntimeFunc = 'get_magic_quotes_runtime';
1386 $setMagicQuotesRuntimeFunc = 'set_magic_quotes_runtime';
1387
1388 // Save magic quotes value.
1389 $magicQuotes = $getMagicQuotesRuntimeFunc();
1390 $setMagicQuotesRuntimeFunc (0);
1391 }
1392
1393 $file_buffer = file_get_contents( $path );
1394 $file_buffer = base64_encode($file_buffer);
1395
1396 if ( $isMagicQuotesSupported ) {
1397 // Restore magic quotes value.
1398 $setMagicQuotesRuntimeFunc($magicQuotes);
1399 }
1400
1401 $struct["name"] = $filename;
1402 $struct["content"] = $file_buffer;
1403
1404 } catch ( Exception $e ) {
1405 return new WP_Error( 'Error creating the attachment structure: ' . $e->getMessage() );
1406 }
1407
1408 return $struct;
1409 }
1410
1411 /**
1412 * Create custom page for form preview
1413 *
1414 * @param array $query_vars - query.
1415 * @return array
1416 */
1417 function sib_query_vars( $query_vars ) {
1418 $query_vars[] = 'sib_form';
1419 return $query_vars;
1420 }
1421
1422 /**
1423 * Parse request
1424 *
1425 * @param mixed $wp - object.
1426 */
1427 function sib_parse_request( &$wp ) {
1428 if ( array_key_exists( 'sib_form', $wp->query_vars ) ) {
1429 include 'inc/sib-form-preview.php';
1430 exit();
1431 }
1432 }
1433
1434 /**
1435 * Load Text domain.
1436 */
1437 static function LoadTextDomain() {
1438 // Load lang file.
1439 $i18n_file_name = 'mailin';
1440 $locale = apply_filters( 'plugin_locale', get_locale(), $i18n_file_name );
1441 // $locale = 'fr_FR';
1442 $filename = plugin_dir_path( __FILE__ ) . '/lang/' . $i18n_file_name . '-' . $locale . '.mo';
1443 load_textdomain( 'mailin', $filename );
1444 }
1445
1446 /**
1447 * Notice the language is difference than site's language
1448 */
1449 static function language_admin_notice() {
1450 if ( ! get_option( SIB_Manager::LANGUAGE_OPTION_NAME ) ) {
1451 $lang_prefix = substr( get_bloginfo( 'language' ), 0, 2 );
1452 $lang = self::getLanguageName( $lang_prefix );
1453 $class = 'error';
1454 $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 );
1455 if ( 'en' !== $lang_prefix && 'fr' !== $lang_prefix ) {
1456 // phpcs:ignore
1457 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>" );
1458 }
1459 }
1460 }
1461
1462 /**
1463 * Notice wp_mail is not possible
1464 */
1465 static function wpMailNotices() {
1466 if ( self::$wp_mail_conflict ) {
1467 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>' );
1468 }
1469 }
1470
1471 /**
1472 * Names of languages.
1473 *
1474 * @param string $prefix - language.
1475 * @return mixed
1476 */
1477 public static function getLanguageName( $prefix = 'en' ) {
1478 $lang = array();
1479 $lang['de'] = 'Deutsch';
1480 $lang['en'] = 'English';
1481 $lang['zh'] = '中文';
1482 $lang['ru'] = 'Русский';
1483 $lang['fi'] = 'suomi';
1484 $lang['fr'] = 'Français';
1485 $lang['nl'] = 'Nederlands';
1486 $lang['sv'] = 'Svenska';
1487 $lang['it'] = 'Italiano';
1488 $lang['ro'] = 'Română';
1489 $lang['hu'] = 'Magyar';
1490 $lang['ja'] = '日本語';
1491 $lang['es'] = 'Español';
1492 $lang['vi'] = 'Tiếng Việt';
1493 $lang['ar'] = 'العربية';
1494 $lang['pt'] = 'Português';
1495 $lang['pb'] = 'Português do Brasil';
1496 $lang['pl'] = 'Polski';
1497 $lang['gl'] = 'galego';
1498 $lang['tr'] = 'Turkish';
1499 $lang['et'] = 'Eesti';
1500 $lang['hr'] = 'Hrvatski';
1501 $lang['eu'] = 'Euskera';
1502 $lang['el'] = 'Ελληνικά';
1503 $lang['ua'] = 'Українська';
1504 $lang['ko'] = '한국어';
1505
1506 return $lang[ $prefix ];
1507 }
1508
1509 /**
1510 * Create language sidebar for wpml plugin.
1511 */
1512 public function sib_create_language_sidebar() {
1513 $languages = apply_filters( 'wpml_active_languages', array() );
1514 $page = isset( $_GET['page'] ) ? sanitize_text_field( $_GET['page'] ) : '';
1515 $action = isset( $_GET['action'] ) ? sanitize_text_field( $_GET['action'] ) : '';
1516 $frmID = isset( $_GET['id'] ) ? sanitize_text_field( $_GET['id'] ) : '';
1517 $pID = isset( $_GET['pid'] ) ? sanitize_text_field( $_GET['pid'] ) : '';
1518 $parent = true;
1519 if ( '' !== $frmID && '' !== $pID ) {
1520 $lang = SIB_Forms_Lang::get_lang( $frmID, $pID );
1521 $parent = false;
1522 } else {
1523 $lang = ICL_LANGUAGE_CODE;
1524 if ( '' !== $frmID && '' === $pID ) {
1525 $pID = $frmID;
1526
1527 }
1528 }
1529
1530 if ( 'sib_page_form' === $page && 'edit' === $action ) {
1531 ?>
1532 <div class="panel panel-default text-left box-border-box sib-small-content">
1533 <div class="panel-heading"><strong><?php esc_attr_e( 'About Brevo', 'mailin' ); ?></strong></div>
1534 <div class="panel-body">
1535 <p>
1536 <label for='sib_form_language'><?php esc_attr_e( 'Language of this form:', 'mailin' ); ?> </label>
1537 <select id="sib_form_lang" name="sib_form_lang" data-selected="">
1538 <?php
1539 foreach ( $languages as $language ) {
1540 $selected = (isset($language['code']) && ($language['code'] == $lang)) ? 'selected' : '';
1541 if ( isset($language['code']) && $language['code'] == $lang && true === $parent ) {
1542 $option_text = '<option value="" ' . $selected . '>' . $language['native_name'] . '</option>';
1543 } else {
1544 $exist = SIB_Forms_Lang::get_form_ID( $pID, $language['language_code'] );
1545
1546 if ( null === $exist ) {
1547 continue;
1548 } else {
1549 $option_text = ( 'selected' === $selected ) ?
1550 sprintf( '<option value="" selected>%s</option>', esc_html( $language['native_name'] ) ) :
1551 sprintf( '<option value="%s" %s>%s</option>',
1552 esc_url( add_query_arg( array(
1553 'page' => sanitize_text_field( $_REQUEST['page'] ),
1554 'action' => 'edit',
1555 'pid' => absint( $pID ),
1556 'lang' => sanitize_text_field( $language['language_code'] )
1557 ) ) ),
1558 $selected,
1559 esc_html( $language['native_name'] )
1560 );
1561 }
1562 }
1563 echo $option_text ;
1564 }
1565 ?>
1566 </select>
1567 </p>
1568 <div class="sib_form_translate">
1569 <p>
1570 <label><?php esc_attr_e( 'Translate this form', 'mailin' ); ?></label>
1571 </p>
1572 <table aria-describedby="wpml-language-table" class="sib_form_trans_table" style="border: 1px solid #8cceea;">
1573 <tr>
1574 <?php
1575 foreach ( $languages as $language ) {
1576 if ( isset($language['code']) && $language['code'] == $lang ) {
1577 continue;
1578 }
1579 ?>
1580 <th style="text-align: center;"><img
1581 src="<?php echo esc_url( $language['country_flag_url'] ); ?>" alt="Flag of <?php echo esc_attr( $language['translated_name'] ); ?>"></th>
1582 <?php
1583 }
1584 ?>
1585 </tr>
1586 <tr style="background-color: #EFF8FC;">
1587 <?php
1588 foreach ( $languages as $language ) {
1589 if ( isset($language['code']) && $language['code'] == $lang ) {
1590 continue;
1591 }
1592 if ( '' === $pID ) {
1593 $img_src = plugins_url( 'img/add_translation_disabled.png', __FILE__ );
1594 $td = '<img src="' . $img_src . '" style="margin:2px;">';
1595 } else {
1596 $exist = SIB_Forms_Lang::get_form_ID( $pID, $language['language_code'] );
1597
1598 if ( null === $exist ) {
1599 $img_src = plugins_url( 'img/add_translation.png', __FILE__ );
1600
1601 $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'] );
1602 $td = $href . '<img src="' . $img_src . '" style="margin:2px;"></a>';
1603 } else {
1604 $img_src = plugins_url( 'img/edit_translation.png', __FILE__ );
1605 $href = sprintf( '<a class="sib-form-redirect" href="%s" style="width: 20px; text-align: center;padding: 2px 1px;">', esc_url( add_query_arg( array(
1606 'page' => sanitize_text_field( $_REQUEST['page'] ),
1607 'action' => 'edit',
1608 'id' => absint( $exist ),
1609 'pid' => absint( $pID ),
1610 'lang' => sanitize_text_field( $language['language_code'] )
1611 ) ) ) );
1612 $td = $href . '<img src="' . $img_src . '" style="margin:2px;"></a>';
1613 }
1614 }
1615 ?>
1616 <td style="text-align: center;"><?php echo wp_kses($td, wp_kses_allowed_html('post')); ?></td>
1617 <?php
1618 }
1619 ?>
1620 </tr>
1621 </table>
1622 </div>
1623 <?php if ( isset( $_GET['pid'] ) ) { ?>
1624 <div class="sib-form-duplicate">
1625 <button class="btn btn-default sib-duplicate-btn"><?php esc_attr_e( 'Copy content from origin form', 'mailin' ); ?></button>
1626 <span class="sib-spin"><i
1627 class="fa fa-circle-o-notch fa-spin fa-lg"></i>&nbsp;&nbsp;</span>
1628 <i title="<?php echo esc_attr_e( 'Copy content from origin form', 'mailin' ); ?>"
1629 data-container="body" data-toggle="popover" data-placement="left"
1630 data-content="<?php echo esc_attr_e( 'You can copy contents from origin form. You need to translate the contents by this language.', 'mailin' ); ?>"
1631 data-html="true" class="fa fa-question-circle popover-help-form"></i>
1632 </div>
1633 <?php } ?>
1634 </div>
1635 </div>
1636 <?php
1637 }
1638 }
1639
1640 public function ajax_get_country_prefix() {
1641 check_ajax_referer( 'sib_front_ajax_nonce', 'security' );
1642 $sms_manager = new SIB_SMS_Code();
1643 $country_list = $sms_manager->get_sms_code_list();
1644 $country_list_html = '';
1645 foreach ( $country_list as $item => $value ) {
1646 $flg_url = plugins_url( 'img/flags/', __FILE__ ).strtolower($item).'.png';
1647 $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>';
1648 $country_list_html .= $item_html;
1649 }
1650 wp_send_json($country_list_html);
1651 }
1652
1653 /**
1654 * @param string $postAttribute
1655 * @param array $sibAttributes
1656 * @return null|string the corresponding sib attribute or null if not found
1657 */
1658 private function getCorrespondingSibAttribute($postAttribute, $sibAttributes)
1659 {
1660 $normalizedPostAttribute = strtoupper(sanitize_text_field($postAttribute));
1661 foreach ($sibAttributes as $sibAttribute) {
1662 if ($normalizedPostAttribute == strtoupper($sibAttribute)) {
1663 return $sibAttribute;
1664 }
1665 }
1666
1667 return null;
1668 }
1669
1670 public function my_upgrade_function() {
1671 $current_plugin_path_name = plugin_basename( __FILE__ );
1672 activate_plugin( $current_plugin_path_name );
1673 }
1674
1675 public static function wordpress_allowed_attributes()
1676 {
1677 global $allowedposttags, $allowedtags, $allowedentitynames;
1678 $attributes = [$allowedposttags, $allowedtags, $allowedentitynames, self::SIB_ATTRIBUTE];
1679 $attributes = call_user_func_array("array_merge", $attributes);
1680
1681 add_filter( 'safe_style_css', function($css_attr) {
1682 array_push($css_attr, 'display');
1683 return $css_attr;
1684 });
1685
1686 return $attributes;
1687 }
1688 }
1689
1690 add_action( 'sendinblue_init', 'sendinblue_init' );
1691 add_filter( 'widget_text', 'do_shortcode' );
1692
1693 /**
1694 * Plugin entry point Process.
1695 */
1696 function sendinblue_init() {
1697 SIB_Manager::LoadTextDomain();
1698 new SIB_Manager();
1699 }
1700
1701 do_action( 'sendinblue_init' );
1702 }
1703