summaryrefslogtreecommitdiff
path: root/Postman/Postman-Email-Log
diff options
context:
space:
mode:
Diffstat (limited to 'Postman/Postman-Email-Log')
-rw-r--r--Postman/Postman-Email-Log/PostmanEmailLogController.php480
-rw-r--r--Postman/Postman-Email-Log/PostmanEmailLogPostType.php51
-rw-r--r--Postman/Postman-Email-Log/PostmanEmailLogService.php359
-rw-r--r--Postman/Postman-Email-Log/PostmanEmailLogView.php462
4 files changed, 1352 insertions, 0 deletions
diff --git a/Postman/Postman-Email-Log/PostmanEmailLogController.php b/Postman/Postman-Email-Log/PostmanEmailLogController.php
new file mode 100644
index 0000000..c496455
--- /dev/null
+++ b/Postman/Postman-Email-Log/PostmanEmailLogController.php
@@ -0,0 +1,480 @@
+<?php
+if ( ! defined( 'ABSPATH' ) ) {
+ exit; // Exit if accessed directly
+}
+
+require_once dirname(__DIR__) . '/PostmanLogFields.php';
+require_once 'PostmanEmailLogService.php';
+require_once 'PostmanEmailLogView.php';
+
+/**
+ *
+ * @author jasonhendriks
+ */
+class PostmanEmailLogController {
+ const RESEND_MAIL_AJAX_SLUG = 'postman_resend_mail';
+ private $rootPluginFilenameAndPath;
+ private $logger;
+
+ /**
+ */
+ function __construct( $rootPluginFilenameAndPath ) {
+ $this->rootPluginFilenameAndPath = $rootPluginFilenameAndPath;
+ $this->logger = new PostmanLogger( get_class( $this ) );
+ if ( PostmanOptions::getInstance()->isMailLoggingEnabled() ) {
+ add_action( 'admin_menu', array(
+ $this,
+ 'postmanAddMenuItem',
+ ),20 );
+ } else {
+ $this->logger->trace( 'not creating PostmanEmailLog admin menu item' );
+ }
+ if ( PostmanUtils::isCurrentPagePostmanAdmin( 'postman_email_log' ) ) {
+ $this->logger->trace( 'on postman email log page' );
+ // $this->logger->debug ( 'Registering ' . $actionName . ' Action Post handler' );
+ add_action( 'admin_post_delete', array(
+ $this,
+ 'delete_log_item',
+ ) );
+ add_action( 'admin_post_view', array(
+ $this,
+ 'view_log_item',
+ ) );
+ add_action( 'admin_post_transcript', array(
+ $this,
+ 'view_transcript_log_item',
+ ) );
+ add_action( 'admin_init', array(
+ $this,
+ 'on_admin_init',
+ ) );
+
+
+ }
+ if ( is_admin() ) {
+ $actionName = self::RESEND_MAIL_AJAX_SLUG;
+ $fullname = 'wp_ajax_' . $actionName;
+ // $this->logger->debug ( 'Registering ' . 'wp_ajax_' . $fullname . ' Ajax handler' );
+ add_action( $fullname, array(
+ $this,
+ 'resendMail',
+ ) );
+ }
+ }
+
+ /**
+ */
+ function on_admin_init() {
+ $this->handleBulkAction();
+ // register the stylesheet and javascript external resources
+ $pluginData = apply_filters( 'postman_get_plugin_metadata', null );
+ wp_register_script( 'postman_resend_email_script', plugins_url( 'script/postman_resend_email_sript.js', $this->rootPluginFilenameAndPath ), array(
+ PostmanViewController::JQUERY_SCRIPT,
+ PostmanViewController::POSTMAN_SCRIPT,
+ ), $pluginData ['version'] );
+ $this->handleCsvExport();
+ }
+
+ function handleCsvExport() {
+ if ( ! empty( $_POST ) && ! wp_verify_nonce( $_REQUEST['post-smtp-log'], 'post-smtp' ) )
+ die( 'Security check' );
+
+ if ( isset( $_POST['postman_export_csv'] ) && current_user_can( Postman::MANAGE_POSTMAN_CAPABILITY_LOGS ) ) {
+ $args = array(
+ 'post_type' => PostmanEmailLogPostType::POSTMAN_CUSTOM_POST_TYPE_SLUG,
+ 'post_status' => PostmanEmailLogService::POSTMAN_CUSTOM_POST_STATUS_PRIVATE,
+ 'posts_per_page' => -1,
+ );
+ $logs = new WP_Query($args);
+
+ if ( empty( $logs->posts ) ) {
+ return;
+ }
+
+ header('Content-Type: text/csv');
+ header('Content-Disposition: attachment; filename="email-logs.csv"');
+
+ $fp = fopen('php://output', 'wb');
+
+ $headers = array_keys( PostmanLogFields::get_instance()->get_fields() );
+ fputcsv($fp, $headers);
+
+ foreach ( $logs->posts as $log ) {
+ $meta = PostmanLogFields::get_instance()->get($log->ID);
+ $data = [];
+ foreach ( $meta as $header => $line ) {
+ $data[] = $line[0];
+ }
+ fputcsv($fp, $data);
+ }
+
+ fclose($fp);
+ die();
+
+ }
+ }
+
+ /**
+ */
+ public function resendMail() {
+ check_admin_referer( 'resend', 'security' );
+
+ // get the email address of the recipient from the HTTP Request
+ $postid = $this->getRequestParameter( 'email' );
+ if ( ! empty( $postid ) ) {
+ $meta_values = PostmanLogFields::get_instance()->get( $postid );
+
+ if ( isset( $_POST['mail_to'] ) && ! empty( $_POST['mail_to'] ) ) {
+ $emails = explode( ',', $_POST['mail_to'] );
+ $to = array_map( 'sanitize_email', $emails );
+ } else {
+ $to = $meta_values ['original_to'] [0];
+ }
+
+ $success = wp_mail( $to, $meta_values ['original_subject'] [0], $meta_values ['original_message'] [0], $meta_values ['original_headers'] [0] );
+
+ // Postman API: retrieve the result of sending this message from Postman
+ $result = apply_filters( 'postman_wp_mail_result', null );
+ $transcript = $result ['transcript'];
+
+ // post-handling
+ if ( $success ) {
+ $this->logger->debug( 'Email was successfully re-sent' );
+ // the message was sent successfully, generate an appropriate message for the user
+ $statusMessage = sprintf( __( 'Your message was delivered (%d ms) to the SMTP server! Congratulations :)', 'post-smtp' ), $result ['time'] );
+
+ // compose the JSON response for the caller
+ $response = array(
+ 'message' => $statusMessage,
+ 'transcript' => $transcript,
+ );
+ $this->logger->trace( 'AJAX response' );
+ $this->logger->trace( $response );
+ // send the JSON response
+ wp_send_json_success( $response );
+ } else {
+ $this->logger->error( 'Email was not successfully re-sent - ' . $result ['exception']->getCode() );
+ // the message was NOT sent successfully, generate an appropriate message for the user
+ $statusMessage = $result ['exception']->getMessage();
+
+ // compose the JSON response for the caller
+ $response = array(
+ 'message' => $statusMessage,
+ 'transcript' => $transcript,
+ );
+ $this->logger->trace( 'AJAX response' );
+ $this->logger->trace( $response );
+ // send the JSON response
+ wp_send_json_error( $response );
+ }
+ } else {
+ // compose the JSON response for the caller
+ $response = array();
+ // send the JSON response
+ wp_send_json_error( $response );
+ }
+ }
+
+ /**
+ * TODO move this somewhere reusable
+ *
+ * @param mixed $parameterName
+ * @return mixed
+ */
+ private function getRequestParameter( $parameterName ) {
+ if ( isset( $_POST [ $parameterName ] ) ) {
+ $value = filter_var( $_POST [ $parameterName ], FILTER_SANITIZE_STRING );
+ $this->logger->trace( sprintf( 'Found parameter "%s"', $parameterName ) );
+ $this->logger->trace( $value );
+ return $value;
+ }
+ }
+
+ /**
+ * From https://www.skyverge.com/blog/add-custom-bulk-action/
+ */
+ function handleBulkAction() {
+ // only do this for administrators
+ if ( PostmanUtils::isAdmin() && isset( $_REQUEST ['email_log_entry'] ) ) {
+ $this->logger->trace( 'handling bulk action' );
+ if ( wp_verify_nonce( $_REQUEST ['_wpnonce'], 'bulk-email_log_entries' ) ) {
+ $this->logger->trace( sprintf( 'nonce "%s" passed validation', sanitize_text_field($_REQUEST ['_wpnonce']) ) );
+ if ( isset( $_REQUEST ['action'] ) && ($_REQUEST ['action'] == 'bulk_delete' || $_REQUEST ['action2'] == 'bulk_delete') ) {
+ $this->logger->trace( sprintf( 'handling bulk delete' ) );
+ $purger = new PostmanEmailLogPurger();
+ $postids = array_map( 'absint', $_REQUEST ['email_log_entry'] );
+ foreach ( $postids as $postid ) {
+ $purger->verifyLogItemExistsAndRemove( $postid );
+ }
+ $mh = new PostmanMessageHandler();
+ $mh->addMessage( __( 'Mail Log Entries were deleted.', 'post-smtp' ) );
+ } else {
+ $this->logger->warn( sprintf( 'action "%s" not recognized', sanitize_text_field($_REQUEST ['action']) ) );
+ }
+ } else {
+ $this->logger->warn( sprintf( 'nonce "%s" failed validation', sanitize_text_field($_REQUEST ['_wpnonce']) ) );
+ }
+ $this->redirectToLogPage();
+ }
+ }
+
+ /**
+ */
+ function delete_log_item() {
+ // only do this for administrators
+ if ( PostmanUtils::isAdmin() ) {
+ $this->logger->trace( 'handling delete item' );
+ $postid = absint($_REQUEST ['email']);
+ if ( wp_verify_nonce( $_REQUEST ['_wpnonce'], 'delete_email_log_item_' . $postid ) ) {
+ $this->logger->trace( sprintf( 'nonce "%s" passed validation', sanitize_text_field($_REQUEST ['_wpnonce']) ) );
+ $purger = new PostmanEmailLogPurger();
+ $purger->verifyLogItemExistsAndRemove( $postid );
+ $mh = new PostmanMessageHandler();
+ $mh->addMessage( __( 'Mail Log Entry was deleted.', 'post-smtp' ) );
+ } else {
+ $this->logger->warn( sprintf( 'nonce "%s" failed validation', sanitize_text_field($_REQUEST ['_wpnonce']) ) );
+ }
+ $this->redirectToLogPage();
+ }
+ }
+
+ /**
+ */
+ function view_log_item() {
+ // only do this for administrators
+ if ( PostmanUtils::isAdmin() ) {
+ $this->logger->trace( 'handling view item' );
+ $postid = absint( $_REQUEST ['email'] );
+ $post = get_post( $postid );
+
+ if ( $post->post_type !== 'postman_sent_mail' ) {
+ return;
+ }
+
+ $meta_values = PostmanLogFields::get_instance()->get( $postid );
+ // https://css-tricks.com/examples/hrs/
+ print '<html><head><style>body {font-family: monospace;} hr {
+ border: 0;
+ border-bottom: 1px dashed #ccc;
+ background: #bbb;
+}</style></head><body>';
+ print '<table>';
+ if ( ! empty( $meta_values ['from_header'] [0] ) ) {
+ printf( '<tr><th style="text-align:right">%s:</th><td>%s</td></tr>', _x( 'From', 'Who is this message From?', 'post-smtp' ), esc_html( $meta_values ['from_header'] [0] ) );
+ }
+ // show the To header (it's optional)
+ if ( ! empty( $meta_values ['to_header'] [0] ) ) {
+ printf( '<tr><th style="text-align:right">%s:</th><td>%s</td></tr>', _x( 'To', 'Who is this message To?', 'post-smtp' ), esc_html( $meta_values ['to_header'] [0] ) );
+ }
+ // show the Cc header (it's optional)
+ if ( ! empty( $meta_values ['cc_header'] [0] ) ) {
+ printf( '<tr><th style="text-align:right">%s:</th><td>%s</td></tr>', _x( 'Cc', 'Who is this message Cc\'d to?', 'post-smtp' ), esc_html( $meta_values ['cc_header'] [0] ) );
+ }
+ // show the Bcc header (it's optional)
+ if ( ! empty( $meta_values ['bcc_header'] [0] ) ) {
+ printf( '<tr><th style="text-align:right">%s:</th><td>%s</td></tr>', _x( 'Bcc', 'Who is this message Bcc\'d to?', 'post-smtp' ), esc_html( $meta_values ['bcc_header'] [0] ) );
+ }
+ // show the Reply-To header (it's optional)
+ if ( ! empty( $meta_values ['reply_to_header'] [0] ) ) {
+ printf( '<tr><th style="text-align:right">%s:</th><td>%s</td></tr>', __( 'Reply-To', 'post-smtp' ), esc_html( $meta_values ['reply_to_header'] [0] ) );
+ }
+ printf( '<tr><th style="text-align:right">%s:</th><td>%s</td></tr>', _x( 'Date', 'What is the date today?', 'post-smtp' ), $post->post_date );
+ printf( '<tr><th style="text-align:right">%s:</th><td>%s</td></tr>', _x( 'Subject', 'What is the subject of this message?', 'post-smtp' ), esc_html( $post->post_title ) );
+ // The Transport UI is always there, in more recent versions that is
+ if ( ! empty( $meta_values ['transport_uri'] [0] ) ) {
+ printf( '<tr><th style="text-align:right">%s:</th><td>%s</td></tr>', _x( 'Delivery-URI', 'What is the unique URI of the configuration?', 'post-smtp' ), esc_html( $meta_values ['transport_uri'] [0] ) );
+ }
+ print '</table>';
+ print '<hr/>';
+ print '<pre>';
+ print $this->sanitize_message( $post->post_content );
+ print '</pre>';
+ print '</body></html>';
+ die();
+ }
+ }
+
+ function sanitize_message( $message ) {
+ $allowed_tags = wp_kses_allowed_html( 'post' );
+ $allowed_tags['style'] = array();
+
+ return wp_kses( $message, $allowed_tags );
+ }
+
+ /**
+ */
+ function view_transcript_log_item() {
+ // only do this for administrators
+ if ( PostmanUtils::isAdmin() ) {
+ $this->logger->trace( 'handling view transcript item' );
+ $postid = absint($_REQUEST ['email']);
+ $post = get_post( $postid );
+ $meta_values = PostmanLogFields::get_instance()->get( $postid );
+ // https://css-tricks.com/examples/hrs/
+ print '<html><head><style>body {font-family: monospace;} hr {
+ border: 0;
+ border-bottom: 1px dashed #ccc;
+ background: #bbb;
+}</style></head><body>';
+ printf( '<p>%s</p>', __( 'This is the conversation between Postman and the mail server. It can be useful for diagnosing problems. <b>DO NOT</b> post it on-line, it may contain your account password.', 'post-smtp' ) );
+ print '<hr/>';
+ print '<pre>';
+ if ( ! empty( $meta_values ['session_transcript'] [0] ) ) {
+ print esc_html( $meta_values ['session_transcript'] [0] );
+ } else {
+ /* Translators: Meaning "Not Applicable" */
+ print __( 'n/a', 'post-smtp' );
+ }
+ print '</pre>';
+ print '</body></html>';
+ die();
+ }
+ }
+
+ /**
+ * For whatever reason, PostmanUtils::get..url doesn't work here? :(
+ */
+ function redirectToLogPage() {
+ PostmanUtils::redirect( PostmanUtils::POSTMAN_EMAIL_LOG_PAGE_RELATIVE_URL );
+ die();
+ }
+
+ /**
+ * Register the page
+ */
+ function postmanAddMenuItem() {
+ // only do this for administrators
+ if ( PostmanUtils::isAdmin() ) {
+ $this->logger->trace( 'created PostmanEmailLog admin menu item' );
+ /*
+ Translators where (%s) is the name of the plugin */
+ $pageTitle = sprintf( __( '%s Email Log', 'post-smtp' ), __( 'Post SMTP', 'post-smtp' ) );
+ $pluginName = _x( 'Email Log', 'The log of Emails that have been delivered', 'post-smtp' );
+
+ $page = add_submenu_page( PostmanViewController::POSTMAN_MENU_SLUG, $pageTitle, $pluginName, Postman::MANAGE_POSTMAN_CAPABILITY_LOGS, 'postman_email_log', array( $this, 'postman_render_email_page' ) );
+
+ // When the plugin options page is loaded, also load the stylesheet
+ add_action( 'admin_print_styles-' . $page, array(
+ $this,
+ 'postman_email_log_enqueue_resources',
+ ) );
+ }
+ }
+ function postman_email_log_enqueue_resources() {
+ $pluginData = apply_filters( 'postman_get_plugin_metadata', null );
+ wp_register_style( 'postman_email_log', plugins_url( 'style/postman-email-log.css', $this->rootPluginFilenameAndPath ), null, $pluginData ['version'] );
+ wp_enqueue_style( 'postman_email_log' );
+ wp_enqueue_script( 'postman_resend_email_script' );
+ wp_enqueue_script( 'sprintf' );
+ wp_localize_script( 'postman_resend_email_script', 'postman_js_email_was_resent', __( 'Email was successfully resent (but without attachments)', 'post-smtp' ) );
+ /* Translators: Where %s is an error message */
+ wp_localize_script( 'postman_resend_email_script', 'postman_js_email_not_resent', __( 'Email could not be resent. Error: %s', 'post-smtp' ) );
+ wp_localize_script( 'postman_resend_email_script', 'postman_js_resend_label', __( 'Resend', 'post-smtp' ) );
+ }
+
+ /**
+ * *************************** RENDER TEST PAGE ********************************
+ * ******************************************************************************
+ * This function renders the admin page and the example list table.
+ * Although it's
+ * possible to call prepare_items() and display() from the constructor, there
+ * are often times where you may need to include logic here between those steps,
+ * so we've instead called those methods explicitly. It keeps things flexible, and
+ * it's the way the list tables are used in the WordPress core.
+ */
+ function postman_render_email_page() {
+
+ // Create an instance of our package class...
+ $testListTable = new PostmanEmailLogView();
+ wp_enqueue_script( 'postman_resend_email_script' );
+ // Fetch, prepare, sort, and filter our data...
+ $testListTable->prepare_items();
+
+ ?>
+<div class="wrap">
+
+ <div id="icon-users" class="icon32">
+ <br />
+ </div>
+ <h2><?php
+ /* Translators where (%s) is the name of the plugin */
+ echo sprintf( __( '%s Email Log', 'post-smtp' ), __( 'Post SMTP', 'post-smtp' ) )?></h2>
+
+ <?php include_once POST_SMTP_PATH . '/Postman/extra/donation.php'; ?>
+
+ <div
+ style="background: #ECECEC; border: 1px solid #CCC; padding: 0 10px; margin-top: 5px; border-radius: 5px; -moz-border-radius: 5px; -webkit-border-radius: 5px;">
+ <p><?php
+
+ echo __( 'This is a record of deliveries made to the mail server. It does not neccessarily indicate sucessful delivery to the recipient.', 'post-smtp' )?></p>
+ </div>
+
+ <?php
+ $from_date = isset( $_POST['from_date'] ) ? sanitize_text_field( $_POST['from_date'] ) : '';
+ $to_date = isset( $_POST['to_date'] ) ? sanitize_text_field( $_POST['to_date'] ) : '';
+ $search = isset( $_POST['search'] ) ? sanitize_text_field( $_POST['search'] ) : '';
+ $page_records = apply_filters( 'postman_log_per_page', array( 10, 15, 25, 50, 75, 100 ) );
+ $postman_page_records = isset( $_POST['postman_page_records'] ) ? absint( $_POST['postman_page_records'] ) : '';
+ ?>
+
+ <form id="postman-email-log-filter" method="post">
+ <input type="hidden" action="post-smtp-filter" value="1">
+ <?php wp_nonce_field('post-smtp', 'post-smtp-log'); ?>
+
+ <div id="email-log-filter" class="postman-log-row">
+ <div class="form-control">
+ <label for="from_date"><?php _e( 'From Date', 'post-smtp' ); ?></label>
+ <input id="from_date" class="email-log-date" value="<?php echo esc_attr($from_date); ?>" type="text" name="from_date" placeholder="<?php _e( 'From Date', 'post-smtp' ); ?>">
+ </div>
+ <div class="form-control">
+ <label for="to_date"><?php _e( 'To Date', 'post-smtp' ); ?></label>
+ <input id="to_date" class="email-log-date" value="<?php echo esc_attr($to_date); ?>" type="text" name="to_date" placeholder="<?php _e( 'To Date', 'post-smtp' ); ?>">
+ </div>
+ <div class="form-control">
+ <label for="search"><?php _e( 'Search', 'post-smtp' ); ?></label>
+ <input id="search" type="text" name="search" value="<?php echo esc_attr($search); ?>" placeholder="<?php _e( 'Search', 'post-smtp' ); ?>">
+ </div>
+ <div class="form-control">
+ <label id="postman_page_records"><?php _e( 'Records per page', 'post-smtp' ); ?></label>
+ <select id="postman_page_records" name="postman_page_records">
+ <?php
+ foreach ( $page_records as $value ) {
+ $selected = selected( $postman_page_records, $value, false );
+ echo '<option value="' . $value . '"' . $selected . '>' . $value . '</option>';
+ }
+ ?>
+ </select>
+ </div>
+
+ <div class="form-control">
+ <button type="submit" id="postman_export_csv" name="postman_export_csv" class="button button-primary"><?php _e( 'Export To CSV', 'post-smtp' ); ?></button>
+ </div>
+
+ <div class="form-control" style="padding: 0 5px 0 5px; margin-right: 50px;">
+ <button type="submit" name="filter" class="button button-primary"><?php _e( 'Filter/Search', 'post-smtp' ); ?></button>
+ </div>
+
+ <div class="form-control">
+ <button type="submit" id="postman_trash_all" name="postman_trash_all" class="button button-primary"><?php _e( 'Trash All', 'post-smtp' ); ?></button>
+ </div>
+
+ </div>
+ <div class="error">Please notice: when you select a date for example 11/20/2017, behind the scene the query select <b>11/20/2017 00:00:00</b>.<br>So if you searching for an email arrived that day at any hour you need to select 11/20/2017 as the <b>From Date</b> and 11/21/2017 as the <b>To Date</b>.</div>
+ </form>
+
+ <!-- Forms are NOT created automatically, so you need to wrap the table in one to use features like bulk actions -->
+ <form id="movies-filter" method="get">
+ <!-- For plugins, we also need to ensure that the form posts back to our current page -->
+ <input type="hidden" name="page"
+ value="<?php echo filter_input( INPUT_GET, 'page', FILTER_SANITIZE_STRING ); ?>" />
+
+ <!-- Now we can render the completed list table -->
+ <?php $testListTable->display()?>
+ </form>
+
+ <?php add_thickbox(); ?>
+
+</div>
+<?php
+ }
+}
diff --git a/Postman/Postman-Email-Log/PostmanEmailLogPostType.php b/Postman/Postman-Email-Log/PostmanEmailLogPostType.php
new file mode 100644
index 0000000..cf297db
--- /dev/null
+++ b/Postman/Postman-Email-Log/PostmanEmailLogPostType.php
@@ -0,0 +1,51 @@
+<?php
+if ( ! defined( 'ABSPATH' ) ) {
+ exit; // Exit if accessed directly
+}
+if (! class_exists ( 'PostmanEmailLogPostType' )) {
+
+ /**
+ * This class creates the Custom Post Type for Email Logs and handles writing these posts.
+ *
+ * @author jasonhendriks
+ */
+ class PostmanEmailLogPostType {
+
+ // constants
+ const POSTMAN_CUSTOM_POST_TYPE_SLUG = 'postman_sent_mail';
+
+ /**
+ * Behavior to run on the WordPress 'init' action
+ */
+ public static function automaticallyCreatePostType() {
+ add_action ( 'init', array (
+ new PostmanEmailLogPostType (),
+ 'create_post_type'
+ ) );
+ }
+
+ /**
+ * Create a custom post type
+ * Callback function - must be public scope
+ *
+ * register_post_type should only be invoked through the 'init' action.
+ * It will not work if called before 'init', and aspects of the newly
+ * created or modified post type will work incorrectly if called later.
+ *
+ * https://codex.wordpress.org/Function_Reference/register_post_type
+ */
+ public static function create_post_type() {
+ register_post_type ( self::POSTMAN_CUSTOM_POST_TYPE_SLUG, array (
+ 'labels' => array (
+ 'name' => _x ( 'Sent Emails', 'The group of Emails that have been delivered', 'post-smtp' ),
+ 'singular_name' => _x ( 'Sent Email', 'An Email that has been delivered', 'post-smtp' )
+ ),
+ 'capability_type' => '',
+ 'capabilities' => array ()
+ ) );
+ $logger = new PostmanLogger ( 'PostmanEmailLogPostType' );
+ $logger->trace ( 'Created post type: ' . self::POSTMAN_CUSTOM_POST_TYPE_SLUG );
+ }
+ }
+}
+
diff --git a/Postman/Postman-Email-Log/PostmanEmailLogService.php b/Postman/Postman-Email-Log/PostmanEmailLogService.php
new file mode 100644
index 0000000..2538700
--- /dev/null
+++ b/Postman/Postman-Email-Log/PostmanEmailLogService.php
@@ -0,0 +1,359 @@
+<?php
+if ( ! defined( 'ABSPATH' ) ) {
+ exit; // Exit if accessed directly
+}
+
+require_once dirname(__DIR__ ) . '/PostmanLogFields.php';
+
+if ( ! class_exists( 'PostmanEmailLog' ) ) {
+ class PostmanEmailLog {
+ public $sender;
+ public $toRecipients;
+ public $ccRecipients;
+ public $bccRecipients;
+ public $subject;
+ public $body;
+ public $success;
+ public $statusMessage;
+ public $sessionTranscript;
+ public $transportUri;
+ public $replyTo;
+ public $originalTo;
+ public $originalSubject;
+ public $originalMessage;
+ public $originalHeaders;
+
+ public function setStatusMessage( $message ) {
+ $this->statusMessage .= $message;
+ }
+ }
+}
+
+if ( ! class_exists( 'PostmanEmailLogService' ) ) {
+
+ /**
+ * This class creates the Custom Post Type for Email Logs and handles writing these posts.
+ *
+ * @author jasonhendriks
+ */
+ class PostmanEmailLogService {
+
+ /*
+ * Private content is published only for your eyes, or the eyes of only those with authorization
+ * permission levels to see private content. Normal users and visitors will not be aware of
+ * private content. It will not appear in the article lists. If a visitor were to guess the URL
+ * for your private post, they would still not be able to see your content. You will only see
+ * the private content when you are logged into your WordPress blog.
+ */
+ const POSTMAN_CUSTOM_POST_STATUS_PRIVATE = 'private';
+
+ // member variables
+ private $logger;
+ private $inst;
+
+ /**
+ * Constructor
+ */
+ private function __construct() {
+ $this->logger = new PostmanLogger( get_class( $this ) );
+ }
+
+ /**
+ * singleton instance
+ */
+ public static function getInstance() {
+ static $inst = null;
+ if ( $inst === null ) {
+ $inst = new PostmanEmailLogService();
+ }
+ return $inst;
+ }
+
+ /**
+ * Logs successful email attempts
+ *
+ * @param PostmanMessage $message
+ * @param mixed $transcript
+ * @param PostmanModuleTransport $transport
+ */
+ public function writeSuccessLog( PostmanEmailLog $log, PostmanMessage $message, $transcript, PostmanModuleTransport $transport ) {
+ if ( PostmanOptions::getInstance()->isMailLoggingEnabled() ) {
+ $statusMessage = '';
+ $status = true;
+ $subject = $message->getSubject();
+ if ( empty( $subject ) ) {
+ $statusMessage = sprintf( '%s: %s', __( 'Warning', 'post-smtp' ), __( 'An empty subject line can result in delivery failure.', 'post-smtp' ) );
+ $status = 'WARN';
+ }
+ $this->createLog( $log, $message, $transcript, $statusMessage, $status, $transport );
+ $this->writeToEmailLog( $log );
+ }
+ }
+
+ /**
+ * Logs failed email attempts, requires more metadata so the email can be resent in the future
+ *
+ * @param PostmanMessage $message
+ * @param mixed $transcript
+ * @param PostmanModuleTransport $transport
+ * @param mixed $statusMessage
+ * @param mixed $originalTo
+ * @param mixed $originalSubject
+ * @param mixed $originalMessage
+ * @param mixed $originalHeaders
+ */
+ public function writeFailureLog( PostmanEmailLog $log, PostmanMessage $message = null, $transcript, PostmanModuleTransport $transport, $statusMessage ) {
+ if ( PostmanOptions::getInstance()->isMailLoggingEnabled() ) {
+ $this->createLog( $log, $message, $transcript, $statusMessage, false, $transport );
+ $this->writeToEmailLog( $log,$message );
+ }
+ }
+
+ /**
+ * Writes an email sending attempt to the Email Log
+ *
+ * From http://wordpress.stackexchange.com/questions/8569/wp-insert-post-php-function-and-custom-fields
+ */
+ private function writeToEmailLog( PostmanEmailLog $log, PostmanMessage $message = null ) {
+
+ $options = PostmanOptions::getInstance();
+
+ $this->checkForLogErrors( $log ,$message );
+ $new_status = $log->statusMessage;
+
+ if ( $options->is_fallback && empty( $log->statusMessage ) ) {
+ $new_status = 'Sent ( ** Fallback ** )';
+ }
+
+ if ( $options->is_fallback && ! empty( $log->statusMessage ) ) {
+ $new_status = '( ** Fallback ** ) ' . $log->statusMessage;
+ }
+
+ // nothing here is sanitized as WordPress should take care of
+ // making database writes safe
+ $my_post = array(
+ 'post_type' => PostmanEmailLogPostType::POSTMAN_CUSTOM_POST_TYPE_SLUG,
+ 'post_title' => $log->subject,
+ 'post_content' => $log->body,
+ 'post_excerpt' => $new_status,
+ 'post_status' => PostmanEmailLogService::POSTMAN_CUSTOM_POST_STATUS_PRIVATE,
+ );
+
+ // Insert the post into the database (WordPress gives us the Post ID)
+ $post_id = wp_insert_post( $my_post, true );
+
+ if ( is_wp_error( $post_id ) ) {
+ add_action( 'admin_notices', function() use( $post_id ) {
+ $class = 'notice notice-error';
+ $message = $post_id->get_error_message();
+
+ printf( '<div class="%1$s"><p>%2$s</p></div>', esc_attr( $class ), esc_html( $message ) );
+ });
+ }
+
+ $this->logger->debug( sprintf( 'Saved message #%s to the database', $post_id ) );
+ $this->logger->trace( $log );
+
+ // Write the meta data related to the email
+ PostmanLogFields::get_instance()->update( $post_id, 'success', $log->success );
+ PostmanLogFields::get_instance()->update( $post_id, 'from_header', $log->sender );
+ if ( ! empty( $log->toRecipients ) ) {
+ PostmanLogFields::get_instance()->update( $post_id, 'to_header', $log->toRecipients );
+ }
+ if ( ! empty( $log->ccRecipients ) ) {
+ PostmanLogFields::get_instance()->update( $post_id, 'cc_header', $log->ccRecipients );
+ }
+ if ( ! empty( $log->bccRecipients ) ) {
+ PostmanLogFields::get_instance()->update( $post_id, 'bcc_header', $log->bccRecipients );
+ }
+ if ( ! empty( $log->replyTo ) ) {
+ PostmanLogFields::get_instance()->update( $post_id, 'reply_to_header', $log->replyTo );
+ }
+ PostmanLogFields::get_instance()->update( $post_id, 'transport_uri', $log->transportUri );
+
+ if ( ! $log->success || true ) {
+ // alwas add the meta data so we can re-send it
+ PostmanLogFields::get_instance()->update( $post_id, 'original_to', $log->originalTo );
+ PostmanLogFields::get_instance()->update( $post_id, 'original_subject', $log->originalSubject );
+ PostmanLogFields::get_instance()->update( $post_id, 'original_message', $log->originalMessage );
+ PostmanLogFields::get_instance()->update( $post_id, 'original_headers', $log->originalHeaders );
+ }
+
+ // we do not sanitize the session transcript - let the reader decide how to handle the data
+ PostmanLogFields::get_instance()->update( $post_id, 'session_transcript', $log->sessionTranscript );
+
+ // truncate the log (remove older entries)
+ $purger = new PostmanEmailLogPurger();
+ $purger->truncateLogItems( PostmanOptions::getInstance()->getMailLoggingMaxEntries() );
+ }
+
+ private function checkForLogErrors( PostmanEmailLog $log, $postMessage ) {
+ $message = __( 'You getting this message because an error detected while delivered your email.', 'post-smtp' );
+ $message .= "\r\n" . sprintf( __( 'For the domain: %1$s','post-smtp' ), get_bloginfo('url') );
+ $message .= "\r\n" . __( 'The log to paste when you open a support issue:', 'post-smtp' ) . "\r\n";
+
+ if ( $log->statusMessage && ! empty( $log->statusMessage ) ) {
+ require_once POST_SMTP_PATH . '/Postman/notifications/PostmanNotify.php';
+
+ $message = $message . $log->statusMessage;
+
+ $notification_service = PostmanOptions::getInstance()->getNotificationService();
+ switch ($notification_service) {
+ case 'default':
+ $notifyer = new PostmanMailNotify;
+ break;
+ case 'pushover':
+ $notifyer = new PostmanPushoverNotify;
+ break;
+ case 'slack':
+ $notifyer = new PostmanSlackNotify;
+ break;
+ default:
+ $notifyer = new PostmanMailNotify;
+ }
+
+ $notifyer = apply_filters( 'post_smtp_notifier', $notifyer, $notification_service );
+
+ // Notifications
+ $notify = new PostmanNotify( $notifyer );
+ $notify->send($message, $log);
+ $notify->push_to_chrome($log->statusMessage);
+ }
+
+ /**
+ * @todo
+ * After commented by me, check if it was needed.
+ */
+ preg_match_all( '/(.*)From/s', $log->sessionTranscript, $matches );
+
+ if ( isset( $matches[1][0] ) && ! empty( $matches[1][0] ) && strpos( strtolower( $matches[1][0] ), 'error' ) !== false ) {
+ $message = $message . $log->sessionTranscript;
+ }
+ }
+
+ /**
+ * Creates a Log object for use by writeToEmailLog()
+ *
+ * @param PostmanMessage $message
+ * @param mixed $transcript
+ * @param mixed $statusMessage
+ * @param mixed $success
+ * @param PostmanModuleTransport $transport
+ * @return PostmanEmailLog
+ */
+ private function createLog( PostmanEmailLog $log, PostmanMessage $message = null, $transcript, $statusMessage, $success, PostmanModuleTransport $transport ) {
+ if ( $message ) {
+ $log->sender = $message->getFromAddress()->format();
+ $log->toRecipients = $this->flattenEmails( $message->getToRecipients() );
+ $log->ccRecipients = $this->flattenEmails( $message->getCcRecipients() );
+ $log->bccRecipients = $this->flattenEmails( $message->getBccRecipients() );
+ $log->subject = $message->getSubject();
+ $log->body = $message->getBody();
+ if ( null !== $message->getReplyTo() ) {
+ $log->replyTo = $message->getReplyTo()->format();
+ }
+ }
+ $log->success = $success;
+ $log->statusMessage = $statusMessage;
+ $log->transportUri = PostmanTransportRegistry::getInstance()->getPublicTransportUri( $transport );
+ $log->sessionTranscript = $log->transportUri . "\n\n" . $transcript;
+ return $log;
+ }
+
+ /**
+ * Creates a readable "TO" entry based on the recipient header
+ *
+ * @param array $addresses
+ * @return string
+ */
+ private static function flattenEmails( array $addresses ) {
+ $flat = '';
+ $count = 0;
+ foreach ( $addresses as $address ) {
+ if ( $count >= 3 ) {
+ $flat .= sprintf( __( '.. +%d more', 'post-smtp' ), sizeof( $addresses ) - $count );
+ break;
+ }
+ if ( $count > 0 ) {
+ $flat .= ', ';
+ }
+ $flat .= $address->format();
+ $count ++;
+ }
+ return $flat;
+ }
+ }
+}
+
+if ( ! class_exists( 'PostmanEmailLogPurger' ) ) {
+ class PostmanEmailLogPurger {
+ private $posts;
+ private $logger;
+
+ /**
+ *
+ * @return mixed
+ */
+ function __construct( $args = array() ) {
+ $this->logger = new PostmanLogger( get_class( $this ) );
+ $defaults = array(
+ 'posts_per_page' => -1,
+ 'offset' => 0,
+ 'category' => '',
+ 'category_name' => '',
+ 'orderby' => 'date',
+ 'order' => 'DESC',
+ 'include' => '',
+ 'exclude' => '',
+ 'meta_key' => '',
+ 'meta_value' => '',
+ 'post_type' => PostmanEmailLogPostType::POSTMAN_CUSTOM_POST_TYPE_SLUG,
+ 'post_mime_type' => '',
+ 'post_parent' => '',
+ 'post_status' => 'private',
+ 'suppress_filters' => true,
+ );
+ $args = wp_parse_args( $args, $defaults );
+ $query = new WP_Query( $args );
+ $this->posts = $query->posts;
+ }
+
+ /**
+ *
+ * @param array $posts
+ * @param mixed $postid
+ */
+ function verifyLogItemExistsAndRemove( $postid ) {
+ $force_delete = true;
+ foreach ( $this->posts as $post ) {
+ if ( $post->ID == $postid ) {
+ $this->logger->debug( 'deleting log item ' . intval( $postid ) );
+ wp_delete_post( $postid, $force_delete );
+ return;
+ }
+ }
+ $this->logger->warn( 'could not find Postman Log Item #' . $postid );
+ }
+ function removeAll() {
+ $this->logger->debug( sprintf( 'deleting %d log items ', sizeof( $this->posts ) ) );
+ $force_delete = true;
+ foreach ( $this->posts as $post ) {
+ wp_delete_post( $post->ID, $force_delete );
+ }
+ }
+
+ /**
+ *
+ * @param mixed $size
+ */
+ function truncateLogItems( $size ) {
+ $index = count( $this->posts );
+ $force_delete = true;
+ while ( $index > $size ) {
+ $postid = $this->posts [ -- $index ]->ID;
+ $this->logger->debug( 'deleting log item ' . $postid );
+ wp_delete_post( $postid, $force_delete );
+ }
+ }
+ }
+}
diff --git a/Postman/Postman-Email-Log/PostmanEmailLogView.php b/Postman/Postman-Email-Log/PostmanEmailLogView.php
new file mode 100644
index 0000000..52cdd4d
--- /dev/null
+++ b/Postman/Postman-Email-Log/PostmanEmailLogView.php
@@ -0,0 +1,462 @@
+<?php
+if ( ! defined( 'ABSPATH' ) ) {
+ exit; // Exit if accessed directly
+}
+require_once dirname(__DIR__) . '/PostmanLogFields.php';
+
+/**
+ * See http://wpengineer.com/2426/wp_list_table-a-step-by-step-guide/
+ */
+if ( ! class_exists( 'WP_List_Table' ) ) {
+ require_once( ABSPATH . 'wp-admin/includes/class-wp-list-table.php' );
+}
+class PostmanEmailLogView extends WP_List_Table {
+ private $logger;
+
+ /**
+ * ************************************************************************
+ * REQUIRED.
+ * Set up a constructor that references the parent constructor. We
+ * use the parent reference to set some default configs.
+ * *************************************************************************
+ */
+ function __construct() {
+ $this->logger = new PostmanLogger( get_class( $this ) );
+
+ // Set parent defaults
+ parent::__construct( array(
+ 'singular' => 'email_log_entry', // singular name of the listed records
+ 'plural' => 'email_log_entries', // plural name of the listed records
+ 'ajax' => false,
+ ) ); // does this table support ajax?
+ }
+
+ /**
+ * ************************************************************************
+ * Recommended.
+ * This method is called when the parent class can't find a method
+ * specifically build for a given column. Generally, it's recommended to include
+ * one method for each column you want to render, keeping your package class
+ * neat and organized. For example, if the class needs to process a column
+ * named 'title', it would first see if a method named $this->column_title()
+ * exists - if it does, that method will be used. If it doesn't, this one will
+ * be used. Generally, you should try to use custom column methods as much as
+ * possible.
+ *
+ * Since we have defined a column_title() method later on, this method doesn't
+ * need to concern itself with any column with a name of 'title'. Instead, it
+ * needs to handle everything else.
+ *
+ * For more detailed insight into how columns are handled, take a look at
+ * WP_List_Table::single_row_columns()
+ *
+ * @param array $item
+ * A singular item (one full row's worth of data)
+ * @param array $column_name
+ * The name/slug of the column to be processed
+ * @return string Text or HTML to be placed inside the column <td>
+ * ************************************************************************
+ */
+ function column_default( $item, $column_name ) {
+ switch ( $column_name ) {
+ case 'sent_to' :
+ case 'date' :
+ case 'status' :
+ return $item [ $column_name ];
+ default :
+ return print_r( $item, true ); // Show the whole array for troubleshooting purposes
+ }
+ }
+
+ /**
+ * ************************************************************************
+ * Recommended.
+ * This is a custom column method and is responsible for what
+ * is rendered in any column with a name/slug of 'title'. Every time the class
+ * needs to render a column, it first looks for a method named
+ * column_{$column_title} - if it exists, that method is run. If it doesn't
+ * exist, column_default() is called instead.
+ *
+ * This example also illustrates how to implement rollover actions. Actions
+ * should be an associative array formatted as 'slug'=>'link html' - and you
+ * will need to generate the URLs yourself. You could even ensure the links
+ *
+ * @see WP_List_Table::::single_row_columns()
+ * @param array $item
+ * A singular item (one full row's worth of data)
+ * @return string Text to be placed inside the column <td> (movie title only)
+ * ************************************************************************
+ */
+ function column_title( $item ) {
+
+ // Build row actions
+ $iframeUri = 'admin-post.php?page=postman_email_log&action=%s&email=%s&TB_iframe=true&width=700&height=550';
+ $deleteUrl = wp_nonce_url( admin_url( sprintf( 'admin-post.php?page=postman_email_log&action=%s&email=%s', 'delete', $item ['ID'] ) ), 'delete_email_log_item_' . $item ['ID'] );
+ $viewUrl = admin_url( sprintf( $iframeUri, 'view', $item ['ID'] ) );
+ $transcriptUrl = admin_url( sprintf( $iframeUri, 'transcript', $item ['ID'] ) );
+ $resendUrl = admin_url( sprintf( $iframeUri, 'resend', $item ['ID'] ) );
+
+ $meta_values = PostmanLogFields::get_instance()->get( $item ['ID'] );
+
+ $actions = array(
+ 'delete' => sprintf( '<a href="%s">%s</a>', $deleteUrl, _x( 'Delete', 'Delete an item from the email log', 'post-smtp' ) ),
+ 'view' => sprintf( '<a href="%s" class="thickbox">%s</a>', $viewUrl, _x( 'View', 'View an item from the email log', 'post-smtp' ) ),
+ );
+
+ if ( ! empty( $meta_values ['session_transcript'] [0] ) ) {
+ $actions ['transcript'] = sprintf( '<a href="%1$s" class="thickbox">%2$s</a>', $transcriptUrl, __( 'Session Transcript', 'post-smtp' ) );
+ } else {
+ $actions ['transcript'] = sprintf( '%2$s', $transcriptUrl, __( 'Session Transcript', 'post-smtp' ) );
+ }
+ if ( ! (empty( $meta_values ['original_to'] [0] ) && empty( $meta_values ['originalHeaders'] [0] )) ) {
+ // $actions ['resend'] = sprintf ( '<a href="%s">%s</a>', $resendUrl, __ ( 'Resend', 'post-smtp' ) );
+ $emails = $meta_values ['original_to'] [0];
+ $to = is_array( $emails ) ? implode( ',', array_walk($emails, 'sanitize_email') ) : sanitize_email( $emails );
+
+ $actions ['resend'] = sprintf( '<span id="%3$s"><a class="postman-open-resend" href="#">%2$s</a></span><div style="display:none;"><input type="hidden" name="security" value="%6$s"><input type="text" name="mail_to" class="regular-text ltr" data-id="%1$s" value="%4$s"><button class="postman-resend button button-primary">%2$s</button><i style="color: black;">%5$s</i></div>', $item ['ID'], __( 'Resend', 'post-smtp' ), 'resend-' . $item ['ID'], esc_attr( $to ), __( 'comma-separated for multiple emails', 'post-smtp' ), wp_create_nonce( 'resend' ) );
+ } else {
+ $actions ['resend'] = sprintf( '%2$s', $resendUrl, __( 'Resend', 'post-smtp' ) );
+ }
+
+ // Return the title contents
+ return sprintf( '%1$s %3$s',
+ /*$1%s*/ $item ['title'],
+ /*$2%s*/ $item ['ID'],
+ /*$3%s*/ $this->row_actions( $actions ) );
+ }
+
+ /**
+ * ************************************************************************
+ * REQUIRED if displaying checkboxes or using bulk actions! The 'cb' column
+ * is given special treatment when columns are processed.
+ * It ALWAYS needs to
+ * have it's own method.
+ *
+ * @see WP_List_Table::::single_row_columns()
+ * @param array $item
+ * A singular item (one full row's worth of data)
+ * @return string Text to be placed inside the column <td> (movie title only)
+ * ************************************************************************
+ */
+ function column_cb( $item ) {
+ return sprintf( '<input type="checkbox" name="%1$s[]" value="%2$s" />',
+ /*$1%s*/ $this->_args ['singular'], // Let's simply repurpose the table's singular label ("movie")
+ /* $2%s */
+ $item ['ID'] ); // The value of the checkbox should be the record's id
+ }
+
+ /**
+ * ************************************************************************
+ * REQUIRED! This method dictates the table's columns and titles.
+ * This should
+ * return an array where the key is the column slug (and class) and the value
+ * is the column's title text. If you need a checkbox for bulk actions, refer
+ * to the $columns array below.
+ *
+ * The 'cb' column is treated differently than the rest. If including a checkbox
+ * column in your table you must create a column_cb() method. If you don't need
+ * bulk actions or checkboxes, simply leave the 'cb' entry out of your array.
+ *
+ * @see WP_List_Table::::single_row_columns()
+ * @return array An associative array containing column information: 'slugs'=>'Visible Titles'
+ * ************************************************************************
+ */
+ function get_columns() {
+ $columns = array(
+ 'cb' => '<input type="checkbox" />', // Render a checkbox instead of text
+ 'title' => _x( 'Subject', 'What is the subject of this message?', 'post-smtp' ),
+ 'sent_to' => __( 'Sent To', 'post-smtp' ),
+ 'status' => __( 'Status', 'post-smtp' ),
+ 'date' => _x( 'Delivery Time', 'When was this email sent?', 'post-smtp' ),
+ );
+ return $columns;
+ }
+
+ /**
+ * ************************************************************************
+ * Optional.
+ * If you want one or more columns to be sortable (ASC/DESC toggle),
+ * you will need to register it here. This should return an array where the
+ * key is the column that needs to be sortable, and the value is db column to
+ * sort by. Often, the key and value will be the same, but this is not always
+ * the case (as the value is a column name from the database, not the list table).
+ *
+ * This method merely defines which columns should be sortable and makes them
+ * clickable - it does not handle the actual sorting. You still need to detect
+ * the ORDERBY and ORDER querystring variables within prepare_items() and sort
+ * your data accordingly (usually by modifying your query).
+ *
+ * @return array An associative array containing all the columns that should be sortable: 'slugs'=>array('data_values',bool)
+ * ************************************************************************
+ */
+ function get_sortable_columns() {
+ return array();
+ $sortable_columns = array(
+ 'title' => array(
+ 'title',
+ false,
+ ), // true means it's already sorted
+ 'status' => array(
+ 'status',
+ false,
+ ),
+ 'date' => array(
+ 'date',
+ false,
+ ),
+ );
+ return $sortable_columns;
+ }
+
+ /**
+ * ************************************************************************
+ * Optional.
+ * If you need to include bulk actions in your list table, this is
+ * the place to define them. Bulk actions are an associative array in the format
+ * 'slug'=>'Visible Title'
+ *
+ * If this method returns an empty value, no bulk action will be rendered. If
+ * you specify any bulk actions, the bulk actions box will be rendered with
+ * the table automatically on display().
+ *
+ * Also note that list tables are not automatically wrapped in <form> elements,
+ * so you will need to create those manually in order for bulk actions to function.
+ *
+ * @return array An associative array containing all the bulk actions: 'slugs'=>'Visible Titles'
+ * ************************************************************************
+ */
+ function get_bulk_actions() {
+ $actions = array(
+ 'bulk_delete' => _x( 'Delete', 'Delete an item from the email log', 'post-smtp' ),
+ );
+ return $actions;
+ }
+
+ /**
+ * ************************************************************************
+ * Optional.
+ * You can handle your bulk actions anywhere or anyhow you prefer.
+ * For this example package, we will handle it in the class to keep things
+ * clean and organized.
+ *
+ * @see $this->prepare_items() ************************************************************************
+ */
+ function process_bulk_action() {
+ }
+
+ /**
+ * ************************************************************************
+ * REQUIRED! This is where you prepare your data for display.
+ * This method will
+ * usually be used to query the database, sort and filter the data, and generally
+ * get it ready to be displayed. At a minimum, we should set $this->items and
+ * $this->set_pagination_args(), although the following properties and methods
+ * are frequently interacted with here...
+ *
+ * @global WPDB $wpdb
+ * @uses $this->_column_headers
+ * @uses $this->items
+ * @uses $this->get_columns()
+ * @uses $this->get_sortable_columns()
+ * @uses $this->get_pagenum()
+ * @uses $this->set_pagination_args()
+ * ************************************************************************
+ */
+ function prepare_items() {
+ if ( ! empty( $_POST ) && ! wp_verify_nonce( $_REQUEST['post-smtp-log'], 'post-smtp' ) )
+ die( 'Security check' );
+
+ /**
+ * First, lets decide how many records per page to show
+ */
+ $per_page = isset( $_POST['postman_page_records'] ) ? absint( $_POST['postman_page_records'] ) : 10;
+
+ /**
+ * REQUIRED.
+ * Now we need to define our column headers. This includes a complete
+ * array of columns to be displayed (slugs & titles), a list of columns
+ * to keep hidden, and a list of columns that are sortable. Each of these
+ * can be defined in another method (as we've done here) before being
+ * used to build the value for our _column_headers property.
+ */
+ $columns = $this->get_columns();
+ $hidden = array();
+ $sortable = $this->get_sortable_columns();
+
+ /**
+ * REQUIRED.
+ * Finally, we build an array to be used by the class for column
+ * headers. The $this->_column_headers property takes an array which contains
+ * 3 other arrays. One for all columns, one for hidden columns, and one
+ * for sortable columns.
+ */
+ $this->_column_headers = array(
+ $columns,
+ $hidden,
+ $sortable,
+ );
+
+ /**
+ * Optional.
+ * You can handle your bulk actions however you see fit. In this
+ * case, we'll handle them within our package just to keep things clean.
+ */
+ $this->process_bulk_action();
+
+ /**
+ * Instead of querying a database, we're going to fetch the example data
+ * property we created for use in this plugin.
+ * This makes this example
+ * package slightly different than one you might build on your own. In
+ * this example, we'll be using array manipulation to sort and paginate
+ * our data. In a real-world implementation, you will probably want to
+ * use sort and pagination data to build a custom query instead, as you'll
+ * be able to use your precisely-queried data immediately.
+ */
+ $data = array();
+
+ $args = array(
+ 'posts_per_page' => -1,
+ 'orderby' => 'date',
+ 'order' => 'DESC',
+ 'post_type' => PostmanEmailLogPostType::POSTMAN_CUSTOM_POST_TYPE_SLUG,
+ 'post_status' => 'private',
+ 'suppress_filters' => true,
+ );
+
+ if ( isset( $_POST['from_date'] ) && ! empty( $_POST['from_date'] ) ) {
+ $from_date = sanitize_text_field( $_POST['from_date'] );
+
+ $args['date_query']['after'] = $from_date;
+ $args['date_query']['column'] = 'post_date';
+ $args['date_query']['inclusive'] = false;
+ }
+
+ if ( isset( $_POST['to_date'] ) && ! empty( $_POST['to_date'] ) ) {
+ $to_date = sanitize_text_field( $_POST['to_date'] );
+
+ $args['date_query']['before'] = $to_date;
+ $args['date_query']['column'] = 'post_date';
+ $args['date_query']['inclusive'] = true;
+ }
+
+ if ( ! empty( $_POST['search'] ) ) {
+
+ if ( isset( $args['date_query'] ) ) {
+ unset( $args['date_query'] ); }
+
+ $args['s'] = sanitize_text_field( $_POST['search'] );
+ }
+
+ if ( isset( $_POST['postman_trash_all'] ) ) {
+ $args['posts_per_page'] = -1;
+ }
+ $posts = new WP_query( $args );
+
+ if ( isset( $_POST['postman_trash_all'] ) ) {
+ foreach ( $posts->posts as $post ) {
+ wp_delete_post( $post->ID, true );
+ }
+
+ $posts->posts = array();
+ }
+
+ $date_format = get_option( 'date_format' );
+ $time_format = get_option( 'time_format' );
+
+ foreach ( $posts->posts as $post ) {
+ $date = $post->post_date;
+ $humanTime = human_time_diff( strtotime( $post->post_date_gmt ) );
+ // if this PHP system support humanTime, than use it
+ if ( ! empty( $humanTime ) ) {
+ /* Translators: where %s indicates the relative time from now */
+ $date = sprintf( _x( '%s ago', 'A relative time as in "five days ago"', 'post-smtp' ), $humanTime );
+ }
+ $meta_values = PostmanLogFields::get_instance()->get( $post->ID );
+ $sent_to = array_map( 'esc_html', explode( ',' , $meta_values ['to_header'] [0] ) );
+ $flattenedPost = array(
+ // the post title must be escaped as they are displayed in the HTML output
+ 'sent_to' => implode( ', ', $sent_to ),
+ 'title' => esc_html( $post->post_title ),
+ // the post status must be escaped as they are displayed in the HTML output
+ 'status' => ($post->post_excerpt != null ? esc_html( $post->post_excerpt ) : __( 'Sent', 'post-smtp' )),
+ 'date' => date( "$date_format $time_format", strtotime( $post->post_date ) ),
+ 'ID' => $post->ID,
+ );
+ array_push( $data, $flattenedPost );
+ }
+
+ /**
+ * This checks for sorting input and sorts the data in our array accordingly.
+ *
+ * In a real-world situation involving a database, you would probably want
+ * to handle sorting by passing the 'orderby' and 'order' values directly
+ * to a custom query. The returned data will be pre-sorted, and this array
+ * sorting technique would be unnecessary.
+ */
+ function usort_reorder( $a, $b ) {
+ $orderby = ( ! empty( $_REQUEST ['orderby'] )) ? sanitize_text_field($_REQUEST ['orderby']) : 'title'; // If no sort, default to title
+ $order = ( ! empty( $_REQUEST ['order'] )) ? sanitize_text_field($_REQUEST ['order']) : 'asc'; // If no order, default to asc
+ $result = strcmp( $a [ $orderby ], $b [ $orderby ] ); // Determine sort order
+ return ($order === 'asc') ? $result : - $result; // Send final sort direction to usort
+ }
+ // usort($data, 'usort_reorder');
+ /**
+ * *********************************************************************
+ * ---------------------------------------------------------------------
+ * vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
+ *
+ * In a real-world situation, this is where you would place your query.
+ *
+ * For information on making queries in WordPress, see this Codex entry:
+ * http://codex.wordpress.org/Class_Reference/wpdb
+ *
+ * ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+ * ---------------------------------------------------------------------
+ * ********************************************************************
+ */
+
+ /**
+ * REQUIRED for pagination.
+ * Let's figure out what page the user is currently
+ * looking at. We'll need this later, so you should always include it in
+ * your own package classes.
+ */
+ $current_page = $this->get_pagenum();
+
+ /**
+ * REQUIRED for pagination.
+ * Let's check how many items are in our data array.
+ * In real-world use, this would be the total number of items in your database,
+ * without filtering. We'll need this later, so you should always include it
+ * in your own package classes.
+ */
+ $total_items = count( $data );
+
+ /**
+ * The WP_List_Table class does not handle pagination for us, so we need
+ * to ensure that the data is trimmed to only the current page.
+ * We can use
+ * array_slice() to
+ */
+ $data = array_slice( $data, (($current_page - 1) * $per_page), $per_page );
+
+ /**
+ * REQUIRED.
+ * Now we can add our *sorted* data to the items property, where
+ * it can be used by the rest of the class.
+ */
+ $this->items = $data;
+
+ /**
+ * REQUIRED.
+ * We also have to register our pagination options & calculations.
+ */
+ $this->set_pagination_args( array(
+ 'total_items' => $total_items, // WE have to calculate the total number of items
+ 'per_page' => $per_page, // WE have to determine how many items to show on a page
+ 'total_pages' => ceil( $total_items / $per_page ),
+ ) ); // WE have to calculate the total number of pages
+ }
+}
+