class-wc-ajax.php 85 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797
  1. <?php
  2. /**
  3. * WooCommerce WC_AJAX. AJAX Event Handlers.
  4. *
  5. * @class WC_AJAX
  6. * @package WooCommerce/Classes
  7. */
  8. defined( 'ABSPATH' ) || exit;
  9. /**
  10. * WC_Ajax class.
  11. */
  12. class WC_AJAX {
  13. /**
  14. * Hook in ajax handlers.
  15. */
  16. public static function init() {
  17. add_action( 'init', array( __CLASS__, 'define_ajax' ), 0 );
  18. add_action( 'template_redirect', array( __CLASS__, 'do_wc_ajax' ), 0 );
  19. self::add_ajax_events();
  20. }
  21. /**
  22. * Get WC Ajax Endpoint.
  23. *
  24. * @param string $request Optional.
  25. * @return string
  26. */
  27. public static function get_endpoint( $request = '' ) {
  28. 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' ), home_url( '/', 'relative' ) ) ), $request ) );
  29. }
  30. /**
  31. * Set WC AJAX constant and headers.
  32. */
  33. public static function define_ajax() {
  34. if ( ! empty( $_GET['wc-ajax'] ) ) {
  35. wc_maybe_define_constant( 'DOING_AJAX', true );
  36. wc_maybe_define_constant( 'WC_DOING_AJAX', true );
  37. if ( ! WP_DEBUG || ( WP_DEBUG && ! WP_DEBUG_DISPLAY ) ) {
  38. @ini_set( 'display_errors', 0 ); // Turn off display_errors during AJAX events to prevent malformed JSON.
  39. }
  40. $GLOBALS['wpdb']->hide_errors();
  41. }
  42. }
  43. /**
  44. * Send headers for WC Ajax Requests.
  45. *
  46. * @since 2.5.0
  47. */
  48. private static function wc_ajax_headers() {
  49. send_origin_headers();
  50. @header( 'Content-Type: text/html; charset=' . get_option( 'blog_charset' ) );
  51. @header( 'X-Robots-Tag: noindex' );
  52. send_nosniff_header();
  53. wc_nocache_headers();
  54. status_header( 200 );
  55. }
  56. /**
  57. * Check for WC Ajax request and fire action.
  58. */
  59. public static function do_wc_ajax() {
  60. global $wp_query;
  61. if ( ! empty( $_GET['wc-ajax'] ) ) {
  62. $wp_query->set( 'wc-ajax', sanitize_text_field( wp_unslash( $_GET['wc-ajax'] ) ) );
  63. }
  64. $action = $wp_query->get( 'wc-ajax' );
  65. if ( $action ) {
  66. self::wc_ajax_headers();
  67. $action = sanitize_text_field( $action );
  68. do_action( 'wc_ajax_' . $action );
  69. wp_die();
  70. }
  71. }
  72. /**
  73. * Hook in methods - uses WordPress ajax handlers (admin-ajax).
  74. */
  75. public static function add_ajax_events() {
  76. // woocommerce_EVENT => nopriv.
  77. $ajax_events = array(
  78. 'get_refreshed_fragments' => true,
  79. 'apply_coupon' => true,
  80. 'remove_coupon' => true,
  81. 'update_shipping_method' => true,
  82. 'get_cart_totals' => true,
  83. 'update_order_review' => true,
  84. 'add_to_cart' => true,
  85. 'remove_from_cart' => true,
  86. 'checkout' => true,
  87. 'get_variation' => true,
  88. 'get_customer_location' => true,
  89. 'feature_product' => false,
  90. 'mark_order_status' => false,
  91. 'get_order_details' => false,
  92. 'add_attribute' => false,
  93. 'add_new_attribute' => false,
  94. 'remove_variation' => false,
  95. 'remove_variations' => false,
  96. 'save_attributes' => false,
  97. 'add_variation' => false,
  98. 'link_all_variations' => false,
  99. 'revoke_access_to_download' => false,
  100. 'grant_access_to_download' => false,
  101. 'get_customer_details' => false,
  102. 'add_order_item' => false,
  103. 'add_order_fee' => false,
  104. 'add_order_shipping' => false,
  105. 'add_order_tax' => false,
  106. 'add_coupon_discount' => false,
  107. 'remove_order_coupon' => false,
  108. 'remove_order_item' => false,
  109. 'remove_order_tax' => false,
  110. 'reduce_order_item_stock' => false,
  111. 'increase_order_item_stock' => false,
  112. 'add_order_item_meta' => false,
  113. 'remove_order_item_meta' => false,
  114. 'calc_line_taxes' => false,
  115. 'save_order_items' => false,
  116. 'load_order_items' => false,
  117. 'add_order_note' => false,
  118. 'delete_order_note' => false,
  119. 'json_search_products' => false,
  120. 'json_search_products_and_variations' => false,
  121. 'json_search_downloadable_products_and_variations' => false,
  122. 'json_search_customers' => false,
  123. 'json_search_categories' => false,
  124. 'term_ordering' => false,
  125. 'product_ordering' => false,
  126. 'refund_line_items' => false,
  127. 'delete_refund' => false,
  128. 'rated' => false,
  129. 'update_api_key' => false,
  130. 'load_variations' => false,
  131. 'save_variations' => false,
  132. 'bulk_edit_variations' => false,
  133. 'tax_rates_save_changes' => false,
  134. 'shipping_zones_save_changes' => false,
  135. 'shipping_zone_add_method' => false,
  136. 'shipping_zone_methods_save_changes' => false,
  137. 'shipping_zone_methods_save_settings' => false,
  138. 'shipping_classes_save_changes' => false,
  139. 'toggle_gateway_enabled' => false,
  140. );
  141. foreach ( $ajax_events as $ajax_event => $nopriv ) {
  142. add_action( 'wp_ajax_woocommerce_' . $ajax_event, array( __CLASS__, $ajax_event ) );
  143. if ( $nopriv ) {
  144. add_action( 'wp_ajax_nopriv_woocommerce_' . $ajax_event, array( __CLASS__, $ajax_event ) );
  145. // WC AJAX can be used for frontend ajax requests.
  146. add_action( 'wc_ajax_' . $ajax_event, array( __CLASS__, $ajax_event ) );
  147. }
  148. }
  149. }
  150. /**
  151. * Get a refreshed cart fragment, including the mini cart HTML.
  152. */
  153. public static function get_refreshed_fragments() {
  154. ob_start();
  155. woocommerce_mini_cart();
  156. $mini_cart = ob_get_clean();
  157. $data = array(
  158. 'fragments' => apply_filters(
  159. 'woocommerce_add_to_cart_fragments', array(
  160. 'div.widget_shopping_cart_content' => '<div class="widget_shopping_cart_content">' . $mini_cart . '</div>',
  161. )
  162. ),
  163. '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() ),
  164. );
  165. wp_send_json( $data );
  166. }
  167. /**
  168. * AJAX apply coupon on checkout page.
  169. */
  170. public static function apply_coupon() {
  171. check_ajax_referer( 'apply-coupon', 'security' );
  172. if ( ! empty( $_POST['coupon_code'] ) ) {
  173. WC()->cart->add_discount( sanitize_text_field( wp_unslash( $_POST['coupon_code'] ) ) );
  174. } else {
  175. wc_add_notice( WC_Coupon::get_generic_coupon_error( WC_Coupon::E_WC_COUPON_PLEASE_ENTER ), 'error' );
  176. }
  177. wc_print_notices();
  178. wp_die();
  179. }
  180. /**
  181. * AJAX remove coupon on cart and checkout page.
  182. */
  183. public static function remove_coupon() {
  184. check_ajax_referer( 'remove-coupon', 'security' );
  185. $coupon = isset( $_POST['coupon'] ) ? wc_clean( $_POST['coupon'] ) : false;
  186. if ( empty( $coupon ) ) {
  187. wc_add_notice( __( 'Sorry there was a problem removing this coupon.', 'woocommerce' ), 'error' );
  188. } else {
  189. WC()->cart->remove_coupon( $coupon );
  190. wc_add_notice( __( 'Coupon has been removed.', 'woocommerce' ) );
  191. }
  192. wc_print_notices();
  193. wp_die();
  194. }
  195. /**
  196. * AJAX update shipping method on cart page.
  197. */
  198. public static function update_shipping_method() {
  199. check_ajax_referer( 'update-shipping-method', 'security' );
  200. wc_maybe_define_constant( 'WOOCOMMERCE_CART', true );
  201. $chosen_shipping_methods = WC()->session->get( 'chosen_shipping_methods' );
  202. if ( isset( $_POST['shipping_method'] ) && is_array( $_POST['shipping_method'] ) ) {
  203. foreach ( $_POST['shipping_method'] as $i => $value ) {
  204. $chosen_shipping_methods[ $i ] = wc_clean( $value );
  205. }
  206. }
  207. WC()->session->set( 'chosen_shipping_methods', $chosen_shipping_methods );
  208. self::get_cart_totals();
  209. }
  210. /**
  211. * AJAX receive updated cart_totals div.
  212. */
  213. public static function get_cart_totals() {
  214. wc_maybe_define_constant( 'WOOCOMMERCE_CART', true );
  215. WC()->cart->calculate_totals();
  216. woocommerce_cart_totals();
  217. wp_die();
  218. }
  219. /**
  220. * Session has expired.
  221. */
  222. private static function update_order_review_expired() {
  223. wp_send_json(
  224. array(
  225. 'fragments' => apply_filters(
  226. 'woocommerce_update_order_review_fragments', array(
  227. '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>',
  228. )
  229. ),
  230. )
  231. );
  232. }
  233. /**
  234. * AJAX update order review on checkout.
  235. */
  236. public static function update_order_review() {
  237. check_ajax_referer( 'update-order-review', 'security' );
  238. wc_maybe_define_constant( 'WOOCOMMERCE_CHECKOUT', true );
  239. if ( WC()->cart->is_empty() && ! is_customize_preview() ) {
  240. self::update_order_review_expired();
  241. }
  242. do_action( 'woocommerce_checkout_update_order_review', $_POST['post_data'] );
  243. $chosen_shipping_methods = WC()->session->get( 'chosen_shipping_methods' );
  244. if ( isset( $_POST['shipping_method'] ) && is_array( $_POST['shipping_method'] ) ) {
  245. foreach ( $_POST['shipping_method'] as $i => $value ) {
  246. $chosen_shipping_methods[ $i ] = wc_clean( $value );
  247. }
  248. }
  249. WC()->session->set( 'chosen_shipping_methods', $chosen_shipping_methods );
  250. WC()->session->set( 'chosen_payment_method', empty( $_POST['payment_method'] ) ? '' : $_POST['payment_method'] );
  251. WC()->customer->set_props(
  252. array(
  253. 'billing_country' => isset( $_POST['country'] ) ? wp_unslash( $_POST['country'] ) : null,
  254. 'billing_state' => isset( $_POST['state'] ) ? wp_unslash( $_POST['state'] ) : null,
  255. 'billing_postcode' => isset( $_POST['postcode'] ) ? wp_unslash( $_POST['postcode'] ) : null,
  256. 'billing_city' => isset( $_POST['city'] ) ? wp_unslash( $_POST['city'] ) : null,
  257. 'billing_address_1' => isset( $_POST['address'] ) ? wp_unslash( $_POST['address'] ) : null,
  258. 'billing_address_2' => isset( $_POST['address_2'] ) ? wp_unslash( $_POST['address_2'] ) : null,
  259. )
  260. );
  261. if ( wc_ship_to_billing_address_only() ) {
  262. WC()->customer->set_props(
  263. array(
  264. 'shipping_country' => isset( $_POST['country'] ) ? wp_unslash( $_POST['country'] ) : null,
  265. 'shipping_state' => isset( $_POST['state'] ) ? wp_unslash( $_POST['state'] ) : null,
  266. 'shipping_postcode' => isset( $_POST['postcode'] ) ? wp_unslash( $_POST['postcode'] ) : null,
  267. 'shipping_city' => isset( $_POST['city'] ) ? wp_unslash( $_POST['city'] ) : null,
  268. 'shipping_address_1' => isset( $_POST['address'] ) ? wp_unslash( $_POST['address'] ) : null,
  269. 'shipping_address_2' => isset( $_POST['address_2'] ) ? wp_unslash( $_POST['address_2'] ) : null,
  270. )
  271. );
  272. } else {
  273. WC()->customer->set_props(
  274. array(
  275. 'shipping_country' => isset( $_POST['s_country'] ) ? wp_unslash( $_POST['s_country'] ) : null,
  276. 'shipping_state' => isset( $_POST['s_state'] ) ? wp_unslash( $_POST['s_state'] ) : null,
  277. 'shipping_postcode' => isset( $_POST['s_postcode'] ) ? wp_unslash( $_POST['s_postcode'] ) : null,
  278. 'shipping_city' => isset( $_POST['s_city'] ) ? wp_unslash( $_POST['s_city'] ) : null,
  279. 'shipping_address_1' => isset( $_POST['s_address'] ) ? wp_unslash( $_POST['s_address'] ) : null,
  280. 'shipping_address_2' => isset( $_POST['s_address_2'] ) ? wp_unslash( $_POST['s_address_2'] ) : null,
  281. )
  282. );
  283. }
  284. if ( wc_string_to_bool( $_POST['has_full_address'] ) ) {
  285. WC()->customer->set_calculated_shipping( true );
  286. } else {
  287. WC()->customer->set_calculated_shipping( false );
  288. }
  289. WC()->customer->save();
  290. WC()->cart->calculate_totals();
  291. // Get order review fragment
  292. ob_start();
  293. woocommerce_order_review();
  294. $woocommerce_order_review = ob_get_clean();
  295. // Get checkout payment fragment
  296. ob_start();
  297. woocommerce_checkout_payment();
  298. $woocommerce_checkout_payment = ob_get_clean();
  299. // Get messages if reload checkout is not true
  300. $messages = '';
  301. if ( ! isset( WC()->session->reload_checkout ) ) {
  302. ob_start();
  303. wc_print_notices();
  304. $messages = ob_get_clean();
  305. }
  306. unset( WC()->session->refresh_totals, WC()->session->reload_checkout );
  307. wp_send_json(
  308. array(
  309. 'result' => empty( $messages ) ? 'success' : 'failure',
  310. 'messages' => $messages,
  311. 'reload' => isset( WC()->session->reload_checkout ) ? 'true' : 'false',
  312. 'fragments' => apply_filters(
  313. 'woocommerce_update_order_review_fragments', array(
  314. '.woocommerce-checkout-review-order-table' => $woocommerce_order_review,
  315. '.woocommerce-checkout-payment' => $woocommerce_checkout_payment,
  316. )
  317. ),
  318. )
  319. );
  320. }
  321. /**
  322. * AJAX add to cart.
  323. */
  324. public static function add_to_cart() {
  325. ob_start();
  326. $product_id = apply_filters( 'woocommerce_add_to_cart_product_id', absint( $_POST['product_id'] ) );
  327. $product = wc_get_product( $product_id );
  328. $quantity = empty( $_POST['quantity'] ) ? 1 : wc_stock_amount( $_POST['quantity'] );
  329. $passed_validation = apply_filters( 'woocommerce_add_to_cart_validation', true, $product_id, $quantity );
  330. $product_status = get_post_status( $product_id );
  331. $variation_id = 0;
  332. $variation = array();
  333. if ( $product && 'variation' === $product->get_type() ) {
  334. $variation_id = $product_id;
  335. $product_id = $product->get_parent_id();
  336. $variation = $product->get_variation_attributes();
  337. }
  338. if ( $passed_validation && false !== WC()->cart->add_to_cart( $product_id, $quantity, $variation_id, $variation ) && 'publish' === $product_status ) {
  339. do_action( 'woocommerce_ajax_added_to_cart', $product_id );
  340. if ( 'yes' === get_option( 'woocommerce_cart_redirect_after_add' ) ) {
  341. wc_add_to_cart_message( array( $product_id => $quantity ), true );
  342. }
  343. // Return fragments
  344. self::get_refreshed_fragments();
  345. } else {
  346. // If there was an error adding to the cart, redirect to the product page to show any errors
  347. $data = array(
  348. 'error' => true,
  349. 'product_url' => apply_filters( 'woocommerce_cart_redirect_after_error', get_permalink( $product_id ), $product_id ),
  350. );
  351. wp_send_json( $data );
  352. }
  353. }
  354. /**
  355. * AJAX remove from cart.
  356. */
  357. public static function remove_from_cart() {
  358. ob_start();
  359. $cart_item_key = wc_clean( $_POST['cart_item_key'] );
  360. if ( $cart_item_key && false !== WC()->cart->remove_cart_item( $cart_item_key ) ) {
  361. self::get_refreshed_fragments();
  362. } else {
  363. wp_send_json_error();
  364. }
  365. }
  366. /**
  367. * Process ajax checkout form.
  368. */
  369. public static function checkout() {
  370. wc_maybe_define_constant( 'WOOCOMMERCE_CHECKOUT', true );
  371. WC()->checkout()->process_checkout();
  372. wp_die( 0 );
  373. }
  374. /**
  375. * Get a matching variation based on posted attributes.
  376. */
  377. public static function get_variation() {
  378. ob_start();
  379. if ( empty( $_POST['product_id'] ) || ! ( $variable_product = wc_get_product( absint( $_POST['product_id'] ) ) ) ) {
  380. wp_die();
  381. }
  382. $data_store = WC_Data_Store::load( 'product' );
  383. $variation_id = $data_store->find_matching_product_variation( $variable_product, wp_unslash( $_POST ) );
  384. $variation = $variation_id ? $variable_product->get_available_variation( $variation_id ) : false;
  385. wp_send_json( $variation );
  386. }
  387. /**
  388. * Locate user via AJAX.
  389. */
  390. public static function get_customer_location() {
  391. $location_hash = WC_Cache_Helper::geolocation_ajax_get_location_hash();
  392. wp_send_json_success( array( 'hash' => $location_hash ) );
  393. }
  394. /**
  395. * Toggle Featured status of a product from admin.
  396. */
  397. public static function feature_product() {
  398. if ( current_user_can( 'edit_products' ) && check_admin_referer( 'woocommerce-feature-product' ) ) {
  399. $product = wc_get_product( absint( $_GET['product_id'] ) );
  400. if ( $product ) {
  401. $product->set_featured( ! $product->get_featured() );
  402. $product->save();
  403. }
  404. }
  405. wp_safe_redirect( wp_get_referer() ? remove_query_arg( array( 'trashed', 'untrashed', 'deleted', 'ids' ), wp_get_referer() ) : admin_url( 'edit.php?post_type=product' ) );
  406. exit;
  407. }
  408. /**
  409. * Mark an order with a status.
  410. */
  411. public static function mark_order_status() {
  412. if ( current_user_can( 'edit_shop_orders' ) && check_admin_referer( 'woocommerce-mark-order-status' ) ) {
  413. $status = sanitize_text_field( $_GET['status'] );
  414. $order = wc_get_order( absint( $_GET['order_id'] ) );
  415. if ( wc_is_order_status( 'wc-' . $status ) && $order ) {
  416. // Initialize payment gateways in case order has hooked status transition actions.
  417. wc()->payment_gateways();
  418. $order->update_status( $status, '', true );
  419. do_action( 'woocommerce_order_edit_status', $order->get_id(), $status );
  420. }
  421. }
  422. wp_safe_redirect( wp_get_referer() ? wp_get_referer() : admin_url( 'edit.php?post_type=shop_order' ) );
  423. exit;
  424. }
  425. /**
  426. * Get order details.
  427. */
  428. public static function get_order_details() {
  429. check_admin_referer( 'woocommerce-preview-order', 'security' );
  430. if ( ! current_user_can( 'edit_shop_orders' ) ) {
  431. wp_die( -1 );
  432. }
  433. $order = wc_get_order( absint( $_GET['order_id'] ) ); // WPCS: sanitization ok.
  434. if ( $order ) {
  435. include_once 'admin/list-tables/class-wc-admin-list-table-orders.php';
  436. wp_send_json_success( WC_Admin_List_Table_Orders::order_preview_get_order_details( $order ) );
  437. }
  438. wp_die();
  439. }
  440. /**
  441. * Add an attribute row.
  442. */
  443. public static function add_attribute() {
  444. ob_start();
  445. check_ajax_referer( 'add-attribute', 'security' );
  446. if ( ! current_user_can( 'edit_products' ) ) {
  447. wp_die( -1 );
  448. }
  449. $i = absint( $_POST['i'] );
  450. $metabox_class = array();
  451. $attribute = new WC_Product_Attribute();
  452. $attribute->set_id( wc_attribute_taxonomy_id_by_name( sanitize_text_field( $_POST['taxonomy'] ) ) );
  453. $attribute->set_name( sanitize_text_field( $_POST['taxonomy'] ) );
  454. $attribute->set_visible( apply_filters( 'woocommerce_attribute_default_visibility', 1 ) );
  455. $attribute->set_variation( apply_filters( 'woocommerce_attribute_default_is_variation', 0 ) );
  456. if ( $attribute->is_taxonomy() ) {
  457. $metabox_class[] = 'taxonomy';
  458. $metabox_class[] = $attribute->get_name();
  459. }
  460. include 'admin/meta-boxes/views/html-product-attribute.php';
  461. wp_die();
  462. }
  463. /**
  464. * Add a new attribute via ajax function.
  465. */
  466. public static function add_new_attribute() {
  467. check_ajax_referer( 'add-attribute', 'security' );
  468. if ( current_user_can( 'manage_product_terms' ) ) {
  469. $taxonomy = esc_attr( $_POST['taxonomy'] );
  470. $term = wc_clean( $_POST['term'] );
  471. if ( taxonomy_exists( $taxonomy ) ) {
  472. $result = wp_insert_term( $term, $taxonomy );
  473. if ( is_wp_error( $result ) ) {
  474. wp_send_json(
  475. array(
  476. 'error' => $result->get_error_message(),
  477. )
  478. );
  479. } else {
  480. $term = get_term_by( 'id', $result['term_id'], $taxonomy );
  481. wp_send_json(
  482. array(
  483. 'term_id' => $term->term_id,
  484. 'name' => $term->name,
  485. 'slug' => $term->slug,
  486. )
  487. );
  488. }
  489. }
  490. }
  491. wp_die( -1 );
  492. }
  493. /**
  494. * Delete variations via ajax function.
  495. */
  496. public static function remove_variations() {
  497. check_ajax_referer( 'delete-variations', 'security' );
  498. if ( current_user_can( 'edit_products' ) ) {
  499. $variation_ids = (array) $_POST['variation_ids'];
  500. foreach ( $variation_ids as $variation_id ) {
  501. if ( 'product_variation' === get_post_type( $variation_id ) ) {
  502. $variation = wc_get_product( $variation_id );
  503. $variation->delete( true );
  504. }
  505. }
  506. }
  507. wp_die( -1 );
  508. }
  509. /**
  510. * Save attributes via ajax.
  511. */
  512. public static function save_attributes() {
  513. check_ajax_referer( 'save-attributes', 'security' );
  514. if ( ! current_user_can( 'edit_products' ) ) {
  515. wp_die( -1 );
  516. }
  517. parse_str( $_POST['data'], $data );
  518. $attributes = WC_Meta_Box_Product_Data::prepare_attributes( $data );
  519. $product_id = absint( $_POST['post_id'] );
  520. $product_type = ! empty( $_POST['product_type'] ) ? wc_clean( $_POST['product_type'] ) : 'simple';
  521. $classname = WC_Product_Factory::get_product_classname( $product_id, $product_type );
  522. $product = new $classname( $product_id );
  523. $product->set_attributes( $attributes );
  524. $product->save();
  525. wp_die();
  526. }
  527. /**
  528. * Add variation via ajax function.
  529. */
  530. public static function add_variation() {
  531. check_ajax_referer( 'add-variation', 'security' );
  532. if ( ! current_user_can( 'edit_products' ) ) {
  533. wp_die( -1 );
  534. }
  535. global $post; // Set $post global so its available, like within the admin screens.
  536. $product_id = intval( $_POST['post_id'] );
  537. $post = get_post( $product_id );
  538. $loop = intval( $_POST['loop'] );
  539. $product_object = wc_get_product( $product_id );
  540. $variation_object = new WC_Product_Variation();
  541. $variation_object->set_parent_id( $product_id );
  542. $variation_object->set_attributes( array_fill_keys( array_map( 'sanitize_title', array_keys( $product_object->get_variation_attributes() ) ), '' ) );
  543. $variation_id = $variation_object->save();
  544. $variation = get_post( $variation_id );
  545. $variation_data = array_merge( array_map( 'maybe_unserialize', get_post_custom( $variation_id ) ), wc_get_product_variation_attributes( $variation_id ) ); // kept for BW compatibility.
  546. include 'admin/meta-boxes/views/html-variation-admin.php';
  547. wp_die();
  548. }
  549. /**
  550. * Link all variations via ajax function.
  551. */
  552. public static function link_all_variations() {
  553. check_ajax_referer( 'link-variations', 'security' );
  554. if ( ! current_user_can( 'edit_products' ) ) {
  555. wp_die( -1 );
  556. }
  557. wc_maybe_define_constant( 'WC_MAX_LINKED_VARIATIONS', 49 );
  558. wc_set_time_limit( 0 );
  559. $post_id = intval( $_POST['post_id'] );
  560. if ( ! $post_id ) {
  561. wp_die();
  562. }
  563. $product = wc_get_product( $post_id );
  564. $attributes = wc_list_pluck( array_filter( $product->get_attributes(), 'wc_attributes_array_filter_variation' ), 'get_slugs' );
  565. if ( ! empty( $attributes ) ) {
  566. // Get existing variations so we don't create duplicates.
  567. $existing_variations = array_map( 'wc_get_product', $product->get_children() );
  568. $existing_attributes = array();
  569. foreach ( $existing_variations as $existing_variation ) {
  570. $existing_attributes[] = $existing_variation->get_attributes();
  571. }
  572. $added = 0;
  573. $possible_attributes = array_reverse( wc_array_cartesian( $attributes ) );
  574. foreach ( $possible_attributes as $possible_attribute ) {
  575. if ( in_array( $possible_attribute, $existing_attributes ) ) {
  576. continue;
  577. }
  578. $variation = new WC_Product_Variation();
  579. $variation->set_parent_id( $post_id );
  580. $variation->set_attributes( $possible_attribute );
  581. do_action( 'product_variation_linked', $variation->save() );
  582. if ( ( $added ++ ) > WC_MAX_LINKED_VARIATIONS ) {
  583. break;
  584. }
  585. }
  586. echo $added;
  587. }
  588. $data_store = $product->get_data_store();
  589. $data_store->sort_all_product_variations( $product->get_id() );
  590. wp_die();
  591. }
  592. /**
  593. * Delete download permissions via ajax function.
  594. */
  595. public static function revoke_access_to_download() {
  596. check_ajax_referer( 'revoke-access', 'security' );
  597. if ( ! current_user_can( 'edit_shop_orders' ) ) {
  598. wp_die( -1 );
  599. }
  600. $download_id = $_POST['download_id'];
  601. $product_id = intval( $_POST['product_id'] );
  602. $order_id = intval( $_POST['order_id'] );
  603. $permission_id = absint( $_POST['permission_id'] );
  604. $data_store = WC_Data_Store::load( 'customer-download' );
  605. $data_store->delete_by_id( $permission_id );
  606. do_action( 'woocommerce_ajax_revoke_access_to_product_download', $download_id, $product_id, $order_id, $permission_id );
  607. wp_die();
  608. }
  609. /**
  610. * Grant download permissions via ajax function.
  611. */
  612. public static function grant_access_to_download() {
  613. check_ajax_referer( 'grant-access', 'security' );
  614. if ( ! current_user_can( 'edit_shop_orders' ) ) {
  615. wp_die( -1 );
  616. }
  617. global $wpdb;
  618. $wpdb->hide_errors();
  619. $order_id = intval( $_POST['order_id'] );
  620. $product_ids = $_POST['product_ids'];
  621. $loop = intval( $_POST['loop'] );
  622. $file_counter = 0;
  623. $order = wc_get_order( $order_id );
  624. if ( ! is_array( $product_ids ) ) {
  625. $product_ids = array( $product_ids );
  626. }
  627. foreach ( $product_ids as $product_id ) {
  628. $product = wc_get_product( $product_id );
  629. $files = $product->get_downloads();
  630. if ( ! $order->get_billing_email() ) {
  631. wp_die();
  632. }
  633. if ( ! empty( $files ) ) {
  634. foreach ( $files as $download_id => $file ) {
  635. if ( $inserted_id = wc_downloadable_file_permission( $download_id, $product_id, $order ) ) {
  636. $download = new WC_Customer_Download( $inserted_id );
  637. $loop ++;
  638. $file_counter ++;
  639. if ( $file->get_name() ) {
  640. $file_count = $file->get_name();
  641. } else {
  642. $file_count = sprintf( __( 'File %d', 'woocommerce' ), $file_counter );
  643. }
  644. include 'admin/meta-boxes/views/html-order-download-permission.php';
  645. }
  646. }
  647. }
  648. }
  649. wp_die();
  650. }
  651. /**
  652. * Get customer details via ajax.
  653. */
  654. public static function get_customer_details() {
  655. check_ajax_referer( 'get-customer-details', 'security' );
  656. if ( ! current_user_can( 'edit_shop_orders' ) ) {
  657. wp_die( -1 );
  658. }
  659. $user_id = absint( $_POST['user_id'] );
  660. $customer = new WC_Customer( $user_id );
  661. if ( has_filter( 'woocommerce_found_customer_details' ) ) {
  662. wc_deprecated_function( 'The woocommerce_found_customer_details filter', '3.0', 'woocommerce_ajax_get_customer_details' );
  663. }
  664. $data = $customer->get_data();
  665. $data['date_created'] = $data['date_created'] ? $data['date_created']->getTimestamp() : null;
  666. $data['date_modified'] = $data['date_modified'] ? $data['date_modified']->getTimestamp() : null;
  667. $customer_data = apply_filters( 'woocommerce_ajax_get_customer_details', $data, $customer, $user_id );
  668. wp_send_json( $customer_data );
  669. }
  670. /**
  671. * Add order item via ajax.
  672. */
  673. public static function add_order_item() {
  674. check_ajax_referer( 'order-item', 'security' );
  675. if ( ! current_user_can( 'edit_shop_orders' ) ) {
  676. wp_die( -1 );
  677. }
  678. try {
  679. $order_id = absint( $_POST['order_id'] );
  680. $order = wc_get_order( $order_id );
  681. $items_to_add = wp_parse_id_list( is_array( $_POST['item_to_add'] ) ? $_POST['item_to_add'] : array( $_POST['item_to_add'] ) );
  682. $items = ( ! empty( $_POST['items'] ) ) ? $_POST['items'] : '';
  683. $added_items = array();
  684. if ( ! $order ) {
  685. throw new Exception( __( 'Invalid order', 'woocommerce' ) );
  686. }
  687. // If we passed through items it means we need to save first before adding a new one.
  688. if ( ! empty( $items ) ) {
  689. $save_items = array();
  690. parse_str( $items, $save_items );
  691. // Save order items.
  692. wc_save_order_items( $order->get_id(), $save_items );
  693. }
  694. foreach ( $items_to_add as $item_to_add ) {
  695. if ( ! in_array( get_post_type( $item_to_add ), array( 'product', 'product_variation' ) ) ) {
  696. continue;
  697. }
  698. $item_id = $order->add_product( wc_get_product( $item_to_add ) );
  699. $item = apply_filters( 'woocommerce_ajax_order_item', $order->get_item( $item_id ), $item_id );
  700. $added_items[ $item_id ] = $item;
  701. do_action( 'woocommerce_ajax_add_order_item_meta', $item_id, $item, $order );
  702. }
  703. $last_item = ! empty( $added_items ) ? end( $added_items ) : null;
  704. wc_do_deprecated_action( 'woocommerce_ajax_added_order_items', array( is_a( $last_item, 'WC_Order_Item' ) ? $last_item->get_id() : null, $last_item, $order ), '3.4', 'woocommerce_ajax_order_items_added action instead.' );
  705. do_action( 'woocommerce_ajax_order_items_added', $added_items, $order );
  706. $data = get_post_meta( $order_id );
  707. ob_start();
  708. include 'admin/meta-boxes/views/html-order-items.php';
  709. wp_send_json_success(
  710. array(
  711. 'html' => ob_get_clean(),
  712. )
  713. );
  714. } catch ( Exception $e ) {
  715. wp_send_json_error( array( 'error' => $e->getMessage() ) );
  716. }
  717. }
  718. /**
  719. * Add order fee via ajax.
  720. */
  721. public static function add_order_fee() {
  722. check_ajax_referer( 'order-item', 'security' );
  723. if ( ! current_user_can( 'edit_shop_orders' ) ) {
  724. wp_die( -1 );
  725. }
  726. try {
  727. $order_id = absint( $_POST['order_id'] );
  728. $amount = wc_clean( $_POST['amount'] );
  729. $order = wc_get_order( $order_id );
  730. $calculate_tax_args = array(
  731. 'country' => strtoupper( wc_clean( $_POST['country'] ) ),
  732. 'state' => strtoupper( wc_clean( $_POST['state'] ) ),
  733. 'postcode' => strtoupper( wc_clean( $_POST['postcode'] ) ),
  734. 'city' => strtoupper( wc_clean( $_POST['city'] ) ),
  735. );
  736. if ( ! $order ) {
  737. throw new exception( __( 'Invalid order', 'woocommerce' ) );
  738. }
  739. if ( strstr( $amount, '%' ) ) {
  740. $formatted_amount = $amount;
  741. $percent = floatval( trim( $amount, '%' ) );
  742. $amount = $order->get_total() * ( $percent / 100 );
  743. } else {
  744. $amount = floatval( $amount );
  745. $formatted_amount = wc_price( $amount, array( 'currency' => $order->get_currency() ) );
  746. }
  747. $fee = new WC_Order_Item_Fee();
  748. $fee->set_amount( $amount );
  749. $fee->set_total( $amount );
  750. $fee->set_name( sprintf( __( '%s fee', 'woocommerce' ), $formatted_amount ) );
  751. $order->add_item( $fee );
  752. $order->calculate_taxes( $calculate_tax_args );
  753. $order->calculate_totals( false );
  754. $order->save();
  755. ob_start();
  756. include 'admin/meta-boxes/views/html-order-items.php';
  757. wp_send_json_success(
  758. array(
  759. 'html' => ob_get_clean(),
  760. )
  761. );
  762. } catch ( Exception $e ) {
  763. wp_send_json_error( array( 'error' => $e->getMessage() ) );
  764. }
  765. }
  766. /**
  767. * Add order shipping cost via ajax.
  768. */
  769. public static function add_order_shipping() {
  770. check_ajax_referer( 'order-item', 'security' );
  771. if ( ! current_user_can( 'edit_shop_orders' ) ) {
  772. wp_die( -1 );
  773. }
  774. try {
  775. $order_id = absint( $_POST['order_id'] );
  776. $order = wc_get_order( $order_id );
  777. $order_taxes = $order->get_taxes();
  778. $shipping_methods = WC()->shipping() ? WC()->shipping->load_shipping_methods() : array();
  779. // Add new shipping
  780. $item = new WC_Order_Item_Shipping();
  781. $item->set_shipping_rate( new WC_Shipping_Rate() );
  782. $item->set_order_id( $order_id );
  783. $item_id = $item->save();
  784. ob_start();
  785. include 'admin/meta-boxes/views/html-order-shipping.php';
  786. wp_send_json_success(
  787. array(
  788. 'html' => ob_get_clean(),
  789. )
  790. );
  791. } catch ( Exception $e ) {
  792. wp_send_json_error( array( 'error' => $e->getMessage() ) );
  793. }
  794. }
  795. /**
  796. * Add order tax column via ajax.
  797. */
  798. public static function add_order_tax() {
  799. check_ajax_referer( 'order-item', 'security' );
  800. if ( ! current_user_can( 'edit_shop_orders' ) ) {
  801. wp_die( -1 );
  802. }
  803. try {
  804. $order_id = absint( $_POST['order_id'] );
  805. $rate_id = absint( $_POST['rate_id'] );
  806. $order = wc_get_order( $order_id );
  807. $data = get_post_meta( $order_id );
  808. // Add new tax
  809. $item = new WC_Order_Item_Tax();
  810. $item->set_rate( $rate_id );
  811. $item->set_order_id( $order_id );
  812. $item->save();
  813. ob_start();
  814. include 'admin/meta-boxes/views/html-order-items.php';
  815. wp_send_json_success(
  816. array(
  817. 'html' => ob_get_clean(),
  818. )
  819. );
  820. } catch ( Exception $e ) {
  821. wp_send_json_error( array( 'error' => $e->getMessage() ) );
  822. }
  823. }
  824. /**
  825. * Add order discount via ajax.
  826. */
  827. public static function add_coupon_discount() {
  828. check_ajax_referer( 'order-item', 'security' );
  829. if ( ! current_user_can( 'edit_shop_orders' ) ) {
  830. wp_die( -1 );
  831. }
  832. try {
  833. $order_id = absint( $_POST['order_id'] );
  834. $order = wc_get_order( $order_id );
  835. $result = $order->apply_coupon( wc_clean( $_POST['coupon'] ) );
  836. if ( is_wp_error( $result ) ) {
  837. throw new Exception( $result->get_error_message() );
  838. }
  839. ob_start();
  840. include 'admin/meta-boxes/views/html-order-items.php';
  841. wp_send_json_success(
  842. array(
  843. 'html' => ob_get_clean(),
  844. )
  845. );
  846. } catch ( Exception $e ) {
  847. wp_send_json_error( array( 'error' => $e->getMessage() ) );
  848. }
  849. }
  850. /**
  851. * Remove coupon from an order via ajax.
  852. */
  853. public static function remove_order_coupon() {
  854. check_ajax_referer( 'order-item', 'security' );
  855. if ( ! current_user_can( 'edit_shop_orders' ) ) {
  856. wp_die( -1 );
  857. }
  858. try {
  859. $order_id = absint( $_POST['order_id'] );
  860. $order = wc_get_order( $order_id );
  861. $order->remove_coupon( wc_clean( $_POST['coupon'] ) );
  862. ob_start();
  863. include 'admin/meta-boxes/views/html-order-items.php';
  864. wp_send_json_success(
  865. array(
  866. 'html' => ob_get_clean(),
  867. )
  868. );
  869. } catch ( Exception $e ) {
  870. wp_send_json_error( array( 'error' => $e->getMessage() ) );
  871. }
  872. }
  873. /**
  874. * Remove an order item.
  875. */
  876. public static function remove_order_item() {
  877. check_ajax_referer( 'order-item', 'security' );
  878. if ( ! current_user_can( 'edit_shop_orders' ) ) {
  879. wp_die( -1 );
  880. }
  881. try {
  882. $order_id = absint( $_POST['order_id'] );
  883. $order_item_ids = $_POST['order_item_ids'];
  884. $items = ( ! empty( $_POST['items'] ) ) ? $_POST['items'] : '';
  885. $calculate_tax_args = array(
  886. 'country' => strtoupper( wc_clean( $_POST['country'] ) ),
  887. 'state' => strtoupper( wc_clean( $_POST['state'] ) ),
  888. 'postcode' => strtoupper( wc_clean( $_POST['postcode'] ) ),
  889. 'city' => strtoupper( wc_clean( $_POST['city'] ) ),
  890. );
  891. if ( ! is_array( $order_item_ids ) && is_numeric( $order_item_ids ) ) {
  892. $order_item_ids = array( $order_item_ids );
  893. }
  894. // If we passed through items it means we need to save first before deleting.
  895. if ( ! empty( $items ) ) {
  896. $save_items = array();
  897. parse_str( $items, $save_items );
  898. // Save order items
  899. wc_save_order_items( $order_id, $save_items );
  900. }
  901. if ( sizeof( $order_item_ids ) > 0 ) {
  902. foreach ( $order_item_ids as $id ) {
  903. wc_delete_order_item( absint( $id ) );
  904. }
  905. }
  906. $order = wc_get_order( $order_id );
  907. $order->calculate_taxes( $calculate_tax_args );
  908. $order->calculate_totals( false );
  909. ob_start();
  910. include 'admin/meta-boxes/views/html-order-items.php';
  911. wp_send_json_success(
  912. array(
  913. 'html' => ob_get_clean(),
  914. )
  915. );
  916. } catch ( Exception $e ) {
  917. wp_send_json_error( array( 'error' => $e->getMessage() ) );
  918. }
  919. }
  920. /**
  921. * Remove an order tax.
  922. */
  923. public static function remove_order_tax() {
  924. check_ajax_referer( 'order-item', 'security' );
  925. if ( ! current_user_can( 'edit_shop_orders' ) ) {
  926. wp_die( -1 );
  927. }
  928. try {
  929. $order_id = absint( $_POST['order_id'] );
  930. $rate_id = absint( $_POST['rate_id'] );
  931. wc_delete_order_item( $rate_id );
  932. $order = wc_get_order( $order_id );
  933. $order->calculate_totals( false );
  934. ob_start();
  935. include 'admin/meta-boxes/views/html-order-items.php';
  936. wp_send_json_success(
  937. array(
  938. 'html' => ob_get_clean(),
  939. )
  940. );
  941. } catch ( Exception $e ) {
  942. wp_send_json_error( array( 'error' => $e->getMessage() ) );
  943. }
  944. }
  945. /**
  946. * Reduce order item stock.
  947. */
  948. public static function reduce_order_item_stock() {
  949. check_ajax_referer( 'order-item', 'security' );
  950. if ( ! current_user_can( 'edit_shop_orders' ) ) {
  951. wp_die( -1 );
  952. }
  953. $order_id = absint( $_POST['order_id'] );
  954. $order_item_ids = isset( $_POST['order_item_ids'] ) ? $_POST['order_item_ids'] : array();
  955. $order_item_qty = isset( $_POST['order_item_qty'] ) ? $_POST['order_item_qty'] : array();
  956. $order = wc_get_order( $order_id );
  957. $order_items = $order->get_items();
  958. $return = array();
  959. if ( $order && ! empty( $order_items ) && sizeof( $order_item_ids ) > 0 ) {
  960. foreach ( $order_items as $item_id => $order_item ) {
  961. // Only reduce checked items
  962. if ( ! in_array( $item_id, $order_item_ids ) ) {
  963. continue;
  964. }
  965. $_product = $order_item->get_product();
  966. if ( $_product && $_product->exists() && $_product->managing_stock() && isset( $order_item_qty[ $item_id ] ) && $order_item_qty[ $item_id ] > 0 ) {
  967. $stock_change = apply_filters( 'woocommerce_reduce_order_stock_quantity', $order_item_qty[ $item_id ], $item_id );
  968. $new_stock = wc_update_product_stock( $_product, $stock_change, 'decrease' );
  969. $item_name = $_product->get_formatted_name();
  970. $return[] = array(
  971. 'note' => sprintf( wp_kses_post( __( '%1$s stock reduced from %2$s to %3$s.', 'woocommerce' ) ), $item_name, $new_stock + $stock_change, $new_stock ),
  972. 'success' => true,
  973. );
  974. }
  975. }
  976. do_action( 'woocommerce_reduce_order_stock', $order );
  977. if ( empty( $return ) ) {
  978. $return[] = array(
  979. 'note' => wp_kses_post( __( 'No products had their stock reduced - they may not have stock management enabled.', 'woocommerce' ) ),
  980. 'success' => false,
  981. );
  982. }
  983. wp_send_json_success( $return );
  984. }
  985. wp_send_json_error();
  986. }
  987. /**
  988. * Increase order item stock.
  989. */
  990. public static function increase_order_item_stock() {
  991. check_ajax_referer( 'order-item', 'security' );
  992. if ( ! current_user_can( 'edit_shop_orders' ) ) {
  993. wp_die( -1 );
  994. }
  995. $order_id = absint( $_POST['order_id'] );
  996. $order_item_ids = isset( $_POST['order_item_ids'] ) ? $_POST['order_item_ids'] : array();
  997. $order_item_qty = isset( $_POST['order_item_qty'] ) ? $_POST['order_item_qty'] : array();
  998. $order = wc_get_order( $order_id );
  999. $order_items = $order->get_items();
  1000. $return = array();
  1001. if ( $order && ! empty( $order_items ) && sizeof( $order_item_ids ) > 0 ) {
  1002. foreach ( $order_items as $item_id => $order_item ) {
  1003. // Only reduce checked items
  1004. if ( ! in_array( $item_id, $order_item_ids ) ) {
  1005. continue;
  1006. }
  1007. $_product = $order_item->get_product();
  1008. if ( $_product && $_product->exists() && $_product->managing_stock() && isset( $order_item_qty[ $item_id ] ) && $order_item_qty[ $item_id ] > 0 ) {
  1009. $old_stock = $_product->get_stock_quantity();
  1010. $stock_change = apply_filters( 'woocommerce_restore_order_stock_quantity', $order_item_qty[ $item_id ], $item_id );
  1011. $new_quantity = wc_update_product_stock( $_product, $stock_change, 'increase' );
  1012. $item_name = $_product->get_formatted_name();
  1013. $return[] = array(
  1014. 'note' => sprintf( wp_kses_post( __( '%1$s stock increased from %2$s to %3$s.', 'woocommerce' ) ), $item_name, $old_stock, $new_quantity ),
  1015. 'success' => true,
  1016. );
  1017. }
  1018. }
  1019. do_action( 'woocommerce_restore_order_stock', $order );
  1020. if ( empty( $return ) ) {
  1021. $return[] = array(
  1022. 'note' => wp_kses_post( __( 'No products had their stock increased - they may not have stock management enabled.', 'woocommerce' ) ),
  1023. 'success' => false,
  1024. );
  1025. }
  1026. wp_send_json_success( $return );
  1027. }
  1028. wp_send_json_error();
  1029. }
  1030. /**
  1031. * Calc line tax.
  1032. */
  1033. public static function calc_line_taxes() {
  1034. check_ajax_referer( 'calc-totals', 'security' );
  1035. if ( ! current_user_can( 'edit_shop_orders' ) ) {
  1036. wp_die( -1 );
  1037. }
  1038. $order_id = absint( $_POST['order_id'] );
  1039. $calculate_tax_args = array(
  1040. 'country' => strtoupper( wc_clean( $_POST['country'] ) ),
  1041. 'state' => strtoupper( wc_clean( $_POST['state'] ) ),
  1042. 'postcode' => strtoupper( wc_clean( $_POST['postcode'] ) ),
  1043. 'city' => strtoupper( wc_clean( $_POST['city'] ) ),
  1044. );
  1045. // Parse the jQuery serialized items
  1046. $items = array();
  1047. parse_str( $_POST['items'], $items );
  1048. // Save order items first
  1049. wc_save_order_items( $order_id, $items );
  1050. // Grab the order and recalculate taxes
  1051. $order = wc_get_order( $order_id );
  1052. $order->calculate_taxes( $calculate_tax_args );
  1053. $order->calculate_totals( false );
  1054. include 'admin/meta-boxes/views/html-order-items.php';
  1055. wp_die();
  1056. }
  1057. /**
  1058. * Save order items via ajax.
  1059. */
  1060. public static function save_order_items() {
  1061. check_ajax_referer( 'order-item', 'security' );
  1062. if ( ! current_user_can( 'edit_shop_orders' ) ) {
  1063. wp_die( -1 );
  1064. }
  1065. if ( isset( $_POST['order_id'], $_POST['items'] ) ) {
  1066. $order_id = absint( $_POST['order_id'] );
  1067. // Parse the jQuery serialized items
  1068. $items = array();
  1069. parse_str( $_POST['items'], $items );
  1070. // Save order items
  1071. wc_save_order_items( $order_id, $items );
  1072. // Return HTML items
  1073. $order = wc_get_order( $order_id );
  1074. include 'admin/meta-boxes/views/html-order-items.php';
  1075. }
  1076. wp_die();
  1077. }
  1078. /**
  1079. * Load order items via ajax.
  1080. */
  1081. public static function load_order_items() {
  1082. check_ajax_referer( 'order-item', 'security' );
  1083. if ( ! current_user_can( 'edit_shop_orders' ) ) {
  1084. wp_die( -1 );
  1085. }
  1086. // Return HTML items
  1087. $order_id = absint( $_POST['order_id'] );
  1088. $order = wc_get_order( $order_id );
  1089. include 'admin/meta-boxes/views/html-order-items.php';
  1090. wp_die();
  1091. }
  1092. /**
  1093. * Add order note via ajax.
  1094. */
  1095. public static function add_order_note() {
  1096. check_ajax_referer( 'add-order-note', 'security' );
  1097. if ( ! current_user_can( 'edit_shop_orders' ) ) {
  1098. wp_die( -1 );
  1099. }
  1100. $post_id = absint( $_POST['post_id'] );
  1101. $note = wp_kses_post( trim( wp_unslash( $_POST['note'] ) ) );
  1102. $note_type = $_POST['note_type'];
  1103. $is_customer_note = ( 'customer' === $note_type ) ? 1 : 0;
  1104. if ( $post_id > 0 ) {
  1105. $order = wc_get_order( $post_id );
  1106. $comment_id = $order->add_order_note( $note, $is_customer_note, true );
  1107. $note = wc_get_order_note( $comment_id );
  1108. $note_classes = array( 'note' );
  1109. $note_classes[] = $is_customer_note ? 'customer-note' : '';
  1110. $note_classes = apply_filters( 'woocommerce_order_note_class', array_filter( $note_classes ), $note );
  1111. ?>
  1112. <li rel="<?php echo absint( $note->id ); ?>" class="<?php echo esc_attr( implode( ' ', $note_classes ) ); ?>">
  1113. <div class="note_content">
  1114. <?php echo wpautop( wptexturize( wp_kses_post( $note->content ) ) ); ?>
  1115. </div>
  1116. <p class="meta">
  1117. <abbr class="exact-date" title="<?php echo $note->date_created->date( 'y-m-d h:i:s' ); ?>">
  1118. <?php printf( __( 'added on %1$s at %2$s', 'woocommerce' ), $note->date_created->date_i18n( wc_date_format() ), $note->date_created->date_i18n( wc_time_format() ) ); ?>
  1119. </abbr>
  1120. <?php
  1121. if ( 'system' !== $note->added_by ) :
  1122. /* translators: %s: note author */
  1123. printf( ' ' . __( 'by %s', 'woocommerce' ), $note->added_by );
  1124. endif;
  1125. ?>
  1126. <a href="#" class="delete_note" role="button"><?php _e( 'Delete note', 'woocommerce' ); ?></a>
  1127. </p>
  1128. </li>
  1129. <?php
  1130. }
  1131. wp_die();
  1132. }
  1133. /**
  1134. * Delete order note via ajax.
  1135. */
  1136. public static function delete_order_note() {
  1137. check_ajax_referer( 'delete-order-note', 'security' );
  1138. if ( ! current_user_can( 'edit_shop_orders' ) ) {
  1139. wp_die( -1 );
  1140. }
  1141. $note_id = (int) $_POST['note_id'];
  1142. if ( $note_id > 0 ) {
  1143. wc_delete_order_note( $note_id );
  1144. }
  1145. wp_die();
  1146. }
  1147. /**
  1148. * Search for products and echo json.
  1149. *
  1150. * @param string $term (default: '')
  1151. * @param bool $include_variations in search or not
  1152. */
  1153. public static function json_search_products( $term = '', $include_variations = false ) {
  1154. check_ajax_referer( 'search-products', 'security' );
  1155. $term = wc_clean( empty( $term ) ? wp_unslash( $_GET['term'] ) : $term );
  1156. if ( empty( $term ) ) {
  1157. wp_die();
  1158. }
  1159. $data_store = WC_Data_Store::load( 'product' );
  1160. $ids = $data_store->search_products( $term, '', (bool) $include_variations );
  1161. if ( ! empty( $_GET['exclude'] ) ) {
  1162. $ids = array_diff( $ids, (array) $_GET['exclude'] );
  1163. }
  1164. if ( ! empty( $_GET['include'] ) ) {
  1165. $ids = array_intersect( $ids, (array) $_GET['include'] );
  1166. }
  1167. if ( ! empty( $_GET['limit'] ) ) {
  1168. $ids = array_slice( $ids, 0, absint( $_GET['limit'] ) );
  1169. }
  1170. $product_objects = array_filter( array_map( 'wc_get_product', $ids ), 'wc_products_array_filter_readable' );
  1171. $products = array();
  1172. foreach ( $product_objects as $product_object ) {
  1173. $products[ $product_object->get_id() ] = rawurldecode( $product_object->get_formatted_name() );
  1174. }
  1175. wp_send_json( apply_filters( 'woocommerce_json_search_found_products', $products ) );
  1176. }
  1177. /**
  1178. * Search for product variations and return json.
  1179. *
  1180. * @see WC_AJAX::json_search_products()
  1181. */
  1182. public static function json_search_products_and_variations() {
  1183. self::json_search_products( '', true );
  1184. }
  1185. /**
  1186. * Search for downloadable product variations and return json.
  1187. *
  1188. * @see WC_AJAX::json_search_products()
  1189. */
  1190. public static function json_search_downloadable_products_and_variations() {
  1191. check_ajax_referer( 'search-products', 'security' );
  1192. $term = (string) wc_clean( wp_unslash( $_GET['term'] ) );
  1193. $data_store = WC_Data_Store::load( 'product' );
  1194. $ids = $data_store->search_products( $term, 'downloadable', true );
  1195. if ( ! empty( $_GET['exclude'] ) ) {
  1196. $ids = array_diff( $ids, (array) $_GET['exclude'] );
  1197. }
  1198. if ( ! empty( $_GET['include'] ) ) {
  1199. $ids = array_intersect( $ids, (array) $_GET['include'] );
  1200. }
  1201. if ( ! empty( $_GET['limit'] ) ) {
  1202. $ids = array_slice( $ids, 0, absint( $_GET['limit'] ) );
  1203. }
  1204. $product_objects = array_filter( array_map( 'wc_get_product', $ids ), 'wc_products_array_filter_readable' );
  1205. $products = array();
  1206. foreach ( $product_objects as $product_object ) {
  1207. $products[ $product_object->get_id() ] = rawurldecode( $product_object->get_formatted_name() );
  1208. }
  1209. wp_send_json( $products );
  1210. }
  1211. /**
  1212. * Search for customers and return json.
  1213. */
  1214. public static function json_search_customers() {
  1215. ob_start();
  1216. check_ajax_referer( 'search-customers', 'security' );
  1217. if ( ! current_user_can( 'edit_shop_orders' ) ) {
  1218. wp_die( -1 );
  1219. }
  1220. $term = wc_clean( wp_unslash( $_GET['term'] ) );
  1221. $exclude = array();
  1222. $limit = '';
  1223. if ( empty( $term ) ) {
  1224. wp_die();
  1225. }
  1226. $ids = array();
  1227. // Search by ID.
  1228. if ( is_numeric( $term ) ) {
  1229. $customer = new WC_Customer( intval( $term ) );
  1230. // Customer does not exists.
  1231. if ( 0 !== $customer->get_id() ) {
  1232. $ids = array( $customer->get_id() );
  1233. }
  1234. }
  1235. // Usernames can be numeric so we first check that no users was found by ID before searching for numeric username, this prevents performance issues with ID lookups.
  1236. if ( empty( $ids ) ) {
  1237. $data_store = WC_Data_Store::load( 'customer' );
  1238. // If search is smaller than 3 characters, limit result set to avoid
  1239. // too many rows being returned.
  1240. if ( 3 > strlen( $term ) ) {
  1241. $limit = 20;
  1242. }
  1243. $ids = $data_store->search_customers( $term, $limit );
  1244. }
  1245. $found_customers = array();
  1246. if ( ! empty( $_GET['exclude'] ) ) {
  1247. $ids = array_diff( $ids, (array) $_GET['exclude'] );
  1248. }
  1249. foreach ( $ids as $id ) {
  1250. $customer = new WC_Customer( $id );
  1251. /* translators: 1: user display name 2: user ID 3: user email */
  1252. $found_customers[ $id ] = sprintf(
  1253. esc_html__( '%1$s (#%2$s &ndash; %3$s)', 'woocommerce' ),
  1254. $customer->get_first_name() . ' ' . $customer->get_last_name(),
  1255. $customer->get_id(),
  1256. $customer->get_email()
  1257. );
  1258. }
  1259. wp_send_json( apply_filters( 'woocommerce_json_search_found_customers', $found_customers ) );
  1260. }
  1261. /**
  1262. * Search for categories and return json.
  1263. */
  1264. public static function json_search_categories() {
  1265. ob_start();
  1266. check_ajax_referer( 'search-categories', 'security' );
  1267. if ( ! current_user_can( 'edit_products' ) ) {
  1268. wp_die( -1 );
  1269. }
  1270. if ( ! $search_text = wc_clean( wp_unslash( $_GET['term'] ) ) ) {
  1271. wp_die();
  1272. }
  1273. $found_categories = array();
  1274. $args = array(
  1275. 'taxonomy' => array( 'product_cat' ),
  1276. 'orderby' => 'id',
  1277. 'order' => 'ASC',
  1278. 'hide_empty' => true,
  1279. 'fields' => 'all',
  1280. 'name__like' => $search_text,
  1281. );
  1282. if ( $terms = get_terms( $args ) ) {
  1283. foreach ( $terms as $term ) {
  1284. $term->formatted_name = '';
  1285. if ( $term->parent ) {
  1286. $ancestors = array_reverse( get_ancestors( $term->term_id, 'product_cat' ) );
  1287. foreach ( $ancestors as $ancestor ) {
  1288. if ( $ancestor_term = get_term( $ancestor, 'product_cat' ) ) {
  1289. $term->formatted_name .= $ancestor_term->name . ' > ';
  1290. }
  1291. }
  1292. }
  1293. $term->formatted_name .= $term->name . ' (' . $term->count . ')';
  1294. $found_categories[ $term->term_id ] = $term;
  1295. }
  1296. }
  1297. wp_send_json( apply_filters( 'woocommerce_json_search_found_categories', $found_categories ) );
  1298. }
  1299. /**
  1300. * Ajax request handling for categories ordering.
  1301. */
  1302. public static function term_ordering() {
  1303. // check permissions again and make sure we have what we need
  1304. if ( ! current_user_can( 'edit_products' ) || empty( $_POST['id'] ) ) {
  1305. wp_die( -1 );
  1306. }
  1307. $id = (int) $_POST['id'];
  1308. $next_id = isset( $_POST['nextid'] ) && (int) $_POST['nextid'] ? (int) $_POST['nextid'] : null;
  1309. $taxonomy = isset( $_POST['thetaxonomy'] ) ? esc_attr( $_POST['thetaxonomy'] ) : null;
  1310. $term = get_term_by( 'id', $id, $taxonomy );
  1311. if ( ! $id || ! $term || ! $taxonomy ) {
  1312. wp_die( 0 );
  1313. }
  1314. wc_reorder_terms( $term, $next_id, $taxonomy );
  1315. $children = get_terms( $taxonomy, "child_of=$id&menu_order=ASC&hide_empty=0" );
  1316. if ( $term && sizeof( $children ) ) {
  1317. echo 'children';
  1318. wp_die();
  1319. }
  1320. }
  1321. /**
  1322. * Ajax request handling for product ordering.
  1323. *
  1324. * Based on Simple Page Ordering by 10up (https://wordpress.org/plugins/simple-page-ordering/).
  1325. */
  1326. public static function product_ordering() {
  1327. global $wpdb;
  1328. if ( ! current_user_can( 'edit_products' ) || empty( $_POST['id'] ) ) {
  1329. wp_die( -1 );
  1330. }
  1331. $sorting_id = absint( $_POST['id'] );
  1332. $previd = absint( isset( $_POST['previd'] ) ? $_POST['previd'] : 0 );
  1333. $nextid = absint( isset( $_POST['nextid'] ) ? $_POST['nextid'] : 0 );
  1334. $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' );
  1335. $index = 0;
  1336. foreach ( $menu_orders as $id => $menu_order ) {
  1337. $id = absint( $id );
  1338. if ( $sorting_id === $id ) {
  1339. continue;
  1340. }
  1341. if ( $nextid === $id ) {
  1342. $index ++;
  1343. }
  1344. $index ++;
  1345. $menu_orders[ $id ] = $index;
  1346. $wpdb->update( $wpdb->posts, array( 'menu_order' => $index ), array( 'ID' => $id ) );
  1347. /**
  1348. * When a single product has gotten it's ordering updated.
  1349. * $id The product ID
  1350. * $index The new menu order
  1351. */
  1352. do_action( 'woocommerce_after_single_product_ordering', $id, $index );
  1353. }
  1354. if ( isset( $menu_orders[ $previd ] ) ) {
  1355. $menu_orders[ $sorting_id ] = $menu_orders[ $previd ] + 1;
  1356. } elseif ( isset( $menu_orders[ $nextid ] ) ) {
  1357. $menu_orders[ $sorting_id ] = $menu_orders[ $nextid ] - 1;
  1358. } else {
  1359. $menu_orders[ $sorting_id ] = 0;
  1360. }
  1361. $wpdb->update( $wpdb->posts, array( 'menu_order' => $menu_orders[ $sorting_id ] ), array( 'ID' => $sorting_id ) );
  1362. do_action( 'woocommerce_after_product_ordering', $sorting_id, $menu_orders );
  1363. wp_send_json( $menu_orders );
  1364. }
  1365. /**
  1366. * Handle a refund via the edit order screen.
  1367. *
  1368. * @throws Exception To return errors.
  1369. */
  1370. public static function refund_line_items() {
  1371. ob_start();
  1372. check_ajax_referer( 'order-item', 'security' );
  1373. if ( ! current_user_can( 'edit_shop_orders' ) ) {
  1374. wp_die( -1 );
  1375. }
  1376. $order_id = absint( $_POST['order_id'] );
  1377. $refund_amount = wc_format_decimal( sanitize_text_field( wp_unslash( $_POST['refund_amount'] ) ), wc_get_price_decimals() );
  1378. $refunded_amount = wc_format_decimal( sanitize_text_field( wp_unslash( $_POST['refunded_amount'] ) ), wc_get_price_decimals() );
  1379. $refund_reason = sanitize_text_field( $_POST['refund_reason'] );
  1380. $line_item_qtys = json_decode( sanitize_text_field( wp_unslash( $_POST['line_item_qtys'] ) ), true );
  1381. $line_item_totals = json_decode( sanitize_text_field( wp_unslash( $_POST['line_item_totals'] ) ), true );
  1382. $line_item_tax_totals = json_decode( sanitize_text_field( wp_unslash( $_POST['line_item_tax_totals'] ) ), true );
  1383. $api_refund = 'true' === $_POST['api_refund'];
  1384. $restock_refunded_items = 'true' === $_POST['restock_refunded_items'];
  1385. $refund = false;
  1386. $response_data = array();
  1387. try {
  1388. $order = wc_get_order( $order_id );
  1389. $order_items = $order->get_items();
  1390. $max_refund = wc_format_decimal( $order->get_total() - $order->get_total_refunded(), wc_get_price_decimals() );
  1391. if ( ! $refund_amount || $max_refund < $refund_amount || 0 > $refund_amount ) {
  1392. throw new exception( __( 'Invalid refund amount', 'woocommerce' ) );
  1393. }
  1394. if ( $refunded_amount !== wc_format_decimal( $order->get_total_refunded(), wc_get_price_decimals() ) ) {
  1395. throw new exception( __( 'Error processing refund. Please try again.', 'woocommerce' ) );
  1396. }
  1397. // Prepare line items which we are refunding.
  1398. $line_items = array();
  1399. $item_ids = array_unique( array_merge( array_keys( $line_item_qtys, $line_item_totals ) ) );
  1400. foreach ( $item_ids as $item_id ) {
  1401. $line_items[ $item_id ] = array(
  1402. 'qty' => 0,
  1403. 'refund_total' => 0,
  1404. 'refund_tax' => array(),
  1405. );
  1406. }
  1407. foreach ( $line_item_qtys as $item_id => $qty ) {
  1408. $line_items[ $item_id ]['qty'] = max( $qty, 0 );
  1409. }
  1410. foreach ( $line_item_totals as $item_id => $total ) {
  1411. $line_items[ $item_id ]['refund_total'] = wc_format_decimal( $total );
  1412. }
  1413. foreach ( $line_item_tax_totals as $item_id => $tax_totals ) {
  1414. $line_items[ $item_id ]['refund_tax'] = array_filter( array_map( 'wc_format_decimal', $tax_totals ) );
  1415. }
  1416. // Create the refund object.
  1417. $refund = wc_create_refund(
  1418. array(
  1419. 'amount' => $refund_amount,
  1420. 'reason' => $refund_reason,
  1421. 'order_id' => $order_id,
  1422. 'line_items' => $line_items,
  1423. 'refund_payment' => $api_refund,
  1424. 'restock_items' => $restock_refunded_items,
  1425. )
  1426. );
  1427. if ( is_wp_error( $refund ) ) {
  1428. throw new Exception( $refund->get_error_message() );
  1429. }
  1430. if ( did_action( 'woocommerce_order_fully_refunded' ) ) {
  1431. $response_data['status'] = 'fully_refunded';
  1432. }
  1433. wp_send_json_success( $response_data );
  1434. } catch ( Exception $e ) {
  1435. wp_send_json_error( array( 'error' => $e->getMessage() ) );
  1436. }
  1437. }
  1438. /**
  1439. * Delete a refund.
  1440. */
  1441. public static function delete_refund() {
  1442. check_ajax_referer( 'order-item', 'security' );
  1443. if ( ! current_user_can( 'edit_shop_orders' ) ) {
  1444. wp_die( -1 );
  1445. }
  1446. $refund_ids = array_map( 'absint', is_array( $_POST['refund_id'] ) ? $_POST['refund_id'] : array( $_POST['refund_id'] ) );
  1447. foreach ( $refund_ids as $refund_id ) {
  1448. if ( $refund_id && 'shop_order_refund' === get_post_type( $refund_id ) ) {
  1449. $refund = wc_get_order( $refund_id );
  1450. $order_id = $refund->get_parent_id();
  1451. $refund->delete( true );
  1452. do_action( 'woocommerce_refund_deleted', $refund_id, $order_id );
  1453. }
  1454. }
  1455. wp_die();
  1456. }
  1457. /**
  1458. * Triggered when clicking the rating footer.
  1459. */
  1460. public static function rated() {
  1461. if ( ! current_user_can( 'manage_woocommerce' ) ) {
  1462. wp_die( -1 );
  1463. }
  1464. update_option( 'woocommerce_admin_footer_text_rated', 1 );
  1465. wp_die();
  1466. }
  1467. /**
  1468. * Create/Update API key.
  1469. */
  1470. public static function update_api_key() {
  1471. ob_start();
  1472. global $wpdb;
  1473. check_ajax_referer( 'update-api-key', 'security' );
  1474. if ( ! current_user_can( 'manage_woocommerce' ) ) {
  1475. wp_die( -1 );
  1476. }
  1477. try {
  1478. if ( empty( $_POST['description'] ) ) {
  1479. throw new Exception( __( 'Description is missing.', 'woocommerce' ) );
  1480. }
  1481. if ( empty( $_POST['user'] ) ) {
  1482. throw new Exception( __( 'User is missing.', 'woocommerce' ) );
  1483. }
  1484. if ( empty( $_POST['permissions'] ) ) {
  1485. throw new Exception( __( 'Permissions is missing.', 'woocommerce' ) );
  1486. }
  1487. $key_id = absint( $_POST['key_id'] );
  1488. $description = sanitize_text_field( wp_unslash( $_POST['description'] ) );
  1489. $permissions = ( in_array( $_POST['permissions'], array( 'read', 'write', 'read_write' ) ) ) ? sanitize_text_field( $_POST['permissions'] ) : 'read';
  1490. $user_id = absint( $_POST['user'] );
  1491. if ( 0 < $key_id ) {
  1492. $data = array(
  1493. 'user_id' => $user_id,
  1494. 'description' => $description,
  1495. 'permissions' => $permissions,
  1496. );
  1497. $wpdb->update(
  1498. $wpdb->prefix . 'woocommerce_api_keys',
  1499. $data,
  1500. array( 'key_id' => $key_id ),
  1501. array(
  1502. '%d',
  1503. '%s',
  1504. '%s',
  1505. ),
  1506. array( '%d' )
  1507. );
  1508. $data['consumer_key'] = '';
  1509. $data['consumer_secret'] = '';
  1510. $data['message'] = __( 'API Key updated successfully.', 'woocommerce' );
  1511. } else {
  1512. $consumer_key = 'ck_' . wc_rand_hash();
  1513. $consumer_secret = 'cs_' . wc_rand_hash();
  1514. $data = array(
  1515. 'user_id' => $user_id,
  1516. 'description' => $description,
  1517. 'permissions' => $permissions,
  1518. 'consumer_key' => wc_api_hash( $consumer_key ),
  1519. 'consumer_secret' => $consumer_secret,
  1520. 'truncated_key' => substr( $consumer_key, -7 ),
  1521. );
  1522. $wpdb->insert(
  1523. $wpdb->prefix . 'woocommerce_api_keys',
  1524. $data,
  1525. array(
  1526. '%d',
  1527. '%s',
  1528. '%s',
  1529. '%s',
  1530. '%s',
  1531. '%s',
  1532. )
  1533. );
  1534. $key_id = $wpdb->insert_id;
  1535. $data['consumer_key'] = $consumer_key;
  1536. $data['consumer_secret'] = $consumer_secret;
  1537. $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' );
  1538. $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=advanced&section=keys' ) ), 'revoke' ) ) . '">' . __( 'Revoke key', 'woocommerce' ) . '</a>';
  1539. }
  1540. wp_send_json_success( $data );
  1541. } catch ( Exception $e ) {
  1542. wp_send_json_error( array( 'message' => $e->getMessage() ) );
  1543. }
  1544. }
  1545. /**
  1546. * Load variations via AJAX.
  1547. */
  1548. public static function load_variations() {
  1549. ob_start();
  1550. check_ajax_referer( 'load-variations', 'security' );
  1551. if ( ! current_user_can( 'edit_products' ) || empty( $_POST['product_id'] ) ) {
  1552. wp_die( -1 );
  1553. }
  1554. // Set $post global so its available, like within the admin screens
  1555. global $post;
  1556. $loop = 0;
  1557. $product_id = absint( $_POST['product_id'] );
  1558. $post = get_post( $product_id );
  1559. $product_object = wc_get_product( $product_id );
  1560. $per_page = ! empty( $_POST['per_page'] ) ? absint( $_POST['per_page'] ) : 10;
  1561. $page = ! empty( $_POST['page'] ) ? absint( $_POST['page'] ) : 1;
  1562. $variations = wc_get_products(
  1563. array(
  1564. 'status' => array( 'private', 'publish' ),
  1565. 'type' => 'variation',
  1566. 'parent' => $product_id,
  1567. 'limit' => $per_page,
  1568. 'page' => $page,
  1569. 'orderby' => array(
  1570. 'menu_order' => 'ASC',
  1571. 'ID' => 'DESC',
  1572. ),
  1573. 'return' => 'objects',
  1574. )
  1575. );
  1576. if ( $variations ) {
  1577. foreach ( $variations as $variation_object ) {
  1578. $variation_id = $variation_object->get_id();
  1579. $variation = get_post( $variation_id );
  1580. $variation_data = array_merge( array_map( 'maybe_unserialize', get_post_custom( $variation_id ) ), wc_get_product_variation_attributes( $variation_id ) ); // kept for BW compatibility.
  1581. include 'admin/meta-boxes/views/html-variation-admin.php';
  1582. $loop++;
  1583. }
  1584. }
  1585. wp_die();
  1586. }
  1587. /**
  1588. * Save variations via AJAX.
  1589. */
  1590. public static function save_variations() {
  1591. ob_start();
  1592. check_ajax_referer( 'save-variations', 'security' );
  1593. // Check permissions again and make sure we have what we need
  1594. if ( ! current_user_can( 'edit_products' ) || empty( $_POST ) || empty( $_POST['product_id'] ) ) {
  1595. wp_die( -1 );
  1596. }
  1597. $product_id = absint( $_POST['product_id'] );
  1598. WC_Admin_Meta_Boxes::$meta_box_errors = array();
  1599. WC_Meta_Box_Product_Data::save_variations( $product_id, get_post( $product_id ) );
  1600. do_action( 'woocommerce_ajax_save_product_variations', $product_id );
  1601. if ( $errors = WC_Admin_Meta_Boxes::$meta_box_errors ) {
  1602. echo '<div class="error notice is-dismissible">';
  1603. foreach ( $errors as $error ) {
  1604. echo '<p>' . wp_kses_post( $error ) . '</p>';
  1605. }
  1606. echo '<button type="button" class="notice-dismiss"><span class="screen-reader-text">' . __( 'Dismiss this notice.', 'woocommerce' ) . '</span></button>';
  1607. echo '</div>';
  1608. delete_option( 'woocommerce_meta_box_errors' );
  1609. }
  1610. wp_die();
  1611. }
  1612. /**
  1613. * Bulk action - Toggle Enabled.
  1614. *
  1615. * @access private
  1616. * @used-by bulk_edit_variations
  1617. * @param array $variations
  1618. * @param array $data
  1619. */
  1620. private static function variation_bulk_action_toggle_enabled( $variations, $data ) {
  1621. foreach ( $variations as $variation_id ) {
  1622. $variation = wc_get_product( $variation_id );
  1623. $variation->set_status( 'private' === $variation->get_status( 'edit' ) ? 'publish' : 'private' );
  1624. $variation->save();
  1625. }
  1626. }
  1627. /**
  1628. * Bulk action - Toggle Downloadable Checkbox.
  1629. *
  1630. * @access private
  1631. * @used-by bulk_edit_variations
  1632. * @param array $variations
  1633. * @param array $data
  1634. */
  1635. private static function variation_bulk_action_toggle_downloadable( $variations, $data ) {
  1636. self::variation_bulk_toggle( $variations, 'downloadable' );
  1637. }
  1638. /**
  1639. * Bulk action - Toggle Virtual Checkbox.
  1640. *
  1641. * @access private
  1642. * @used-by bulk_edit_variations
  1643. * @param array $variations
  1644. * @param array $data
  1645. */
  1646. private static function variation_bulk_action_toggle_virtual( $variations, $data ) {
  1647. self::variation_bulk_toggle( $variations, 'virtual' );
  1648. }
  1649. /**
  1650. * Bulk action - Toggle Manage Stock Checkbox.
  1651. *
  1652. * @access private
  1653. * @used-by bulk_edit_variations
  1654. * @param array $variations
  1655. * @param array $data
  1656. */
  1657. private static function variation_bulk_action_toggle_manage_stock( $variations, $data ) {
  1658. self::variation_bulk_toggle( $variations, 'manage_stock' );
  1659. }
  1660. /**
  1661. * Bulk action - Set Regular Prices.
  1662. *
  1663. * @access private
  1664. * @used-by bulk_edit_variations
  1665. * @param array $variations
  1666. * @param array $data
  1667. */
  1668. private static function variation_bulk_action_variable_regular_price( $variations, $data ) {
  1669. self::variation_bulk_set( $variations, 'regular_price', $data['value'] );
  1670. }
  1671. /**
  1672. * Bulk action - Set Sale Prices.
  1673. *
  1674. * @access private
  1675. * @used-by bulk_edit_variations
  1676. * @param array $variations
  1677. * @param array $data
  1678. */
  1679. private static function variation_bulk_action_variable_sale_price( $variations, $data ) {
  1680. self::variation_bulk_set( $variations, 'sale_price', $data['value'] );
  1681. }
  1682. /**
  1683. * Bulk action - Set Stock Status as In Stock.
  1684. *
  1685. * @access private
  1686. * @used-by bulk_edit_variations
  1687. * @param array $variations
  1688. * @param array $data
  1689. */
  1690. private static function variation_bulk_action_variable_stock_status_instock( $variations, $data ) {
  1691. self::variation_bulk_set( $variations, 'stock_status', 'instock' );
  1692. }
  1693. /**
  1694. * Bulk action - Set Stock Status as Out of Stock.
  1695. *
  1696. * @access private
  1697. * @used-by bulk_edit_variations
  1698. * @param array $variations
  1699. * @param array $data
  1700. */
  1701. private static function variation_bulk_action_variable_stock_status_outofstock( $variations, $data ) {
  1702. self::variation_bulk_set( $variations, 'stock_status', 'outofstock' );
  1703. }
  1704. /**
  1705. * Bulk action - Set Stock Status as On Backorder.
  1706. *
  1707. * @access private
  1708. * @used-by bulk_edit_variations
  1709. * @param array $variations
  1710. * @param array $data
  1711. */
  1712. private static function variation_bulk_action_variable_stock_status_onbackorder( $variations, $data ) {
  1713. self::variation_bulk_set( $variations, 'stock_status', 'onbackorder' );
  1714. }
  1715. /**
  1716. * Bulk action - Set Stock.
  1717. *
  1718. * @access private
  1719. * @used-by bulk_edit_variations
  1720. * @param array $variations
  1721. * @param array $data
  1722. */
  1723. private static function variation_bulk_action_variable_stock( $variations, $data ) {
  1724. if ( ! isset( $data['value'] ) ) {
  1725. return;
  1726. }
  1727. $quantity = wc_stock_amount( wc_clean( $data['value'] ) );
  1728. foreach ( $variations as $variation_id ) {
  1729. $variation = wc_get_product( $variation_id );
  1730. if ( $variation->managing_stock() ) {
  1731. $variation->set_stock_quantity( $quantity );
  1732. } else {
  1733. $variation->set_stock_quantity( null );
  1734. }
  1735. $variation->save();
  1736. }
  1737. }
  1738. /**
  1739. * Bulk action - Set Weight.
  1740. *
  1741. * @access private
  1742. * @used-by bulk_edit_variations
  1743. * @param array $variations
  1744. * @param array $data
  1745. */
  1746. private static function variation_bulk_action_variable_weight( $variations, $data ) {
  1747. self::variation_bulk_set( $variations, 'weight', $data['value'] );
  1748. }
  1749. /**
  1750. * Bulk action - Set Length.
  1751. *
  1752. * @access private
  1753. * @used-by bulk_edit_variations
  1754. * @param array $variations
  1755. * @param array $data
  1756. */
  1757. private static function variation_bulk_action_variable_length( $variations, $data ) {
  1758. self::variation_bulk_set( $variations, 'length', $data['value'] );
  1759. }
  1760. /**
  1761. * Bulk action - Set Width.
  1762. *
  1763. * @access private
  1764. * @used-by bulk_edit_variations
  1765. * @param array $variations
  1766. * @param array $data
  1767. */
  1768. private static function variation_bulk_action_variable_width( $variations, $data ) {
  1769. self::variation_bulk_set( $variations, 'width', $data['value'] );
  1770. }
  1771. /**
  1772. * Bulk action - Set Height.
  1773. *
  1774. * @access private
  1775. * @used-by bulk_edit_variations
  1776. * @param array $variations
  1777. * @param array $data
  1778. */
  1779. private static function variation_bulk_action_variable_height( $variations, $data ) {
  1780. self::variation_bulk_set( $variations, 'height', $data['value'] );
  1781. }
  1782. /**
  1783. * Bulk action - Set Download Limit.
  1784. *
  1785. * @access private
  1786. * @used-by bulk_edit_variations
  1787. * @param array $variations
  1788. * @param array $data
  1789. */
  1790. private static function variation_bulk_action_variable_download_limit( $variations, $data ) {
  1791. self::variation_bulk_set( $variations, 'download_limit', $data['value'] );
  1792. }
  1793. /**
  1794. * Bulk action - Set Download Expiry.
  1795. *
  1796. * @access private
  1797. * @used-by bulk_edit_variations
  1798. * @param array $variations
  1799. * @param array $data
  1800. */
  1801. private static function variation_bulk_action_variable_download_expiry( $variations, $data ) {
  1802. self::variation_bulk_set( $variations, 'download_expiry', $data['value'] );
  1803. }
  1804. /**
  1805. * Bulk action - Delete all.
  1806. *
  1807. * @access private
  1808. * @used-by bulk_edit_variations
  1809. * @param array $variations
  1810. * @param array $data
  1811. */
  1812. private static function variation_bulk_action_delete_all( $variations, $data ) {
  1813. if ( isset( $data['allowed'] ) && 'true' === $data['allowed'] ) {
  1814. foreach ( $variations as $variation_id ) {
  1815. $variation = wc_get_product( $variation_id );
  1816. $variation->delete( true );
  1817. }
  1818. }
  1819. }
  1820. /**
  1821. * Bulk action - Sale Schedule.
  1822. *
  1823. * @access private
  1824. * @used-by bulk_edit_variations
  1825. * @param array $variations
  1826. * @param array $data
  1827. */
  1828. private static function variation_bulk_action_variable_sale_schedule( $variations, $data ) {
  1829. if ( ! isset( $data['date_from'] ) && ! isset( $data['date_to'] ) ) {
  1830. return;
  1831. }
  1832. foreach ( $variations as $variation_id ) {
  1833. $variation = wc_get_product( $variation_id );
  1834. if ( 'false' !== $data['date_from'] ) {
  1835. $variation->set_date_on_sale_from( wc_clean( $data['date_from'] ) );
  1836. }
  1837. if ( 'false' !== $data['date_to'] ) {
  1838. $variation->set_date_on_sale_to( wc_clean( $data['date_to'] ) );
  1839. }
  1840. $variation->save();
  1841. }
  1842. }
  1843. /**
  1844. * Bulk action - Increase Regular Prices.
  1845. *
  1846. * @access private
  1847. * @used-by bulk_edit_variations
  1848. * @param array $variations
  1849. * @param array $data
  1850. */
  1851. private static function variation_bulk_action_variable_regular_price_increase( $variations, $data ) {
  1852. self::variation_bulk_adjust_price( $variations, 'regular_price', '+', wc_clean( $data['value'] ) );
  1853. }
  1854. /**
  1855. * Bulk action - Decrease Regular Prices.
  1856. *
  1857. * @access private
  1858. * @used-by bulk_edit_variations
  1859. * @param array $variations
  1860. * @param array $data
  1861. */
  1862. private static function variation_bulk_action_variable_regular_price_decrease( $variations, $data ) {
  1863. self::variation_bulk_adjust_price( $variations, 'regular_price', '-', wc_clean( $data['value'] ) );
  1864. }
  1865. /**
  1866. * Bulk action - Increase Sale Prices.
  1867. *
  1868. * @access private
  1869. * @used-by bulk_edit_variations
  1870. * @param array $variations
  1871. * @param array $data
  1872. */
  1873. private static function variation_bulk_action_variable_sale_price_increase( $variations, $data ) {
  1874. self::variation_bulk_adjust_price( $variations, 'sale_price', '+', wc_clean( $data['value'] ) );
  1875. }
  1876. /**
  1877. * Bulk action - Decrease Sale Prices.
  1878. *
  1879. * @access private
  1880. * @used-by bulk_edit_variations
  1881. * @param array $variations
  1882. * @param array $data
  1883. */
  1884. private static function variation_bulk_action_variable_sale_price_decrease( $variations, $data ) {
  1885. self::variation_bulk_adjust_price( $variations, 'sale_price', '-', wc_clean( $data['value'] ) );
  1886. }
  1887. /**
  1888. * Bulk action - Set Price.
  1889. *
  1890. * @access private
  1891. * @used-by bulk_edit_variations
  1892. * @param array $variations
  1893. * @param string $operator + or -
  1894. * @param string $field price being adjusted _regular_price or _sale_price
  1895. * @param string $value Price or Percent
  1896. */
  1897. private static function variation_bulk_adjust_price( $variations, $field, $operator, $value ) {
  1898. foreach ( $variations as $variation_id ) {
  1899. $variation = wc_get_product( $variation_id );
  1900. $field_value = $variation->{"get_$field"}( 'edit' );
  1901. if ( '%' === substr( $value, -1 ) ) {
  1902. $percent = wc_format_decimal( substr( $value, 0, -1 ) );
  1903. $field_value += ( ( $field_value / 100 ) * $percent ) * "{$operator}1";
  1904. } else {
  1905. $field_value += $value * "{$operator}1";
  1906. }
  1907. $variation->{"set_$field"}( $field_value );
  1908. $variation->save();
  1909. }
  1910. }
  1911. /**
  1912. * Bulk set convenience function.
  1913. *
  1914. * @access private
  1915. * @param array $variations
  1916. * @param string $field
  1917. * @param string $value
  1918. */
  1919. private static function variation_bulk_set( $variations, $field, $value ) {
  1920. foreach ( $variations as $variation_id ) {
  1921. $variation = wc_get_product( $variation_id );
  1922. $variation->{ "set_$field" }( wc_clean( $value ) );
  1923. $variation->save();
  1924. }
  1925. }
  1926. /**
  1927. * Bulk toggle convenience function.
  1928. *
  1929. * @access private
  1930. * @param array $variations
  1931. * @param string $field
  1932. */
  1933. private static function variation_bulk_toggle( $variations, $field ) {
  1934. foreach ( $variations as $variation_id ) {
  1935. $variation = wc_get_product( $variation_id );
  1936. $prev_value = $variation->{ "get_$field" }( 'edit' );
  1937. $variation->{ "set_$field" }( ! $prev_value );
  1938. $variation->save();
  1939. }
  1940. }
  1941. /**
  1942. * Bulk edit variations via AJAX.
  1943. *
  1944. * @uses WC_AJAX::variation_bulk_set()
  1945. * @uses WC_AJAX::variation_bulk_adjust_price()
  1946. * @uses WC_AJAX::variation_bulk_action_variable_sale_price_decrease()
  1947. * @uses WC_AJAX::variation_bulk_action_variable_sale_price_increase()
  1948. * @uses WC_AJAX::variation_bulk_action_variable_regular_price_decrease()
  1949. * @uses WC_AJAX::variation_bulk_action_variable_regular_price_increase()
  1950. * @uses WC_AJAX::variation_bulk_action_variable_sale_schedule()
  1951. * @uses WC_AJAX::variation_bulk_action_delete_all()
  1952. * @uses WC_AJAX::variation_bulk_action_variable_download_expiry()
  1953. * @uses WC_AJAX::variation_bulk_action_variable_download_limit()
  1954. * @uses WC_AJAX::variation_bulk_action_variable_height()
  1955. * @uses WC_AJAX::variation_bulk_action_variable_width()
  1956. * @uses WC_AJAX::variation_bulk_action_variable_length()
  1957. * @uses WC_AJAX::variation_bulk_action_variable_weight()
  1958. * @uses WC_AJAX::variation_bulk_action_variable_stock()
  1959. * @uses WC_AJAX::variation_bulk_action_variable_sale_price()
  1960. * @uses WC_AJAX::variation_bulk_action_variable_regular_price()
  1961. * @uses WC_AJAX::variation_bulk_action_toggle_manage_stock()
  1962. * @uses WC_AJAX::variation_bulk_action_toggle_virtual()
  1963. * @uses WC_AJAX::variation_bulk_action_toggle_downloadable()
  1964. * @uses WC_AJAX::variation_bulk_action_toggle_enabled
  1965. */
  1966. public static function bulk_edit_variations() {
  1967. ob_start();
  1968. check_ajax_referer( 'bulk-edit-variations', 'security' );
  1969. // Check permissions again and make sure we have what we need
  1970. if ( ! current_user_can( 'edit_products' ) || empty( $_POST['product_id'] ) || empty( $_POST['bulk_action'] ) ) {
  1971. wp_die( -1 );
  1972. }
  1973. $product_id = absint( $_POST['product_id'] );
  1974. $bulk_action = wc_clean( $_POST['bulk_action'] );
  1975. $data = ! empty( $_POST['data'] ) ? array_map( 'wc_clean', $_POST['data'] ) : array();
  1976. $variations = array();
  1977. if ( apply_filters( 'woocommerce_bulk_edit_variations_need_children', true ) ) {
  1978. $variations = get_posts(
  1979. array(
  1980. 'post_parent' => $product_id,
  1981. 'posts_per_page' => -1,
  1982. 'post_type' => 'product_variation',
  1983. 'fields' => 'ids',
  1984. 'post_status' => array( 'publish', 'private' ),
  1985. )
  1986. );
  1987. }
  1988. if ( method_exists( __CLASS__, "variation_bulk_action_$bulk_action" ) ) {
  1989. call_user_func( array( __CLASS__, "variation_bulk_action_$bulk_action" ), $variations, $data );
  1990. } else {
  1991. do_action( 'woocommerce_bulk_edit_variations_default', $bulk_action, $data, $product_id, $variations );
  1992. }
  1993. do_action( 'woocommerce_bulk_edit_variations', $bulk_action, $data, $product_id, $variations );
  1994. WC_Product_Variable::sync( $product_id );
  1995. wc_delete_product_transients( $product_id );
  1996. wp_die();
  1997. }
  1998. /**
  1999. * Handle submissions from assets/js/settings-views-html-settings-tax.js Backbone model.
  2000. */
  2001. public static function tax_rates_save_changes() {
  2002. if ( ! isset( $_POST['wc_tax_nonce'], $_POST['changes'] ) ) {
  2003. wp_send_json_error( 'missing_fields' );
  2004. wp_die();
  2005. }
  2006. $current_class = ! empty( $_POST['current_class'] ) ? $_POST['current_class'] : ''; // This is sanitized seven lines later.
  2007. if ( ! wp_verify_nonce( $_POST['wc_tax_nonce'], 'wc_tax_nonce-class:' . $current_class ) ) {
  2008. wp_send_json_error( 'bad_nonce' );
  2009. wp_die();
  2010. }
  2011. $current_class = WC_Tax::format_tax_rate_class( $current_class );
  2012. // Check User Caps
  2013. if ( ! current_user_can( 'manage_woocommerce' ) ) {
  2014. wp_send_json_error( 'missing_capabilities' );
  2015. wp_die();
  2016. }
  2017. $changes = $_POST['changes'];
  2018. foreach ( $changes as $tax_rate_id => $data ) {
  2019. if ( isset( $data['deleted'] ) ) {
  2020. if ( isset( $data['newRow'] ) ) {
  2021. // So the user added and deleted a new row.
  2022. // That's fine, it's not in the database anyways. NEXT!
  2023. continue;
  2024. }
  2025. WC_Tax::_delete_tax_rate( $tax_rate_id );
  2026. }
  2027. $tax_rate = array_intersect_key(
  2028. $data, array(
  2029. 'tax_rate_country' => 1,
  2030. 'tax_rate_state' => 1,
  2031. 'tax_rate' => 1,
  2032. 'tax_rate_name' => 1,
  2033. 'tax_rate_priority' => 1,
  2034. 'tax_rate_compound' => 1,
  2035. 'tax_rate_shipping' => 1,
  2036. 'tax_rate_order' => 1,
  2037. )
  2038. );
  2039. if ( isset( $tax_rate['tax_rate'] ) ) {
  2040. $tax_rate['tax_rate'] = wc_format_decimal( $tax_rate['tax_rate'] );
  2041. }
  2042. if ( isset( $data['newRow'] ) ) {
  2043. $tax_rate['tax_rate_class'] = $current_class;
  2044. $tax_rate_id = WC_Tax::_insert_tax_rate( $tax_rate );
  2045. } elseif ( ! empty( $tax_rate ) ) {
  2046. WC_Tax::_update_tax_rate( $tax_rate_id, $tax_rate );
  2047. }
  2048. if ( isset( $data['postcode'] ) ) {
  2049. $postcode = array_map( 'wc_clean', $data['postcode'] );
  2050. $postcode = array_map( 'wc_normalize_postcode', $postcode );
  2051. WC_Tax::_update_tax_rate_postcodes( $tax_rate_id, $postcode );
  2052. }
  2053. if ( isset( $data['city'] ) ) {
  2054. WC_Tax::_update_tax_rate_cities( $tax_rate_id, array_map( 'wc_clean', $data['city'] ) );
  2055. }
  2056. }
  2057. WC_Cache_Helper::incr_cache_prefix( 'taxes' );
  2058. WC_Cache_Helper::get_transient_version( 'shipping', true );
  2059. wp_send_json_success(
  2060. array(
  2061. 'rates' => WC_Tax::get_rates_for_tax_class( $current_class ),
  2062. )
  2063. );
  2064. }
  2065. /**
  2066. * Handle submissions from assets/js/wc-shipping-zones.js Backbone model.
  2067. */
  2068. public static function shipping_zones_save_changes() {
  2069. if ( ! isset( $_POST['wc_shipping_zones_nonce'], $_POST['changes'] ) ) {
  2070. wp_send_json_error( 'missing_fields' );
  2071. wp_die();
  2072. }
  2073. if ( ! wp_verify_nonce( $_POST['wc_shipping_zones_nonce'], 'wc_shipping_zones_nonce' ) ) {
  2074. wp_send_json_error( 'bad_nonce' );
  2075. wp_die();
  2076. }
  2077. // Check User Caps
  2078. if ( ! current_user_can( 'manage_woocommerce' ) ) {
  2079. wp_send_json_error( 'missing_capabilities' );
  2080. wp_die();
  2081. }
  2082. $changes = $_POST['changes'];
  2083. foreach ( $changes as $zone_id => $data ) {
  2084. if ( isset( $data['deleted'] ) ) {
  2085. if ( isset( $data['newRow'] ) ) {
  2086. // So the user added and deleted a new row.
  2087. // That's fine, it's not in the database anyways. NEXT!
  2088. continue;
  2089. }
  2090. WC_Shipping_Zones::delete_zone( $zone_id );
  2091. continue;
  2092. }
  2093. $zone_data = array_intersect_key(
  2094. $data, array(
  2095. 'zone_id' => 1,
  2096. 'zone_order' => 1,
  2097. )
  2098. );
  2099. if ( isset( $zone_data['zone_id'] ) ) {
  2100. $zone = new WC_Shipping_Zone( $zone_data['zone_id'] );
  2101. if ( isset( $zone_data['zone_order'] ) ) {
  2102. $zone->set_zone_order( $zone_data['zone_order'] );
  2103. }
  2104. $zone->save();
  2105. }
  2106. }
  2107. wp_send_json_success(
  2108. array(
  2109. 'zones' => WC_Shipping_Zones::get_zones( 'json' ),
  2110. )
  2111. );
  2112. }
  2113. /**
  2114. * Handle submissions from assets/js/wc-shipping-zone-methods.js Backbone model.
  2115. */
  2116. public static function shipping_zone_add_method() {
  2117. if ( ! isset( $_POST['wc_shipping_zones_nonce'], $_POST['zone_id'], $_POST['method_id'] ) ) {
  2118. wp_send_json_error( 'missing_fields' );
  2119. wp_die();
  2120. }
  2121. if ( ! wp_verify_nonce( $_POST['wc_shipping_zones_nonce'], 'wc_shipping_zones_nonce' ) ) {
  2122. wp_send_json_error( 'bad_nonce' );
  2123. wp_die();
  2124. }
  2125. // Check User Caps
  2126. if ( ! current_user_can( 'manage_woocommerce' ) ) {
  2127. wp_send_json_error( 'missing_capabilities' );
  2128. wp_die();
  2129. }
  2130. $zone_id = wc_clean( $_POST['zone_id'] );
  2131. $zone = new WC_Shipping_Zone( $zone_id );
  2132. $instance_id = $zone->add_shipping_method( wc_clean( $_POST['method_id'] ) );
  2133. wp_send_json_success(
  2134. array(
  2135. 'instance_id' => $instance_id,
  2136. 'zone_id' => $zone->get_id(),
  2137. 'zone_name' => $zone->get_zone_name(),
  2138. 'methods' => $zone->get_shipping_methods( false, 'json' ),
  2139. )
  2140. );
  2141. }
  2142. /**
  2143. * Handle submissions from assets/js/wc-shipping-zone-methods.js Backbone model.
  2144. */
  2145. public static function shipping_zone_methods_save_changes() {
  2146. if ( ! isset( $_POST['wc_shipping_zones_nonce'], $_POST['zone_id'], $_POST['changes'] ) ) {
  2147. wp_send_json_error( 'missing_fields' );
  2148. wp_die();
  2149. }
  2150. if ( ! wp_verify_nonce( $_POST['wc_shipping_zones_nonce'], 'wc_shipping_zones_nonce' ) ) {
  2151. wp_send_json_error( 'bad_nonce' );
  2152. wp_die();
  2153. }
  2154. if ( ! current_user_can( 'manage_woocommerce' ) ) {
  2155. wp_send_json_error( 'missing_capabilities' );
  2156. wp_die();
  2157. }
  2158. global $wpdb;
  2159. $zone_id = wc_clean( $_POST['zone_id'] );
  2160. $zone = new WC_Shipping_Zone( $zone_id );
  2161. $changes = $_POST['changes'];
  2162. if ( isset( $changes['zone_name'] ) ) {
  2163. $zone->set_zone_name( wc_clean( $changes['zone_name'] ) );
  2164. }
  2165. if ( isset( $changes['zone_locations'] ) ) {
  2166. $zone->clear_locations( array( 'state', 'country', 'continent' ) );
  2167. $locations = array_filter( array_map( 'wc_clean', (array) $changes['zone_locations'] ) );
  2168. foreach ( $locations as $location ) {
  2169. // Each posted location will be in the format type:code
  2170. $location_parts = explode( ':', $location );
  2171. switch ( $location_parts[0] ) {
  2172. case 'state':
  2173. $zone->add_location( $location_parts[1] . ':' . $location_parts[2], 'state' );
  2174. break;
  2175. case 'country':
  2176. $zone->add_location( $location_parts[1], 'country' );
  2177. break;
  2178. case 'continent':
  2179. $zone->add_location( $location_parts[1], 'continent' );
  2180. break;
  2181. }
  2182. }
  2183. }
  2184. if ( isset( $changes['zone_postcodes'] ) ) {
  2185. $zone->clear_locations( 'postcode' );
  2186. $postcodes = array_filter( array_map( 'strtoupper', array_map( 'wc_clean', explode( "\n", $changes['zone_postcodes'] ) ) ) );
  2187. foreach ( $postcodes as $postcode ) {
  2188. $zone->add_location( $postcode, 'postcode' );
  2189. }
  2190. }
  2191. if ( isset( $changes['methods'] ) ) {
  2192. foreach ( $changes['methods'] as $instance_id => $data ) {
  2193. $method_id = $wpdb->get_var( $wpdb->prepare( "SELECT method_id FROM {$wpdb->prefix}woocommerce_shipping_zone_methods WHERE instance_id = %d", $instance_id ) );
  2194. if ( isset( $data['deleted'] ) ) {
  2195. $shipping_method = WC_Shipping_Zones::get_shipping_method( $instance_id );
  2196. $option_key = $shipping_method->get_instance_option_key();
  2197. if ( $wpdb->delete( "{$wpdb->prefix}woocommerce_shipping_zone_methods", array( 'instance_id' => $instance_id ) ) ) {
  2198. delete_option( $option_key );
  2199. do_action( 'woocommerce_shipping_zone_method_deleted', $instance_id, $method_id, $zone_id );
  2200. }
  2201. continue;
  2202. }
  2203. $method_data = array_intersect_key(
  2204. $data, array(
  2205. 'method_order' => 1,
  2206. 'enabled' => 1,
  2207. )
  2208. );
  2209. if ( isset( $method_data['method_order'] ) ) {
  2210. $wpdb->update( "{$wpdb->prefix}woocommerce_shipping_zone_methods", array( 'method_order' => absint( $method_data['method_order'] ) ), array( 'instance_id' => absint( $instance_id ) ) );
  2211. }
  2212. if ( isset( $method_data['enabled'] ) ) {
  2213. $is_enabled = absint( 'yes' === $method_data['enabled'] );
  2214. if ( $wpdb->update( "{$wpdb->prefix}woocommerce_shipping_zone_methods", array( 'is_enabled' => $is_enabled ), array( 'instance_id' => absint( $instance_id ) ) ) ) {
  2215. do_action( 'woocommerce_shipping_zone_method_status_toggled', $instance_id, $method_id, $zone_id, $is_enabled );
  2216. }
  2217. }
  2218. }
  2219. }
  2220. $zone->save();
  2221. wp_send_json_success(
  2222. array(
  2223. 'zone_id' => $zone->get_id(),
  2224. 'zone_name' => $zone->get_zone_name(),
  2225. 'methods' => $zone->get_shipping_methods( false, 'json' ),
  2226. )
  2227. );
  2228. }
  2229. /**
  2230. * Save method settings
  2231. */
  2232. public static function shipping_zone_methods_save_settings() {
  2233. if ( ! isset( $_POST['wc_shipping_zones_nonce'], $_POST['instance_id'], $_POST['data'] ) ) {
  2234. wp_send_json_error( 'missing_fields' );
  2235. wp_die();
  2236. }
  2237. if ( ! wp_verify_nonce( $_POST['wc_shipping_zones_nonce'], 'wc_shipping_zones_nonce' ) ) {
  2238. wp_send_json_error( 'bad_nonce' );
  2239. wp_die();
  2240. }
  2241. if ( ! current_user_can( 'manage_woocommerce' ) ) {
  2242. wp_send_json_error( 'missing_capabilities' );
  2243. wp_die();
  2244. }
  2245. $instance_id = absint( $_POST['instance_id'] );
  2246. $zone = WC_Shipping_Zones::get_zone_by( 'instance_id', $instance_id );
  2247. $shipping_method = WC_Shipping_Zones::get_shipping_method( $instance_id );
  2248. $shipping_method->set_post_data( $_POST['data'] );
  2249. $shipping_method->process_admin_options();
  2250. WC_Cache_Helper::get_transient_version( 'shipping', true );
  2251. wp_send_json_success(
  2252. array(
  2253. 'zone_id' => $zone->get_id(),
  2254. 'zone_name' => $zone->get_zone_name(),
  2255. 'methods' => $zone->get_shipping_methods( false, 'json' ),
  2256. 'errors' => $shipping_method->get_errors(),
  2257. )
  2258. );
  2259. }
  2260. /**
  2261. * Handle submissions from assets/js/wc-shipping-classes.js Backbone model.
  2262. */
  2263. public static function shipping_classes_save_changes() {
  2264. if ( ! isset( $_POST['wc_shipping_classes_nonce'], $_POST['changes'] ) ) {
  2265. wp_send_json_error( 'missing_fields' );
  2266. wp_die();
  2267. }
  2268. if ( ! wp_verify_nonce( $_POST['wc_shipping_classes_nonce'], 'wc_shipping_classes_nonce' ) ) {
  2269. wp_send_json_error( 'bad_nonce' );
  2270. wp_die();
  2271. }
  2272. if ( ! current_user_can( 'manage_woocommerce' ) ) {
  2273. wp_send_json_error( 'missing_capabilities' );
  2274. wp_die();
  2275. }
  2276. $changes = $_POST['changes'];
  2277. foreach ( $changes as $term_id => $data ) {
  2278. $term_id = absint( $term_id );
  2279. if ( isset( $data['deleted'] ) ) {
  2280. if ( isset( $data['newRow'] ) ) {
  2281. // So the user added and deleted a new row.
  2282. // That's fine, it's not in the database anyways. NEXT!
  2283. continue;
  2284. }
  2285. wp_delete_term( $term_id, 'product_shipping_class' );
  2286. continue;
  2287. }
  2288. $update_args = array();
  2289. if ( isset( $data['name'] ) ) {
  2290. $update_args['name'] = wc_clean( $data['name'] );
  2291. }
  2292. if ( isset( $data['slug'] ) ) {
  2293. $update_args['slug'] = wc_clean( $data['slug'] );
  2294. }
  2295. if ( isset( $data['description'] ) ) {
  2296. $update_args['description'] = wc_clean( $data['description'] );
  2297. }
  2298. if ( isset( $data['newRow'] ) ) {
  2299. $update_args = array_filter( $update_args );
  2300. if ( empty( $update_args['name'] ) ) {
  2301. continue;
  2302. }
  2303. $inserted_term = wp_insert_term( $update_args['name'], 'product_shipping_class', $update_args );
  2304. $term_id = is_wp_error( $inserted_term ) ? 0 : $inserted_term['term_id'];
  2305. } else {
  2306. wp_update_term( $term_id, 'product_shipping_class', $update_args );
  2307. }
  2308. do_action( 'woocommerce_shipping_classes_save_class', $term_id, $data );
  2309. }
  2310. $wc_shipping = WC_Shipping::instance();
  2311. wp_send_json_success(
  2312. array(
  2313. 'shipping_classes' => $wc_shipping->get_shipping_classes(),
  2314. )
  2315. );
  2316. }
  2317. /**
  2318. * Toggle payment gateway on or off via AJAX.
  2319. *
  2320. * @since 3.4.0
  2321. */
  2322. public static function toggle_gateway_enabled() {
  2323. if ( current_user_can( 'manage_woocommerce' ) && check_ajax_referer( 'woocommerce-toggle-payment-gateway-enabled', 'security' ) ) {
  2324. // Load gateways.
  2325. $payment_gateways = WC()->payment_gateways->payment_gateways();
  2326. // Get posted gateway.
  2327. $gateway_id = wc_clean( wp_unslash( $_POST['gateway_id'] ) );
  2328. foreach ( $payment_gateways as $gateway ) {
  2329. if ( ! in_array( $gateway_id, array( $gateway->id, sanitize_title( get_class( $gateway ) ) ), true ) ) {
  2330. continue;
  2331. }
  2332. $enabled = $gateway->get_option( 'enabled', 'no' );
  2333. if ( ! wc_string_to_bool( $enabled ) ) {
  2334. if ( $gateway->needs_setup() ) {
  2335. wp_send_json_error( 'needs_setup' );
  2336. wp_die();
  2337. } else {
  2338. $gateway->update_option( 'enabled', 'yes' );
  2339. }
  2340. } else {
  2341. // Disable the gateway.
  2342. $gateway->update_option( 'enabled', 'no' );
  2343. }
  2344. wp_send_json_success( ! wc_string_to_bool( $enabled ) );
  2345. wp_die();
  2346. }
  2347. }
  2348. wp_send_json_error( 'invalid_gateway_id' );
  2349. wp_die();
  2350. }
  2351. }
  2352. WC_AJAX::init();