summaryrefslogtreecommitdiff
path: root/Postman/Postman-Email-Log
diff options
context:
space:
mode:
authoryehudah <yehudah@b8457f37-d9ea-0310-8a92-e5e31aec5664>2017-10-15 06:46:12 +0000
committeryehudah <yehudah@b8457f37-d9ea-0310-8a92-e5e31aec5664>2017-10-15 06:46:12 +0000
commitca6c8f41c1a2b9a4b5acae91419a6a114e1c77c6 (patch)
tree40ff112761d82af1d8c1c89d30ede8206502e17b /Postman/Postman-Email-Log
parent8812fbf61bde539d1599e239044595ccb8a2c3a5 (diff)
downloadPost-SMTP-ca6c8f41c1a2b9a4b5acae91419a6a114e1c77c6.zip
release
Diffstat (limited to 'Postman/Postman-Email-Log')
-rw-r--r--Postman/Postman-Email-Log/PostmanEmailLogController.php356
-rw-r--r--Postman/Postman-Email-Log/PostmanEmailLogPostType.php48
-rw-r--r--Postman/Postman-Email-Log/PostmanEmailLogService.php279
-rw-r--r--Postman/Postman-Email-Log/PostmanEmailLogView.php419
4 files changed, 1102 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..2aacba6
--- /dev/null
+++ b/Postman/Postman-Email-Log/PostmanEmailLogController.php
@@ -0,0 +1,356 @@
+<?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'
+ ) );
+ } 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'] );
+ }
+
+ /**
+ */
+ public function resendMail() {
+ // get the email address of the recipient from the HTTP Request
+ $postid = $this->getRequestParameter ( 'email' );
+ if (! empty ( $postid )) {
+ $post = get_post ( $postid );
+ $meta_values = get_post_meta ( $postid );
+
+ $success = wp_mail ( $meta_values ['original_to'] [0], $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 :)', Postman::TEXT_DOMAIN ), $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 unknown $parameterName
+ * @return unknown
+ */
+ 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', $_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 = $_REQUEST ['email_log_entry'];
+ foreach ( $postids as $postid ) {
+ $purger->verifyLogItemExistsAndRemove ( $postid );
+ }
+ $mh = new PostmanMessageHandler ();
+ $mh->addMessage ( __ ( 'Mail Log Entries were deleted.', Postman::TEXT_DOMAIN ) );
+ } else {
+ $this->logger->warn ( sprintf ( 'action "%s" not recognized', $_REQUEST ['action'] ) );
+ }
+ } else {
+ $this->logger->warn ( sprintf ( 'nonce "%s" failed validation', $_REQUEST ['_wpnonce'] ) );
+ }
+ $this->redirectToLogPage ();
+ }
+ }
+
+ /**
+ */
+ function delete_log_item() {
+ // only do this for administrators
+ if (PostmanUtils::isAdmin ()) {
+ $this->logger->trace ( 'handling delete item' );
+ $postid = $_REQUEST ['email'];
+ if (wp_verify_nonce ( $_REQUEST ['_wpnonce'], 'delete_email_log_item_' . $postid )) {
+ $this->logger->trace ( sprintf ( 'nonce "%s" passed validation', $_REQUEST ['_wpnonce'] ) );
+ $purger = new PostmanEmailLogPurger ();
+ $purger->verifyLogItemExistsAndRemove ( $postid );
+ $mh = new PostmanMessageHandler ();
+ $mh->addMessage ( __ ( 'Mail Log Entry was deleted.', Postman::TEXT_DOMAIN ) );
+ } else {
+ $this->logger->warn ( sprintf ( 'nonce "%s" failed validation', $_REQUEST ['_wpnonce'] ) );
+ }
+ $this->redirectToLogPage ();
+ }
+ }
+
+ /**
+ */
+ function view_log_item() {
+ // only do this for administrators
+ if (PostmanUtils::isAdmin ()) {
+ $this->logger->trace ( 'handling view item' );
+ $postid = $_REQUEST ['email'];
+ $post = get_post ( $postid );
+ $meta_values = get_post_meta ( $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?', Postman::TEXT_DOMAIN ), 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?', Postman::TEXT_DOMAIN ), 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?', Postman::TEXT_DOMAIN ), 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?', Postman::TEXT_DOMAIN ), 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', Postman::TEXT_DOMAIN ), 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?', Postman::TEXT_DOMAIN ), $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?', Postman::TEXT_DOMAIN ), 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?', Postman::TEXT_DOMAIN ), esc_html ( $meta_values ['transport_uri'] [0] ) );
+ }
+ print '</table>';
+ print '<hr/>';
+ print '<pre>';
+ print esc_html ( $post->post_content );
+ print '</pre>';
+ print '</body></html>';
+ die ();
+ }
+ }
+
+ /**
+ */
+ function view_transcript_log_item() {
+ // only do this for administrators
+ if (PostmanUtils::isAdmin ()) {
+ $this->logger->trace ( 'handling view transcript item' );
+ $postid = $_REQUEST ['email'];
+ $post = get_post ( $postid );
+ $meta_values = get_post_meta ( $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.', Postman::TEXT_DOMAIN ) );
+ 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', Postman::TEXT_DOMAIN );
+ }
+ 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 */
+ $page = add_management_page ( sprintf ( __ ( '%s Email Log', Postman::TEXT_DOMAIN ), __ ( 'Postman SMTP', Postman::TEXT_DOMAIN ) ), _x ( 'Email Log', 'The log of Emails that have been delivered', Postman::TEXT_DOMAIN ), 'read_private_posts', '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)', Postman::TEXT_DOMAIN ) );
+ /* 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', Postman::TEXT_DOMAIN ) );
+ wp_localize_script ( 'postman_resend_email_script', 'postman_js_resend_label', __ ( 'Resend', Postman::TEXT_DOMAIN ) );
+ }
+
+ /**
+ * *************************** 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', Postman::TEXT_DOMAIN ), __ ( 'Postman SMTP', Postman::TEXT_DOMAIN ) )?></h2>
+
+ <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.', Postman::TEXT_DOMAIN )?></p>
+ </div>
+
+ <!-- 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..d45f92d
--- /dev/null
+++ b/Postman/Postman-Email-Log/PostmanEmailLogPostType.php
@@ -0,0 +1,48 @@
+<?php
+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', Postman::TEXT_DOMAIN ),
+ 'singular_name' => _x ( 'Sent Email', 'An Email that has been delivered', Postman::TEXT_DOMAIN )
+ ),
+ '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..b6dd98b
--- /dev/null
+++ b/Postman/Postman-Email-Log/PostmanEmailLogService.php
@@ -0,0 +1,279 @@
+<?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;
+ }
+}
+
+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 unknown $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', Postman::TEXT_DOMAIN ), __ ( 'An empty subject line can result in delivery failure.', Postman::TEXT_DOMAIN ) );
+ $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 unknown $transcript
+ * @param PostmanModuleTransport $transport
+ * @param unknown $statusMessage
+ * @param unknown $originalTo
+ * @param unknown $originalSubject
+ * @param unknown $originalMessage
+ * @param unknown $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 );
+ }
+ }
+
+ /**
+ * 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) {
+ // 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' => $log->statusMessage,
+ '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 );
+ $this->logger->debug ( sprintf ( 'Saved message #%s to the database', $post_id ) );
+ $this->logger->trace ( $log );
+
+ // Write the meta data related to the email
+ update_post_meta ( $post_id, 'success', $log->success );
+ update_post_meta ( $post_id, 'from_header', $log->sender );
+ if (! empty ( $log->toRecipients )) {
+ update_post_meta ( $post_id, 'to_header', $log->toRecipients );
+ }
+ if (! empty ( $log->ccRecipients )) {
+ update_post_meta ( $post_id, 'cc_header', $log->ccRecipients );
+ }
+ if (! empty ( $log->bccRecipients )) {
+ update_post_meta ( $post_id, 'bcc_header', $log->bccRecipients );
+ }
+ if (! empty ( $log->replyTo )) {
+ update_post_meta ( $post_id, 'reply_to_header', $log->replyTo );
+ }
+ update_post_meta ( $post_id, 'transport_uri', $log->transportUri );
+
+ if (! $log->success || true) {
+ // alwas add the meta data so we can re-send it
+ update_post_meta ( $post_id, 'original_to', $log->originalTo );
+ update_post_meta ( $post_id, 'original_subject', $log->originalSubject );
+ update_post_meta ( $post_id, 'original_message', $log->originalMessage );
+ update_post_meta ( $post_id, 'original_headers', $log->originalHeaders );
+ }
+
+ // we do not sanitize the session transcript - let the reader decide how to handle the data
+ update_post_meta ( $post_id, 'session_transcript', $log->sessionTranscript );
+
+ // truncate the log (remove older entries)
+ $purger = new PostmanEmailLogPurger ();
+ $purger->truncateLogItems ( PostmanOptions::getInstance ()->getMailLoggingMaxEntries () );
+ }
+
+ /**
+ * Creates a Log object for use by writeToEmailLog()
+ *
+ * @param PostmanMessage $message
+ * @param unknown $transcript
+ * @param unknown $statusMessage
+ * @param unknown $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', Postman::TEXT_DOMAIN ), 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 unknown
+ */
+ function __construct() {
+ $this->logger = new PostmanLogger ( get_class ( $this ) );
+ $args = array (
+ 'posts_per_page' => 1000,
+ '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
+ );
+ $this->posts = get_posts ( $args );
+ }
+
+ /**
+ *
+ * @param array $posts
+ * @param unknown $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 unknown $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..ef06a29
--- /dev/null
+++ b/Postman/Postman-Email-Log/PostmanEmailLogView.php
@@ -0,0 +1,419 @@
+<?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 '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 = get_post_meta ( $item ['ID'] );
+
+ $actions = array (
+ 'delete' => sprintf ( '<a href="%s">%s</a>', $deleteUrl, _x ( 'Delete', 'Delete an item from the email log', Postman::TEXT_DOMAIN ) ),
+ 'view' => sprintf ( '<a href="%s" class="thickbox">%s</a>', $viewUrl, _x ( 'View', 'View an item from the email log', Postman::TEXT_DOMAIN ) )
+ );
+
+ if (! empty ( $meta_values ['session_transcript'] [0] )) {
+ $actions ['transcript'] = sprintf ( '<a href="%1$s" class="thickbox">%2$s</a>', $transcriptUrl, __ ( 'Session Transcript', Postman::TEXT_DOMAIN ) );
+ } else {
+ $actions ['transcript'] = sprintf ( '%2$s', $transcriptUrl, __ ( 'Session Transcript', Postman::TEXT_DOMAIN ) );
+ }
+ if (! (empty ( $meta_values ['original_to'] [0] ) && empty ( $meta_values ['originalHeaders'] [0] ))) {
+ // $actions ['resend'] = sprintf ( '<a href="%s">%s</a>', $resendUrl, __ ( 'Resend', Postman::TEXT_DOMAIN ) );
+ $actions ['resend'] = sprintf ( '<span id="%3$s"><a href="javascript:postman_resend_email(%1$s);">%2$s</a></span>', $item ['ID'], __ ( 'Resend', Postman::TEXT_DOMAIN ), 'resend-' . $item ['ID'] );
+ } else {
+ $actions ['resend'] = sprintf ( '%2$s', $resendUrl, __ ( 'Resend', Postman::TEXT_DOMAIN ) );
+ }
+
+ // 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?', Postman::TEXT_DOMAIN ),
+ 'status' => __ ( 'Status', Postman::TEXT_DOMAIN ),
+ 'date' => _x ( 'Delivery Time', 'When was this email sent?', Postman::TEXT_DOMAIN )
+ );
+ 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', Postman::TEXT_DOMAIN )
+ );
+ 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() {
+
+ /**
+ * First, lets decide how many records per page to show
+ */
+ $per_page = 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' => 1000,
+ '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
+ );
+ $posts = get_posts ( $args );
+ foreach ( $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"', Postman::TEXT_DOMAIN ), $humanTime );
+ }
+ $flattenedPost = array (
+ // the post title must be escaped as they are displayed in the HTML output
+ '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', Postman::TEXT_DOMAIN )),
+ 'date' => $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'] )) ? $_REQUEST ['orderby'] : 'title'; // If no sort, default to title
+ $order = (! empty ( $_REQUEST ['order'] )) ? $_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
+ }
+}
+