summaryrefslogtreecommitdiff
path: root/Postman/PostmanAdminController.php
blob: 1e43c6de2aa4f0e4d899bdaf5099e680be8b48c4 (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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
<?php
if ( ! defined( 'ABSPATH' ) ) {
    exit; // Exit if accessed directly
}

if ( ! class_exists( 'PostmanAdminController' ) ) {

	require_once 'PostmanOptions.php';
	require_once 'PostmanState.php';
	require_once 'PostmanState.php';
	require_once 'PostmanOAuthToken.php';
	require_once 'Postman-Connectivity-Test/Postman-PortTest.php';
	require_once 'Postman-Configuration/PostmanSmtpDiscovery.php';
	require_once 'PostmanInputSanitizer.php';
	require_once 'Postman-Configuration/PostmanImportableConfiguration.php';
	require_once 'PostmanConfigTextHelper.php';
	require_once 'PostmanAjaxController.php';
	require_once 'PostmanViewController.php';
	require_once 'PostmanPreRequisitesCheck.php';
	require_once 'Postman-Auth/PostmanAuthenticationManagerFactory.php';

	class PostmanAdminController {

		// this is the slug used in the URL
		const MANAGE_OPTIONS_PAGE_SLUG = 'postman/manage-options';

		// NONCE NAMES
		const PURGE_DATA_SLUG = 'postman_purge_data';
		const IMPORT_SETTINGS_SLUG = 'postman_import_settings';

		// The Postman Group is used for saving data, make sure it is globally unique
		const SETTINGS_GROUP_NAME = 'postman_group';

		// a database entry specifically for the form that sends test e-mail
		const TEST_OPTIONS = 'postman_test_options';
		const SMTP_OPTIONS = 'postman_smtp_options';
		const SMTP_SECTION = 'postman_smtp_section';
		const BASIC_AUTH_OPTIONS = 'postman_basic_auth_options';
		const BASIC_AUTH_SECTION = 'postman_basic_auth_section';
		const OAUTH_AUTH_OPTIONS = 'postman_oauth_options';
		const OAUTH_SECTION = 'postman_oauth_section';
		const MESSAGE_SENDER_OPTIONS = 'postman_message_sender_options';
		const MESSAGE_SENDER_SECTION = 'postman_message_sender_section';
		const MESSAGE_FROM_OPTIONS = 'postman_message_from_options';
		const MESSAGE_FROM_SECTION = 'postman_message_from_section';
		const MESSAGE_OPTIONS = 'postman_message_options';
		const MESSAGE_SECTION = 'postman_message_section';
		const MESSAGE_HEADERS_OPTIONS = 'postman_message_headers_options';
		const MESSAGE_HEADERS_SECTION = 'postman_message_headers_section';
		const NETWORK_OPTIONS = 'postman_network_options';
		const NETWORK_SECTION = 'postman_network_section';
		const LOGGING_OPTIONS = 'postman_logging_options';
		const LOGGING_SECTION = 'postman_logging_section';
		const MULTISITE_OPTIONS = 'postman_multisite_options';
		const MULTISITE_SECTION = 'postman_multisite_section';
		const ADVANCED_OPTIONS = 'postman_advanced_options';
		const ADVANCED_SECTION = 'postman_advanced_section';
		const NOTIFICATIONS_OPTIONS = 'postman_notifications_options';
		const NOTIFICATIONS_SECTION = 'postman_notifications_section';
		const NOTIFICATIONS_PUSHOVER_CRED = 'postman_pushover_cred';
		const NOTIFICATIONS_SLACK_CRED = 'postman_slack_cred';
		const EMAIL_VALIDATION_SECTION = 'postman_email_validation_section';
		const EMAIL_VALIDATION_OPTIONS = 'postman_email_validation_options';

		// slugs
		const POSTMAN_TEST_SLUG = 'postman-test';

		// logging
		private $logger;

		// Holds the values to be used in the fields callbacks
		private $rootPluginFilenameAndPath;
		private $options;
		private $authorizationToken;
		private $importableConfiguration;

		// helpers
		private $messageHandler;
		private $oauthScribe;
		private $wpMailBinder;

		/**
		 * Constructor
		 *
		 * @param mixed               $rootPluginFilenameAndPath
		 * @param PostmanOptions        $options
		 * @param PostmanOAuthToken     $authorizationToken
		 * @param PostmanMessageHandler $messageHandler
		 * @param PostmanWpMailBinder   $binder
		 */
		public function __construct( $rootPluginFilenameAndPath, PostmanOptions $options, PostmanOAuthToken $authorizationToken, PostmanMessageHandler $messageHandler, PostmanWpMailBinder $binder ) {
			assert( ! empty( $rootPluginFilenameAndPath ) );
			assert( ! empty( $options ) );
			assert( ! empty( $authorizationToken ) );
			assert( ! empty( $messageHandler ) );
			assert( ! empty( $binder ) );
			assert( PostmanUtils::isAdmin() );
			assert( is_admin() );

			$this->logger = new PostmanLogger( get_class( $this ) );
			$this->options = $options;
			$this->authorizationToken = $authorizationToken;
			$this->messageHandler = $messageHandler;
			$this->rootPluginFilenameAndPath = $rootPluginFilenameAndPath;
			$this->wpMailBinder = $binder;

			// check if the user saved data, and if validation was successful
			$session = PostmanSession::getInstance();
			if ( $session->isSetAction() ) {
				$this->logger->debug( sprintf( 'session action: %s', $session->getAction() ) );
			}
			if ( $session->getAction() == PostmanInputSanitizer::VALIDATION_SUCCESS ) {
				// unset the action
				$session->unsetAction();
				// do a redirect on the init hook
				$this->registerInitFunction( 'handleSuccessfulSave' );
				// add a saved message to be shown after the redirect
				$this->messageHandler->addMessage( _x( 'Settings saved.', 'The plugin successfully saved new settings.', 'post-smtp' ) );
				return;
			} else {
				// unset the action in the failed case as well
				$session->unsetAction();
			}

			// test to see if an OAuth authentication is in progress
			if ( $session->isSetOauthInProgress() ) {
				// there is only a three minute window that Postman will expect a Grant Code, once Grant is clicked by the user
				$this->logger->debug( 'Looking for grant code' );
				if ( isset( $_GET ['code'] ) ) {
					$this->logger->debug( 'Found authorization grant code' );

					// queue the function that processes the incoming grant code
					$this->registerInitFunction( 'handleAuthorizationGrant' );
					return;
				}
			}
            do_action('post_smtp_handle_oauth', $this->messageHandler );

			// continue to initialize the AdminController
			add_action( 'init', array(
					$this,
					'on_init',
			) );

            // continue to initialize the AdminController
            add_action( 'wpmu_options', array(
                $this,
                'wpmu_options',
            ) );

            add_action( 'update_wpmu_options', array(
                $this,
                'update_wpmu_options',
            ) );

			// Adds "Settings" link to the plugin action page
			add_filter( 'plugin_action_links_' . plugin_basename( $this->rootPluginFilenameAndPath ), array(
					$this,
					'postmanModifyLinksOnPluginsListPage',
			) );

			require_once( 'PostmanPluginFeedback.php' );
		}


		function wpmu_options() {
		    $options = get_site_option( PostmanOptions::POSTMAN_NETWORK_OPTIONS );
		    ?>
            <input type="hidden" name="<?php echo PostmanOptions::POSTMAN_NETWORK_OPTIONS; ?>[post_smtp_global_settings]" value="null">
            <input type="hidden" name="<?php echo PostmanOptions::POSTMAN_NETWORK_OPTIONS; ?>[post_smtp_allow_overwrite]" value="null">
            <h2><?php _e( 'Post SMTP Settings', 'post-smtp' ); ?></h2>
            <table id="menu" class="form-table">
                <tr>
                    <th scope="row">
                        <?php _e( 'Enable global settings', 'post-smtp' ); ?>
                    </th>
                    <td>
                        <?php $checked = checked( $options['post_smtp_global_settings'], 1, false ); ?>
                        <label for="post-smtp-global-settings">
                            <input id="post-smtp-global-settings" type="checkbox"
                                   name="<?php echo PostmanOptions::POSTMAN_NETWORK_OPTIONS; ?>[post_smtp_global_settings]"
                                   value="1"
                                   <?php echo $checked; ?>
                            >
                            <p class="description">
                                <?php _e('Same settings as the main site/blog (id:1)', 'post-smtp' ); ?>
                            </p>
                        </label>
                    </td>
                </tr>
                <tr>
                    <th scope="row">
                        <?php _e( 'Allow user to load saved options', 'post-smtp' ); ?>
                    </th>
                    <td>
                        <?php $checked = checked( $options['post_smtp_allow_overwrite'], 1, false ); ?>
                        <label for="post-smtp-allow-overwrite">
                            <input id="post-smtp-allow-overwrite" type="checkbox"
                                   name="<?php echo PostmanOptions::POSTMAN_NETWORK_OPTIONS; ?>[post_smtp_allow_overwrite]"
                                   value="1"
                                <?php echo $checked; ?>
                            >
                        </label>
                    </td>
                </tr>
            </table>
            <?php
        }

        function update_wpmu_options() {
            $options = get_site_option( PostmanOptions::POSTMAN_NETWORK_OPTIONS );
		    if ( isset( $_POST[ PostmanOptions::POSTMAN_NETWORK_OPTIONS ] ) ) {
		        foreach ( $_POST[ PostmanOptions::POSTMAN_NETWORK_OPTIONS ] as $key => $value ) {
                    $options[$key] = sanitize_text_field( $value );

                    if ( $value == 'null' ) {
                        unset( $options[$key] );
                    }
                }

                update_site_option( PostmanOptions::POSTMAN_NETWORK_OPTIONS, $options );
            } else {
                update_site_option( PostmanOptions::POSTMAN_NETWORK_OPTIONS, array() );
            }
        }

		/**
		 * Functions to execute on the init event
		 *
		 * "Typically used by plugins to initialize. The current user is already authenticated by this time."
		 * ref: http://codex.wordpress.org/Plugin_API/Action_Reference#Actions_Run_During_a_Typical_Request
		 */
		public function on_init() {
			// only administrators should be able to trigger this
			if ( PostmanUtils::isAdmin() ) {
								$transport = PostmanTransportRegistry::getInstance()->getCurrentTransport();
				$this->oauthScribe = $transport->getScribe();

				// register content handlers
				$viewController = new PostmanViewController( $this->rootPluginFilenameAndPath, $this->options, $this->authorizationToken, $this->oauthScribe, $this );

				// register action handlers
				$this->registerAdminPostAction( self::PURGE_DATA_SLUG, 'handlePurgeDataAction' );
				$this->registerAdminPostAction( self::IMPORT_SETTINGS_SLUG, 'importSettingsAction' );
				$this->registerAdminPostAction( PostmanUtils::REQUEST_OAUTH2_GRANT_SLUG, 'handleOAuthPermissionRequestAction' );

				if ( PostmanUtils::isCurrentPagePostmanAdmin() ) {
					$this->checkPreRequisites();
				}
			}
		}

		/**
		 *
		 */
		private function checkPreRequisites() {
			$states = PostmanPreRequisitesCheck::getState();
			foreach ( $states as $state ) {
				if ( ! $state ['ready'] ) {
					/* Translators: where %1$s is the name of the library */
					$message = sprintf( __( 'This PHP installation requires the <b>%1$s</b> library.', 'post-smtp' ), $state ['name'] );
					if ( $state ['required'] ) {
						$this->messageHandler->addError( $message );
					} else {
						// $this->messageHandler->addWarning ( $message );
					}
				}
			}
		}

		/**
		 *
		 * @param mixed $actionName
		 * @param mixed $callbackName
		 */
		private function registerInitFunction( $callbackName ) {
			$this->logger->debug( 'Registering init function ' . $callbackName );
			add_action( 'init', array(
					$this,
					$callbackName,
			) );
		}

		/**
		 * Registers actions posted by am HTML FORM with the WordPress 'action' parameter
		 *
		 * @param mixed $actionName
		 * @param mixed $callbankName
		 */
		private function registerAdminPostAction( $actionName, $callbankName ) {
			// $this->logger->debug ( 'Registering ' . $actionName . ' Action Post handler' );
			add_action( 'admin_post_' . $actionName, array(
					$this,
					$callbankName,
			) );
		}

		/**
		 * Add "Settings" link to the plugin action page
		 *
		 * @param mixed $links
		 * @return multitype:
		 */
		public function postmanModifyLinksOnPluginsListPage( $links ) {
			// only administrators should be able to trigger this
			if ( PostmanUtils::isAdmin() ) {
				$mylinks = array(
                        sprintf( '<a href="%s" target="_blank" class="postman_settings">%s</a>', 'https://www.paypal.com/cgi-bin/webscr?cmd=_xclick&business=yehuda@myinbox.in&item_name=Donation+for+PostSMTP', __( 'Donate', 'post-smtp' ) ),
						sprintf( '<a href="%s" class="postman_settings">%s</a>', PostmanUtils::getSettingsPageUrl(), __( 'Settings', 'post-smtp' ) ),
						sprintf( '<a href="%s" class="postman_settings">%s</a>', 'https://postmansmtp.com', __( 'Visit us', 'post-smtp' ) ),
				);
				return array_merge( $mylinks, $links );
			}
		}

		/**
		 * This function runs after a successful, error-free save
		 */
		public function handleSuccessfulSave() {
			// WordPress likes to keep GET parameters around for a long time
			// (something in the call to settings_fields() does this)
			// here we redirect after a successful save to clear those parameters
			PostmanUtils::redirect( PostmanUtils::POSTMAN_HOME_PAGE_RELATIVE_URL );
		}

		/**
		 * This function handle the request to import plugin data
		 */
		public function importSettingsAction() {
			$this->logger->debug( 'is wpnonce import-settings?' );
			$success = true;
			if ( wp_verify_nonce( $_REQUEST ['_wpnonce'], PostmanAdminController::IMPORT_SETTINGS_SLUG ) ) {
				$success = PostmanOptions::getInstance()->import( sanitize_textarea_field($_POST ['settings']) );
			} else {
				$success = false;
			}
			if ( ! $success ) {
				$this->messageHandler->addError( __( 'There was an error importing the data.', 'post-smtp' ) );
				$this->logger->error( 'There was an error importing the data' );
			}
			PostmanUtils::redirect( PostmanUtils::POSTMAN_HOME_PAGE_RELATIVE_URL );
		}
		/**
		 * This function handle the request to purge plugin data
		 */
		public function handlePurgeDataAction() {
			$this->logger->debug( 'is wpnonce purge-data?' );
			if ( wp_verify_nonce( $_REQUEST ['_wpnonce'], PostmanAdminController::PURGE_DATA_SLUG ) ) {
				$this->logger->debug( 'Purging stored data' );
				delete_option( PostmanOptions::POSTMAN_OPTIONS );
				delete_option( PostmanOAuthToken::OPTIONS_NAME );
				delete_option( PostmanAdminController::TEST_OPTIONS );
				$logPurger = new PostmanEmailLogPurger();
				$logPurger->removeAll();
				$this->messageHandler->addMessage( __( 'Plugin data was removed.', 'post-smtp' ) );
				PostmanUtils::redirect( PostmanUtils::POSTMAN_HOME_PAGE_RELATIVE_URL );
			}
		}

		/**
		 * Handles the authorization grant
		 */
		function handleAuthorizationGrant() {
			$logger = $this->logger;
			$options = $this->options;
			$authorizationToken = $this->authorizationToken;
			$logger->debug( 'Authorization in progress' );
			$transactionId = PostmanSession::getInstance()->getOauthInProgress();

			// begin transaction
			PostmanUtils::lock();

			$authenticationManager = PostmanAuthenticationManagerFactory::getInstance()->createAuthenticationManager();
			try {
				if ( $authenticationManager->processAuthorizationGrantCode( $transactionId ) ) {
					$logger->debug( 'Authorization successful' );
					// save to database
					$authorizationToken->save();
					$this->messageHandler->addMessage( __( 'The OAuth 2.0 authorization was successful. Ready to send e-mail.', 'post-smtp' ) );
				} else {
					$this->messageHandler->addError( __( 'Your email provider did not grant Postman permission. Try again.', 'post-smtp' ) );
				}
			} catch ( PostmanStateIdMissingException $e ) {
				$this->messageHandler->addError( __( 'The grant code from Google had no accompanying state and may be a forgery', 'post-smtp' ) );
			} catch ( Exception $e ) {
				$logger->error( 'Error: ' . get_class( $e ) . ' code=' . $e->getCode() . ' message=' . $e->getMessage() );
				/* translators: %s is the error message */
				$this->messageHandler->addError( sprintf( __( 'Error authenticating with this Client ID. [%s]', 'post-smtp' ), '<em>' . $e->getMessage() . '</em>' ) );
			}

			// clean-up
			PostmanUtils::unlock();
			PostmanSession::getInstance()->unsetOauthInProgress();

			// redirect home
			PostmanUtils::redirect( PostmanUtils::POSTMAN_HOME_PAGE_RELATIVE_URL );
		}

		/**
		 * This method is called when a user clicks on a "Request Permission from Google" link.
		 * This link will create a remote API call for Google and redirect the user from WordPress to Google.
		 * Google will redirect back to WordPress after the user responds.
		 */
		public function handleOAuthPermissionRequestAction() {
			$this->logger->debug( 'handling OAuth Permission request' );
			$authenticationManager = PostmanAuthenticationManagerFactory::getInstance()->createAuthenticationManager();
			$transactionId = $authenticationManager->generateRequestTransactionId();
			PostmanSession::getInstance()->setOauthInProgress( $transactionId );
			$authenticationManager->requestVerificationCode( $transactionId );
		}
	}
}