PluginProbe
SMTP for SendGrid – YaySMTP / trunk
SMTP for SendGrid – YaySMTP vtrunk
trunk 1.3 1.3.1 1.4 1.5 1.5.1
smtp-sendgrid / includes / Functions.php

Functions.php in SMTP for SendGrid – YaySMTP trunk, at includes/Functions.php

390 lines 14.6 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 namespace YaySMTPSendgrid;
3
4 use YaySMTPSendgrid\Helper\LogErrors;
5 use YaySMTPSendgrid\Helper\Utils;
6
7 defined( 'ABSPATH' ) || exit;
8
9 class Functions {
10 protected static $instance = null;
11
12 public static function getInstance() {
13 if ( null == self::$instance ) {
14 self::$instance = new self();
15 self::$instance->doHooks();
16 }
17
18 return self::$instance;
19 }
20
21 private function doHooks() {
22 if ( ! current_user_can( 'manage_options' ) ) {
23 return;
24 }
25
26 add_action( 'wp_ajax_' . YAY_SMTP_SENDGRID_PREFIX . '_save_settings', array( $this, 'saveSettings' ) );
27 add_action( 'wp_ajax_' . YAY_SMTP_SENDGRID_PREFIX . '_send_mail', array( $this, 'sendTestMail' ) );
28 add_action( 'wp_ajax_' . YAY_SMTP_SENDGRID_PREFIX . '_email_logs', array( $this, 'getListEmailLogs' ) );
29 add_action( 'wp_ajax_' . YAY_SMTP_SENDGRID_PREFIX . '_set_email_logs_setting', array( $this, 'setYaySmtpEmailLogSetting' ) );
30 add_action( 'wp_ajax_' . YAY_SMTP_SENDGRID_PREFIX . '_delete_email_logs', array( $this, 'deleteEmailLogs' ) );
31 add_action( 'wp_ajax_' . YAY_SMTP_SENDGRID_PREFIX . '_delete_all_email_logs', array( $this, 'deleteAllEmailLogs' ) );
32 add_action( 'wp_ajax_' . YAY_SMTP_SENDGRID_PREFIX . '_detail_email_logs', array( $this, 'getEmailLog' ) );
33 }
34
35 private function __construct() {}
36
37 public function saveSettings() {
38 try {
39 Utils::checkNonce();
40 if ( isset( $_POST['settings'] ) ) {
41 $settings = Utils::saniValArray( $_POST['settings'] );
42 $yaysmtpSettingsDB = get_option( YAY_SMTP_SENDGRID_PREFIX . '_settings' );
43
44 $yaysmtpSettings = array();
45 if ( ! empty( $yaysmtpSettingsDB ) && is_array( $yaysmtpSettingsDB ) ) {
46 $yaysmtpSettings = $yaysmtpSettingsDB;
47
48 // Update "succ_sent_mail_last" option to SHOW/HIDE Debug Box on main page.
49 if ( isset( $yaysmtpSettings['currentMailer'] ) ) {
50 $currentMailerDB = $yaysmtpSettings['currentMailer'];
51 if ( ! empty( $currentMailerDB ) && $currentMailerDB != $settings['mailerProvider'] ) {
52 $yaysmtpSettings['succ_sent_mail_last'] = true;
53 }
54 }
55 }
56
57 $yaysmtpSettings['fromEmail'] = $settings['fromEmail'];
58 $yaysmtpSettings['fromName'] = $settings['fromName'];
59 $yaysmtpSettings['forceFromEmail'] = $settings['forceFromEmail'];
60 $yaysmtpSettings['forceFromName'] = $settings['forceFromName'];
61
62 $yaysmtpSettings['currentMailer'] = $settings['mailerProvider'];
63 if ( ! empty( $settings['mailerProvider'] ) ) {
64 $mailerSettings = ! empty( $settings['mailerSettings'] ) ? $settings['mailerSettings'] : array();
65
66 if ( ! empty( $mailerSettings ) ) {
67 foreach ( $mailerSettings as $key => $val ) {
68 if ( 'pass' === $key ) {
69 $yaysmtpSettings[ $settings['mailerProvider'] ][ $key ] = Utils::encrypt( $val, 'smtppass' );
70 } else {
71 $yaysmtpSettings[ $settings['mailerProvider'] ][ $key ] = $val;
72 }
73 }
74 }
75 }
76
77 update_option( YAY_SMTP_SENDGRID_PREFIX . '_settings', $yaysmtpSettings );
78
79 wp_send_json_success( array( 'mess' => __( 'Settings saved.', 'smtp-sendgrid' ) ) );
80 }
81 wp_send_json_error( array( 'mess' => __( 'Settings Failed.', 'smtp-sendgrid' ) ) );
82 } catch ( \Exception $ex ) {
83 LogErrors::getMessageException( $ex, true );
84 } catch ( \Error $ex ) {
85 LogErrors::getMessageException( $ex, true );
86 }
87 }
88
89 public function sendTestMail() {
90 try {
91 Utils::checkNonce();
92 if ( isset( $_POST['emailAddress'] ) ) {
93 $emailAddress = sanitize_email( $_POST['emailAddress'] );
94 // check email
95 if ( ! is_email( $emailAddress ) ) {
96 wp_send_json_error( array( 'mess' => __( 'Invalid email format!', 'smtp-sendgrid' ) ) );
97 }
98
99 $headers = "Content-Type: text/html\r\n";
100 $subjectEmail = __( 'YaySMTP - Test email was sent successfully!', 'smtp-sendgrid' );
101 $html = __( 'Yay! Your test email was sent successfully! Thanks for using <a href="https://yaycommerce.com/yaysmtp-wordpress-mail-smtp/">YaySMTP</a><br><br>Best regards,<br>YayCommerce', 'smtp-sendgrid' );
102
103 if ( ! empty( $emailAddress ) ) {
104 $sendMailSucc = wp_mail( $emailAddress, $subjectEmail, $html, $headers );
105 if ( $sendMailSucc ) {
106 Utils::setYaySmtpSetting( 'succ_sent_mail_last', true );
107 wp_send_json_success( array( 'mess' => __( 'Email has been sent.', 'smtp-sendgrid' ) ) );
108 } else {
109 Utils::setYaySmtpSetting( 'succ_sent_mail_last', false );
110 if ( Utils::getCurrentMailer() == 'smtp' ) {
111 LogErrors::clearErr();
112 LogErrors::setErr( 'This error may be caused by: Incorrect From email, SMTP Host, Post, Username or Password.' );
113 $debugText = implode( '<br>', LogErrors::getErr() );
114 } else {
115 $debugText = implode( '<br>', LogErrors::getErr() );
116 }
117 wp_send_json_error(
118 array(
119 'debugText' => $debugText,
120 'mess' => __(
121 'Email sent failed.',
122 'smtp-sendgrid'
123 ),
124 )
125 );
126 }
127 }
128 } else {
129 wp_send_json_error( array( 'mess' => __( 'Email Address is not empty.', 'smtp-sendgrid' ) ) );
130 }
131 wp_send_json_error( array( 'mess' => __( 'Error send mail!', 'smtp-sendgrid' ) ) );
132 } catch ( \Exception $ex ) {
133 LogErrors::getMessageException( $ex, true );
134 } catch ( \Error $ex ) {
135 LogErrors::getMessageException( $ex, true );
136 }
137 }
138
139 public function getListEmailLogs() {
140 try {
141 Utils::checkNonce();
142 if ( isset( $_POST['params'] ) ) {
143 $params = Utils::saniValArray( $_POST['params'] );
144 global $wpdb;
145
146 $yaySmtpEmailLogSetting = Utils::getYaySmtpEmailLogSetting();
147 $showSubjectColumn = isset( $yaySmtpEmailLogSetting ) && isset( $yaySmtpEmailLogSetting['show_subject_cl'] ) ? (int) $yaySmtpEmailLogSetting['show_subject_cl'] : 1;
148 $showToColumn = isset( $yaySmtpEmailLogSetting ) && isset( $yaySmtpEmailLogSetting['show_to_cl'] ) ? (int) $yaySmtpEmailLogSetting['show_to_cl'] : 1;
149 $showStatusColumn = isset( $yaySmtpEmailLogSetting ) && isset( $yaySmtpEmailLogSetting['show_status_cl'] ) ? (int) $yaySmtpEmailLogSetting['show_status_cl'] : 1;
150 $showDatetimeColumn = isset( $yaySmtpEmailLogSetting ) && isset( $yaySmtpEmailLogSetting['show_datetime_cl'] ) ? (int) $yaySmtpEmailLogSetting['show_datetime_cl'] : 1;
151 $showActionColumn = isset( $yaySmtpEmailLogSetting ) && isset( $yaySmtpEmailLogSetting['show_action_cl'] ) ? (int) $yaySmtpEmailLogSetting['show_action_cl'] : 1;
152 $showStatus = isset( $yaySmtpEmailLogSetting ) && isset( $yaySmtpEmailLogSetting['status'] ) ? $yaySmtpEmailLogSetting['status'] : 'all';
153
154 $showColSettings = array(
155 'showSubjectCol' => $showSubjectColumn,
156 'showToCol' => $showToColumn,
157 'showStatusCol' => $showStatusColumn,
158 'showDatetimeCol' => $showDatetimeColumn,
159 'showActionCol' => $showActionColumn,
160 );
161
162 $limit = ! empty( $params['limit'] ) && is_numeric( $params['limit'] ) ? (int) $params['limit'] : 10;
163 $page = ! empty( $params['page'] ) && is_numeric( $params['page'] ) ? (int) $params['page'] : 1;
164 $offset = ( $page - 1 ) * $limit;
165
166 $valSearch = ! empty( $params['valSearch'] ) ? $params['valSearch'] : '';
167 $sortField = ! empty( $params['sortField'] ) ? $params['sortField'] : 'date_time';
168 $sortVal = 'DESC';
169 if ( ! empty( $params['sortVal'] ) && 'ascending' === $params['sortVal'] ) {
170 $sortVal = 'ASC';
171 }
172
173 $status = ! empty( $params['status'] ) ? $params['status'] : $showStatus;
174 if ( 'sent' === $status ) {
175 $statusWhere = 'status = 1';
176 } elseif ( 'not_send' === $status ) {
177 $statusWhere = 'status = 0 OR status =2';
178 } elseif ( 'empty' === $status ) {
179 $statusWhere = 'status <> 1 AND status <> 0 and status <> 2';
180 } else {
181 $statusWhere = 'status = 1 OR status = 0 OR status = 2';
182 }
183
184 // Result ALL
185 $totalItems = 0;
186 $table = YAY_SMTP_SENDGRID_PREFIX . '_email_logs';
187 if ( ! empty( $valSearch ) ) {
188 $subjectWhere = $wpdb->prepare( "subject LIKE %s", '%' . $wpdb->esc_like( $valSearch ) . '%' );
189 $toEmailWhere = $wpdb->prepare( "email_to LIKE %s", '%' . $wpdb->esc_like( $valSearch ) . '%' );
190 $whereQuery = "({$subjectWhere} OR {$toEmailWhere}) AND ({$statusWhere})";
191
192 $totalItems = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->prefix}$table WHERE $whereQuery" );
193
194 $sqlRepare = $wpdb->prepare(
195 "SELECT l.id, l.subject, l.email_from, l.email_to, l.mailer, l.date_time, l.status FROM {$wpdb->prefix}$table AS l WHERE $whereQuery ORDER BY " . sanitize_sql_orderby($sortField . ' ' . $sortVal) . " LIMIT %d OFFSET %d",
196 $limit,
197 $offset
198 );
199 } else {
200 $totalItems = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->prefix}$table WHERE $statusWhere" );
201
202 $sqlRepare = $wpdb->prepare(
203 "SELECT l.id, l.subject, l.email_from, l.email_to, l.mailer, l.date_time, l.status FROM {$wpdb->prefix}$table AS l WHERE $statusWhere ORDER BY " . sanitize_sql_orderby($sortField . ' ' . $sortVal) . " LIMIT %d OFFSET %d",
204 $limit,
205 $offset
206 );
207 }
208
209 // Result Custom
210 $results = $wpdb->get_results( $sqlRepare );
211
212 $emailLogsList = array();
213 $dateTimeFormat = get_option( 'date_format' ) . " \\a\\t " . get_option( 'time_format' );
214 foreach ( $results as $result ) {
215 $emailTo = maybe_unserialize( $result->email_to );
216 $emailEl = array(
217 'id' => $result->id,
218 'subject' => wp_kses_post( $result->subject ),
219 'email_from' => $result->email_from,
220 'email_to' => $emailTo,
221 'mailer' => $result->mailer,
222 'date_time' => get_date_from_gmt( $result->date_time, "$dateTimeFormat" ),
223 'status' => $result->status,
224 );
225 $emailLogsList[] = $emailEl;
226 }
227
228 wp_send_json_success(
229 array(
230 'data' => $emailLogsList,
231 'totalItem' => $totalItems,
232 'totalPage' => $limit < 0 ? 1 : ceil( $totalItems / $limit ),
233 'currentPage' => $page,
234 'limit' => $limit,
235 'showColSettings' => $showColSettings,
236 'mess' => __( 'Successful', 'smtp-sendgrid' ),
237 )
238 );
239 }
240 wp_send_json_error( array( 'mess' => __( 'Failed.', 'smtp-sendgrid' ) ) );
241 } catch ( \Exception $ex ) {
242 LogErrors::getMessageException( $ex, true );
243 } catch ( \Error $ex ) {
244 LogErrors::getMessageException( $ex, true );
245 }
246 }
247
248 public function setYaySmtpEmailLogSetting() {
249 try {
250 Utils::checkNonce();
251 if ( isset( $_POST['params'] ) ) {
252 $params = Utils::saniValArray( $_POST['params'] );
253 foreach ( $params as $key => $val ) {
254 Utils::setYaySmtpEmailLogSetting( $key, $val );
255 }
256 wp_send_json_success(
257 array(
258 'mess' => __( 'Save Settings Successful', 'smtp-sendgrid' ),
259 )
260 );
261 }
262 wp_send_json_error( array( 'mess' => __( 'Save Settings Failed.', 'smtp-sendgrid' ) ) );
263 } catch ( \Exception $ex ) {
264 LogErrors::getMessageException( $ex, true );
265 } catch ( \Error $ex ) {
266 LogErrors::getMessageException( $ex, true );
267 }
268 }
269
270 public function deleteEmailLogs() {
271 try {
272 Utils::checkNonce();
273 if ( isset( $_POST['params'] ) ) {
274 global $wpdb;
275 $params = Utils::saniValArray( $_POST['params'] );
276 $ids = isset( $params['ids'] ) ? $params['ids'] : ''; // '1,2,3'
277
278 $ids_array = explode( ',', (string) $ids );
279 $ids_array = array_map( 'intval', $ids_array );
280 $id_placeholders = implode( ', ', array_fill( 0, count( $ids_array ), '%d' ) );
281
282 if ( empty( $ids ) ) {
283 wp_send_json_error( array( 'mess' => __( 'No email log id found', 'smtp-sendgrid' ) ) );
284 }
285
286 $deleted = $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->prefix}yay_smtp_sendgrid_email_logs WHERE ID IN( $id_placeholders )", $ids_array ) );
287
288 if ( '' !== $wpdb->last_error ) {
289 wp_send_json_error( array( 'mess' => __( $wpdb->last_error, 'smtp-sendgrid' ) ) );
290 }
291
292 if ( ! $deleted ) {
293 wp_send_json_error( array( 'mess' => __( 'Something wrong, Email logs not deleted', 'smtp-sendgrid' ) ) );
294 }
295
296 wp_send_json_success(
297 array(
298 'mess' => __( 'Delete successful.', 'smtp-sendgrid' ),
299 )
300 );
301 }
302 wp_send_json_error( array( 'mess' => __( 'No email log id found.', 'smtp-sendgrid' ) ) );
303
304 } catch ( \Exception $ex ) {
305 LogErrors::getMessageException( $ex, true );
306 } catch ( \Error $ex ) {
307 LogErrors::getMessageException( $ex, true );
308 }
309 }
310
311 public function deleteAllEmailLogs() {
312 try {
313 Utils::checkNonce();
314 global $wpdb;
315 $wpdb->query( "DELETE FROM {$wpdb->prefix}yay_smtp_sendgrid_email_logs" );
316
317 wp_send_json_success(
318 array(
319 'mess' => __( 'Delete successful.', 'smtp-sendgrid' ),
320 )
321 );
322
323 } catch ( \Exception $ex ) {
324 LogErrors::getMessageException( $ex, true );
325 } catch ( \Error $ex ) {
326 LogErrors::getMessageException( $ex, true );
327 }
328 }
329
330 public function getEmailLog() {
331 try {
332 Utils::checkNonce();
333 if ( isset( $_POST['params'] ) ) {
334 global $wpdb;
335 $params = Utils::saniValArray( $_POST['params'] );
336 $id = isset( $params['id'] ) ? (int) $params['id'] : '';
337
338 if ( empty( $id ) ) {
339 wp_send_json_error( array( 'mess' => __( 'No email log id found', 'smtp-sendgrid' ) ) );
340 }
341
342 $resultQuery = $wpdb->get_row( $wpdb->prepare( "Select * FROM {$wpdb->prefix}yay_smtp_sendgrid_email_logs WHERE id = %d", $id ) );
343
344 if ( '' !== $wpdb->last_error ) {
345 wp_send_json_error( array( 'mess' => __( $wpdb->last_error, 'smtp-sendgrid' ) ) );
346 }
347
348 if ( ! empty( $resultQuery ) ) {
349 $dateTimeFormat = get_option( 'date_format' ) . " \\a\\t " . get_option( 'time_format' );
350 $emailTo = maybe_unserialize( $resultQuery->email_to );
351 $resultArr = array(
352 'id' => $resultQuery->id,
353 'subject' => wp_kses_post( $resultQuery->subject ),
354 'email_from' => $resultQuery->email_from,
355 'email_to' => $emailTo,
356 'mailer' => $resultQuery->mailer,
357 'date_time' => get_date_from_gmt( $resultQuery->date_time, "$dateTimeFormat" ),
358 'status' => $resultQuery->status,
359 );
360
361 if ( ! empty( $resultQuery->content_type ) ) {
362 $resultArr['content_type'] = $resultQuery->content_type;
363 $resultArr['body_content'] = Utils::wpKses( maybe_serialize( $resultQuery->body_content ));
364 }
365
366 if ( ! empty( $resultQuery->reason_error ) ) {
367 $resultArr['reason_error'] = $resultQuery->reason_error;
368 }
369
370 wp_send_json_success(
371 array(
372 'mess' => __( 'Get email log #' . $id . ' successful.', 'smtp-sendgrid' ),
373 'data' => $resultArr,
374 )
375 );
376 } else {
377 wp_send_json_error( array( 'mess' => __( 'No email log found.', 'smtp-sendgrid' ) ) );
378 }
379 }
380 wp_send_json_error( array( 'mess' => __( 'No email log id found.', 'smtp-sendgrid' ) ) );
381
382 } catch ( \Exception $ex ) {
383 LogErrors::getMessageException( $ex, true );
384 } catch ( \Error $ex ) {
385 LogErrors::getMessageException( $ex, true );
386 }
387 }
388
389 }
390