summaryrefslogtreecommitdiff
path: root/Postman/Postman-Email-Log/PostmanEmailLogService.php
blob: e5c4bfef33681e93736bf22ef1fa41ebd149f6f6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
<?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 ) {

			$this->checkForLogErrors( $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() );
		}

		private function checkForLogErrors( PostmanEmailLog $log ) {
			if ( $log->statusMessage && ! empty( $log->statusMessage ) ) {
				mail( get_bloginfo( 'admin_email' ), __( 'Post SMTP email error', Postman::TEXT_DOMAIN ), $log->statusMessage );
			}

			if ( strpos( strtolower( $log->sessionTranscript ), 'error' ) !== false ) {
				mail( get_bloginfo( 'admin_email' ), __( 'Post SMTP session transcript error', Postman::TEXT_DOMAIN ), $log->sessionTranscript );
			}
		}

		/**
		 * 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 );
			}
		}
	}
}