Açıklama Yok

wc-user-functions.php 27KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927
  1. <?php
  2. /**
  3. * WooCommerce Customer Functions
  4. *
  5. * Functions for customers.
  6. *
  7. * @package WooCommerce\Functions
  8. * @version 2.2.0
  9. */
  10. defined( 'ABSPATH' ) || exit;
  11. /**
  12. * Prevent any user who cannot 'edit_posts' (subscribers, customers etc) from seeing the admin bar.
  13. *
  14. * Note: get_option( 'woocommerce_lock_down_admin', true ) is a deprecated option here for backwards compatibility. Defaults to true.
  15. *
  16. * @param bool $show_admin_bar If should display admin bar.
  17. * @return bool
  18. */
  19. function wc_disable_admin_bar( $show_admin_bar ) {
  20. if ( apply_filters( 'woocommerce_disable_admin_bar', true ) && ! ( current_user_can( 'edit_posts' ) || current_user_can( 'manage_woocommerce' ) ) ) {
  21. $show_admin_bar = false;
  22. }
  23. return $show_admin_bar;
  24. }
  25. add_filter( 'show_admin_bar', 'wc_disable_admin_bar', 10, 1 ); // phpcs:ignore WordPress.VIP.AdminBarRemoval.RemovalDetected
  26. if ( ! function_exists( 'wc_create_new_customer' ) ) {
  27. /**
  28. * Create a new customer.
  29. *
  30. * @param string $email Customer email.
  31. * @param string $username Customer username.
  32. * @param string $password Customer password.
  33. * @param array $args List of arguments to pass to `wp_insert_user()`.
  34. * @return int|WP_Error Returns WP_Error on failure, Int (user ID) on success.
  35. */
  36. function wc_create_new_customer( $email, $username = '', $password = '', $args = array() ) {
  37. if ( empty( $email ) || ! is_email( $email ) ) {
  38. return new WP_Error( 'registration-error-invalid-email', __( 'Please provide a valid email address.', 'woocommerce' ) );
  39. }
  40. if ( email_exists( $email ) ) {
  41. return new WP_Error( 'registration-error-email-exists', apply_filters( 'woocommerce_registration_error_email_exists', __( 'An account is already registered with your email address. <a href="#" class="showlogin">Please log in.</a>', 'woocommerce' ), $email ) );
  42. }
  43. if ( 'yes' === get_option( 'woocommerce_registration_generate_username', 'yes' ) && empty( $username ) ) {
  44. $username = wc_create_new_customer_username( $email, $args );
  45. }
  46. $username = sanitize_user( $username );
  47. if ( empty( $username ) || ! validate_username( $username ) ) {
  48. return new WP_Error( 'registration-error-invalid-username', __( 'Please enter a valid account username.', 'woocommerce' ) );
  49. }
  50. if ( username_exists( $username ) ) {
  51. return new WP_Error( 'registration-error-username-exists', __( 'An account is already registered with that username. Please choose another.', 'woocommerce' ) );
  52. }
  53. // Handle password creation.
  54. $password_generated = false;
  55. if ( 'yes' === get_option( 'woocommerce_registration_generate_password' ) && empty( $password ) ) {
  56. $password = wp_generate_password();
  57. $password_generated = true;
  58. }
  59. if ( empty( $password ) ) {
  60. return new WP_Error( 'registration-error-missing-password', __( 'Please enter an account password.', 'woocommerce' ) );
  61. }
  62. // Use WP_Error to handle registration errors.
  63. $errors = new WP_Error();
  64. do_action( 'woocommerce_register_post', $username, $email, $errors );
  65. $errors = apply_filters( 'woocommerce_registration_errors', $errors, $username, $email );
  66. if ( $errors->get_error_code() ) {
  67. return $errors;
  68. }
  69. $new_customer_data = apply_filters(
  70. 'woocommerce_new_customer_data',
  71. array_merge(
  72. $args,
  73. array(
  74. 'user_login' => $username,
  75. 'user_pass' => $password,
  76. 'user_email' => $email,
  77. 'role' => 'customer',
  78. )
  79. )
  80. );
  81. $customer_id = wp_insert_user( $new_customer_data );
  82. if ( is_wp_error( $customer_id ) ) {
  83. return $customer_id;
  84. }
  85. do_action( 'woocommerce_created_customer', $customer_id, $new_customer_data, $password_generated );
  86. return $customer_id;
  87. }
  88. }
  89. /**
  90. * Create a unique username for a new customer.
  91. *
  92. * @since 3.6.0
  93. * @param string $email New customer email address.
  94. * @param array $new_user_args Array of new user args, maybe including first and last names.
  95. * @param string $suffix Append string to username to make it unique.
  96. * @return string Generated username.
  97. */
  98. function wc_create_new_customer_username( $email, $new_user_args = array(), $suffix = '' ) {
  99. $username_parts = array();
  100. if ( isset( $new_user_args['first_name'] ) ) {
  101. $username_parts[] = sanitize_user( $new_user_args['first_name'], true );
  102. }
  103. if ( isset( $new_user_args['last_name'] ) ) {
  104. $username_parts[] = sanitize_user( $new_user_args['last_name'], true );
  105. }
  106. // Remove empty parts.
  107. $username_parts = array_filter( $username_parts );
  108. // If there are no parts, e.g. name had unicode chars, or was not provided, fallback to email.
  109. if ( empty( $username_parts ) ) {
  110. $email_parts = explode( '@', $email );
  111. $email_username = $email_parts[0];
  112. // Exclude common prefixes.
  113. if ( in_array(
  114. $email_username,
  115. array(
  116. 'sales',
  117. 'hello',
  118. 'mail',
  119. 'contact',
  120. 'info',
  121. ),
  122. true
  123. ) ) {
  124. // Get the domain part.
  125. $email_username = $email_parts[1];
  126. }
  127. $username_parts[] = sanitize_user( $email_username, true );
  128. }
  129. $username = wc_strtolower( implode( '.', $username_parts ) );
  130. if ( $suffix ) {
  131. $username .= $suffix;
  132. }
  133. /**
  134. * WordPress 4.4 - filters the list of blocked usernames.
  135. *
  136. * @since 3.7.0
  137. * @param array $usernames Array of blocked usernames.
  138. */
  139. $illegal_logins = (array) apply_filters( 'illegal_user_logins', array() );
  140. // Stop illegal logins and generate a new random username.
  141. if ( in_array( strtolower( $username ), array_map( 'strtolower', $illegal_logins ), true ) ) {
  142. $new_args = array();
  143. /**
  144. * Filter generated customer username.
  145. *
  146. * @since 3.7.0
  147. * @param string $username Generated username.
  148. * @param string $email New customer email address.
  149. * @param array $new_user_args Array of new user args, maybe including first and last names.
  150. * @param string $suffix Append string to username to make it unique.
  151. */
  152. $new_args['first_name'] = apply_filters(
  153. 'woocommerce_generated_customer_username',
  154. 'woo_user_' . zeroise( wp_rand( 0, 9999 ), 4 ),
  155. $email,
  156. $new_user_args,
  157. $suffix
  158. );
  159. return wc_create_new_customer_username( $email, $new_args, $suffix );
  160. }
  161. if ( username_exists( $username ) ) {
  162. // Generate something unique to append to the username in case of a conflict with another user.
  163. $suffix = '-' . zeroise( wp_rand( 0, 9999 ), 4 );
  164. return wc_create_new_customer_username( $email, $new_user_args, $suffix );
  165. }
  166. /**
  167. * Filter new customer username.
  168. *
  169. * @since 3.7.0
  170. * @param string $username Customer username.
  171. * @param string $email New customer email address.
  172. * @param array $new_user_args Array of new user args, maybe including first and last names.
  173. * @param string $suffix Append string to username to make it unique.
  174. */
  175. return apply_filters( 'woocommerce_new_customer_username', $username, $email, $new_user_args, $suffix );
  176. }
  177. /**
  178. * Login a customer (set auth cookie and set global user object).
  179. *
  180. * @param int $customer_id Customer ID.
  181. */
  182. function wc_set_customer_auth_cookie( $customer_id ) {
  183. wp_set_current_user( $customer_id );
  184. wp_set_auth_cookie( $customer_id, true );
  185. // Update session.
  186. WC()->session->init_session_cookie();
  187. }
  188. /**
  189. * Get past orders (by email) and update them.
  190. *
  191. * @param int $customer_id Customer ID.
  192. * @return int
  193. */
  194. function wc_update_new_customer_past_orders( $customer_id ) {
  195. $linked = 0;
  196. $complete = 0;
  197. $customer = get_user_by( 'id', absint( $customer_id ) );
  198. $customer_orders = wc_get_orders(
  199. array(
  200. 'limit' => -1,
  201. 'customer' => array( array( 0, $customer->user_email ) ),
  202. 'return' => 'ids',
  203. )
  204. );
  205. if ( ! empty( $customer_orders ) ) {
  206. foreach ( $customer_orders as $order_id ) {
  207. $order = wc_get_order( $order_id );
  208. if ( ! $order ) {
  209. continue;
  210. }
  211. $order->set_customer_id( $customer->ID );
  212. $order->save();
  213. if ( $order->has_downloadable_item() ) {
  214. $data_store = WC_Data_Store::load( 'customer-download' );
  215. $data_store->delete_by_order_id( $order->get_id() );
  216. wc_downloadable_product_permissions( $order->get_id(), true );
  217. }
  218. do_action( 'woocommerce_update_new_customer_past_order', $order_id, $customer );
  219. if ( get_post_status( $order_id ) === 'wc-completed' ) {
  220. $complete++;
  221. }
  222. $linked++;
  223. }
  224. }
  225. if ( $complete ) {
  226. update_user_meta( $customer_id, 'paying_customer', 1 );
  227. update_user_meta( $customer_id, '_order_count', '' );
  228. update_user_meta( $customer_id, '_money_spent', '' );
  229. delete_user_meta( $customer_id, '_last_order' );
  230. }
  231. return $linked;
  232. }
  233. /**
  234. * Order payment completed - This is a paying customer.
  235. *
  236. * @param int $order_id Order ID.
  237. */
  238. function wc_paying_customer( $order_id ) {
  239. $order = wc_get_order( $order_id );
  240. $customer_id = $order->get_customer_id();
  241. if ( $customer_id > 0 && 'shop_order_refund' !== $order->get_type() ) {
  242. $customer = new WC_Customer( $customer_id );
  243. if ( ! $customer->get_is_paying_customer() ) {
  244. $customer->set_is_paying_customer( true );
  245. $customer->save();
  246. }
  247. }
  248. }
  249. add_action( 'woocommerce_payment_complete', 'wc_paying_customer' );
  250. add_action( 'woocommerce_order_status_completed', 'wc_paying_customer' );
  251. /**
  252. * Checks if a user (by email or ID or both) has bought an item.
  253. *
  254. * @param string $customer_email Customer email to check.
  255. * @param int $user_id User ID to check.
  256. * @param int $product_id Product ID to check.
  257. * @return bool
  258. */
  259. function wc_customer_bought_product( $customer_email, $user_id, $product_id ) {
  260. global $wpdb;
  261. $result = apply_filters( 'woocommerce_pre_customer_bought_product', null, $customer_email, $user_id, $product_id );
  262. if ( null !== $result ) {
  263. return $result;
  264. }
  265. $transient_name = 'wc_customer_bought_product_' . md5( $customer_email . $user_id );
  266. $transient_version = WC_Cache_Helper::get_transient_version( 'orders' );
  267. $transient_value = get_transient( $transient_name );
  268. if ( isset( $transient_value['value'], $transient_value['version'] ) && $transient_value['version'] === $transient_version ) {
  269. $result = $transient_value['value'];
  270. } else {
  271. $customer_data = array( $user_id );
  272. if ( $user_id ) {
  273. $user = get_user_by( 'id', $user_id );
  274. if ( isset( $user->user_email ) ) {
  275. $customer_data[] = $user->user_email;
  276. }
  277. }
  278. if ( is_email( $customer_email ) ) {
  279. $customer_data[] = $customer_email;
  280. }
  281. $customer_data = array_map( 'esc_sql', array_filter( array_unique( $customer_data ) ) );
  282. $statuses = array_map( 'esc_sql', wc_get_is_paid_statuses() );
  283. if ( count( $customer_data ) === 0 ) {
  284. return false;
  285. }
  286. $result = $wpdb->get_col(
  287. "
  288. SELECT im.meta_value FROM {$wpdb->posts} AS p
  289. INNER JOIN {$wpdb->postmeta} AS pm ON p.ID = pm.post_id
  290. INNER JOIN {$wpdb->prefix}woocommerce_order_items AS i ON p.ID = i.order_id
  291. INNER JOIN {$wpdb->prefix}woocommerce_order_itemmeta AS im ON i.order_item_id = im.order_item_id
  292. WHERE p.post_status IN ( 'wc-" . implode( "','wc-", $statuses ) . "' )
  293. AND pm.meta_key IN ( '_billing_email', '_customer_user' )
  294. AND im.meta_key IN ( '_product_id', '_variation_id' )
  295. AND im.meta_value != 0
  296. AND pm.meta_value IN ( '" . implode( "','", $customer_data ) . "' )
  297. "
  298. ); // WPCS: unprepared SQL ok.
  299. $result = array_map( 'absint', $result );
  300. $transient_value = array(
  301. 'version' => $transient_version,
  302. 'value' => $result,
  303. );
  304. set_transient( $transient_name, $transient_value, DAY_IN_SECONDS * 30 );
  305. }
  306. return in_array( absint( $product_id ), $result, true );
  307. }
  308. /**
  309. * Checks if the current user has a role.
  310. *
  311. * @param string $role The role.
  312. * @return bool
  313. */
  314. function wc_current_user_has_role( $role ) {
  315. return wc_user_has_role( wp_get_current_user(), $role );
  316. }
  317. /**
  318. * Checks if a user has a role.
  319. *
  320. * @param int|\WP_User $user The user.
  321. * @param string $role The role.
  322. * @return bool
  323. */
  324. function wc_user_has_role( $user, $role ) {
  325. if ( ! is_object( $user ) ) {
  326. $user = get_userdata( $user );
  327. }
  328. if ( ! $user || ! $user->exists() ) {
  329. return false;
  330. }
  331. return in_array( $role, $user->roles, true );
  332. }
  333. /**
  334. * Checks if a user has a certain capability.
  335. *
  336. * @param array $allcaps All capabilities.
  337. * @param array $caps Capabilities.
  338. * @param array $args Arguments.
  339. *
  340. * @return array The filtered array of all capabilities.
  341. */
  342. function wc_customer_has_capability( $allcaps, $caps, $args ) {
  343. if ( isset( $caps[0] ) ) {
  344. switch ( $caps[0] ) {
  345. case 'view_order':
  346. $user_id = intval( $args[1] );
  347. $order = wc_get_order( $args[2] );
  348. if ( $order && $user_id === $order->get_user_id() ) {
  349. $allcaps['view_order'] = true;
  350. }
  351. break;
  352. case 'pay_for_order':
  353. $user_id = intval( $args[1] );
  354. $order_id = isset( $args[2] ) ? $args[2] : null;
  355. // When no order ID, we assume it's a new order
  356. // and thus, customer can pay for it.
  357. if ( ! $order_id ) {
  358. $allcaps['pay_for_order'] = true;
  359. break;
  360. }
  361. $order = wc_get_order( $order_id );
  362. if ( $order && ( $user_id === $order->get_user_id() || ! $order->get_user_id() ) ) {
  363. $allcaps['pay_for_order'] = true;
  364. }
  365. break;
  366. case 'order_again':
  367. $user_id = intval( $args[1] );
  368. $order = wc_get_order( $args[2] );
  369. if ( $order && $user_id === $order->get_user_id() ) {
  370. $allcaps['order_again'] = true;
  371. }
  372. break;
  373. case 'cancel_order':
  374. $user_id = intval( $args[1] );
  375. $order = wc_get_order( $args[2] );
  376. if ( $order && $user_id === $order->get_user_id() ) {
  377. $allcaps['cancel_order'] = true;
  378. }
  379. break;
  380. case 'download_file':
  381. $user_id = intval( $args[1] );
  382. $download = $args[2];
  383. if ( $download && $user_id === $download->get_user_id() ) {
  384. $allcaps['download_file'] = true;
  385. }
  386. break;
  387. }
  388. }
  389. return $allcaps;
  390. }
  391. add_filter( 'user_has_cap', 'wc_customer_has_capability', 10, 3 );
  392. /**
  393. * Safe way of allowing shop managers restricted capabilities that will remove
  394. * access to the capabilities if WooCommerce is deactivated.
  395. *
  396. * @since 3.5.4
  397. * @param bool[] $allcaps Array of key/value pairs where keys represent a capability name and boolean values
  398. * represent whether the user has that capability.
  399. * @param string[] $caps Required primitive capabilities for the requested capability.
  400. * @param array $args Arguments that accompany the requested capability check.
  401. * @param WP_User $user The user object.
  402. * @return bool[]
  403. */
  404. function wc_shop_manager_has_capability( $allcaps, $caps, $args, $user ) {
  405. if ( wc_user_has_role( $user, 'shop_manager' ) ) {
  406. // @see wc_modify_map_meta_cap, which limits editing to customers.
  407. $allcaps['edit_users'] = true;
  408. }
  409. return $allcaps;
  410. }
  411. add_filter( 'user_has_cap', 'wc_shop_manager_has_capability', 10, 4 );
  412. /**
  413. * Modify the list of editable roles to prevent non-admin adding admin users.
  414. *
  415. * @param array $roles Roles.
  416. * @return array
  417. */
  418. function wc_modify_editable_roles( $roles ) {
  419. if ( is_multisite() && is_super_admin() ) {
  420. return $roles;
  421. }
  422. if ( ! wc_current_user_has_role( 'administrator' ) ) {
  423. unset( $roles['administrator'] );
  424. if ( wc_current_user_has_role( 'shop_manager' ) ) {
  425. $shop_manager_editable_roles = apply_filters( 'woocommerce_shop_manager_editable_roles', array( 'customer' ) );
  426. return array_intersect_key( $roles, array_flip( $shop_manager_editable_roles ) );
  427. }
  428. }
  429. return $roles;
  430. }
  431. add_filter( 'editable_roles', 'wc_modify_editable_roles' );
  432. /**
  433. * Modify capabilities to prevent non-admin users editing admin users.
  434. *
  435. * $args[0] will be the user being edited in this case.
  436. *
  437. * @param array $caps Array of caps.
  438. * @param string $cap Name of the cap we are checking.
  439. * @param int $user_id ID of the user being checked against.
  440. * @param array $args Arguments.
  441. * @return array
  442. */
  443. function wc_modify_map_meta_cap( $caps, $cap, $user_id, $args ) {
  444. if ( is_multisite() && is_super_admin() ) {
  445. return $caps;
  446. }
  447. switch ( $cap ) {
  448. case 'edit_user':
  449. case 'remove_user':
  450. case 'promote_user':
  451. case 'delete_user':
  452. if ( ! isset( $args[0] ) || $args[0] === $user_id ) {
  453. break;
  454. } else {
  455. if ( ! wc_current_user_has_role( 'administrator' ) ) {
  456. if ( wc_user_has_role( $args[0], 'administrator' ) ) {
  457. $caps[] = 'do_not_allow';
  458. } elseif ( wc_current_user_has_role( 'shop_manager' ) ) {
  459. // Shop managers can only edit customer info.
  460. $userdata = get_userdata( $args[0] );
  461. $shop_manager_editable_roles = apply_filters( 'woocommerce_shop_manager_editable_roles', array( 'customer' ) );
  462. if ( property_exists( $userdata, 'roles' ) && ! empty( $userdata->roles ) && ! array_intersect( $userdata->roles, $shop_manager_editable_roles ) ) {
  463. $caps[] = 'do_not_allow';
  464. }
  465. }
  466. }
  467. }
  468. break;
  469. }
  470. return $caps;
  471. }
  472. add_filter( 'map_meta_cap', 'wc_modify_map_meta_cap', 10, 4 );
  473. /**
  474. * Get customer download permissions from the database.
  475. *
  476. * @param int $customer_id Customer/User ID.
  477. * @return array
  478. */
  479. function wc_get_customer_download_permissions( $customer_id ) {
  480. $data_store = WC_Data_Store::load( 'customer-download' );
  481. return apply_filters( 'woocommerce_permission_list', $data_store->get_downloads_for_customer( $customer_id ), $customer_id );
  482. }
  483. /**
  484. * Get customer available downloads.
  485. *
  486. * @param int $customer_id Customer/User ID.
  487. * @return array
  488. */
  489. function wc_get_customer_available_downloads( $customer_id ) {
  490. $downloads = array();
  491. $_product = null;
  492. $order = null;
  493. $file_number = 0;
  494. // Get results from valid orders only.
  495. $results = wc_get_customer_download_permissions( $customer_id );
  496. if ( $results ) {
  497. foreach ( $results as $result ) {
  498. $order_id = intval( $result->order_id );
  499. if ( ! $order || $order->get_id() !== $order_id ) {
  500. // New order.
  501. $order = wc_get_order( $order_id );
  502. $_product = null;
  503. }
  504. // Make sure the order exists for this download.
  505. if ( ! $order ) {
  506. continue;
  507. }
  508. // Check if downloads are permitted.
  509. if ( ! $order->is_download_permitted() ) {
  510. continue;
  511. }
  512. $product_id = intval( $result->product_id );
  513. if ( ! $_product || $_product->get_id() !== $product_id ) {
  514. // New product.
  515. $file_number = 0;
  516. $_product = wc_get_product( $product_id );
  517. }
  518. // Check product exists and has the file.
  519. if ( ! $_product || ! $_product->exists() || ! $_product->has_file( $result->download_id ) ) {
  520. continue;
  521. }
  522. $download_file = $_product->get_file( $result->download_id );
  523. // Download name will be 'Product Name' for products with a single downloadable file, and 'Product Name - File X' for products with multiple files.
  524. $download_name = apply_filters(
  525. 'woocommerce_downloadable_product_name',
  526. $download_file['name'],
  527. $_product,
  528. $result->download_id,
  529. $file_number
  530. );
  531. $downloads[] = array(
  532. 'download_url' => add_query_arg(
  533. array(
  534. 'download_file' => $product_id,
  535. 'order' => $result->order_key,
  536. 'email' => rawurlencode( $result->user_email ),
  537. 'key' => $result->download_id,
  538. ),
  539. home_url( '/' )
  540. ),
  541. 'download_id' => $result->download_id,
  542. 'product_id' => $_product->get_id(),
  543. 'product_name' => $_product->get_name(),
  544. 'product_url' => $_product->is_visible() ? $_product->get_permalink() : '', // Since 3.3.0.
  545. 'download_name' => $download_name,
  546. 'order_id' => $order->get_id(),
  547. 'order_key' => $order->get_order_key(),
  548. 'downloads_remaining' => $result->downloads_remaining,
  549. 'access_expires' => $result->access_expires,
  550. 'file' => array(
  551. 'name' => $download_file->get_name(),
  552. 'file' => $download_file->get_file(),
  553. ),
  554. );
  555. $file_number++;
  556. }
  557. }
  558. return apply_filters( 'woocommerce_customer_available_downloads', $downloads, $customer_id );
  559. }
  560. /**
  561. * Get total spent by customer.
  562. *
  563. * @param int $user_id User ID.
  564. * @return string
  565. */
  566. function wc_get_customer_total_spent( $user_id ) {
  567. $customer = new WC_Customer( $user_id );
  568. return $customer->get_total_spent();
  569. }
  570. /**
  571. * Get total orders by customer.
  572. *
  573. * @param int $user_id User ID.
  574. * @return int
  575. */
  576. function wc_get_customer_order_count( $user_id ) {
  577. $customer = new WC_Customer( $user_id );
  578. return $customer->get_order_count();
  579. }
  580. /**
  581. * Reset _customer_user on orders when a user is deleted.
  582. *
  583. * @param int $user_id User ID.
  584. */
  585. function wc_reset_order_customer_id_on_deleted_user( $user_id ) {
  586. global $wpdb;
  587. $wpdb->update(
  588. $wpdb->postmeta,
  589. array(
  590. 'meta_value' => 0,
  591. ),
  592. array(
  593. 'meta_key' => '_customer_user',
  594. 'meta_value' => $user_id,
  595. )
  596. ); // WPCS: slow query ok.
  597. }
  598. add_action( 'deleted_user', 'wc_reset_order_customer_id_on_deleted_user' );
  599. /**
  600. * Get review verification status.
  601. *
  602. * @param int $comment_id Comment ID.
  603. * @return bool
  604. */
  605. function wc_review_is_from_verified_owner( $comment_id ) {
  606. $verified = get_comment_meta( $comment_id, 'verified', true );
  607. return '' === $verified ? WC_Comments::add_comment_purchase_verification( $comment_id ) : (bool) $verified;
  608. }
  609. /**
  610. * Disable author archives for customers.
  611. *
  612. * @since 2.5.0
  613. */
  614. function wc_disable_author_archives_for_customers() {
  615. global $author;
  616. if ( is_author() ) {
  617. $user = get_user_by( 'id', $author );
  618. if ( user_can( $user, 'customer' ) && ! user_can( $user, 'edit_posts' ) ) {
  619. wp_safe_redirect( wc_get_page_permalink( 'shop' ) );
  620. exit;
  621. }
  622. }
  623. }
  624. add_action( 'template_redirect', 'wc_disable_author_archives_for_customers' );
  625. /**
  626. * Hooks into the `profile_update` hook to set the user last updated timestamp.
  627. *
  628. * @since 2.6.0
  629. * @param int $user_id The user that was updated.
  630. * @param array $old The profile fields pre-change.
  631. */
  632. function wc_update_profile_last_update_time( $user_id, $old ) {
  633. wc_set_user_last_update_time( $user_id );
  634. }
  635. add_action( 'profile_update', 'wc_update_profile_last_update_time', 10, 2 );
  636. /**
  637. * Hooks into the update user meta function to set the user last updated timestamp.
  638. *
  639. * @since 2.6.0
  640. * @param int $meta_id ID of the meta object that was changed.
  641. * @param int $user_id The user that was updated.
  642. * @param string $meta_key Name of the meta key that was changed.
  643. * @param string $_meta_value Value of the meta that was changed.
  644. */
  645. function wc_meta_update_last_update_time( $meta_id, $user_id, $meta_key, $_meta_value ) {
  646. $keys_to_track = apply_filters( 'woocommerce_user_last_update_fields', array( 'first_name', 'last_name' ) );
  647. $update_time = in_array( $meta_key, $keys_to_track, true ) ? true : false;
  648. $update_time = 'billing_' === substr( $meta_key, 0, 8 ) ? true : $update_time;
  649. $update_time = 'shipping_' === substr( $meta_key, 0, 9 ) ? true : $update_time;
  650. if ( $update_time ) {
  651. wc_set_user_last_update_time( $user_id );
  652. }
  653. }
  654. add_action( 'update_user_meta', 'wc_meta_update_last_update_time', 10, 4 );
  655. /**
  656. * Sets a user's "last update" time to the current timestamp.
  657. *
  658. * @since 2.6.0
  659. * @param int $user_id The user to set a timestamp for.
  660. */
  661. function wc_set_user_last_update_time( $user_id ) {
  662. update_user_meta( $user_id, 'last_update', gmdate( 'U' ) );
  663. }
  664. /**
  665. * Get customer saved payment methods list.
  666. *
  667. * @since 2.6.0
  668. * @param int $customer_id Customer ID.
  669. * @return array
  670. */
  671. function wc_get_customer_saved_methods_list( $customer_id ) {
  672. return apply_filters( 'woocommerce_saved_payment_methods_list', array(), $customer_id );
  673. }
  674. /**
  675. * Get info about customer's last order.
  676. *
  677. * @since 2.6.0
  678. * @param int $customer_id Customer ID.
  679. * @return WC_Order|bool Order object if successful or false.
  680. */
  681. function wc_get_customer_last_order( $customer_id ) {
  682. $customer = new WC_Customer( $customer_id );
  683. return $customer->get_last_order();
  684. }
  685. /**
  686. * Add support for searching by display_name.
  687. *
  688. * @since 3.2.0
  689. * @param array $search_columns Column names.
  690. * @return array
  691. */
  692. function wc_user_search_columns( $search_columns ) {
  693. $search_columns[] = 'display_name';
  694. return $search_columns;
  695. }
  696. add_filter( 'user_search_columns', 'wc_user_search_columns' );
  697. /**
  698. * When a user is deleted in WordPress, delete corresponding WooCommerce data.
  699. *
  700. * @param int $user_id User ID being deleted.
  701. */
  702. function wc_delete_user_data( $user_id ) {
  703. global $wpdb;
  704. // Clean up sessions.
  705. $wpdb->delete(
  706. $wpdb->prefix . 'woocommerce_sessions',
  707. array(
  708. 'session_key' => $user_id,
  709. )
  710. );
  711. // Revoke API keys.
  712. $wpdb->delete(
  713. $wpdb->prefix . 'woocommerce_api_keys',
  714. array(
  715. 'user_id' => $user_id,
  716. )
  717. );
  718. // Clean up payment tokens.
  719. $payment_tokens = WC_Payment_Tokens::get_customer_tokens( $user_id );
  720. foreach ( $payment_tokens as $payment_token ) {
  721. $payment_token->delete();
  722. }
  723. }
  724. add_action( 'delete_user', 'wc_delete_user_data' );
  725. /**
  726. * Store user agents. Used for tracker.
  727. *
  728. * @since 3.0.0
  729. * @param string $user_login User login.
  730. * @param int|object $user User.
  731. */
  732. function wc_maybe_store_user_agent( $user_login, $user ) {
  733. if ( 'yes' === get_option( 'woocommerce_allow_tracking', 'no' ) && user_can( $user, 'manage_woocommerce' ) ) {
  734. $admin_user_agents = array_filter( (array) get_option( 'woocommerce_tracker_ua', array() ) );
  735. $admin_user_agents[] = wc_get_user_agent();
  736. update_option( 'woocommerce_tracker_ua', array_unique( $admin_user_agents ) );
  737. }
  738. }
  739. add_action( 'wp_login', 'wc_maybe_store_user_agent', 10, 2 );
  740. /**
  741. * Update logic triggered on login.
  742. *
  743. * @since 3.4.0
  744. * @param string $user_login User login.
  745. * @param object $user User.
  746. */
  747. function wc_user_logged_in( $user_login, $user ) {
  748. wc_update_user_last_active( $user->ID );
  749. update_user_meta( $user->ID, '_woocommerce_load_saved_cart_after_login', 1 );
  750. }
  751. add_action( 'wp_login', 'wc_user_logged_in', 10, 2 );
  752. /**
  753. * Update when the user was last active.
  754. *
  755. * @since 3.4.0
  756. */
  757. function wc_current_user_is_active() {
  758. if ( ! is_user_logged_in() ) {
  759. return;
  760. }
  761. wc_update_user_last_active( get_current_user_id() );
  762. }
  763. add_action( 'wp', 'wc_current_user_is_active', 10 );
  764. /**
  765. * Set the user last active timestamp to now.
  766. *
  767. * @since 3.4.0
  768. * @param int $user_id User ID to mark active.
  769. */
  770. function wc_update_user_last_active( $user_id ) {
  771. if ( ! $user_id ) {
  772. return;
  773. }
  774. update_user_meta( $user_id, 'wc_last_active', (string) strtotime( gmdate( 'Y-m-d', time() ) ) );
  775. }
  776. /**
  777. * Translate WC roles using the woocommerce textdomain.
  778. *
  779. * @since 3.7.0
  780. * @param string $translation Translated text.
  781. * @param string $text Text to translate.
  782. * @param string $context Context information for the translators.
  783. * @param string $domain Text domain. Unique identifier for retrieving translated strings.
  784. * @return string
  785. */
  786. function wc_translate_user_roles( $translation, $text, $context, $domain ) {
  787. // translate_user_role() only accepts a second parameter starting in WP 5.2.
  788. if ( version_compare( get_bloginfo( 'version' ), '5.2', '<' ) ) {
  789. return $translation;
  790. }
  791. if ( 'User role' === $context && 'default' === $domain && in_array( $text, array( 'Shop manager', 'Customer' ), true ) ) {
  792. return translate_user_role( $text, 'woocommerce' );
  793. }
  794. return $translation;
  795. }
  796. add_filter( 'gettext_with_context', 'wc_translate_user_roles', 10, 4 );