class-wc-ajax.php 73.5 KB
Newer Older
imac's avatar
imac committed
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 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380
<?php

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * WooCommerce WC_AJAX.
 *
 * AJAX Event Handler.
 *
 * @class    WC_AJAX
 * @package  WooCommerce/Classes
 * @category Class
 * @author   WooThemes
 */
class WC_AJAX {

	/**
	 * Hook in ajax handlers.
	 */
	public static function init() {
		add_action( 'init', array( __CLASS__, 'define_ajax' ), 0 );
		add_action( 'template_redirect', array( __CLASS__, 'do_wc_ajax' ), 0 );
		self::add_ajax_events();
	}

	/**
	 * Get WC Ajax Endpoint.
	 *
	 * @param  string $request Optional
	 * @return string
	 */
	public static function get_endpoint( $request = '' ) {
		return esc_url_raw( apply_filters( 'woocommerce_ajax_get_endpoint', add_query_arg( 'wc-ajax', $request, remove_query_arg( array( 'remove_item', 'add-to-cart', 'added-to-cart' ) ) ), $request ) );
	}

	/**
	 * Set WC AJAX constant and headers.
	 */
	public static function define_ajax() {
		if ( ! empty( $_GET['wc-ajax'] ) ) {
			wc_maybe_define_constant( 'DOING_AJAX', true );
			wc_maybe_define_constant( 'WC_DOING_AJAX', true );
			if ( ! WP_DEBUG || ( WP_DEBUG && ! WP_DEBUG_DISPLAY ) ) {
				@ini_set( 'display_errors', 0 ); // Turn off display_errors during AJAX events to prevent malformed JSON
			}
			$GLOBALS['wpdb']->hide_errors();
		}
	}

	/**
	 * Send headers for WC Ajax Requests.
	 *
	 * @since 2.5.0
	 */
	private static function wc_ajax_headers() {
		send_origin_headers();
		@header( 'Content-Type: text/html; charset=' . get_option( 'blog_charset' ) );
		@header( 'X-Robots-Tag: noindex' );
		send_nosniff_header();
		nocache_headers();
		status_header( 200 );
	}

	/**
	 * Check for WC Ajax request and fire action.
	 */
	public static function do_wc_ajax() {
		global $wp_query;

		if ( ! empty( $_GET['wc-ajax'] ) ) {
			$wp_query->set( 'wc-ajax', sanitize_text_field( $_GET['wc-ajax'] ) );
		}

		if ( $action = $wp_query->get( 'wc-ajax' ) ) {
			self::wc_ajax_headers();
			do_action( 'wc_ajax_' . sanitize_text_field( $action ) );
			wp_die();
		}
	}

	/**
	 * Hook in methods - uses WordPress ajax handlers (admin-ajax).
	 */
	public static function add_ajax_events() {
		// woocommerce_EVENT => nopriv
		$ajax_events = array(
			'get_refreshed_fragments'                          => true,
			'apply_coupon'                                     => true,
			'remove_coupon'                                    => true,
			'update_shipping_method'                           => true,
			'get_cart_totals'                                  => true,
			'update_order_review'                              => true,
			'add_to_cart'                                      => true,
			'checkout'                                         => true,
			'get_variation'                                    => true,
			'get_customer_location'                            => true,
			'feature_product'                                  => false,
			'mark_order_status'                                => false,
			'add_attribute'                                    => false,
			'add_new_attribute'                                => false,
			'remove_variation'                                 => false,
			'remove_variations'                                => false,
			'save_attributes'                                  => false,
			'add_variation'                                    => false,
			'link_all_variations'                              => false,
			'revoke_access_to_download'                        => false,
			'grant_access_to_download'                         => false,
			'get_customer_details'                             => false,
			'add_order_item'                                   => false,
			'add_order_fee'                                    => false,
			'add_order_shipping'                               => false,
			'add_order_tax'                                    => false,
			'remove_order_item'                                => false,
			'remove_order_tax'                                 => false,
			'reduce_order_item_stock'                          => false,
			'increase_order_item_stock'                        => false,
			'add_order_item_meta'                              => false,
			'remove_order_item_meta'                           => false,
			'calc_line_taxes'                                  => false,
			'save_order_items'                                 => false,
			'load_order_items'                                 => false,
			'add_order_note'                                   => false,
			'delete_order_note'                                => false,
			'json_search_products'                             => false,
			'json_search_products_and_variations'              => false,
			'json_search_downloadable_products_and_variations' => false,
			'json_search_customers'                            => false,
			'term_ordering'                                    => false,
			'product_ordering'                                 => false,
			'refund_line_items'                                => false,
			'delete_refund'                                    => false,
			'rated'                                            => false,
			'update_api_key'                                   => false,
			'load_variations'                                  => false,
			'save_variations'                                  => false,
			'bulk_edit_variations'                             => false,
			'tax_rates_save_changes'                           => false,
			'shipping_zones_save_changes'                      => false,
			'shipping_zone_add_method'                         => false,
			'shipping_zone_methods_save_changes'               => false,
			'shipping_zone_methods_save_settings'              => false,
			'shipping_classes_save_changes'                    => false,
		);

		foreach ( $ajax_events as $ajax_event => $nopriv ) {
			add_action( 'wp_ajax_woocommerce_' . $ajax_event, array( __CLASS__, $ajax_event ) );

			if ( $nopriv ) {
				add_action( 'wp_ajax_nopriv_woocommerce_' . $ajax_event, array( __CLASS__, $ajax_event ) );

				// WC AJAX can be used for frontend ajax requests.
				add_action( 'wc_ajax_' . $ajax_event, array( __CLASS__, $ajax_event ) );
			}
		}
	}

	/**
	 * Get a refreshed cart fragment, including the mini cart HTML.
	 */
	public static function get_refreshed_fragments() {
		ob_start();

		woocommerce_mini_cart();

		$mini_cart = ob_get_clean();

		$data = array(
			'fragments' => apply_filters( 'woocommerce_add_to_cart_fragments', array(
					'div.widget_shopping_cart_content' => '<div class="widget_shopping_cart_content">' . $mini_cart . '</div>',
				)
			),
			'cart_hash' => apply_filters( 'woocommerce_add_to_cart_hash', WC()->cart->get_cart_for_session() ? md5( json_encode( WC()->cart->get_cart_for_session() ) ) : '', WC()->cart->get_cart_for_session() ),
		);

		wp_send_json( $data );
	}

	/**
	 * AJAX apply coupon on checkout page.
	 */
	public static function apply_coupon() {

		check_ajax_referer( 'apply-coupon', 'security' );

		if ( ! empty( $_POST['coupon_code'] ) ) {
			WC()->cart->add_discount( sanitize_text_field( $_POST['coupon_code'] ) );
		} else {
			wc_add_notice( WC_Coupon::get_generic_coupon_error( WC_Coupon::E_WC_COUPON_PLEASE_ENTER ), 'error' );
		}

		wc_print_notices();
		wp_die();
	}

	/**
	 * AJAX remove coupon on cart and checkout page.
	 */
	public static function remove_coupon() {
		check_ajax_referer( 'remove-coupon', 'security' );

		$coupon = isset( $_POST['coupon'] ) ? wc_clean( $_POST['coupon'] ) : false;

		if ( empty( $coupon ) ) {
			wc_add_notice( __( 'Sorry there was a problem removing this coupon.', 'woocommerce' ), 'error' );
		} else {
			WC()->cart->remove_coupon( $coupon );
			wc_add_notice( __( 'Coupon has been removed.', 'woocommerce' ) );
		}

		wc_print_notices();
		wp_die();
	}

	/**
	 * AJAX update shipping method on cart page.
	 */
	public static function update_shipping_method() {
		check_ajax_referer( 'update-shipping-method', 'security' );

		wc_maybe_define_constant( 'WOOCOMMERCE_CART', true );

		$chosen_shipping_methods = WC()->session->get( 'chosen_shipping_methods' );

		if ( isset( $_POST['shipping_method'] ) && is_array( $_POST['shipping_method'] ) ) {
			foreach ( $_POST['shipping_method'] as $i => $value ) {
				$chosen_shipping_methods[ $i ] = wc_clean( $value );
			}
		}

		WC()->session->set( 'chosen_shipping_methods', $chosen_shipping_methods );

		self::get_cart_totals();
	}

	/**
	 * AJAX receive updated cart_totals div.
	 */
	public static function get_cart_totals() {
		wc_maybe_define_constant( 'WOOCOMMERCE_CART', true );
		WC()->cart->calculate_totals();
		woocommerce_cart_totals();
		wp_die();
	}

	/**
	 * Session has expired.
	 */
	private static function update_order_review_expired() {
		wp_send_json( array(
			'fragments' => apply_filters( 'woocommerce_update_order_review_fragments', array(
				'form.woocommerce-checkout' => '<div class="woocommerce-error">' . __( 'Sorry, your session has expired.', 'woocommerce' ) . ' <a href="' . esc_url( wc_get_page_permalink( 'shop' ) ) . '" class="wc-backward">' . __( 'Return to shop', 'woocommerce' ) . '</a></div>',
			) ),
		) );
	}

	/**
	 * AJAX update order review on checkout.
	 */
	public static function update_order_review() {
		check_ajax_referer( 'update-order-review', 'security' );

		wc_maybe_define_constant( 'WOOCOMMERCE_CHECKOUT', true );

		if ( WC()->cart->is_empty() ) {
			self::update_order_review_expired();
		}

		do_action( 'woocommerce_checkout_update_order_review', $_POST['post_data'] );

		$chosen_shipping_methods = WC()->session->get( 'chosen_shipping_methods' );

		if ( isset( $_POST['shipping_method'] ) && is_array( $_POST['shipping_method'] ) ) {
			foreach ( $_POST['shipping_method'] as $i => $value ) {
				$chosen_shipping_methods[ $i ] = wc_clean( $value );
			}
		}

		WC()->session->set( 'chosen_shipping_methods', $chosen_shipping_methods );
		WC()->session->set( 'chosen_payment_method', empty( $_POST['payment_method'] ) ? '' : $_POST['payment_method'] );
		WC()->customer->set_props( array(
			'billing_country'   => isset( $_POST['country'] ) ? $_POST['country']     : null,
			'billing_state'     => isset( $_POST['state'] ) ? $_POST['state']         : null,
			'billing_postcode'  => isset( $_POST['postcode'] ) ? $_POST['postcode']   : null,
			'billing_city'      => isset( $_POST['city'] ) ? $_POST['city']           : null,
			'billing_address_1' => isset( $_POST['address'] ) ? $_POST['address']     : null,
			'billing_address_2' => isset( $_POST['address_2'] ) ? $_POST['address_2'] : null,
		) );

		if ( wc_ship_to_billing_address_only() ) {
			WC()->customer->set_props( array(
				'shipping_country'   => isset( $_POST['country'] ) ? $_POST['country']     : null,
				'shipping_state'     => isset( $_POST['state'] ) ? $_POST['state']         : null,
				'shipping_postcode'  => isset( $_POST['postcode'] ) ? $_POST['postcode']   : null,
				'shipping_city'      => isset( $_POST['city'] ) ? $_POST['city']           : null,
				'shipping_address_1' => isset( $_POST['address'] ) ? $_POST['address']     : null,
				'shipping_address_2' => isset( $_POST['address_2'] ) ? $_POST['address_2'] : null,
			) );
			if ( ! empty( $_POST['country'] ) ) {
				WC()->customer->set_calculated_shipping( true );
			}
		} else {
			WC()->customer->set_props( array(
				'shipping_country'   => isset( $_POST['s_country'] ) ? $_POST['s_country']     : null,
				'shipping_state'     => isset( $_POST['s_state'] ) ? $_POST['s_state']         : null,
				'shipping_postcode'  => isset( $_POST['s_postcode'] ) ? $_POST['s_postcode']   : null,
				'shipping_city'      => isset( $_POST['s_city'] ) ? $_POST['s_city']           : null,
				'shipping_address_1' => isset( $_POST['s_address'] ) ? $_POST['s_address']     : null,
				'shipping_address_2' => isset( $_POST['s_address_2'] ) ? $_POST['s_address_2'] : null,
			) );
			if ( ! empty( $_POST['s_country'] ) ) {
				WC()->customer->set_calculated_shipping( true );
			}
		}

		WC()->customer->save();
		WC()->cart->calculate_totals();

		// Get order review fragment
		ob_start();
		woocommerce_order_review();
		$woocommerce_order_review = ob_get_clean();

		// Get checkout payment fragment
		ob_start();
		woocommerce_checkout_payment();
		$woocommerce_checkout_payment = ob_get_clean();

		// Get messages if reload checkout is not true
		$messages = '';
		if ( ! isset( WC()->session->reload_checkout ) ) {
			ob_start();
			wc_print_notices();
			$messages = ob_get_clean();
		}

		unset( WC()->session->refresh_totals, WC()->session->reload_checkout );

		wp_send_json( array(
			'result'    => empty( $messages ) ? 'success' : 'failure',
			'messages'  => $messages,
			'reload'    => isset( WC()->session->reload_checkout ) ? 'true' : 'false',
			'fragments' => apply_filters( 'woocommerce_update_order_review_fragments', array(
				'.woocommerce-checkout-review-order-table' => $woocommerce_order_review,
				'.woocommerce-checkout-payment'            => $woocommerce_checkout_payment,
			) ),
		) );
	}

	/**
	 * AJAX add to cart.
	 */
	public static function add_to_cart() {
		ob_start();

		$product_id        = apply_filters( 'woocommerce_add_to_cart_product_id', absint( $_POST['product_id'] ) );
		$quantity          = empty( $_POST['quantity'] ) ? 1 : wc_stock_amount( $_POST['quantity'] );
		$passed_validation = apply_filters( 'woocommerce_add_to_cart_validation', true, $product_id, $quantity );
		$product_status    = get_post_status( $product_id );

		if ( $passed_validation && false !== WC()->cart->add_to_cart( $product_id, $quantity ) && 'publish' === $product_status ) {

			do_action( 'woocommerce_ajax_added_to_cart', $product_id );

			if ( get_option( 'woocommerce_cart_redirect_after_add' ) == 'yes' ) {
				wc_add_to_cart_message( array( $product_id => $quantity ), true );
			}

			// Return fragments
			self::get_refreshed_fragments();

		} else {

			// If there was an error adding to the cart, redirect to the product page to show any errors
			$data = array(
				'error'       => true,
				'product_url' => apply_filters( 'woocommerce_cart_redirect_after_error', get_permalink( $product_id ), $product_id ),
			);

			wp_send_json( $data );
		}
	}

	/**
	 * Process ajax checkout form.
	 */
	public static function checkout() {
		wc_maybe_define_constant( 'WOOCOMMERCE_CHECKOUT', true );
		WC()->checkout()->process_checkout();
		wp_die( 0 );
	}

	/**
	 * Get a matching variation based on posted attributes.
	 */
	public static function get_variation() {
		ob_start();

		if ( empty( $_POST['product_id'] ) || ! ( $variable_product = wc_get_product( absint( $_POST['product_id'] ) ) ) ) {
			wp_die();
		}

		$data_store   = WC_Data_Store::load( 'product' );
		$variation_id = $data_store->find_matching_product_variation( $variable_product, wp_unslash( $_POST ) );
		$variation    = $variation_id ? $variable_product->get_available_variation( $variation_id ) : false;
		wp_send_json( $variation );
	}

	/**
	 * Locate user via AJAX.
	 */
	public static function get_customer_location() {
		$location_hash = WC_Cache_Helper::geolocation_ajax_get_location_hash();
		wp_send_json_success( array( 'hash' => $location_hash ) );
	}

	/**
	 * Toggle Featured status of a product from admin.
	 */
	public static function feature_product() {
		if ( current_user_can( 'edit_products' ) && check_admin_referer( 'woocommerce-feature-product' ) ) {
			$product = wc_get_product( absint( $_GET['product_id'] ) );

			if ( $product ) {
				$product->set_featured( ! $product->get_featured() );
				$product->save();
			}
		}

		wp_safe_redirect( wp_get_referer() ? remove_query_arg( array( 'trashed', 'untrashed', 'deleted', 'ids' ), wp_get_referer() ) : admin_url( 'edit.php?post_type=product' ) );
		exit;
	}

	/**
	 * Mark an order with a status.
	 */
	public static function mark_order_status() {
		if ( current_user_can( 'edit_shop_orders' ) && check_admin_referer( 'woocommerce-mark-order-status' ) ) {
			$status = sanitize_text_field( $_GET['status'] );
			$order  = wc_get_order( absint( $_GET['order_id'] ) );

			if ( wc_is_order_status( 'wc-' . $status ) && $order ) {
				$order->update_status( $status, '', true );
				do_action( 'woocommerce_order_edit_status', $order->get_id(), $status );
			}
		}

		wp_safe_redirect( wp_get_referer() ? wp_get_referer() : admin_url( 'edit.php?post_type=shop_order' ) );
		exit;
	}

	/**
	 * Add an attribute row.
	 */
	public static function add_attribute() {
		ob_start();

		check_ajax_referer( 'add-attribute', 'security' );

		if ( ! current_user_can( 'edit_products' ) ) {
			wp_die( -1 );
		}

		$i             = absint( $_POST['i'] );
		$metabox_class = array();
		$attribute     = new WC_Product_Attribute();

		$attribute->set_id( wc_attribute_taxonomy_id_by_name( sanitize_text_field( $_POST['taxonomy'] ) ) );
		$attribute->set_name( sanitize_text_field( $_POST['taxonomy'] ) );
		$attribute->set_visible( apply_filters( 'woocommerce_attribute_default_visibility', 1 ) );
		$attribute->set_variation( apply_filters( 'woocommerce_attribute_default_is_variation', 0 ) );

		if ( $attribute->is_taxonomy() ) {
			$metabox_class[] = 'taxonomy';
			$metabox_class[] = $attribute->get_name();
		}

		include( 'admin/meta-boxes/views/html-product-attribute.php' );
		wp_die();
	}

	/**
	 * Add a new attribute via ajax function.
	 */
	public static function add_new_attribute() {
		check_ajax_referer( 'add-attribute', 'security' );

		if ( current_user_can( 'manage_product_terms' ) ) {
			$taxonomy = esc_attr( $_POST['taxonomy'] );
			$term     = wc_clean( $_POST['term'] );

			if ( taxonomy_exists( $taxonomy ) ) {

				$result = wp_insert_term( $term, $taxonomy );

				if ( is_wp_error( $result ) ) {
					wp_send_json( array(
						'error' => $result->get_error_message(),
					) );
				} else {
					$term = get_term_by( 'id', $result['term_id'], $taxonomy );
					wp_send_json( array(
						'term_id' => $term->term_id,
						'name'    => $term->name,
						'slug'    => $term->slug,
					) );
				}
			}
		}
		wp_die( -1 );
	}

	/**
	 * Delete variations via ajax function.
	 */
	public static function remove_variations() {
		check_ajax_referer( 'delete-variations', 'security' );

		if ( current_user_can( 'edit_products' ) ) {
			$variation_ids = (array) $_POST['variation_ids'];

			foreach ( $variation_ids as $variation_id ) {
				if ( 'product_variation' === get_post_type( $variation_id ) ) {
					$variation = wc_get_product( $variation_id );
					$variation->delete( true );
				}
			}
		}

		wp_die( -1 );
	}

	/**
	 * Save attributes via ajax.
	 */
	public static function save_attributes() {
		check_ajax_referer( 'save-attributes', 'security' );

		if ( ! current_user_can( 'edit_products' ) ) {
			wp_die( -1 );
		}

		parse_str( $_POST['data'], $data );

		$attributes   = WC_Meta_Box_Product_Data::prepare_attributes( $data );
		$product_id   = absint( $_POST['post_id'] );
		$product_type = ! empty( $_POST['product_type'] ) ? wc_clean( $_POST['product_type'] ) : 'simple';
		$classname    = WC_Product_Factory::get_product_classname( $product_id, $product_type );
		$product      = new $classname( $product_id );

		$product->set_attributes( $attributes );
		$product->save();
		wp_die();
	}

	/**
	 * Add variation via ajax function.
	 */
	public static function add_variation() {

		check_ajax_referer( 'add-variation', 'security' );

		if ( ! current_user_can( 'edit_products' ) ) {
			wp_die( -1 );
		}

		global $post; // Set $post global so its available, like within the admin screens

		$product_id       = intval( $_POST['post_id'] );
		$post             = get_post( $product_id );
		$loop             = intval( $_POST['loop'] );
		$product_object   = wc_get_product( $product_id );
		$variation_object = new WC_Product_Variation();
		$variation_object->set_parent_id( $product_id );
		$variation_id     = $variation_object->save();
		$variation        = get_post( $variation_id );
		$variation_data   = array_merge( array_map( 'maybe_unserialize', get_post_custom( $variation_id ) ), wc_get_product_variation_attributes( $variation_id ) ); // kept for BW compat.
		include( 'admin/meta-boxes/views/html-variation-admin.php' );
		wp_die();
	}

	/**
	 * Link all variations via ajax function.
	 */
	public static function link_all_variations() {
		check_ajax_referer( 'link-variations', 'security' );

		if ( ! current_user_can( 'edit_products' ) ) {
			wp_die( -1 );
		}

		wc_maybe_define_constant( 'WC_MAX_LINKED_VARIATIONS', 49 );
		wc_set_time_limit( 0 );

		$post_id = intval( $_POST['post_id'] );

		if ( ! $post_id ) {
			wp_die();
		}

		$variations = array();
		$product    = wc_get_product( $post_id );
		$attributes = wc_list_pluck( array_filter( $product->get_attributes(), 'wc_attributes_array_filter_variation' ), 'get_slugs' );

		if ( ! empty( $attributes ) ) {
			// Get existing variations so we don't create duplicates.
			$existing_variations = array_map( 'wc_get_product', $product->get_children() );
			$existing_attributes = array();

			foreach ( $existing_variations as $existing_variation ) {
				$existing_attributes[] = $existing_variation->get_attributes();
			}

			$added               = 0;
			$possible_attributes = wc_array_cartesian( $attributes );

			foreach ( $possible_attributes as $possible_attribute ) {
				if ( in_array( $possible_attribute, $existing_attributes ) ) {
					continue;
				}
				$variation = new WC_Product_Variation();
				$variation->set_parent_id( $post_id );
				$variation->set_attributes( $possible_attribute );

				do_action( 'product_variation_linked', $variation->save() );

				if ( ( $added ++ ) > WC_MAX_LINKED_VARIATIONS ) {
					break;
				}
			}

			echo $added;
		}

		$data_store = $product->get_data_store();
		$data_store->sort_all_product_variations( $product->get_id() );
		wp_die();
	}

	/**
	 * Delete download permissions via ajax function.
	 */
	public static function revoke_access_to_download() {
		check_ajax_referer( 'revoke-access', 'security' );

		if ( ! current_user_can( 'edit_shop_orders' ) ) {
			wp_die( -1 );
		}
		$download_id   = $_POST['download_id'];
		$product_id    = intval( $_POST['product_id'] );
		$order_id      = intval( $_POST['order_id'] );
		$permission_id = absint( $_POST['permission_id'] );
		$data_store    = WC_Data_Store::load( 'customer-download' );
		$data_store->delete_by_id( $permission_id );

		do_action( 'woocommerce_ajax_revoke_access_to_product_download', $download_id, $product_id, $order_id, $permission_id );

		wp_die();
	}

	/**
	 * Grant download permissions via ajax function.
	 */
	public static function grant_access_to_download() {

		check_ajax_referer( 'grant-access', 'security' );

		if ( ! current_user_can( 'edit_shop_orders' ) ) {
			wp_die( -1 );
		}

		global $wpdb;

		$wpdb->hide_errors();

		$order_id     = intval( $_POST['order_id'] );
		$product_ids  = $_POST['product_ids'];
		$loop         = intval( $_POST['loop'] );
		$file_counter = 0;
		$order        = wc_get_order( $order_id );

		if ( ! is_array( $product_ids ) ) {
			$product_ids = array( $product_ids );
		}

		foreach ( $product_ids as $product_id ) {
			$product = wc_get_product( $product_id );
			$files   = $product->get_downloads();

			if ( ! $order->get_billing_email() ) {
				wp_die();
			}

			if ( ! empty( $files ) ) {
				foreach ( $files as $download_id => $file ) {
					if ( $inserted_id = wc_downloadable_file_permission( $download_id, $product_id, $order ) ) {
						$download = new WC_Customer_Download( $inserted_id );
						$loop ++;
						$file_counter ++;

						if ( $file->get_name() ) {
							$file_count = $file->get_name();
						} else {
							$file_count = sprintf( __( 'File %d', 'woocommerce' ), $file_counter );
						}
						include( 'admin/meta-boxes/views/html-order-download-permission.php' );
					}
				}
			}
		}
		wp_die();
	}

	/**
	 * Get customer details via ajax.
	 */
	public static function get_customer_details() {
		check_ajax_referer( 'get-customer-details', 'security' );

		if ( ! current_user_can( 'edit_shop_orders' ) ) {
			wp_die( -1 );
		}

		$user_id  = absint( $_POST['user_id'] );
		$customer = new WC_Customer( $user_id );

		if ( has_filter( 'woocommerce_found_customer_details' ) ) {
			wc_deprecated_function( 'The woocommerce_found_customer_details filter', '3.0', 'woocommerce_ajax_get_customer_details' );
		}

		$data = $customer->get_data();
		$data['date_created']  = $data['date_created'] ? $data['date_created']->getTimestamp() : null;
		$data['date_modified'] = $data['date_modified'] ? $data['date_modified']->getTimestamp() : null;

		$customer_data = apply_filters( 'woocommerce_ajax_get_customer_details', $data, $customer, $user_id );
		wp_send_json( $customer_data );
	}

	/**
	 * Add order item via ajax.
	 */
	public static function add_order_item() {
		check_ajax_referer( 'order-item', 'security' );

		if ( ! current_user_can( 'edit_shop_orders' ) ) {
			wp_die( -1 );
		}

		try {
			$order_id     = absint( $_POST['order_id'] );
			$order        = wc_get_order( $order_id );
			$items_to_add = wp_parse_id_list( is_array( $_POST['item_to_add'] ) ? $_POST['item_to_add'] : array( $_POST['item_to_add'] ) );

			if ( ! $order ) {
				throw new Exception( __( 'Invalid order', 'woocommerce' ) );
			}

			ob_start();

			foreach ( $items_to_add as $item_to_add ) {
				if ( ! in_array( get_post_type( $item_to_add ), array( 'product', 'product_variation' ) ) ) {
					continue;
				}
				$item_id     = $order->add_product( wc_get_product( $item_to_add ) );
				$item        = apply_filters( 'woocommerce_ajax_order_item', $order->get_item( $item_id ), $item_id );
				$order_taxes = $order->get_taxes();
				$class       = 'new_row';

				do_action( 'woocommerce_ajax_add_order_item_meta', $item_id, $item );
				include( 'admin/meta-boxes/views/html-order-item.php' );
			}

			wp_send_json_success( array(
				'html' => ob_get_clean(),
			) );
		} catch ( Exception $e ) {
			wp_send_json_error( array( 'error' => $e->getMessage() ) );
		}
	}

	/**
	 * Add order fee via ajax.
	 */
	public static function add_order_fee() {
		check_ajax_referer( 'order-item', 'security' );

		if ( ! current_user_can( 'edit_shop_orders' ) ) {
			wp_die( -1 );
		}

		try {
			$order_id    = absint( $_POST['order_id'] );
			$order       = wc_get_order( $order_id );
			$order_taxes = $order->get_taxes();
			$item        = new WC_Order_Item_Fee();
			$item->set_order_id( $order_id );
			$item_id     = $item->save();

			ob_start();
			include( 'admin/meta-boxes/views/html-order-fee.php' );

			wp_send_json_success( array(
				'html' => ob_get_clean(),
			) );
		} catch ( Exception $e ) {
			wp_send_json_error( array( 'error' => $e->getMessage() ) );
		}
	}

	/**
	 * Add order shipping cost via ajax.
	 */
	public static function add_order_shipping() {
		check_ajax_referer( 'order-item', 'security' );

		if ( ! current_user_can( 'edit_shop_orders' ) ) {
			wp_die( -1 );
		}

		try {
			$order_id         = absint( $_POST['order_id'] );
			$order            = wc_get_order( $order_id );
			$order_taxes      = $order->get_taxes();
			$shipping_methods = WC()->shipping() ? WC()->shipping->load_shipping_methods() : array();

			// Add new shipping
			$item = new WC_Order_Item_Shipping();
			$item->set_shipping_rate( new WC_Shipping_Rate() );
			$item->set_order_id( $order_id );
			$item_id = $item->save();

			ob_start();
			include( 'admin/meta-boxes/views/html-order-shipping.php' );

			wp_send_json_success( array(
				'html' => ob_get_clean(),
			) );
		} catch ( Exception $e ) {
			wp_send_json_error( array( 'error' => $e->getMessage() ) );
		}
	}

	/**
	 * Add order tax column via ajax.
	 */
	public static function add_order_tax() {
		check_ajax_referer( 'order-item', 'security' );

		if ( ! current_user_can( 'edit_shop_orders' ) ) {
			wp_die( -1 );
		}

		try {
			$order_id = absint( $_POST['order_id'] );
			$rate_id  = absint( $_POST['rate_id'] );
			$order    = wc_get_order( $order_id );
			$data     = get_post_meta( $order_id );

			// Add new tax
			$item = new WC_Order_Item_Tax();
			$item->set_rate( $rate_id );
			$item->set_order_id( $order_id );
			$item->save();

			ob_start();
			include( 'admin/meta-boxes/views/html-order-items.php' );

			wp_send_json_success( array(
				'html' => ob_get_clean(),
			) );
		} catch ( Exception $e ) {
			wp_send_json_error( array( 'error' => $e->getMessage() ) );
		}
	}

	/**
	 * Remove an order item.
	 */
	public static function remove_order_item() {
		check_ajax_referer( 'order-item', 'security' );

		if ( ! current_user_can( 'edit_shop_orders' ) ) {
			wp_die( -1 );
		}

		$order_item_ids = $_POST['order_item_ids'];

		if ( ! is_array( $order_item_ids ) && is_numeric( $order_item_ids ) ) {
			$order_item_ids = array( $order_item_ids );
		}

		if ( sizeof( $order_item_ids ) > 0 ) {
			foreach ( $order_item_ids as $id ) {
				wc_delete_order_item( absint( $id ) );
			}
		}
		wp_die();
	}

	/**
	 * Remove an order tax.
	 */
	public static function remove_order_tax() {
		check_ajax_referer( 'order-item', 'security' );

		if ( ! current_user_can( 'edit_shop_orders' ) ) {
			wp_die( -1 );
		}

		$order_id = absint( $_POST['order_id'] );
		$rate_id  = absint( $_POST['rate_id'] );

		wc_delete_order_item( $rate_id );

		// Return HTML items
		$order = wc_get_order( $order_id );
		include( 'admin/meta-boxes/views/html-order-items.php' );
		wp_die();
	}

	/**
	 * Reduce order item stock.
	 */
	public static function reduce_order_item_stock() {
		check_ajax_referer( 'order-item', 'security' );
		if ( ! current_user_can( 'edit_shop_orders' ) ) {
			wp_die( -1 );
		}
		$order_id       = absint( $_POST['order_id'] );
		$order_item_ids = isset( $_POST['order_item_ids'] ) ? $_POST['order_item_ids'] : array();
		$order_item_qty = isset( $_POST['order_item_qty'] ) ? $_POST['order_item_qty'] : array();
		$order          = wc_get_order( $order_id );
		$order_items    = $order->get_items();
		$return         = array();
		if ( $order && ! empty( $order_items ) && sizeof( $order_item_ids ) > 0 ) {
			foreach ( $order_items as $item_id => $order_item ) {
				// Only reduce checked items
				if ( ! in_array( $item_id, $order_item_ids ) ) {
					continue;
				}
				$_product = $order_item->get_product();
				if ( $_product && $_product->exists() && $_product->managing_stock() && isset( $order_item_qty[ $item_id ] ) && $order_item_qty[ $item_id ] > 0 ) {
					$stock_change = apply_filters( 'woocommerce_reduce_order_stock_quantity', $order_item_qty[ $item_id ], $item_id );
					$new_stock    = wc_update_product_stock( $_product, $stock_change, 'decrease' );
					$item_name    = $_product->get_sku() ? $_product->get_sku() : $_product->get_id();
					$note         = sprintf( __( 'Item %1$s stock reduced from %2$s to %3$s.', 'woocommerce' ), $item_name, $new_stock + $stock_change, $new_stock );
					$return[]     = $note;
					$order->add_order_note( $note );
				}
			}
			do_action( 'woocommerce_reduce_order_stock', $order );
			if ( empty( $return ) ) {
				$return[] = __( 'No products had their stock reduced - they may not have stock management enabled.', 'woocommerce' );
			}
			echo wp_kses_post( implode( ', ', $return ) );
		}
		wp_die();
	}

	/**
	 * Increase order item stock.
	 */
	public static function increase_order_item_stock() {
		check_ajax_referer( 'order-item', 'security' );
		if ( ! current_user_can( 'edit_shop_orders' ) ) {
			wp_die( -1 );
		}
		$order_id       = absint( $_POST['order_id'] );
		$order_item_ids = isset( $_POST['order_item_ids'] ) ? $_POST['order_item_ids'] : array();
		$order_item_qty = isset( $_POST['order_item_qty'] ) ? $_POST['order_item_qty'] : array();
		$order          = wc_get_order( $order_id );
		$order_items    = $order->get_items();
		$return         = array();
		if ( $order && ! empty( $order_items ) && sizeof( $order_item_ids ) > 0 ) {
			foreach ( $order_items as $item_id => $order_item ) {
				// Only reduce checked items
				if ( ! in_array( $item_id, $order_item_ids ) ) {
					continue;
				}
				$_product = $order_item->get_product();
				if ( $_product && $_product->exists() && $_product->managing_stock() && isset( $order_item_qty[ $item_id ] ) && $order_item_qty[ $item_id ] > 0 ) {
					$old_stock    = $_product->get_stock_quantity();
					$stock_change = apply_filters( 'woocommerce_restore_order_stock_quantity', $order_item_qty[ $item_id ], $item_id );
					$new_quantity = wc_update_product_stock( $_product, $stock_change, 'increase' );
					$item_name    = $_product->get_sku() ? $_product->get_sku() : $_product->get_id();
					$note         = sprintf( __( 'Item %1$s stock increased from %2$s to %3$s.', 'woocommerce' ), $item_name, $old_stock, $new_quantity );
					$return[]     = $note;
					$order->add_order_note( $note );
				}
			}
			do_action( 'woocommerce_restore_order_stock', $order );
			if ( empty( $return ) ) {
				$return[] = __( 'No products had their stock increased - they may not have stock management enabled.', 'woocommerce' );
			}
			echo wp_kses_post( implode( ', ', $return ) );
		}
		wp_die();
	}

	/**
	 * Calc line tax.
	 */
	public static function calc_line_taxes() {
		check_ajax_referer( 'calc-totals', 'security' );

		if ( ! current_user_can( 'edit_shop_orders' ) ) {
			wp_die( -1 );
		}

		$order_id           = absint( $_POST['order_id'] );
		$calculate_tax_args = array(
			'country'  => strtoupper( wc_clean( $_POST['country'] ) ),
			'state'    => strtoupper( wc_clean( $_POST['state'] ) ),
			'postcode' => strtoupper( wc_clean( $_POST['postcode'] ) ),
			'city'     => strtoupper( wc_clean( $_POST['city'] ) ),
		);

		// Parse the jQuery serialized items
		$items = array();
		parse_str( $_POST['items'], $items );

		// Save order items first
		wc_save_order_items( $order_id, $items );

		// Grab the order and recalc taxes
		$order = wc_get_order( $order_id );
		$order->calculate_taxes( $calculate_tax_args );
		$order->calculate_totals( false );
		include( 'admin/meta-boxes/views/html-order-items.php' );
		wp_die();
	}

	/**
	 * Save order items via ajax.
	 */
	public static function save_order_items() {
		check_ajax_referer( 'order-item', 'security' );

		if ( ! current_user_can( 'edit_shop_orders' ) ) {
			wp_die( -1 );
		}

		if ( isset( $_POST['order_id'], $_POST['items'] ) ) {
			$order_id = absint( $_POST['order_id'] );

			// Parse the jQuery serialized items
			$items = array();
			parse_str( $_POST['items'], $items );

			// Save order items
			wc_save_order_items( $order_id, $items );

			// Return HTML items
			$order = wc_get_order( $order_id );
			include( 'admin/meta-boxes/views/html-order-items.php' );
		}
		wp_die();
	}

	/**
	 * Load order items via ajax.
	 */
	public static function load_order_items() {
		check_ajax_referer( 'order-item', 'security' );

		if ( ! current_user_can( 'edit_shop_orders' ) ) {
			wp_die( -1 );
		}

		// Return HTML items
		$order_id = absint( $_POST['order_id'] );
		$order    = wc_get_order( $order_id );
		include( 'admin/meta-boxes/views/html-order-items.php' );
		wp_die();
	}

	/**
	 * Add order note via ajax.
	 */
	public static function add_order_note() {
		check_ajax_referer( 'add-order-note', 'security' );

		if ( ! current_user_can( 'edit_shop_orders' ) ) {
			wp_die( -1 );
		}

		$post_id   = absint( $_POST['post_id'] );
		$note      = wp_kses_post( trim( stripslashes( $_POST['note'] ) ) );
		$note_type = $_POST['note_type'];

		$is_customer_note = ( 'customer' === $note_type ) ? 1 : 0;

		if ( $post_id > 0 ) {
			$order      = wc_get_order( $post_id );
			$comment_id = $order->add_order_note( $note, $is_customer_note, true );

			echo '<li rel="' . esc_attr( $comment_id ) . '" class="note ';
			if ( $is_customer_note ) {
				echo 'customer-note';
			}
			echo '"><div class="note_content">';
			echo wpautop( wptexturize( $note ) );
			echo '</div><p class="meta"><a href="#" class="delete_note">' . __( 'Delete note', 'woocommerce' ) . '</a></p>';
			echo '</li>';
		}
		wp_die();
	}

	/**
	 * Delete order note via ajax.
	 */
	public static function delete_order_note() {
		check_ajax_referer( 'delete-order-note', 'security' );

		if ( ! current_user_can( 'edit_shop_orders' ) ) {
			wp_die( -1 );
		}

		$note_id = (int) $_POST['note_id'];

		if ( $note_id > 0 ) {
			wp_delete_comment( $note_id );
		}
		wp_die();
	}

	/**
	 * Search for products and echo json.
	 *
	 * @param string $term (default: '')
	 * @param bool $include_variations in search or not
	 */
	public static function json_search_products( $term = '', $include_variations = false ) {
		check_ajax_referer( 'search-products', 'security' );

		$term = wc_clean( empty( $term ) ? stripslashes( $_GET['term'] ) : $term );

		if ( empty( $term ) ) {
			wp_die();
		}

		$data_store = WC_Data_Store::load( 'product' );
		$ids        = $data_store->search_products( $term, '', (bool) $include_variations );

		if ( ! empty( $_GET['exclude'] ) ) {
			$ids = array_diff( $ids, (array) $_GET['exclude'] );
		}

		if ( ! empty( $_GET['include'] ) ) {
			$ids = array_intersect( $ids, (array) $_GET['include'] );
		}

		if ( ! empty( $_GET['limit'] ) ) {
			$ids = array_slice( $ids, 0, absint( $_GET['limit'] ) );
		}

		$product_objects = array_filter( array_map( 'wc_get_product', $ids ), 'wc_products_array_filter_editable' );
		$products        = array();

		foreach ( $product_objects as $product_object ) {
			$products[ $product_object->get_id() ] = rawurldecode( $product_object->get_formatted_name() );
		}

		wp_send_json( apply_filters( 'woocommerce_json_search_found_products', $products ) );
	}

	/**
	 * Search for product variations and return json.
	 *
	 * @see WC_AJAX::json_search_products()
	 */
	public static function json_search_products_and_variations() {
		self::json_search_products( '', true );
	}

	/**
	 * Search for downloadable product variations and return json.
	 *
	 * @see WC_AJAX::json_search_products()
	 */
	public static function json_search_downloadable_products_and_variations() {
		check_ajax_referer( 'search-products', 'security' );

		$term       = (string) wc_clean( stripslashes( $_GET['term'] ) );
		$data_store = WC_Data_Store::load( 'product' );
		$ids        = $data_store->search_products( $term, 'downloadable', true );

		if ( ! empty( $_GET['exclude'] ) ) {
			$ids = array_diff( $ids, (array) $_GET['exclude'] );
		}

		if ( ! empty( $_GET['include'] ) ) {
			$ids = array_intersect( $ids, (array) $_GET['include'] );
		}

		if ( ! empty( $_GET['limit'] ) ) {
			$ids = array_slice( $ids, 0, absint( $_GET['limit'] ) );
		}

		$product_objects = array_filter( array_map( 'wc_get_product', $ids ), 'wc_products_array_filter_editable' );
		$products        = array();

		foreach ( $product_objects as $product_object ) {
			$products[ $product_object->get_id() ] = rawurldecode( $product_object->get_formatted_name() );
		}

		wp_send_json( $products );
	}

	/**
	 * Search for customers and return json.
	 */
	public static function json_search_customers() {
		ob_start();

		check_ajax_referer( 'search-customers', 'security' );

		if ( ! current_user_can( 'edit_shop_orders' ) ) {
			wp_die( -1 );
		}

		$term    = wc_clean( stripslashes( $_GET['term'] ) );
		$exclude = array();
		$limit   = '';

		if ( empty( $term ) ) {
			wp_die();
		}

		// Search by ID.
		if ( is_numeric( $term ) ) {
			$customer = new WC_Customer( intval( $term ) );

			// Customer does not exists.
			if ( 0 === $customer->get_id() ) {
				wp_die();
			}

			$ids = array( $customer->get_id() );
		} else {
			$data_store = WC_Data_Store::load( 'customer' );

			// If search is smaller than 3 characters, limit result set to avoid
			// too many rows being returned.
			if ( 3 > strlen( $term ) ) {
				$limit = 20;
			}
			$ids = $data_store->search_customers( $term, $limit );
		}

		$found_customers = array();

		if ( ! empty( $_GET['exclude'] ) ) {
			$ids = array_diff( $ids, (array) $_GET['exclude'] );
		}

		foreach ( $ids as $id ) {
			$customer = new WC_Customer( $id );
			/* translators: 1: user display name 2: user ID 3: user email */
			$found_customers[ $id ] = sprintf(
				esc_html__( '%1$s (#%2$s &ndash; %3$s)', 'woocommerce' ),
				$customer->get_first_name() . ' ' . $customer->get_last_name(),
				$customer->get_id(),
				$customer->get_email()
			);
		}

		wp_send_json( apply_filters( 'woocommerce_json_search_found_customers', $found_customers ) );
	}

	/**
	 * Ajax request handling for categories ordering.
	 */
	public static function term_ordering() {

		// check permissions again and make sure we have what we need
		if ( ! current_user_can( 'edit_products' ) || empty( $_POST['id'] ) ) {
			wp_die( -1 );
		}

		$id       = (int) $_POST['id'];
		$next_id  = isset( $_POST['nextid'] ) && (int) $_POST['nextid'] ? (int) $_POST['nextid'] : null;
		$taxonomy = isset( $_POST['thetaxonomy'] ) ? esc_attr( $_POST['thetaxonomy'] ) : null;
		$term     = get_term_by( 'id', $id, $taxonomy );

		if ( ! $id || ! $term || ! $taxonomy ) {
			wp_die( 0 );
		}

		wc_reorder_terms( $term, $next_id, $taxonomy );

		$children = get_terms( $taxonomy, "child_of=$id&menu_order=ASC&hide_empty=0" );

		if ( $term && sizeof( $children ) ) {
			echo 'children';
			wp_die();
		}
	}

	/**
	 * Ajax request handling for product ordering.
	 *
	 * Based on Simple Page Ordering by 10up (https://wordpress.org/plugins/simple-page-ordering/).
	 */
	public static function product_ordering() {
		global $wpdb;

		if ( ! current_user_can( 'edit_products' ) || empty( $_POST['id'] ) ) {
			wp_die( -1 );
		}

		$sorting_id  = absint( $_POST['id'] );
		$previd      = absint( isset( $_POST['previd'] ) ? $_POST['previd'] : 0 );
		$nextid      = absint( isset( $_POST['nextid'] ) ? $_POST['nextid'] : 0 );
		$menu_orders = wp_list_pluck( $wpdb->get_results( "SELECT ID, menu_order FROM {$wpdb->posts} WHERE post_type = 'product' ORDER BY menu_order ASC, post_title ASC" ), 'menu_order', 'ID' );
		$index       = 0;

		foreach ( $menu_orders as $id => $menu_order ) {
			$id = absint( $id );

			if ( $sorting_id === $id ) {
				continue;
			}
			if ( $nextid === $id ) {
				$index ++;
			}
			$index ++;
			$menu_orders[ $id ] = $index;
			$wpdb->update( $wpdb->posts, array( 'menu_order' => $index ), array( 'ID' => $id ) );

			/**
			 * When a single product has gotten it's ordering updated.
			 * $id The product ID
			 * $index The new menu order
			*/
			do_action( 'woocommerce_after_single_product_ordering', $id, $index );
		}

		if ( isset( $menu_orders[ $previd ] ) ) {
			$menu_orders[ $sorting_id ] = $menu_orders[ $previd ] + 1;
		} elseif ( isset( $menu_orders[ $nextid ] ) ) {
			$menu_orders[ $sorting_id ] = $menu_orders[ $nextid ] - 1;
		} else {
			$menu_orders[ $sorting_id ] = 0;
		}

		$wpdb->update( $wpdb->posts, array( 'menu_order' => $menu_orders[ $sorting_id ] ), array( 'ID' => $sorting_id ) );

		do_action( 'woocommerce_after_product_ordering' );
		wp_send_json( $menu_orders );
	}

	/**
	 * Handle a refund via the edit order screen.
	 */
	public static function refund_line_items() {
		ob_start();

		check_ajax_referer( 'order-item', 'security' );

		if ( ! current_user_can( 'edit_shop_orders' ) ) {
			wp_die( -1 );
		}

		$order_id               = absint( $_POST['order_id'] );
		$refund_amount          = wc_format_decimal( sanitize_text_field( $_POST['refund_amount'] ), wc_get_price_decimals() );
		$refund_reason          = sanitize_text_field( $_POST['refund_reason'] );
		$line_item_qtys         = json_decode( sanitize_text_field( stripslashes( $_POST['line_item_qtys'] ) ), true );
		$line_item_totals       = json_decode( sanitize_text_field( stripslashes( $_POST['line_item_totals'] ) ), true );
		$line_item_tax_totals   = json_decode( sanitize_text_field( stripslashes( $_POST['line_item_tax_totals'] ) ), true );
		$api_refund             = 'true' === $_POST['api_refund'];
		$restock_refunded_items = 'true' === $_POST['restock_refunded_items'];
		$refund                 = false;
		$response_data          = array();

		try {
			$order       = wc_get_order( $order_id );
			$order_items = $order->get_items();
			$max_refund  = wc_format_decimal( $order->get_total() - $order->get_total_refunded(), wc_get_price_decimals() );

			if ( ! $refund_amount || $max_refund < $refund_amount || 0 > $refund_amount ) {
				throw new exception( __( 'Invalid refund amount', 'woocommerce' ) );
			}

			// Prepare line items which we are refunding
			$line_items = array();
			$item_ids   = array_unique( array_merge( array_keys( $line_item_qtys, $line_item_totals ) ) );

			foreach ( $item_ids as $item_id ) {
				$line_items[ $item_id ] = array( 'qty' => 0, 'refund_total' => 0, 'refund_tax' => array() );
			}
			foreach ( $line_item_qtys as $item_id => $qty ) {
				$line_items[ $item_id ]['qty'] = max( $qty, 0 );
			}
			foreach ( $line_item_totals as $item_id => $total ) {
				$line_items[ $item_id ]['refund_total'] = wc_format_decimal( $total );
			}
			foreach ( $line_item_tax_totals as $item_id => $tax_totals ) {
				$line_items[ $item_id ]['refund_tax'] = array_filter( array_map( 'wc_format_decimal', $tax_totals ) );
			}

			// Create the refund object.
			$refund = wc_create_refund( array(
				'amount'         => $refund_amount,
				'reason'         => $refund_reason,
				'order_id'       => $order_id,
				'line_items'     => $line_items,
				'refund_payment' => $api_refund,
				'restock_items'  => $restock_refunded_items,
			) );

			if ( is_wp_error( $refund ) ) {
				throw new Exception( $refund->get_error_message() );
			}

			if ( did_action( 'woocommerce_order_fully_refunded' ) ) {
				$response_data['status'] = 'fully_refunded';
			}

			wp_send_json_success( $response_data );

		} catch ( Exception $e ) {
			if ( $refund && is_a( $refund, 'WC_Order_Refund' ) ) {
				wp_delete_post( $refund->get_id(), true );
			}
			wp_send_json_error( array( 'error' => $e->getMessage() ) );
		}
	}

	/**
	 * Delete a refund.
	 */
	public static function delete_refund() {
		check_ajax_referer( 'order-item', 'security' );

		if ( ! current_user_can( 'edit_shop_orders' ) ) {
			wp_die( -1 );
		}

		$refund_ids = array_map( 'absint', is_array( $_POST['refund_id'] ) ? $_POST['refund_id'] : array( $_POST['refund_id'] ) );
		foreach ( $refund_ids as $refund_id ) {
			if ( $refund_id && 'shop_order_refund' === get_post_type( $refund_id ) ) {
				$refund   = wc_get_order( $refund_id );
				$order_id = $refund->get_parent_id();
				$refund->delete( true );
				do_action( 'woocommerce_refund_deleted', $refund_id, $order_id );
			}
		}
		wp_die();
	}

	/**
	 * Triggered when clicking the rating footer.
	 */
	public static function rated() {
		if ( ! current_user_can( 'manage_woocommerce' ) ) {
			wp_die( -1 );
		}
		update_option( 'woocommerce_admin_footer_text_rated', 1 );
		wp_die();
	}

	/**
	 * Create/Update API key.
	 */
	public static function update_api_key() {
		ob_start();

		global $wpdb;

		check_ajax_referer( 'update-api-key', 'security' );

		if ( ! current_user_can( 'manage_woocommerce' ) ) {
			wp_die( -1 );
		}

		try {
			if ( empty( $_POST['description'] ) ) {
				throw new Exception( __( 'Description is missing.', 'woocommerce' ) );
			}
			if ( empty( $_POST['user'] ) ) {
				throw new Exception( __( 'User is missing.', 'woocommerce' ) );
			}
			if ( empty( $_POST['permissions'] ) ) {
				throw new Exception( __( 'Permissions is missing.', 'woocommerce' ) );
			}

			$key_id      = absint( $_POST['key_id'] );
			$description = sanitize_text_field( wp_unslash( $_POST['description'] ) );
			$permissions = ( in_array( $_POST['permissions'], array( 'read', 'write', 'read_write' ) ) ) ? sanitize_text_field( $_POST['permissions'] ) : 'read';
			$user_id     = absint( $_POST['user'] );

			if ( 0 < $key_id ) {
				$data = array(
					'user_id'     => $user_id,
					'description' => $description,
					'permissions' => $permissions,
				);

				$wpdb->update(
					$wpdb->prefix . 'woocommerce_api_keys',
					$data,
					array( 'key_id' => $key_id ),
					array(
						'%d',
						'%s',
						'%s',
					),
					array( '%d' )
				);

				$data['consumer_key']    = '';
				$data['consumer_secret'] = '';
				$data['message']         = __( 'API Key updated successfully.', 'woocommerce' );
			} else {
				$consumer_key    = 'ck_' . wc_rand_hash();
				$consumer_secret = 'cs_' . wc_rand_hash();

				$data = array(
					'user_id'         => $user_id,
					'description'     => $description,
					'permissions'     => $permissions,
					'consumer_key'    => wc_api_hash( $consumer_key ),
					'consumer_secret' => $consumer_secret,
					'truncated_key'   => substr( $consumer_key, -7 ),
				);

				$wpdb->insert(
					$wpdb->prefix . 'woocommerce_api_keys',
					$data,
					array(
						'%d',
						'%s',
						'%s',
						'%s',
						'%s',
						'%s',
					)
				);

				$key_id                  = $wpdb->insert_id;
				$data['consumer_key']    = $consumer_key;
				$data['consumer_secret'] = $consumer_secret;
				$data['message']         = __( 'API Key generated successfully. Make sure to copy your new keys now as the secret key will be hidden once you leave this page.', 'woocommerce' );
				$data['revoke_url']      = '<a style="color: #a00; text-decoration: none;" href="' . esc_url( wp_nonce_url( add_query_arg( array( 'revoke-key' => $key_id ), admin_url( 'admin.php?page=wc-settings&tab=api&section=keys' ) ), 'revoke' ) ) . '">' . __( 'Revoke key', 'woocommerce' ) . '</a>';
			}

			wp_send_json_success( $data );
		} catch ( Exception $e ) {
			wp_send_json_error( array( 'message' => $e->getMessage() ) );
		}
	}

	/**
	 * Load variations via AJAX.
	 */
	public static function load_variations() {
		ob_start();

		check_ajax_referer( 'load-variations', 'security' );

		if ( ! current_user_can( 'edit_products' ) || empty( $_POST['product_id'] ) ) {
			wp_die( -1 );
		}

		// Set $post global so its available, like within the admin screens
		global $post;

		$loop           = 0;
		$product_id     = absint( $_POST['product_id'] );
		$post           = get_post( $product_id );
		$product_object = wc_get_product( $product_id );
		$per_page       = ! empty( $_POST['per_page'] ) ? absint( $_POST['per_page'] ) : 10;
		$page           = ! empty( $_POST['page'] ) ? absint( $_POST['page'] ) : 1;
		$variations     = wc_get_products( array(
			'status'         => array( 'private', 'publish' ),
			'type'           => 'variation',
			'parent'         => $product_id,
			'limit'          => $per_page,
			'page'           => $page,
			'orderby'        => array(
				'menu_order' => 'ASC',
				'ID'         => 'DESC',
			),
			'return'         => 'objects',
		) );

		if ( $variations ) {
			foreach ( $variations as $variation_object ) {
				$variation_id   = $variation_object->get_id();
				$variation      = get_post( $variation_id );
				$variation_data = array_merge( array_map( 'maybe_unserialize', get_post_custom( $variation_id ) ), wc_get_product_variation_attributes( $variation_id ) ); // kept for BW compat.
				include( 'admin/meta-boxes/views/html-variation-admin.php' );
				$loop++;
			}
		}
		wp_die();
	}

	/**
	 * Save variations via AJAX.
	 */
	public static function save_variations() {
		ob_start();

		check_ajax_referer( 'save-variations', 'security' );

		// Check permissions again and make sure we have what we need
		if ( ! current_user_can( 'edit_products' ) || empty( $_POST ) || empty( $_POST['product_id'] ) ) {
			wp_die( -1 );
		}

		$product_id = absint( $_POST['product_id'] );
		WC_Admin_Meta_Boxes::$meta_box_errors = array();
		WC_Meta_Box_Product_Data::save_variations( $product_id, get_post( $product_id ) );

		do_action( 'woocommerce_ajax_save_product_variations', $product_id );

		if ( $errors = WC_Admin_Meta_Boxes::$meta_box_errors ) {
			echo '<div class="error notice is-dismissible">';

			foreach ( $errors as $error ) {
				echo '<p>' . wp_kses_post( $error ) . '</p>';
			}

			echo '<button type="button" class="notice-dismiss"><span class="screen-reader-text">' . __( 'Dismiss this notice.', 'woocommerce' ) . '</span></button>';
			echo '</div>';

			delete_option( 'woocommerce_meta_box_errors' );
		}

		wp_die();
	}

	/**
	 * Bulk action - Toggle Enabled.
	 * @access private
	 * @used-by bulk_edit_variations
	 * @param  array $variations
	 * @param  array $data
	 */
	private static function variation_bulk_action_toggle_enabled( $variations, $data ) {
		foreach ( $variations as $variation_id ) {
			$variation = wc_get_product( $variation_id );
			$variation->set_status( 'private' === $variation->get_status( 'edit' ) ? 'publish' : 'private' );
			$variation->save();
		}
	}

	/**
	 * Bulk action - Toggle Downloadable Checkbox.
	 * @access private
	 * @used-by bulk_edit_variations
	 * @param  array $variations
	 * @param  array $data
	 */
	private static function variation_bulk_action_toggle_downloadable( $variations, $data ) {
		self::variation_bulk_toggle( $variations, 'downloadable' );
	}

	/**
	 * Bulk action - Toggle Virtual Checkbox.
	 * @access private
	 * @used-by bulk_edit_variations
	 * @param  array $variations
	 * @param  array $data
	 */
	private static function variation_bulk_action_toggle_virtual( $variations, $data ) {
		self::variation_bulk_toggle( $variations, 'virtual' );
	}

	/**
	 * Bulk action - Toggle Manage Stock Checkbox.
	 * @access private
	 * @used-by bulk_edit_variations
	 * @param  array $variations
	 * @param  array $data
	 */
	private static function variation_bulk_action_toggle_manage_stock( $variations, $data ) {
		self::variation_bulk_toggle( $variations, 'manage_stock' );
	}

	/**
	 * Bulk action - Set Regular Prices.
	 * @access private
	 * @used-by bulk_edit_variations
	 * @param  array $variations
	 * @param  array $data
	 */
	private static function variation_bulk_action_variable_regular_price( $variations, $data ) {
		self::variation_bulk_set( $variations, 'regular_price', $data['value'] );
	}

	/**
	 * Bulk action - Set Sale Prices.
	 * @access private
	 * @used-by bulk_edit_variations
	 * @param  array $variations
	 * @param  array $data
	 */
	private static function variation_bulk_action_variable_sale_price( $variations, $data ) {
		self::variation_bulk_set( $variations, 'sale_price', $data['value'] );
	}

	/**
	 * Bulk action - Set Stock Status as In Stock.
	 * @access private
	 * @used-by bulk_edit_variations
	 * @param  array $variations
	 * @param  array $data
	 */
	private static function variation_bulk_action_variable_stock_status_instock( $variations, $data ) {
		self::variation_bulk_set( $variations, 'stock_status', 'instock' );
	}

	/**
	 * Bulk action - Set Stock Status as Out of Stock.
	 * @access private
	 * @used-by bulk_edit_variations
	 * @param  array $variations
	 * @param  array $data
	 */
	private static function variation_bulk_action_variable_stock_status_outofstock( $variations, $data ) {
		self::variation_bulk_set( $variations, 'stock_status', 'outofstock' );
	}

	/**
	 * Bulk action - Set Stock.
	 * @access private
	 * @used-by bulk_edit_variations
	 * @param  array $variations
	 * @param  array $data
	 */
	private static function variation_bulk_action_variable_stock( $variations, $data ) {
		if ( ! isset( $data['value'] ) ) {
			return;
		}

		$quantity = wc_stock_amount( wc_clean( $data['value'] ) );

		foreach ( $variations as $variation_id ) {
			$variation = wc_get_product( $variation_id );
			if ( $variation->managing_stock() ) {
				$variation->set_stock_quantity( $quantity );
			} else {
				$variation->set_stock_quantity( null );
			}
			$variation->save();
		}
	}

	/**
	 * Bulk action - Set Weight.
	 * @access private
	 * @used-by bulk_edit_variations
	 * @param  array $variations
	 * @param  array $data
	 */
	private static function variation_bulk_action_variable_weight( $variations, $data ) {
		self::variation_bulk_set( $variations, 'weight', $data['value'] );
	}

	/**
	 * Bulk action - Set Length.
	 * @access private
	 * @used-by bulk_edit_variations
	 * @param  array $variations
	 * @param  array $data
	 */
	private static function variation_bulk_action_variable_length( $variations, $data ) {
		self::variation_bulk_set( $variations, 'length', $data['value'] );
	}

	/**
	 * Bulk action - Set Width.
	 * @access private
	 * @used-by bulk_edit_variations
	 * @param  array $variations
	 * @param  array $data
	 */
	private static function variation_bulk_action_variable_width( $variations, $data ) {
		self::variation_bulk_set( $variations, 'width', $data['value'] );
	}

	/**
	 * Bulk action - Set Height.
	 * @access private
	 * @used-by bulk_edit_variations
	 * @param  array $variations
	 * @param  array $data
	 */
	private static function variation_bulk_action_variable_height( $variations, $data ) {
		self::variation_bulk_set( $variations, 'height', $data['value'] );
	}

	/**
	 * Bulk action - Set Download Limit.
	 * @access private
	 * @used-by bulk_edit_variations
	 * @param  array $variations
	 * @param  array $data
	 */
	private static function variation_bulk_action_variable_download_limit( $variations, $data ) {
		self::variation_bulk_set( $variations, 'download_limit', $data['value'] );
	}

	/**
	 * Bulk action - Set Download Expiry.
	 * @access private
	 * @used-by bulk_edit_variations
	 * @param  array $variations
	 * @param  array $data
	 */
	private static function variation_bulk_action_variable_download_expiry( $variations, $data ) {
		self::variation_bulk_set( $variations, 'download_expiry', $data['value'] );
	}

	/**
	 * Bulk action - Delete all.
	 * @access private
	 * @used-by bulk_edit_variations
	 * @param  array $variations
	 * @param  array $data
	 */
	private static function variation_bulk_action_delete_all( $variations, $data ) {
		if ( isset( $data['allowed'] ) && 'true' === $data['allowed'] ) {
			foreach ( $variations as $variation_id ) {
				$variation = wc_get_product( $variation_id );
				$variation->delete( true );
			}
		}
	}

	/**
	 * Bulk action - Sale Schedule.
	 * @access private
	 * @used-by bulk_edit_variations
	 * @param  array $variations
	 * @param  array $data
	 */
	private static function variation_bulk_action_variable_sale_schedule( $variations, $data ) {
		if ( ! isset( $data['date_from'] ) && ! isset( $data['date_to'] ) ) {
			return;
		}

		foreach ( $variations as $variation_id ) {
			$variation = wc_get_product( $variation_id );

			if ( 'false' !== $data['date_from'] ) {
				$variation->set_date_on_sale_from( wc_clean( $data['date_from'] ) );
			}

			if ( 'false' !== $data['date_to'] ) {
				$variation->set_date_on_sale_to( wc_clean( $data['date_to'] ) );
			}

			$variation->save();
		}
	}

	/**
	 * Bulk action - Increase Regular Prices.
	 * @access private
	 * @used-by bulk_edit_variations
	 * @param  array $variations
	 * @param  array $data
	 */
	private static function variation_bulk_action_variable_regular_price_increase( $variations, $data ) {
		self::variation_bulk_adjust_price( $variations, 'regular_price', '+', wc_clean( $data['value'] ) );
	}

	/**
	 * Bulk action - Decrease Regular Prices.
	 * @access private
	 * @used-by bulk_edit_variations
	 * @param  array $variations
	 * @param  array $data
	 */
	private static function variation_bulk_action_variable_regular_price_decrease( $variations, $data ) {
		self::variation_bulk_adjust_price( $variations, 'regular_price', '-', wc_clean( $data['value'] ) );
	}

	/**
	 * Bulk action - Increase Sale Prices.
	 * @access private
	 * @used-by bulk_edit_variations
	 * @param  array $variations
	 * @param  array $data
	 */
	private static function variation_bulk_action_variable_sale_price_increase( $variations, $data ) {
		self::variation_bulk_adjust_price( $variations, 'sale_price', '+', wc_clean( $data['value'] ) );
	}

	/**
	 * Bulk action - Decrease Sale Prices.
	 * @access private
	 * @used-by bulk_edit_variations
	 * @param  array $variations
	 * @param  array $data
	 */
	private static function variation_bulk_action_variable_sale_price_decrease( $variations, $data ) {
		self::variation_bulk_adjust_price( $variations, 'sale_price', '-', wc_clean( $data['value'] ) );
	}

	/**
	 * Bulk action - Set Price.
	 * @access private
	 * @used-by bulk_edit_variations
	 * @param array $variations
	 * @param string $operator + or -
	 * @param string $field price being adjusted _regular_price or _sale_price
	 * @param string $value Price or Percent
	 */
	private static function variation_bulk_adjust_price( $variations, $field, $operator, $value ) {
		foreach ( $variations as $variation_id ) {
			$variation   = wc_get_product( $variation_id );
			$field_value = $variation->{"get_$field"}( 'edit' );

			if ( '%' === substr( $value, -1 ) ) {
				$percent = wc_format_decimal( substr( $value, 0, -1 ) );
				$field_value += ( ( $field_value / 100 ) * $percent ) * "{$operator}1";
			} else {
				$field_value += $value * "{$operator}1";
			}

			$variation->{"set_$field"}( $field_value );
			$variation->save();
		}
	}

	/**
	 * Bulk set convenience function.
	 * @access private
	 * @param array $variations
	 * @param string $field
	 * @param string $value
	 */
	private static function variation_bulk_set( $variations, $field, $value ) {
		foreach ( $variations as $variation_id ) {
			$variation = wc_get_product( $variation_id );
			$variation->{ "set_$field" }( wc_clean( $value ) );
			$variation->save();
		}
	}

	/**
	 * Bulk toggle convenience function.
	 * @access private
	 * @param array $variations
	 * @param string $field
	 */
	private static function variation_bulk_toggle( $variations, $field ) {
		foreach ( $variations as $variation_id ) {
			$variation = wc_get_product( $variation_id );
			$prev_value = $variation->{ "get_$field" }( 'edit' );
			$variation->{ "set_$field" }( ! $prev_value );
			$variation->save();
		}
	}

	/**
	 * Bulk edit variations via AJAX.
	 * @uses WC_AJAX::variation_bulk_set()
	 * @uses WC_AJAX::variation_bulk_adjust_price()
	 * @uses WC_AJAX::variation_bulk_action_variable_sale_price_decrease()
	 * @uses WC_AJAX::variation_bulk_action_variable_sale_price_increase()
	 * @uses WC_AJAX::variation_bulk_action_variable_regular_price_decrease()
	 * @uses WC_AJAX::variation_bulk_action_variable_regular_price_increase()
	 * @uses WC_AJAX::variation_bulk_action_variable_sale_schedule()
	 * @uses WC_AJAX::variation_bulk_action_delete_all()
	 * @uses WC_AJAX::variation_bulk_action_variable_download_expiry()
	 * @uses WC_AJAX::variation_bulk_action_variable_download_limit()
	 * @uses WC_AJAX::variation_bulk_action_variable_height()
	 * @uses WC_AJAX::variation_bulk_action_variable_width()
	 * @uses WC_AJAX::variation_bulk_action_variable_length()
	 * @uses WC_AJAX::variation_bulk_action_variable_weight()
	 * @uses WC_AJAX::variation_bulk_action_variable_stock()
	 * @uses WC_AJAX::variation_bulk_action_variable_sale_price()
	 * @uses WC_AJAX::variation_bulk_action_variable_regular_price()
	 * @uses WC_AJAX::variation_bulk_action_toggle_manage_stock()
	 * @uses WC_AJAX::variation_bulk_action_toggle_virtual()
	 * @uses WC_AJAX::variation_bulk_action_toggle_downloadable()
	 * @uses WC_AJAX::variation_bulk_action_toggle_enabled
	 */
	public static function bulk_edit_variations() {
		ob_start();

		check_ajax_referer( 'bulk-edit-variations', 'security' );

		// Check permissions again and make sure we have what we need
		if ( ! current_user_can( 'edit_products' ) || empty( $_POST['product_id'] ) || empty( $_POST['bulk_action'] ) ) {
			wp_die( -1 );
		}

		$product_id  = absint( $_POST['product_id'] );
		$bulk_action = wc_clean( $_POST['bulk_action'] );
		$data        = ! empty( $_POST['data'] ) ? array_map( 'wc_clean', $_POST['data'] ) : array();
		$variations  = array();

		if ( apply_filters( 'woocommerce_bulk_edit_variations_need_children', true ) ) {
			$variations = get_posts( array(
				'post_parent'    => $product_id,
				'posts_per_page' => -1,
				'post_type'      => 'product_variation',
				'fields'         => 'ids',
				'post_status'    => array( 'publish', 'private' ),
			) );
		}

		if ( method_exists( __CLASS__, "variation_bulk_action_$bulk_action" ) ) {
			call_user_func( array( __CLASS__, "variation_bulk_action_$bulk_action" ), $variations, $data );
		} else {
			do_action( 'woocommerce_bulk_edit_variations_default', $bulk_action, $data, $product_id, $variations );
		}

		do_action( 'woocommerce_bulk_edit_variations', $bulk_action, $data, $product_id, $variations );
		WC_Product_Variable::sync( $product_id );
		wc_delete_product_transients( $product_id );
		wp_die();
	}

	/**
	 * Handle submissions from assets/js/settings-views-html-settings-tax.js Backbone model.
	 */
	public static function tax_rates_save_changes() {
		if ( ! isset( $_POST['wc_tax_nonce'], $_POST['changes'] ) ) {
			wp_send_json_error( 'missing_fields' );
			exit;
		}

		$current_class = ! empty( $_POST['current_class'] ) ? $_POST['current_class'] : ''; // This is sanitized seven lines later.

		if ( ! wp_verify_nonce( $_POST['wc_tax_nonce'], 'wc_tax_nonce-class:' . $current_class ) ) {
			wp_send_json_error( 'bad_nonce' );
			exit;
		}

		$current_class = WC_Tax::format_tax_rate_class( $current_class );

		// Check User Caps
		if ( ! current_user_can( 'manage_woocommerce' ) ) {
			wp_send_json_error( 'missing_capabilities' );
			exit;
		}

		$changes = $_POST['changes'];
		foreach ( $changes as $tax_rate_id => $data ) {
			if ( isset( $data['deleted'] ) ) {
				if ( isset( $data['newRow'] ) ) {
					// So the user added and deleted a new row.
					// That's fine, it's not in the database anyways. NEXT!
					continue;
				}
				WC_Tax::_delete_tax_rate( $tax_rate_id );
			}

			$tax_rate = array_intersect_key( $data, array(
				'tax_rate_country'  => 1,
				'tax_rate_state'    => 1,
				'tax_rate'          => 1,
				'tax_rate_name'     => 1,
				'tax_rate_priority' => 1,
				'tax_rate_compound' => 1,
				'tax_rate_shipping' => 1,
				'tax_rate_order'    => 1,
			) );

			if ( isset( $data['newRow'] ) ) {
				// Hurrah, shiny and new!
				$tax_rate['tax_rate_class'] = $current_class;
				$tax_rate_id = WC_Tax::_insert_tax_rate( $tax_rate );
			} else {
				// Updating an existing rate ...
				if ( ! empty( $tax_rate ) ) {
					WC_Tax::_update_tax_rate( $tax_rate_id, $tax_rate );
				}
			}

			if ( isset( $data['postcode'] ) ) {
				$postcode = array_map( 'wc_clean', $data['postcode'] );
				$postcode = array_map( 'wc_normalize_postcode', $postcode );
				WC_Tax::_update_tax_rate_postcodes( $tax_rate_id, $postcode );
			}
			if ( isset( $data['city'] ) ) {
				WC_Tax::_update_tax_rate_cities( $tax_rate_id, array_map( 'wc_clean', $data['city'] ) );
			}
		}

		wp_send_json_success( array(
			'rates' => WC_Tax::get_rates_for_tax_class( $current_class ),
		) );
	}

	/**
	 * Handle submissions from assets/js/wc-shipping-zones.js Backbone model.
	 */
	public static function shipping_zones_save_changes() {
		if ( ! isset( $_POST['wc_shipping_zones_nonce'], $_POST['changes'] ) ) {
			wp_send_json_error( 'missing_fields' );
			exit;
		}

		if ( ! wp_verify_nonce( $_POST['wc_shipping_zones_nonce'], 'wc_shipping_zones_nonce' ) ) {
			wp_send_json_error( 'bad_nonce' );
			exit;
		}

		// Check User Caps
		if ( ! current_user_can( 'manage_woocommerce' ) ) {
			wp_send_json_error( 'missing_capabilities' );
			exit;
		}

		$changes = $_POST['changes'];
		foreach ( $changes as $zone_id => $data ) {
			if ( isset( $data['deleted'] ) ) {
				if ( isset( $data['newRow'] ) ) {
					// So the user added and deleted a new row.
					// That's fine, it's not in the database anyways. NEXT!
					continue;
				}
				WC_Shipping_Zones::delete_zone( $zone_id );
				continue;
			}

			$zone_data = array_intersect_key( $data, array(
				'zone_id'        => 1,
				'zone_order'     => 1,
			) );

			if ( isset( $zone_data['zone_id'] ) ) {
				$zone = new WC_Shipping_Zone( $zone_data['zone_id'] );

				if ( isset( $zone_data['zone_order'] ) ) {
					$zone->set_zone_order( $zone_data['zone_order'] );
				}

				$zone->save();
			}
		}

		wp_send_json_success( array(
			'zones' => WC_Shipping_Zones::get_zones(),
		) );
	}

	/**
	 * Handle submissions from assets/js/wc-shipping-zone-methods.js Backbone model.
	 */
	public static function shipping_zone_add_method() {
		if ( ! isset( $_POST['wc_shipping_zones_nonce'], $_POST['zone_id'], $_POST['method_id'] ) ) {
			wp_send_json_error( 'missing_fields' );
			exit;
		}

		if ( ! wp_verify_nonce( $_POST['wc_shipping_zones_nonce'], 'wc_shipping_zones_nonce' ) ) {
			wp_send_json_error( 'bad_nonce' );
			exit;
		}

		// Check User Caps
		if ( ! current_user_can( 'manage_woocommerce' ) ) {
			wp_send_json_error( 'missing_capabilities' );
			exit;
		}

		$zone_id     = wc_clean( $_POST['zone_id'] );
		$zone        = new WC_Shipping_Zone( $zone_id );
		$instance_id = $zone->add_shipping_method( wc_clean( $_POST['method_id'] ) );

		wp_send_json_success( array(
			'instance_id' => $instance_id,
			'zone_id'     => $zone->get_id(),
			'zone_name'   => $zone->get_zone_name(),
			'methods'     => $zone->get_shipping_methods(),
		) );
	}

	/**
	 * Handle submissions from assets/js/wc-shipping-zone-methods.js Backbone model.
	 */
	public static function shipping_zone_methods_save_changes() {
		if ( ! isset( $_POST['wc_shipping_zones_nonce'], $_POST['zone_id'], $_POST['changes'] ) ) {
			wp_send_json_error( 'missing_fields' );
			exit;
		}

		if ( ! wp_verify_nonce( $_POST['wc_shipping_zones_nonce'], 'wc_shipping_zones_nonce' ) ) {
			wp_send_json_error( 'bad_nonce' );
			exit;
		}

		if ( ! current_user_can( 'manage_woocommerce' ) ) {
			wp_send_json_error( 'missing_capabilities' );
			exit;
		}

		global $wpdb;

		$zone_id = wc_clean( $_POST['zone_id'] );
		$zone    = new WC_Shipping_Zone( $zone_id );
		$changes = $_POST['changes'];

		if ( isset( $changes['zone_name'] ) ) {
			$zone->set_zone_name( wc_clean( $changes['zone_name'] ) );
		}

		if ( isset( $changes['zone_locations'] ) ) {
			$zone->clear_locations( array( 'state', 'country', 'continent' ) );
			$locations = array_filter( array_map( 'wc_clean', (array) $changes['zone_locations'] ) );
			foreach ( $locations as $location ) {
				// Each posted location will be in the format type:code
				$location_parts = explode( ':', $location );
				switch ( $location_parts[0] ) {
					case 'state' :
						$zone->add_location( $location_parts[1] . ':' . $location_parts[2], 'state' );
					break;
					case 'country' :
						$zone->add_location( $location_parts[1], 'country' );
					break;
					case 'continent' :
						$zone->add_location( $location_parts[1], 'continent' );
					break;
				}
			}
		}

		if ( isset( $changes['zone_postcodes'] ) ) {
			$zone->clear_locations( 'postcode' );
			$postcodes = array_filter( array_map( 'strtoupper', array_map( 'wc_clean', explode( "\n", $changes['zone_postcodes'] ) ) ) );
			foreach ( $postcodes as $postcode ) {
				$zone->add_location( $postcode, 'postcode' );
			}
		}

		if ( isset( $changes['methods'] ) ) {
			foreach ( $changes['methods'] as $instance_id => $data ) {
				$method_id = $wpdb->get_var( $wpdb->prepare( "SELECT method_id FROM {$wpdb->prefix}woocommerce_shipping_zone_methods WHERE instance_id = %d", $instance_id ) );

				if ( isset( $data['deleted'] ) ) {
					$shipping_method = WC_Shipping_Zones::get_shipping_method( $instance_id );
					$option_key      = $shipping_method->get_instance_option_key();
					if ( $wpdb->delete( "{$wpdb->prefix}woocommerce_shipping_zone_methods", array( 'instance_id' => $instance_id ) ) ) {
						delete_option( $option_key );
						do_action( 'woocommerce_shipping_zone_method_deleted', $instance_id, $method_id, $zone_id );
					}
					continue;
				}

				$method_data = array_intersect_key( $data, array(
					'method_order' => 1,
					'enabled'      => 1,
				) );

				if ( isset( $method_data['method_order'] ) ) {
					$wpdb->update( "{$wpdb->prefix}woocommerce_shipping_zone_methods", array( 'method_order' => absint( $method_data['method_order'] ) ), array( 'instance_id' => absint( $instance_id ) ) );
				}

				if ( isset( $method_data['enabled'] ) ) {
					$is_enabled = absint( 'yes' === $method_data['enabled'] );
					if ( $wpdb->update( "{$wpdb->prefix}woocommerce_shipping_zone_methods", array( 'is_enabled' => $is_enabled ), array( 'instance_id' => absint( $instance_id ) ) ) ) {
						do_action( 'woocommerce_shipping_zone_method_status_toggled', $instance_id, $method_id, $zone_id, $is_enabled );
					}
				}
			}
		}

		$zone->save();

		wp_send_json_success( array(
			'zone_id'   => $zone->get_id(),
			'zone_name' => $zone->get_zone_name(),
			'methods'   => $zone->get_shipping_methods(),
		) );
	}

	/**
	 * Save method settings
	 */
	public static function shipping_zone_methods_save_settings() {
		if ( ! isset( $_POST['wc_shipping_zones_nonce'], $_POST['instance_id'], $_POST['data'] ) ) {
			wp_send_json_error( 'missing_fields' );
			exit;
		}

		if ( ! wp_verify_nonce( $_POST['wc_shipping_zones_nonce'], 'wc_shipping_zones_nonce' ) ) {
			wp_send_json_error( 'bad_nonce' );
			exit;
		}

		if ( ! current_user_can( 'manage_woocommerce' ) ) {
			wp_send_json_error( 'missing_capabilities' );
			exit;
		}

		$instance_id     = absint( $_POST['instance_id'] );
		$zone            = WC_Shipping_Zones::get_zone_by( 'instance_id', $instance_id );
		$shipping_method = WC_Shipping_Zones::get_shipping_method( $instance_id );
		$shipping_method->set_post_data( $_POST['data'] );
		$shipping_method->process_admin_options();

		wp_send_json_success( array(
			'zone_id'   => $zone->get_id(),
			'zone_name' => $zone->get_zone_name(),
			'methods'   => $zone->get_shipping_methods(),
			'errors'    => $shipping_method->get_errors(),
		) );
	}

	/**
	 * Handle submissions from assets/js/wc-shipping-classes.js Backbone model.
	 */
	public static function shipping_classes_save_changes() {
		if ( ! isset( $_POST['wc_shipping_classes_nonce'], $_POST['changes'] ) ) {
			wp_send_json_error( 'missing_fields' );
			exit;
		}

		if ( ! wp_verify_nonce( $_POST['wc_shipping_classes_nonce'], 'wc_shipping_classes_nonce' ) ) {
			wp_send_json_error( 'bad_nonce' );
			exit;
		}

		if ( ! current_user_can( 'manage_woocommerce' ) ) {
			wp_send_json_error( 'missing_capabilities' );
			exit;
		}

		$changes = $_POST['changes'];

		foreach ( $changes as $term_id => $data ) {
			$term_id = absint( $term_id );

			if ( isset( $data['deleted'] ) ) {
				if ( isset( $data['newRow'] ) ) {
					// So the user added and deleted a new row.
					// That's fine, it's not in the database anyways. NEXT!
					continue;
				}
				wp_delete_term( $term_id, 'product_shipping_class' );
				continue;
			}

			$update_args = array();

			if ( isset( $data['name'] ) ) {
				$update_args['name'] = wc_clean( $data['name'] );
			}

			if ( isset( $data['slug'] ) ) {
				$update_args['slug'] = wc_clean( $data['slug'] );
			}

			if ( isset( $data['description'] ) ) {
				$update_args['description'] = wc_clean( $data['description'] );
			}

			if ( isset( $data['newRow'] ) ) {
				$update_args = array_filter( $update_args );
				if ( empty( $update_args['name'] ) ) {
					continue;
				}
				$term_id = wp_insert_term( $update_args['name'], 'product_shipping_class', $update_args );
			} else {
				wp_update_term( $term_id, 'product_shipping_class', $update_args );
			}

			do_action( 'woocommerce_shipping_classes_save_class', $term_id, $data );
		}

		$wc_shipping = WC_Shipping::instance();

		wp_send_json_success( array(
			'shipping_classes' => $wc_shipping->get_shipping_classes(),
		) );
	}
}

WC_AJAX::init();