Sin descripción

class-wc-ajax.php 100KB

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