postman_wizard.js 15.4 KB
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 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569
var transports = [];

connectivtyTestResults = {};
portTestInProgress = false;

/**
 * Functions to run on document load
 */
jQuery(document).ready(function() {
	jQuery(postman_input_sender_email).focus();
	initializeJQuerySteps();
	// add an event on the plugin selection
	jQuery('input[name="input_plugin"]').click(function() {
		getConfiguration();
	});

	// add an event on the transport input field
	// when the user changes the transport, determine whether
	// to show or hide the SMTP Settings
	jQuery('select#input_transport_type').change(function() {
		hide('#wizard_oauth2_help');
		reloadOauthSection();
		switchBetweenPasswordAndOAuth();
	});

});

function checkGoDaddyAndCheckEmail(email) {
	hide('#godaddy_block');
	hide('#godaddy_spf_required');
	// are we hosted on GoDaddy? check.
	var data = {
		'action' : 'postman_wizard_port_test',
		'hostname' : 'relay-hosting.secureserver.net',
		'port' : 25,
		'timeout' : 3
	};
	goDaddy = 'unknown';
	checkedEmail = false;
	jQuery.post(ajaxurl, data, function(response) {
		if (postmanValidateAjaxResponseWithPopup(response)) {
			checkEmail(response.success, email);
		}
	}).fail(function(response) {
		ajaxFailed(response);
	});
}

function checkEmail(goDaddyHostDetected, email) {
	var data = {
		'action' : 'postman_check_email',
		'go_daddy' : goDaddyHostDetected,
		'email' : email
	};
	jQuery.post(
			ajaxurl,
			data,
			function(response) {
				if (postmanValidateAjaxResponseWithPopup(response)) {
					checkedEmail = true;
					smtpDiscovery = response.data;
					if (response.data.hostname != null
							&& response.data.hostname) {
						jQuery(postman_hostname_element_name).val(
								response.data.hostname);
					}
					enableSmtpHostnameInput(goDaddyHostDetected);
				}
			}).fail(function(response) {
		ajaxFailed(response);
	});
}

function enableSmtpHostnameInput(goDaddyHostDetected) {
	if (goDaddyHostDetected && !smtpDiscovery.is_google) {
		// this is a godaddy server and we are using a godaddy smtp server
		// (gmail excepted)
		if (smtpDiscovery.is_go_daddy) {
			// we detected GoDaddy, and the user has entered a GoDaddy hosted
			// email
		} else if (smtpDiscovery.is_well_known) {
			// this is a godaddy server but the SMTP must be the email
			// service
			show('#godaddy_block');
		} else {
			// this is a godaddy server and we're using a (possibly) custom
			// domain
			show('#godaddy_spf_required');
		}
	}
	enable('#input_hostname');
	jQuery('li').removeClass('disabled');
	hideLoaderIcon();
}

/**
 * Initialize the Steps wizard
 */
function initializeJQuerySteps() {
	jQuery("#postman_wizard").steps(
			{
				bodyTag : "fieldset",
				headerTag : "h5",
				transitionEffect : "slideLeft",
				stepsOrientation : "vertical",
				autoFocus : true,
				startIndex : parseInt(postman_setup_wizard.start_page),
				labels : {
					current : steps_current_step,
					pagination : steps_pagination,
					finish : steps_finish,
					next : steps_next,
					previous : steps_previous,
					loading : steps_loading
				},
				onStepChanging : function(event, currentIndex, newIndex) {
					return handleStepChange(event, currentIndex, newIndex,
							jQuery(this));

				},
				onInit : function() {
					jQuery(postman_input_sender_email).focus();
				},
				onStepChanged : function(event, currentIndex, priorIndex) {
					return postHandleStepChange(event, currentIndex,
							priorIndex, jQuery(this));
				},
				onFinishing : function(event, currentIndex) {
					var form = jQuery(this);

					// Disable validation on fields that
					// are disabled.
					// At this point it's recommended to
					// do an overall check (mean
					// ignoring
					// only disabled fields)
					// form.validate().settings.ignore =
					// ":disabled";

					// Start validation; Prevent form
					// submission if false
					return form.valid();
				},
				onFinished : function(event, currentIndex) {
					var form = jQuery(this);

					// Submit form input
					form.submit();
				}
			}).validate({
		errorPlacement : function(error, element) {
			element.before(error);
		}
	});
}

function handleStepChange(event, currentIndex, newIndex, form) {
	// Always allow going backward even if
	// the current step contains invalid fields!
	if (currentIndex > newIndex) {
		if (currentIndex === 2 && !(checkedEmail)) {
			return false;
		}
		if (currentIndex === 3 && portTestInProgress) {
			return false;
		}
		return true;
	}

	// Clean up if user went backward
	// before
	if (currentIndex < newIndex) {
		// To remove error styles
		jQuery(".body:eq(" + newIndex + ") label.error", form).remove();
		jQuery(".body:eq(" + newIndex + ") .error", form).removeClass("error");
	}

	// Disable validation on fields that
	// are disabled or hidden.
	form.validate().settings.ignore = ":disabled,:hidden";

	// Start validation; Prevent going
	// forward if false
	valid = form.valid();
	if (!valid) {
		return false;
	}

	if (currentIndex === 1) {
		// page 1 : look-up the email
		// address for the smtp server
		checkGoDaddyAndCheckEmail(jQuery(postman_input_sender_email).val());

	} else if (currentIndex === 2) {

		if (!(checkedEmail)) {
			return false;
		}
		// page 2 : check the port
		portsChecked = 0;
		portsToCheck = 0;
		totalAvail = 0;

		getHostsToCheck(jQuery(postman_hostname_element_name).val());

	} else if (currentIndex === 3) {

		// user has clicked next but we haven't finished the check
		if (portTestInProgress) {
			return false;
		}
		// or all ports are unavailable
		if (portCheckBlocksUi) {
			return false;
		}
		valid = form.valid();
		if (!valid) {
			return false;
		}
		var chosenPort = jQuery(postman_port_element_name).val();
		var hostname = jQuery(postman_hostname_element_name).val();
		var authType = jQuery(postman_input_auth_type).val()

	}

	return true;
}

function postHandleStepChange(event, currentIndex, priorIndex, myself) {
	var chosenPort = jQuery('#input_auth_type').val();
	// Suppress (skip) "Warning" step if
	// the user is old enough and wants
	// to the previous step.
	if (currentIndex === 2) {
		jQuery(postman_hostname_element_name).focus();
		// this is the second place i disable the next button but Steps
		// re-enables it after the screen slides
		if (priorIndex === 1) {
			disable('#input_hostname');
			jQuery('li').addClass('disabled');
			showLoaderIcon();
		}
	}
	if (currentIndex === 3) {
		if (priorIndex === 2) {
			// this is the second place i disable the next button but Steps
			// re-enables it after the screen slides
			jQuery('li').addClass('disabled');
			showLoaderIcon();
		}
	}
	if (currentIndex === 4) {
		if (redirectUrlWarning) {
			alert(postman_wizard_bad_redirect_url);
		}
		if (chosenPort == 'none') {
			if (priorIndex === 5) {

				myself.steps("previous");
				return;
			}
			myself.steps("next");
		}
	}

}

/**
 * Asks the server for a List of sockets to perform port checks upon.
 * 
 * @param hostname
 */
function getHostsToCheck(hostname) {
	jQuery('table#wizard_port_test').html('');
	jQuery('#wizard_recommendation').html('');
	hide('.user_override');
	hide('#smtp_not_secure');
	hide('#smtp_mitm');
	connectivtyTestResults = {};
	portCheckBlocksUi = true;
	portTestInProgress = true;
	var data = {
		'action' : 'postman_get_hosts_to_test',
		'hostname' : hostname,
		'original_smtp_server' : smtpDiscovery.hostname
	};
	jQuery.post(ajaxurl, data, function(response) {
		if (postmanValidateAjaxResponseWithPopup(response)) {
			handleHostsToCheckResponse(response.data);
		}
	}).fail(function(response) {
		ajaxFailed(response);
	});
}

/**
 * Handles the response from the server of the list of sockets to check.
 * 
 * @param hostname
 * @param response
 */
function handleHostsToCheckResponse(response) {
	for ( var x in response.hosts) {
		var hostname = response.hosts[x].host;
		var port = response.hosts[x].port;
		var transport = response.hosts[x].transport_id;
		portsToCheck++;
		show('#connectivity_test_status');
		updateStatus(postman_port_test.in_progress + " " + portsToCheck);
		var data = {
			'action' : 'postman_wizard_port_test',
			'hostname' : hostname,
			'port' : port,
			'transport' : transport
		};
		postThePortTest(hostname, port, data);
	}
}

/**
 * Asks the server to run a connectivity test on the given port
 * 
 * @param hostname
 * @param port
 * @param data
 */
function postThePortTest(hostname, port, data) {
	jQuery.post(ajaxurl, data, function(response) {
		if (postmanValidateAjaxResponseWithPopup(response)) {
			handlePortTestResponse(hostname, port, data, response);
		}
	}).fail(function(response) {
		ajaxFailed(response);
		portsChecked++;
		afterPortsChecked();
	});
}

/**
 * Handles the result of the port test
 * 
 * @param hostname
 * @param port
 * @param data
 * @param response
 */
function handlePortTestResponse(hostname, port, data, response) {
	if (!response.data.try_smtps) {
		portsChecked++;
		updateStatus(postman_port_test.in_progress + " "
				+ (portsToCheck - portsChecked));
		connectivtyTestResults[hostname + '_' + port] = response.data;
		if (response.success) {
			// a totalAvail > 0 is our signal to go to the next step
			totalAvail++;
		}
		afterPortsChecked();
	} else {
		// SMTP failed, try again on the SMTPS port
		data['action'] = 'postman_wizard_port_test_smtps';
		postThePortTest(hostname, port, data);
	}
}

/**
 * 
 * @param message
 */
function updateStatus(message) {
	jQuery('#port_test_status').html(
			'<span style="color:blue">' + message + '</span>');
}

/**
 * This functions runs after ALL the ports have been checked. It's chief
 * function is to push the results of the port test back to the server to get a
 * suggested configuration.
 */
function afterPortsChecked() {
	if (portsChecked >= portsToCheck) {
		hideLoaderIcon();
		if (totalAvail != 0) {
			jQuery('li').removeClass('disabled');
			portCheckBlocksUi = false;
		}
		var data = {
			'action' : 'get_wizard_configuration_options',
			'original_smtp_server' : smtpDiscovery.hostname,
			'host_data' : connectivtyTestResults
		};
		postTheConfigurationRequest(data);
		hide('#connectivity_test_status');
	}
}

function userOverrideMenu() {
	disable('input.user_socket_override');
	disable('input.user_auth_override');
	var data = {
		'action' : 'get_wizard_configuration_options',
		'original_smtp_server' : smtpDiscovery.hostname,
		'user_port_override' : jQuery(
				"input:radio[name='user_socket_override']:checked").val(),
		'user_auth_override' : jQuery(
				"input:radio[name='user_auth_override']:checked").val(),
		'host_data' : connectivtyTestResults
	};
	postTheConfigurationRequest(data);
}

function postTheConfigurationRequest(data) {
	jQuery.post(
			ajaxurl,
			data,
			function(response) {
				if (postmanValidateAjaxResponseWithPopup(response)) {
					portTestInProgress = false;
					var $message = '';
					if (response.success) {
						$message = '<span style="color:green">'
								+ response.data.configuration.message
								+ '</span>';
						handleConfigurationResponse(response.data);
						enable('input.user_socket_override');
						enable('input.user_auth_override');
						// enable both next/back buttons
						jQuery('li').removeClass('disabled');
					} else {
						$message = '<span style="color:red">'
								+ response.data.configuration.message
								+ '</span>';
						// enable the back button only
						jQuery('li').removeClass('disabled');
						jQuery('li + li').addClass('disabled');
					}
					if (!response.data.configuration.user_override) {
						jQuery('#wizard_recommendation').append($message);
					}
				}
			}).fail(function(response) {
		ajaxFailed(response);
	});
}
function handleConfigurationResponse(response) {
	jQuery('#input_transport_type').val(response.configuration.transport_type);
	transports.forEach(function(item) {
		item.handleConfigurationResponse(response);
	})

	// this stuff builds the options and is common to all transports
	// populate user Port Override menu
	show('.user_override');
	var el1 = jQuery('#user_socket_override');
	el1.html('');
	for (i = 0; i < response.override_menu.length; i++) {
		buildRadioButtonGroup(el1, 'user_socket_override',
				response.override_menu[i].selected,
				response.override_menu[i].value,
				response.override_menu[i].description,
				response.override_menu[i].secure);
		// populate user Auth Override menu
		if (response.override_menu[i].selected) {
			if (response.override_menu[i].mitm) {
				show('#smtp_mitm');
				jQuery('#smtp_mitm')
						.html(
								sprintf(
										postman_port_test.mitm,
										response.override_menu[i].reported_hostname_domain_only,
										response.override_menu[i].hostname_domain_only));
			} else {
				hide('#smtp_mitm');
			}
			var el2 = jQuery('#user_auth_override');
			el2.html('');
			hide('#smtp_not_secure');
			for (j = 0; j < response.override_menu[i].auth_items.length; j++) {
				buildRadioButtonGroup(el2, 'user_auth_override',
						response.override_menu[i].auth_items[j].selected,
						response.override_menu[i].auth_items[j].value,
						response.override_menu[i].auth_items[j].name, false);
				if (response.override_menu[i].auth_items[j].selected
						&& !response.override_menu[i].secure
						&& response.override_menu[i].auth_items[j].value != 'none') {
					show('#smtp_not_secure');
				}
			}
			// add an event on the user port override field
			jQuery('input.user_auth_override').change(function() {
				userOverrideMenu();
			});
		}

	}
	// add an event on the user port override field
	jQuery('input.user_socket_override').change(function() {
		userOverrideMenu();
	});
}

function buildRadioButtonGroup(tableElement, radioGroupName, isSelected, value,
		label, isSecure) {
	var radioInputValue = ' value="' + value + '"';
	var radioInputChecked = '';
	if (isSelected) {
		radioInputChecked = ' checked = "checked"';
	}
	var secureIcon = '';
	if (isSecure) {
		secureIcon = '&#x1f512; ';
	}
	tableElement.append('<tr><td><input class="' + radioGroupName
			+ '" type="radio" name="' + radioGroupName + '"'
			+ radioInputChecked + radioInputValue + '/></td><td>' + secureIcon
			+ label + '</td></tr>');
}

/**
 * Handles population of the configuration based on the options set in a
 * 3rd-party SMTP plugin
 */
function getConfiguration() {
	var plugin = jQuery('input[name="input_plugin"]' + ':checked').val();
	if (plugin != '') {
		var data = {
			'action' : 'import_configuration',
			'plugin' : plugin
		};
		jQuery
				.post(
						ajaxurl,
						data,
						function(response) {
							if (response.success) {
								jQuery('select#input_transport_type').val(
										'smtp');
								jQuery(postman_input_sender_email).val(
										response.sender_email);
								jQuery(postman_input_sender_name).val(
										response.sender_name);
								jQuery(postman_hostname_element_name).val(
										response.hostname);
								jQuery(postman_port_element_name).val(
										response.port);
								jQuery(postman_input_auth_type).val(
										response.auth_type);
								jQuery('#input_enc_type')
										.val(response.enc_type);
								jQuery(postman_input_basic_username).val(
										response.basic_auth_username);
								jQuery(postman_input_basic_password).val(
										response.basic_auth_password);
								switchBetweenPasswordAndOAuth();
							}
						}).fail(function(response) {
					ajaxFailed(response);
				});
	} else {
		jQuery(postman_input_sender_email).val('');
		jQuery(postman_input_sender_name).val('');
		jQuery(postman_input_basic_username).val('');
		jQuery(postman_input_basic_password).val('');
		jQuery(postman_hostname_element_name).val('');
		jQuery(postman_port_element_name).val('');
		jQuery(postman_input_auth_type).val('none');
		jQuery(postman_enc_for_password_el).val('none');
		switchBetweenPasswordAndOAuth();
	}
}