Bez popisu

wc-admin-functions.php 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  1. <?php
  2. /**
  3. * WooCommerce Admin Functions
  4. *
  5. * @package WooCommerce\Admin\Functions
  6. * @version 2.4.0
  7. */
  8. if ( ! defined( 'ABSPATH' ) ) {
  9. exit;
  10. }
  11. /**
  12. * Get all WooCommerce screen ids.
  13. *
  14. * @return array
  15. */
  16. function wc_get_screen_ids() {
  17. $wc_screen_id = sanitize_title( __( 'WooCommerce', 'woocommerce' ) );
  18. $screen_ids = array(
  19. 'toplevel_page_' . $wc_screen_id,
  20. $wc_screen_id . '_page_wc-reports',
  21. $wc_screen_id . '_page_wc-shipping',
  22. $wc_screen_id . '_page_wc-settings',
  23. $wc_screen_id . '_page_wc-status',
  24. $wc_screen_id . '_page_wc-addons',
  25. 'toplevel_page_wc-reports',
  26. 'product_page_product_attributes',
  27. 'product_page_product_exporter',
  28. 'product_page_product_importer',
  29. 'edit-product',
  30. 'product',
  31. 'edit-shop_coupon',
  32. 'shop_coupon',
  33. 'edit-product_cat',
  34. 'edit-product_tag',
  35. 'profile',
  36. 'user-edit',
  37. );
  38. foreach ( wc_get_order_types() as $type ) {
  39. $screen_ids[] = $type;
  40. $screen_ids[] = 'edit-' . $type;
  41. }
  42. $attributes = wc_get_attribute_taxonomies();
  43. if ( $attributes ) {
  44. foreach ( $attributes as $attribute ) {
  45. $screen_ids[] = 'edit-' . wc_attribute_taxonomy_name( $attribute->attribute_name );
  46. }
  47. }
  48. return apply_filters( 'woocommerce_screen_ids', $screen_ids );
  49. }
  50. /**
  51. * Create a page and store the ID in an option.
  52. *
  53. * @param mixed $slug Slug for the new page.
  54. * @param string $option Option name to store the page's ID.
  55. * @param string $page_title (default: '') Title for the new page.
  56. * @param string $page_content (default: '') Content for the new page.
  57. * @param int $post_parent (default: 0) Parent for the new page.
  58. * @param string $post_status (default: publish) The post status of the new page.
  59. * @return int page ID.
  60. */
  61. function wc_create_page( $slug, $option = '', $page_title = '', $page_content = '', $post_parent = 0, $post_status = 'publish' ) {
  62. global $wpdb;
  63. $option_value = get_option( $option );
  64. if ( $option_value > 0 ) {
  65. $page_object = get_post( $option_value );
  66. if ( $page_object && 'page' === $page_object->post_type && ! in_array( $page_object->post_status, array( 'pending', 'trash', 'future', 'auto-draft' ), true ) ) {
  67. // Valid page is already in place.
  68. return $page_object->ID;
  69. }
  70. }
  71. if ( strlen( $page_content ) > 0 ) {
  72. // Search for an existing page with the specified page content (typically a shortcode).
  73. $shortcode = str_replace( array( '<!-- wp:shortcode -->', '<!-- /wp:shortcode -->' ), '', $page_content );
  74. $valid_page_found = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_type='page' AND post_status NOT IN ( 'pending', 'trash', 'future', 'auto-draft' ) AND post_content LIKE %s LIMIT 1;", "%{$shortcode}%" ) );
  75. } else {
  76. // Search for an existing page with the specified page slug.
  77. $valid_page_found = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_type='page' AND post_status NOT IN ( 'pending', 'trash', 'future', 'auto-draft' ) AND post_name = %s LIMIT 1;", $slug ) );
  78. }
  79. $valid_page_found = apply_filters( 'woocommerce_create_page_id', $valid_page_found, $slug, $page_content );
  80. if ( $valid_page_found ) {
  81. if ( $option ) {
  82. update_option( $option, $valid_page_found );
  83. }
  84. return $valid_page_found;
  85. }
  86. // Search for a matching valid trashed page.
  87. if ( strlen( $page_content ) > 0 ) {
  88. // Search for an existing page with the specified page content (typically a shortcode).
  89. $trashed_page_found = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_type='page' AND post_status = 'trash' AND post_content LIKE %s LIMIT 1;", "%{$page_content}%" ) );
  90. } else {
  91. // Search for an existing page with the specified page slug.
  92. $trashed_page_found = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_type='page' AND post_status = 'trash' AND post_name = %s LIMIT 1;", $slug ) );
  93. }
  94. if ( $trashed_page_found ) {
  95. $page_id = $trashed_page_found;
  96. $page_data = array(
  97. 'ID' => $page_id,
  98. 'post_status' => $post_status,
  99. );
  100. wp_update_post( $page_data );
  101. } else {
  102. $page_data = array(
  103. 'post_status' => $post_status,
  104. 'post_type' => 'page',
  105. 'post_author' => 1,
  106. 'post_name' => $slug,
  107. 'post_title' => $page_title,
  108. 'post_content' => $page_content,
  109. 'post_parent' => $post_parent,
  110. 'comment_status' => 'closed',
  111. );
  112. $page_id = wp_insert_post( $page_data );
  113. do_action( 'woocommerce_page_created', $page_id, $page_data );
  114. }
  115. if ( $option ) {
  116. update_option( $option, $page_id );
  117. }
  118. return $page_id;
  119. }
  120. /**
  121. * Output admin fields.
  122. *
  123. * Loops through the woocommerce options array and outputs each field.
  124. *
  125. * @param array $options Opens array to output.
  126. */
  127. function woocommerce_admin_fields( $options ) {
  128. if ( ! class_exists( 'WC_Admin_Settings', false ) ) {
  129. include dirname( __FILE__ ) . '/class-wc-admin-settings.php';
  130. }
  131. WC_Admin_Settings::output_fields( $options );
  132. }
  133. /**
  134. * Update all settings which are passed.
  135. *
  136. * @param array $options Option fields to save.
  137. * @param array $data Passed data.
  138. */
  139. function woocommerce_update_options( $options, $data = null ) {
  140. if ( ! class_exists( 'WC_Admin_Settings', false ) ) {
  141. include dirname( __FILE__ ) . '/class-wc-admin-settings.php';
  142. }
  143. WC_Admin_Settings::save_fields( $options, $data );
  144. }
  145. /**
  146. * Get a setting from the settings API.
  147. *
  148. * @param mixed $option_name Option name to save.
  149. * @param mixed $default Default value to save.
  150. * @return string
  151. */
  152. function woocommerce_settings_get_option( $option_name, $default = '' ) {
  153. if ( ! class_exists( 'WC_Admin_Settings', false ) ) {
  154. include dirname( __FILE__ ) . '/class-wc-admin-settings.php';
  155. }
  156. return WC_Admin_Settings::get_option( $option_name, $default );
  157. }
  158. /**
  159. * Sees if line item stock has already reduced stock, and whether those values need adjusting e.g. after changing item qty.
  160. *
  161. * @since 3.6.0
  162. * @param WC_Order_Item $item Item object.
  163. * @param integer $item_quantity Optional quantity to check against. Read from object if not passed.
  164. * @return boolean|array|WP_Error Array of changes or error object when stock is updated (@see wc_update_product_stock). False if nothing changes.
  165. */
  166. function wc_maybe_adjust_line_item_product_stock( $item, $item_quantity = -1 ) {
  167. if ( 'line_item' !== $item->get_type() ) {
  168. return false;
  169. }
  170. /**
  171. * Prevent adjust line item product stock.
  172. *
  173. * @since 3.7.1
  174. * @param bool $prevent If should prevent.
  175. * @param WC_Order_Item $item Item object.
  176. * @param int $item_quantity Optional quantity to check against.
  177. */
  178. if ( apply_filters( 'woocommerce_prevent_adjust_line_item_product_stock', false, $item, $item_quantity ) ) {
  179. return false;
  180. }
  181. $product = $item->get_product();
  182. if ( ! $product || ! $product->managing_stock() ) {
  183. return false;
  184. }
  185. $item_quantity = wc_stock_amount( $item_quantity >= 0 ? $item_quantity : $item->get_quantity() );
  186. $already_reduced_stock = wc_stock_amount( $item->get_meta( '_reduced_stock', true ) );
  187. $restock_refunded_items = wc_stock_amount( $item->get_meta( '_restock_refunded_items', true ) );
  188. $order = $item->get_order();
  189. $refunded_item_quantity = $order->get_qty_refunded_for_item( $item->get_id() );
  190. $diff = $item_quantity - $restock_refunded_items - $already_reduced_stock;
  191. /*
  192. * 0 as $item_quantity usually indicates we're deleting the order item.
  193. * Let's restore back the reduced count.
  194. */
  195. if ( 0 === $item_quantity ) {
  196. $diff = $already_reduced_stock * -1;
  197. }
  198. if ( $diff < 0 ) {
  199. $new_stock = wc_update_product_stock( $product, $diff * -1, 'increase' );
  200. } elseif ( $diff > 0 ) {
  201. $new_stock = wc_update_product_stock( $product, $diff, 'decrease' );
  202. } else {
  203. return false;
  204. }
  205. if ( is_wp_error( $new_stock ) ) {
  206. return $new_stock;
  207. }
  208. $item->update_meta_data( '_reduced_stock', $item_quantity - $restock_refunded_items );
  209. $item->save();
  210. if ( $item_quantity > 0 ) {
  211. // If stock was reduced, then we need to mark this on parent order object as well so that cancel logic works properly.
  212. $order_data_store = WC_Data_Store::load( 'order' );
  213. if ( $item->get_order_id() && ! $order_data_store->get_stock_reduced( $item->get_order_id() ) ) {
  214. $order_data_store->set_stock_reduced( $item->get_order_id(), true );
  215. }
  216. }
  217. return array(
  218. 'from' => $new_stock + $diff,
  219. 'to' => $new_stock,
  220. );
  221. }
  222. /**
  223. * Save order items. Uses the CRUD.
  224. *
  225. * @since 2.2
  226. * @param int $order_id Order ID.
  227. * @param array $items Order items to save.
  228. */
  229. function wc_save_order_items( $order_id, $items ) {
  230. // Allow other plugins to check change in order items before they are saved.
  231. do_action( 'woocommerce_before_save_order_items', $order_id, $items );
  232. $qty_change_order_notes = array();
  233. $order = wc_get_order( $order_id );
  234. // Line items and fees.
  235. if ( isset( $items['order_item_id'] ) ) {
  236. $data_keys = array(
  237. 'line_tax' => array(),
  238. 'line_subtotal_tax' => array(),
  239. 'order_item_name' => null,
  240. 'order_item_qty' => null,
  241. 'order_item_tax_class' => null,
  242. 'line_total' => null,
  243. 'line_subtotal' => null,
  244. );
  245. foreach ( $items['order_item_id'] as $item_id ) {
  246. $item = WC_Order_Factory::get_order_item( absint( $item_id ) );
  247. if ( ! $item ) {
  248. continue;
  249. }
  250. $item_data = array();
  251. foreach ( $data_keys as $key => $default ) {
  252. $item_data[ $key ] = isset( $items[ $key ][ $item_id ] ) ? wc_check_invalid_utf8( wp_unslash( $items[ $key ][ $item_id ] ) ) : $default;
  253. }
  254. if ( '0' === $item_data['order_item_qty'] ) {
  255. $changed_stock = wc_maybe_adjust_line_item_product_stock( $item, 0 );
  256. if ( $changed_stock && ! is_wp_error( $changed_stock ) ) {
  257. $qty_change_order_notes[] = $item->get_name() . ' &ndash; ' . $changed_stock['from'] . '&rarr;' . $changed_stock['to'];
  258. }
  259. $item->delete();
  260. continue;
  261. }
  262. $item->set_props(
  263. array(
  264. 'name' => $item_data['order_item_name'],
  265. 'quantity' => $item_data['order_item_qty'],
  266. 'tax_class' => $item_data['order_item_tax_class'],
  267. 'total' => $item_data['line_total'],
  268. 'subtotal' => $item_data['line_subtotal'],
  269. 'taxes' => array(
  270. 'total' => $item_data['line_tax'],
  271. 'subtotal' => $item_data['line_subtotal_tax'],
  272. ),
  273. )
  274. );
  275. if ( 'fee' === $item->get_type() ) {
  276. $item->set_amount( $item_data['line_total'] );
  277. }
  278. if ( isset( $items['meta_key'][ $item_id ], $items['meta_value'][ $item_id ] ) ) {
  279. foreach ( $items['meta_key'][ $item_id ] as $meta_id => $meta_key ) {
  280. $meta_key = substr( wp_unslash( $meta_key ), 0, 255 );
  281. $meta_value = isset( $items['meta_value'][ $item_id ][ $meta_id ] ) ? wp_unslash( $items['meta_value'][ $item_id ][ $meta_id ] ) : '';
  282. if ( '' === $meta_key && '' === $meta_value ) {
  283. if ( ! strstr( $meta_id, 'new-' ) ) {
  284. $item->delete_meta_data_by_mid( $meta_id );
  285. }
  286. } elseif ( strstr( $meta_id, 'new-' ) ) {
  287. $item->add_meta_data( $meta_key, $meta_value, false );
  288. } else {
  289. $item->update_meta_data( $meta_key, $meta_value, $meta_id );
  290. }
  291. }
  292. }
  293. // Allow other plugins to change item object before it is saved.
  294. do_action( 'woocommerce_before_save_order_item', $item );
  295. $item->save();
  296. if ( in_array( $order->get_status(), array( 'processing', 'completed', 'on-hold' ) ) ) {
  297. $changed_stock = wc_maybe_adjust_line_item_product_stock( $item );
  298. if ( $changed_stock && ! is_wp_error( $changed_stock ) ) {
  299. $qty_change_order_notes[] = $item->get_name() . ' (' . $changed_stock['from'] . '&rarr;' . $changed_stock['to'] . ')';
  300. }
  301. }
  302. }
  303. }
  304. // Shipping Rows.
  305. if ( isset( $items['shipping_method_id'] ) ) {
  306. $data_keys = array(
  307. 'shipping_method' => null,
  308. 'shipping_method_title' => null,
  309. 'shipping_cost' => 0,
  310. 'shipping_taxes' => array(),
  311. );
  312. foreach ( $items['shipping_method_id'] as $item_id ) {
  313. $item = WC_Order_Factory::get_order_item( absint( $item_id ) );
  314. if ( ! $item ) {
  315. continue;
  316. }
  317. $item_data = array();
  318. foreach ( $data_keys as $key => $default ) {
  319. $item_data[ $key ] = isset( $items[ $key ][ $item_id ] ) ? wc_clean( wp_unslash( $items[ $key ][ $item_id ] ) ) : $default;
  320. }
  321. $item->set_props(
  322. array(
  323. 'method_id' => $item_data['shipping_method'],
  324. 'method_title' => $item_data['shipping_method_title'],
  325. 'total' => $item_data['shipping_cost'],
  326. 'taxes' => array(
  327. 'total' => $item_data['shipping_taxes'],
  328. ),
  329. )
  330. );
  331. if ( isset( $items['meta_key'][ $item_id ], $items['meta_value'][ $item_id ] ) ) {
  332. foreach ( $items['meta_key'][ $item_id ] as $meta_id => $meta_key ) {
  333. $meta_value = isset( $items['meta_value'][ $item_id ][ $meta_id ] ) ? wp_unslash( $items['meta_value'][ $item_id ][ $meta_id ] ) : '';
  334. if ( '' === $meta_key && '' === $meta_value ) {
  335. if ( ! strstr( $meta_id, 'new-' ) ) {
  336. $item->delete_meta_data_by_mid( $meta_id );
  337. }
  338. } elseif ( strstr( $meta_id, 'new-' ) ) {
  339. $item->add_meta_data( $meta_key, $meta_value, false );
  340. } else {
  341. $item->update_meta_data( $meta_key, $meta_value, $meta_id );
  342. }
  343. }
  344. }
  345. $item->save();
  346. }
  347. }
  348. $order = wc_get_order( $order_id );
  349. if ( ! empty( $qty_change_order_notes ) ) {
  350. /* translators: %s item name. */
  351. $order->add_order_note( sprintf( __( 'Adjusted stock: %s', 'woocommerce' ), implode( ', ', $qty_change_order_notes ) ), false, true );
  352. }
  353. $order->update_taxes();
  354. $order->calculate_totals( false );
  355. // Inform other plugins that the items have been saved.
  356. do_action( 'woocommerce_saved_order_items', $order_id, $items );
  357. }
  358. /**
  359. * Get HTML for some action buttons. Used in list tables.
  360. *
  361. * @since 3.3.0
  362. * @param array $actions Actions to output.
  363. * @return string
  364. */
  365. function wc_render_action_buttons( $actions ) {
  366. $actions_html = '';
  367. foreach ( $actions as $action ) {
  368. if ( isset( $action['group'] ) ) {
  369. $actions_html .= '<div class="wc-action-button-group"><label>' . $action['group'] . '</label> <span class="wc-action-button-group__items">' . wc_render_action_buttons( $action['actions'] ) . '</span></div>';
  370. } elseif ( isset( $action['action'], $action['url'], $action['name'] ) ) {
  371. $actions_html .= sprintf( '<a class="button wc-action-button wc-action-button-%1$s %1$s" href="%2$s" aria-label="%3$s" title="%3$s">%4$s</a>', esc_attr( $action['action'] ), esc_url( $action['url'] ), esc_attr( isset( $action['title'] ) ? $action['title'] : $action['name'] ), esc_html( $action['name'] ) );
  372. }
  373. }
  374. return $actions_html;
  375. }
  376. /**
  377. * Shows a notice if variations are missing prices.
  378. *
  379. * @since 3.6.0
  380. * @param WC_Product $product_object Product object.
  381. */
  382. function wc_render_invalid_variation_notice( $product_object ) {
  383. global $wpdb;
  384. // Give ability for extensions to hide this notice.
  385. if ( ! apply_filters( 'woocommerce_show_invalid_variations_notice', true, $product_object ) ) {
  386. return;
  387. }
  388. $variation_ids = $product_object ? $product_object->get_children() : array();
  389. if ( empty( $variation_ids ) ) {
  390. return;
  391. }
  392. $variation_count = count( $variation_ids );
  393. // Check if a variation exists without pricing data.
  394. // phpcs:disable WordPress.DB.PreparedSQL.NotPrepared
  395. $invalid_variation_count = $wpdb->get_var(
  396. "
  397. SELECT count(post_id) FROM {$wpdb->postmeta}
  398. WHERE post_id in (" . implode( ',', array_map( 'absint', $variation_ids ) ) . ")
  399. AND meta_key='_price'
  400. AND meta_value >= 0
  401. AND meta_value != ''
  402. "
  403. );
  404. // phpcs:enable WordPress.DB.PreparedSQL.NotPrepared
  405. if ( 0 < ( $variation_count - $invalid_variation_count ) ) {
  406. ?>
  407. <div id="message" class="inline notice woocommerce-message woocommerce-notice-invalid-variation">
  408. <p>
  409. <?php
  410. echo wp_kses_post(
  411. sprintf(
  412. /* Translators: %d variation count. */
  413. _n( '%d variation does not have a price.', '%d variations do not have prices.', ( $variation_count - $invalid_variation_count ), 'woocommerce' ),
  414. ( $variation_count - $invalid_variation_count )
  415. ) . '&nbsp;' .
  416. __( 'Variations (and their attributes) that do not have prices will not be shown in your store.', 'woocommerce' )
  417. );
  418. ?>
  419. </p>
  420. </div>
  421. <?php
  422. }
  423. }
  424. /**
  425. * Get current admin page URL.
  426. *
  427. * Returns an empty string if it cannot generate a URL.
  428. *
  429. * @internal
  430. * @since 4.4.0
  431. * @return string
  432. */
  433. function wc_get_current_admin_url() {
  434. $uri = isset( $_SERVER['REQUEST_URI'] ) ? esc_url_raw( wp_unslash( $_SERVER['REQUEST_URI'] ) ) : '';
  435. $uri = preg_replace( '|^.*/wp-admin/|i', '', $uri );
  436. if ( ! $uri ) {
  437. return '';
  438. }
  439. return remove_query_arg( array( '_wpnonce', '_wc_notice_nonce', 'wc_db_update', 'wc_db_update_nonce', 'wc-hide-notice' ), admin_url( $uri ) );
  440. }