diff --git a/.distignore b/.distignore index e27e472d616..cbeeef597c5 100644 --- a/.distignore +++ b/.distignore @@ -3,15 +3,17 @@ *.lock *.md *.zip +/bin/ +/build/ +/node_modules/ +/tests/ babel.config.js -bin/ -build/ CHANGELOG.txt composer.* +contributors.html docker-compose.yaml Dockerfile Gruntfile.js -node_modules/ none package-lock.json package.json @@ -21,4 +23,4 @@ phpunit.xml phpunit.xml.dist README.md renovate.json -tests +webpack.config.js diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md index 3019353697d..82dc600b065 100644 --- a/.github/ISSUE_TEMPLATE.md +++ b/.github/ISSUE_TEMPLATE.md @@ -1,48 +1,7 @@ - + - +**Prerequisites (mark completed items with an [x]):** +- [ ] I have checked that my issue type is not listed here https://github.com/woocommerce/woocommerce/issues/new/choose +- [ ] My issue is not a security issue, support request, bug report, enhancement or feature request (Please use the link above if it is). - - - - - - -## Prerequisites - - - -- [ ] I have searched for similar issues in both open and closed tickets and cannot find a duplicate -- [ ] The issue still exists against the latest `master` branch of WooCommerce on Github (this is **not** the same version as on WordPress.org!) -- [ ] I have attempted to find the simplest possible steps to reproduce the issue -- [ ] I have included a failing test as a pull request (Optional) - -## Steps to reproduce the issue - - - -1. -2. -3. - -## Expected/actual behavior - -When I follow those steps, I see... - -I was expecting to see... - -## Isolating the problem - - - -- [ ] This bug happens with only WooCommerce plugin active -- [ ] This bug happens with a default WordPress theme active, or [Storefront](https://woocommerce.com/storefront/) -- [ ] I can reproduce this bug consistently using the steps above - -## WordPress Environment - -
-``` -Copy and paste the system status report from **WooCommerce > System Status** in WordPress admin here. -``` -
+**Issue Description:** diff --git a/.github/ISSUE_TEMPLATE/1-Security-issue.md b/.github/ISSUE_TEMPLATE/1-Security-issue.md index 9775c1c2c0c..7c78be16976 100644 --- a/.github/ISSUE_TEMPLATE/1-Security-issue.md +++ b/.github/ISSUE_TEMPLATE/1-Security-issue.md @@ -1,5 +1,5 @@ --- -name: "\U0001F46E‍♂️ Security issue" +name: "\U0001F512 Security issue" about: Please report security issues *only* via https://www.hackerone.com title: '' labels: '' diff --git a/.github/ISSUE_TEMPLATE/2-External-issues.md b/.github/ISSUE_TEMPLATE/2-External-issues.md index 5d1e0e7c6ab..59f52cf6770 100644 --- a/.github/ISSUE_TEMPLATE/2-External-issues.md +++ b/.github/ISSUE_TEMPLATE/2-External-issues.md @@ -1,10 +1,18 @@ --- name: "\U0001F47D External issues" -about: Please report WooCommerce REST API or WooCommerce Gutenberg Products Blocks issues directly to their respective repositories. +about: Please report WooCommerce REST API, WooCommerce Admin or WooCommerce Gutenberg Products Blocks issues directly to their respective repositories. title: '' labels: '' assignees: '' --- -Please report WooCommerce REST API (https://github.com/woocommerce/woocommerce-rest-api) or WooCommerce Gutenberg Products Blocks (https://github.com/woocommerce/woocommerce-gutenberg-products-block) issues directly to their respective repositories. +Please report issues for the following features directly to their respective repositories. + +WooCommerce REST API: https://github.com/woocommerce/woocommerce-rest-api + +WooCommerce Admin: https://github.com/woocommerce/woocommerce-admin + +WooCommerce Gutenberg Products Blocks: https://github.com/woocommerce/woocommerce-gutenberg-products-block + +Action Scheduler: https://github.com/woocommerce/action-scheduler diff --git a/.github/ISSUE_TEMPLATE/3-Support.md b/.github/ISSUE_TEMPLATE/3-Support.md index 6804c6d2c99..3ae796e2030 100644 --- a/.github/ISSUE_TEMPLATE/3-Support.md +++ b/.github/ISSUE_TEMPLATE/3-Support.md @@ -16,10 +16,13 @@ Usage docs can be found here: https://docs.woocommerce.com/ If you have a problem, you may want to start with the self help guide here: https://docs.woocommerce.com/document/woocommerce-self-service-guide/ **Technical support for premium extensions or if you're a WooCommerce.com customer** - from a human being - submit a ticket via the helpdesk +Contact WooCommerce support by opening a ticket. https://woocommerce.com/contact-us/ +**For help with custom code** +WooCommerce Slack Community: https://woocommerce.com/community-slack/ in the `#developers` channel. + **General usage and development questions** - WooCommerce Slack Community: https://woocommerce.com/community-slack/ - WordPress.org Forums: https://wordpress.org/support/plugin/woocommerce -- The WooCommerce Help and Share Facebook group +- The Official WooCommerce Facebook Group https://www.facebook.com/groups/advanced.woocommerce/ diff --git a/.github/ISSUE_TEMPLATE/4-Bug-report.md b/.github/ISSUE_TEMPLATE/4-Bug-report.md index 261ca9edb8b..c0316763647 100644 --- a/.github/ISSUE_TEMPLATE/4-Bug-report.md +++ b/.github/ISSUE_TEMPLATE/4-Bug-report.md @@ -8,11 +8,30 @@ assignees: '' --- -**Describe the bug** -A clear and concise description of what the bug is. Please be as descriptive as possible; issues lacking detail, or for any other reason than to report a bug, may be closed without action. +Please provide us with the information requested in this bug report. Without these details, we won't be able to fully evaluate this issue. +Bug reports lacking detail, or for any other reason than to report a bug, may be closed without action. -**To Reproduce** -Steps to reproduce the behavior: + + + + + + +**Prerequisites (mark completed items with an [x]):** +- [ ] I have have carried out troubleshooting steps and I believe I have found a bug. +- [ ] I have searched for similar bugs in both open and closed issues and cannot find a duplicate. + +**Describe the bug** +A clear and concise description of what the bug is. + +**Expected behavior** +A clear and concise description of what you expected to happen. + +**Actual behavior** +A clear and concise description of what actually happens. Please be as descriptive as possible; + +**Steps to reproduce the bug (We need to be able to reproduce the bug in order to fix it.)** +Steps to reproduce the bug: 1. Go to '...' 2. Click on '....' 3. Scroll down to '....' @@ -21,8 +40,7 @@ Steps to reproduce the behavior: **Screenshots** If applicable, add screenshots to help explain your problem. -**Expected behavior** -A clear and concise description of what you expected to happen. + **Isolating the problem (mark completed items with an [x]):** - [ ] I have deactivated other plugins and confirmed this bug occurs when only WooCommerce plugin is active. @@ -30,8 +48,11 @@ A clear and concise description of what you expected to happen. - [ ] I can reproduce this bug consistently using the steps above. **WordPress Environment** +We use the [WooCommerce System Status Report](https://docs.woocommerce.com/document/understanding-the-woocommerce-system-status-report/) to help us evaluate the issue. +Without this report we won't be able to fully evaluate this issue.
``` -Copy and paste the system status report from **WooCommerce > System Status** in WordPress admin. +The System Status Report is found in your WordPress admin under **WooCommerce > Status**. +Please select “Get system report”, then “Copy for support”, and then paste it here. ```
diff --git a/.github/ISSUE_TEMPLATE/5-Enhancement.md b/.github/ISSUE_TEMPLATE/5-Enhancement.md index 9f625ac6afc..b616509eedd 100644 --- a/.github/ISSUE_TEMPLATE/5-Enhancement.md +++ b/.github/ISSUE_TEMPLATE/5-Enhancement.md @@ -8,6 +8,10 @@ assignees: '' --- + + + + **Is your feature request related to a problem? Please describe.** A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] diff --git a/.github/ISSUE_TEMPLATE/6-Feature-request.md b/.github/ISSUE_TEMPLATE/6-Feature-request.md index 4b05fbc4035..e20ce518c65 100644 --- a/.github/ISSUE_TEMPLATE/6-Feature-request.md +++ b/.github/ISSUE_TEMPLATE/6-Feature-request.md @@ -8,6 +8,10 @@ assignees: '' --- + + + + **Is your feature request related to a problem? Please describe.** A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] diff --git a/.gitignore b/.gitignore index bf4e1e84926..4906d0e7c9e 100644 --- a/.gitignore +++ b/.gitignore @@ -56,6 +56,7 @@ tests/cli/vendor # Composer /vendor/ contributors.md +contributors.html # Packages /packages/* diff --git a/.travis.yml b/.travis.yml index 713257fc843..c8bca1a3bb9 100644 --- a/.travis.yml +++ b/.travis.yml @@ -30,9 +30,6 @@ env: jobs: fast_finish: true include: - - name: "Coding standard check" - php: 7.4 - env: WP_VERSION=latest WP_MULTISITE=0 RUN_PHPCS=1 - name: "Core E2E Tests" php: 7.4 env: WP_VERSION=latest WP_MULTISITE=0 RUN_E2E=1 @@ -45,24 +42,24 @@ jobs: - npm run test:e2e after_script: - npm run docker:down - - name: "Unit tests code coverage" - php: 7.4 - env: WP_VERSION=latest WP_MULTISITE=0 RUN_CODE_COVERAGE=1 - - name: "WooCommerce unit tests using WordPress nightly" + - name: "WP Nightly" php: 7.4 env: WP_VERSION=nightly WP_MULTISITE=0 - - name: "WP latest - 1" + - name: "WP Latest" + php: 7.2 + env: WP_VERSION=5.4 WP_MULTISITE=0 + - name: "WP Latest - 1" php: 7.2 env: WP_VERSION=5.3 WP_MULTISITE=0 - - name: "WP latest - 2" + - name: "WP Latest - 2" php: 7.2 env: WP_VERSION=5.2 WP_MULTISITE=0 - - name: "WP 5.1" - php: 7.2 - env: WP_VERSION=5.1 WP_MULTISITE=0 - - name: "WP 5.0" - php: 7.0 - env: WP_VERSION=5.0 WP_MULTISITE=0 + - name: "Code Standards" + php: 7.4 + env: WP_VERSION=latest WP_MULTISITE=0 RUN_PHPCS=1 + - name: "Code Coverage" + php: 7.4 + env: WP_VERSION=latest WP_MULTISITE=0 RUN_CODE_COVERAGE=1 allow_failures: - php: 7.4 env: WP_VERSION=latest WP_MULTISITE=0 RUN_CODE_COVERAGE=1 diff --git a/CHANGELOG.txt b/CHANGELOG.txt index 39309fc7ac9..0df226a570a 100644 --- a/CHANGELOG.txt +++ b/CHANGELOG.txt @@ -1,5 +1,84 @@ == Changelog == += 4.2.0 - 2020-06-02 = + +**WooCommerce** +* Enhancement - Added Ghanaian regions to the state dropdown. #26273 +* Enhancement - Added Mozambique provinces to the state dropdown. #26162 +* Enhancement - Added support for the new group descriptions available on WordPress privacy exporters as of WP 5.3. #25575 +* Fix - Fixed false positives when checking if uploads directory is public. #26600 +* Fix - Introduced a new admin body class for supporting styling issues in WP 5.3+. #26251 +* Fix - Removed case conversion of meta keys from CSV imports. #25517 +* Fix - Allow schedule coupons via CRUD. #26387 +* Fix - Password visibility toggle when password strength check fails. #26132 +* Fix - Cross-sell placement when product has no description. #26334 +* Fix - Display of the rate limit warning during payment method creation. #26411 +* Fix - Made the shipping zone matching query's `zone_id` field more specific. #26308 +* Fix - Corrected the display of RTL languages on the WooCommerce.com addons page. #26080 +* Fix - Removed the postcode field for Ghana. #26272 +* Fix - Made the hiding of state fields more explicit for Germany, Denmark, and Sweden. #25598 +* Fix - Ensured that global attribute prefixes are passed to the `woocommerce_attribute_label` filter. #26022 +* Dev - Increased WordPress minimum version to 5.2 according to policy. #26550 +* Dev - Added the customer as a third argument to the `woocommerce_matched_rates` filter. #26361 +* Dev - Introduced `woocommerce_menu_order_count` filter. #26044 +* Dev - Introduced `should_send_ajax_request.adding_to_cart `cart event to allow short-circuiting cart addition. #25760 +* Dev - Made the jQuery selector for checkout form rows less specific. #25654 +* Dev - Changed the `{site_address}` placeholder to `{site_url}` for clarity. #25630 +* Dev - Deprecated `.wp-policy-help` and replaced with with the `.privacy-policy-tutorial` and `.wp-suggested-text` classes added in WP 5.1. #26072 +* Dev - Updated `automattic/jetpack-autoloader` to 1.7.0. #26559 +* Dev - Add a way to fetch basic object data. #26025 + +**REST API 1.0.8** +* Enhancement - Add support for trash status for products in V2 and V3 API. #184 +* Dev - Updated minimum PHP requirement to 7.0 to keep up with WooCommerce Core. +* Dev - Fixed failing unit tests. #105 + +**WooCommerce Admin 1.2.3** +* Enhancement - Add onboarding payments note #4157 +* Enhancement - Marketing Inbox Note #4030 +* Performance - Use Route based code splitting to reduce bundle size #4094 +* Performance - trim down inbox note API request. #3977 +* Fix - Proper display of elements in wc-admin pages when in a RTL environment. #4051 +* Fix - Update UX when knowledge base articles fail to retrieve #4133 +* Fix - Updated messaging after last step in OBW. #4148 +* Fix - Reset profiler when visiting old OBW URL #4166. +* Fix - Dashboard flash before OBW chunk loads #4259 +* Tweak - Enable the default homepage template to be filtered #4072 +* Tweak - Create admin note if Jetpack or WooCommerce Services plugin doesn't get installed due to an error during OBW #3888 +* Tweak - Update Email Marketing note. #4167 +* Tweak - Adjust "demo products" verbiage to "Sample Products" #4184 +* Tweak - Don't reschedule imports on failed imports #4263 +* Tweak - Remove obsolete inbox messages #4182 +* Tweak - Updates to WooCommerce Payments in Setup Checklist #4293 +* Dev - Make query selector for admin alerts more specific #4289 +* Dev - Guard against null themes in OBW #4244 +* Dev - Update wcadmin db version after db callback #4323 +* Dev - Only migrate options on version change #4324 +* Dev - Use `PAGE_ROOT` constant to reduce redundant strings #4238 +* Dev - Decouple Plugins DataStore from onboarding feature #4048 +* Dev - Move API out of Onboarding #4093 +* Dev - Add Profiler Step View Tracks #4141 +* Dev - Add React Testing Library #4221 +* Dev - Add List and Link components to Storybook #4219 +* Dev - Cast Shipping Total to float #4042 +* Dev - Dynamic Currency with Context API #4027 +* Dev - Remove Duplicate array entry #4049 + += 4.1.1 - 2020-05-19 = + +* Enhancement - Added notice about public uploads directory. #26207 +* Tweak - Disallow directory listing in woocommerce_uploads when "Redirect only" it's the selected download method. #26399 +* Fix - Added correct handling of nonces to database update notice dismissal. #26500 +* Dev - Updated WooCommerce admin version to 1.1.3 and Action Scheduler to 3.1.6. +* Dev - Add prop `isEnabled` and a function to dynamically enable tracks. #26493 + +**WooCommerce Admin** +* Tweak - Onboarding: Add Jetpack flow back to onboarding profiler. #4382 +* Fix - Respect tracking opt-in before new page load. #4368 + +**ActionScheduler** +* Fix - Shutdown deprecated notice changed to a warning when as_* functions called without data store initialization. #546 + = 4.1.0 - 2020-05-05 = **WooCommerce** @@ -8,6 +87,7 @@ * Enhancement - Added option to ignore discounts from cart's total amount to enable free shipping. #24776 * Enhancement - Changed show password icon color to a darker grey hue. #25625 * Enhancement - Use new Setup Wizard for all users. #26016 +* Security - Fixed unescaped meta data while duplicating products. Reported by Slavco. * Tweak - Show notice for WP min version to WP 5.2. #26094 * Tweak - Improve the string for untested WooCommerce extensions in the system status page to avoid confusion. #25904 * Tweak - Updated KZT (₸) symbol. #25609 diff --git a/Gruntfile.js b/Gruntfile.js index 0a8316eb8c9..d831b5da2b2 100644 --- a/Gruntfile.js +++ b/Gruntfile.js @@ -198,56 +198,6 @@ module.exports = function( grunt ) { } }, - // Exec shell commands. - shell: { - options: { - stdout: true, - stderr: true - }, - e2e_test: { - command: 'npm run --silent test:single tests/e2e-tests/' + grunt.option( 'file' ) - }, - e2e_tests: { - command: 'npm run --silent test' - }, - e2e_tests_grep: { - command: 'npm run --silent test:grep "' + grunt.option( 'grep' ) + '"' - }, - contributors: { - command: [ - 'echo "Generating contributor list since <%= fromDate %>"', - './node_modules/.bin/githubcontrib --owner woocommerce --repo woocommerce --fromDate <%= fromDate %>' + - ' --authToken <%= authToken %> --cols 6 --sortBy contributions --format md --sortOrder desc' + - ' --showlogin true --sha <%= sha %> --filter renovate-bot > contributors.md' - ].join( '&&' ) - } - }, - - prompt: { - contributors: { - options: { - questions: [ - { - config: 'fromDate', - type: 'input', - message: 'What date (YYYY-MM-DD) should we get contributions since?' - }, - { - config: 'sha', - type: 'input', - message: 'What branch should we get contributors from?' - }, - { - config: 'authToken', - type: 'input', - message: '(optional) Provide a personal access token.' + - ' This will allow 5000 requests per hour rather than 60 - use if nothing is generated.' - } - ] - } - } - }, - // PHP Code Sniffer. phpcs: { options: { @@ -283,7 +233,6 @@ module.exports = function( grunt ) { // Load NPM tasks to be used here. grunt.loadNpmTasks( 'grunt-sass' ); - grunt.loadNpmTasks( 'grunt-shell' ); grunt.loadNpmTasks( 'grunt-phpcs' ); grunt.loadNpmTasks( 'grunt-rtlcss' ); grunt.loadNpmTasks( 'grunt-postcss' ); @@ -295,7 +244,6 @@ module.exports = function( grunt ) { grunt.loadNpmTasks( 'grunt-contrib-copy' ); grunt.loadNpmTasks( 'grunt-contrib-watch' ); grunt.loadNpmTasks( 'grunt-contrib-clean' ); - grunt.loadNpmTasks( 'grunt-prompt' ); // Register tasks. grunt.registerTask( 'default', [ @@ -329,25 +277,8 @@ module.exports = function( grunt ) { 'css' ]); - grunt.registerTask( 'contributors', [ - 'prompt:contributors', - 'shell:contributors' - ]); - // Only an alias to 'default' task. grunt.registerTask( 'dev', [ 'default' ]); - - grunt.registerTask( 'e2e-tests', [ - 'shell:e2e_tests' - ]); - - grunt.registerTask( 'e2e-tests-grep', [ - 'shell:e2e_tests_grep' - ]); - - grunt.registerTask( 'e2e-test', [ - 'shell:e2e_test' - ]); }; diff --git a/assets/js/frontend/add-to-cart-variation.js b/assets/js/frontend/add-to-cart-variation.js index 9c0a7b77e5e..c7c603725ee 100644 --- a/assets/js/frontend/add-to-cart-variation.js +++ b/assets/js/frontend/add-to-cart-variation.js @@ -43,7 +43,7 @@ // Init after gallery. setTimeout( function() { $form.trigger( 'check_variations' ); - $form.trigger( 'wc_variation_form' ); + $form.trigger( 'wc_variation_form', self ); self.loading = false; }, 100 ); }; @@ -160,12 +160,12 @@ /** * Looks for matching variations for current selected attributes. */ - VariationForm.prototype.onFindVariation = function( event ) { + VariationForm.prototype.onFindVariation = function( event, chosenAttributes ) { var form = event.data.variationForm, - attributes = form.getChosenAttributes(), + attributes = 'undefined' !== typeof chosenAttributes ? chosenAttributes : form.getChosenAttributes(), currentAttributes = attributes.data; - if ( attributes.count === attributes.chosenCount ) { + if ( attributes.count && attributes.count === attributes.chosenCount ) { if ( form.useAjax ) { if ( form.xhr ) { form.xhr.abort(); diff --git a/assets/js/frontend/cart.js b/assets/js/frontend/cart.js index ec1d843d31d..622c8eb1437 100644 --- a/assets/js/frontend/cart.js +++ b/assets/js/frontend/cart.js @@ -105,7 +105,7 @@ jQuery( function( $ ) { } $( '.woocommerce-cart-form' ).replaceWith( $new_form ); - $( '.woocommerce-cart-form' ).find( ':input[name="update_cart"]' ).prop( 'disabled', true ); + $( '.woocommerce-cart-form' ).find( ':input[name="update_cart"]' ).prop( 'disabled', true ).attr( 'aria-disabled', true ); if ( $notices.length > 0 ) { show_notice( $notices ); @@ -304,14 +304,14 @@ jQuery( function( $ ) { '.woocommerce-cart-form .cart_item :input', this.input_changed ); - $( '.woocommerce-cart-form :input[name="update_cart"]' ).prop( 'disabled', true ); + $( '.woocommerce-cart-form :input[name="update_cart"]' ).prop( 'disabled', true ).attr( 'aria-disabled', true ); }, /** * After an input is changed, enable the update cart button. */ input_changed: function() { - $( '.woocommerce-cart-form :input[name="update_cart"]' ).prop( 'disabled', false ); + $( '.woocommerce-cart-form :input[name="update_cart"]' ).prop( 'disabled', false ).attr( 'aria-disabled', false ); }, /** diff --git a/assets/js/frontend/single-product.js b/assets/js/frontend/single-product.js index 30b3d6fd991..618791c6a47 100644 --- a/assets/js/frontend/single-product.js +++ b/assets/js/frontend/single-product.js @@ -9,7 +9,7 @@ jQuery( function( $ ) { $( 'body' ) // Tabs .on( 'init', '.wc-tabs-wrapper, .woocommerce-tabs', function() { - $( '.wc-tab, .woocommerce-tabs .panel:not(.panel .panel)' ).hide(); + $( this ).find( '.wc-tab, .woocommerce-tabs .panel:not(.panel .panel)' ).hide(); var hash = window.location.hash; var url = window.location.href; diff --git a/assets/js/frontend/woocommerce.js b/assets/js/frontend/woocommerce.js index 1913904b64a..8c0414fff1b 100644 --- a/assets/js/frontend/woocommerce.js +++ b/assets/js/frontend/woocommerce.js @@ -81,15 +81,17 @@ jQuery( function( $ ) { // Show password visiblity hover icon on woocommerce forms $( '.woocommerce form .woocommerce-Input[type="password"]' ).wrap( '' ); - $( '.password-input' ).prepend( '' ); + // Add 'password-input' class to the password wrapper in checkout page. + $( '.woocommerce form input' ).filter(':password').parent('span').addClass('password-input'); + $( '.password-input' ).append( '' ); $( '.show-password-input' ).click( function() { $( this ).toggleClass( 'display-password' ); if ( $( this ).hasClass( 'display-password' ) ) { - $( this ).siblings( ['input[name^="password"]', 'input[type="password"]'] ).prop( 'type', 'text' ); + $( this ).siblings( ['input[type="password"]'] ).prop( 'type', 'text' ); } else { - $( this ).siblings( 'input[name^="password"]' ).prop( 'type', 'password' ); + $( this ).siblings( 'input[type="text"]' ).prop( 'type', 'password' ); } } ); diff --git a/assets/js/selectWoo/selectWoo.full.js b/assets/js/selectWoo/selectWoo.full.js index 613204ba441..e29e8f9f90a 100644 --- a/assets/js/selectWoo/selectWoo.full.js +++ b/assets/js/selectWoo/selectWoo.full.js @@ -755,6 +755,12 @@ S2.define('select2/utils',[ }); }; + Utils.entityDecode = function(html) { + var txt = document.createElement("textarea"); + txt.innerHTML = html; + return txt.value; + } + // Append an array of jQuery nodes to a given element. Utils.appendMany = function ($element, $nodes) { // jQuery 1.7.x does not support $.fn.append() with an array @@ -1611,9 +1617,9 @@ S2.define('select2/selection/single',[ var selection = data[0]; var $rendered = this.$selection.find('.select2-selection__rendered'); - var formatted = this.display(selection, $rendered); + var formatted = Utils.entityDecode(this.display(selection, $rendered)); - $rendered.empty().append(formatted); + $rendered.empty().text(formatted); $rendered.prop('title', selection.title || selection.text); }; @@ -1744,10 +1750,10 @@ S2.define('select2/selection/multiple',[ var $selection = this.selectionContainer(); var formatted = this.display(selection, $selection); if ('string' === typeof formatted) { - formatted = formatted.trim(); + formatted = Utils.entityDecode(formatted.trim()); } - $selection.append(formatted); + $selection.text(formatted); $selection.prop('title', selection.title || selection.text); $selection.data('data', selection); @@ -1786,7 +1792,7 @@ S2.define('select2/selection/placeholder',[ Placeholder.prototype.createPlaceholder = function (decorated, placeholder) { var $placeholder = this.selectionContainer(); - $placeholder.html(this.display(placeholder)); + $placeholder.text(Utils.entityDecode(this.display(placeholder))); $placeholder.addClass('select2-selection__placeholder') .removeClass('select2-selection__choice'); diff --git a/assets/js/selectWoo/selectWoo.full.min.js b/assets/js/selectWoo/selectWoo.full.min.js index 4654399e175..80e0b925426 100644 --- a/assets/js/selectWoo/selectWoo.full.min.js +++ b/assets/js/selectWoo/selectWoo.full.min.js @@ -5,7 +5,7 @@ * Released under the MIT license * https://github.com/woocommerce/selectWoo/blob/master/LICENSE.md */ -!function(n){"function"==typeof define&&define.amd?define(["jquery"],n):"object"==typeof module&&module.exports?module.exports=function(e,t){return t===undefined&&(t="undefined"!=typeof window?require("jquery"):require("jquery")(e)),n(t),t}:n(jQuery)}(function(i){var e=function(){if(i&&i.fn&&i.fn.select2&&i.fn.select2.amd)var e=i.fn.select2.amd;var t,o,c,n;return e&&e.requirejs||(e?o=e:e={},function(h){var s,r,f,g,m={},v={},y={},w={},n=Object.prototype.hasOwnProperty,i=[].slice,_=/\.js$/;function $(e,t){return n.call(e,t)}function a(e,t){var n,i,o,s,r,a,l,c,u,d,p,h=t&&t.split("/"),f=y.map,g=f&&f["*"]||{};if(e){for(r=(e=e.split("/")).length-1,y.nodeIdCompat&&_.test(e[r])&&(e[r]=e[r].replace(_,"")),"."===e[0].charAt(0)&&h&&(e=h.slice(0,h.length-1).concat(e)),u=0;u":">",'"':""","'":"'","/":"/"};return"string"!=typeof e?e:String(e).replace(/[&<>"'\/\\]/g,function(e){return t[e]})},e.appendMany=function(e,t){if("1.7"===s.fn.jquery.substr(0,3)){var n=s();s.map(t,function(e){n=n.add(e)}),t=n}e.append(t)},e.isTouchscreen=function(){return"undefined"==typeof e._isTouchscreenCache&&(e._isTouchscreenCache="ontouchstart"in document.documentElement),e._isTouchscreenCache},e}),e.define("select2/results",["jquery","./utils"],function(h,e){function i(e,t,n){this.$element=e,this.data=n,this.options=t,i.__super__.constructor.call(this)}return e.Extend(i,e.Observable),i.prototype.render=function(){var e=h('');return this.options.get("multiple")&&e.attr("aria-multiselectable","true"),this.$results=e},i.prototype.clear=function(){this.$results.empty()},i.prototype.displayMessage=function(e){var t=this.options.get("escapeMarkup");this.clear(),this.hideLoading();var n=h(''),i=this.options.get("translations").get(e.message);n.append(t(i(e.args))),n[0].className+=" select2-results__message",this.$results.append(n)},i.prototype.hideMessages=function(){this.$results.find(".select2-results__message").remove()},i.prototype.append=function(e){this.hideLoading();var t=[];if(null!=e.results&&0!==e.results.length){e.results=this.sort(e.results);for(var n=0;n",{"class":"select2-results__options select2-results__options--nested",role:"listbox"});p.append(l),s.attr("role","list"),s.append(r),s.append(p)}else this.template(e,t);return h.data(t,"data",e),t},i.prototype.bind=function(t,e){var l=this,n=t.id+"-results";this.$results.attr("id",n),t.on("results:all",function(e){l.clear(),l.append(e.data),t.isOpen()&&(l.setClasses(),l.highlightFirstItem())}),t.on("results:append",function(e){l.append(e.data),t.isOpen()&&l.setClasses()}),t.on("query",function(e){l.hideMessages(),l.showLoading(e)}),t.on("select",function(){t.isOpen()&&(l.setClasses(),l.highlightFirstItem())}),t.on("unselect",function(){t.isOpen()&&(l.setClasses(),l.highlightFirstItem())}),t.on("open",function(){l.$results.attr("aria-expanded","true"),l.$results.attr("aria-hidden","false"),l.setClasses(),l.ensureHighlightVisible()}),t.on("close",function(){l.$results.attr("aria-expanded","false"),l.$results.attr("aria-hidden","true"),l.$results.removeAttr("aria-activedescendant")}),t.on("results:toggle",function(){var e=l.getHighlightedResults();0!==e.length&&e.trigger("mouseup")}),t.on("results:select",function(){var e=l.getHighlightedResults();if(0!==e.length){var t=e.data("data");"true"==e.attr("data-selected")?l.trigger("close",{}):l.trigger("select",{data:t})}}),t.on("results:previous",function(){var e=l.getHighlightedResults(),t=l.$results.find("[data-selected]"),n=t.index(e);if(0!==n){var i=n-1;0===e.length&&(i=0);var o=t.eq(i);o.trigger("mouseenter");var s=l.$results.offset().top,r=o.offset().top,a=l.$results.scrollTop()+(r-s);0===i?l.$results.scrollTop(0):r-s<0&&l.$results.scrollTop(a)}}),t.on("results:next",function(){var e=l.getHighlightedResults(),t=l.$results.find("[data-selected]"),n=t.index(e)+1;if(!(n>=t.length)){var i=t.eq(n);i.trigger("mouseenter");var o=l.$results.offset().top+l.$results.outerHeight(!1),s=i.offset().top+i.outerHeight(!1),r=l.$results.scrollTop()+s-o;0===n?l.$results.scrollTop(0):othis.$results.outerHeight()||s<0)&&this.$results.scrollTop(o)}},i.prototype.template=function(e,t){var n=this.options.get("templateResult"),i=this.options.get("escapeMarkup"),o=n(e,t);null==o?t.style.display="none":"string"==typeof o?t.innerHTML=i(o):h(t).append(o)},i}),e.define("select2/keys",[],function(){return{BACKSPACE:8,TAB:9,ENTER:13,SHIFT:16,CTRL:17,ALT:18,ESC:27,SPACE:32,PAGE_UP:33,PAGE_DOWN:34,END:35,HOME:36,LEFT:37,UP:38,RIGHT:39,DOWN:40,DELETE:46}}),e.define("select2/selection/base",["jquery","../utils","../keys"],function(i,e,o){function n(e,t){this.$element=e,this.options=t,n.__super__.constructor.call(this)}return e.Extend(n,e.Observable),n.prototype.render=function(){var e=i('');return this._tabindex=0,null!=this.$element.data("old-tabindex")?this._tabindex=this.$element.data("old-tabindex"):null!=this.$element.attr("tabindex")&&(this._tabindex=this.$element.attr("tabindex")),e.attr("title",this.$element.attr("title")),e.attr("tabindex",this._tabindex),this.$selection=e},n.prototype.bind=function(e,t){var n=this,i=(e.id,e.id+"-results");this.options.get("minimumResultsForSearch"),Infinity;this.container=e,this.$selection.on("focus",function(e){n.trigger("focus",e)}),this.$selection.on("blur",function(e){n._handleBlur(e)}),this.$selection.on("keydown",function(e){n.trigger("keypress",e),e.which===o.SPACE&&e.preventDefault()}),e.on("results:focus",function(e){n.$selection.attr("aria-activedescendant",e.data._resultId)}),e.on("selection:update",function(e){n.update(e.data)}),e.on("open",function(){n.$selection.attr("aria-expanded","true"),n.$selection.attr("aria-owns",i),n._attachCloseHandler(e)}),e.on("close",function(){n.$selection.attr("aria-expanded","false"),n.$selection.removeAttr("aria-activedescendant"),n.$selection.removeAttr("aria-owns"),window.setTimeout(function(){n.$selection.focus()},1),n._detachCloseHandler(e)}),e.on("enable",function(){n.$selection.attr("tabindex",n._tabindex)}),e.on("disable",function(){n.$selection.attr("tabindex","-1")})},n.prototype._handleBlur=function(e){var t=this;window.setTimeout(function(){document.activeElement==t.$selection[0]||i.contains(t.$selection[0],document.activeElement)||t.trigger("blur",e)},1)},n.prototype._attachCloseHandler=function(e){i(document.body).on("mousedown.select2."+e.id,function(e){var t=i(e.target),n=t.closest(".select2");i(".select2.select2-container--open").each(function(){var e=i(this);this!=n[0]&&(e.data("element").select2("close"),setTimeout(function(){e.find("*:focus").blur(),t.focus()},1))})})},n.prototype._detachCloseHandler=function(e){i(document.body).off("mousedown.select2."+e.id)},n.prototype.position=function(e,t){t.find(".selection").append(e)},n.prototype.destroy=function(){this._detachCloseHandler(this.container)},n.prototype.update=function(e){throw new Error("The `update` method must be defined in child classes.")},n}),e.define("select2/selection/single",["jquery","./base","../utils","../keys"],function(e,t,n,i){function o(){o.__super__.constructor.apply(this,arguments)}return n.Extend(o,t),o.prototype.render=function(){var e=o.__super__.render.call(this);return e.addClass("select2-selection--single"),e.html(''),e},o.prototype.bind=function(t,e){var n=this;o.__super__.bind.apply(this,arguments);var i=t.id+"-container";this.$selection.find(".select2-selection__rendered").attr("id",i).attr("role","textbox").attr("aria-readonly","true"),this.$selection.attr("aria-labelledby",i),this.$selection.attr("role","combobox"),this.$selection.on("mousedown",function(e){1===e.which&&n.trigger("toggle",{originalEvent:e})}),this.$selection.on("focus",function(e){}),this.$selection.on("keydown",function(e){!t.isOpen()&&48<=e.which&&e.which<=90&&t.open()}),this.$selection.on("blur",function(e){}),t.on("focus",function(e){t.isOpen()||n.$selection.focus()}),t.on("selection:update",function(e){n.update(e.data)})},o.prototype.clear=function(){this.$selection.find(".select2-selection__rendered").empty()},o.prototype.display=function(e,t){var n=this.options.get("templateSelection");return this.options.get("escapeMarkup")(n(e,t))},o.prototype.selectionContainer=function(){return e("")},o.prototype.update=function(e){if(0!==e.length){var t=e[0],n=this.$selection.find(".select2-selection__rendered"),i=this.display(t,n);n.empty().append(i),n.prop("title",t.title||t.text)}else this.clear()},o}),e.define("select2/selection/multiple",["jquery","./base","../utils"],function(i,e,a){function o(e,t){o.__super__.constructor.apply(this,arguments)}return a.Extend(o,e),o.prototype.render=function(){var e=o.__super__.render.call(this);return e.addClass("select2-selection--multiple"),e.html('
    '),e},o.prototype.bind=function(t,e){var n=this;o.__super__.bind.apply(this,arguments),this.$selection.on("click",function(e){n.trigger("toggle",{originalEvent:e})}),this.$selection.on("click",".select2-selection__choice__remove",function(e){if(!n.options.get("disabled")){var t=i(this).parent().data("data");n.trigger("unselect",{originalEvent:e,data:t})}}),this.$selection.on("keydown",function(e){!t.isOpen()&&48<=e.which&&e.which<=90&&t.open()}),t.on("focus",function(){n.focusOnSearch()})},o.prototype.clear=function(){this.$selection.find(".select2-selection__rendered").empty()},o.prototype.display=function(e,t){var n=this.options.get("templateSelection");return this.options.get("escapeMarkup")(n(e,t))},o.prototype.selectionContainer=function(){return i('
  • ')},o.prototype.focusOnSearch=function(){var e=this;"undefined"!=typeof e.$search&&setTimeout(function(){e._keyUpPrevented=!0,e.$search.focus()},1)},o.prototype.update=function(e){if(this.clear(),0!==e.length){for(var t=[],n=0;n×');n.data("data",t),this.$selection.find(".select2-selection__rendered").prepend(n)}},e}),e.define("select2/selection/search",["jquery","../utils","../keys"],function(i,e,a){function t(e,t,n){e.call(this,t,n)}return t.prototype.render=function(e){var t=i('');this.$searchContainer=t,this.$search=t.find("input");var n=e.call(this);return this._transferTabIndex(),n},t.prototype.bind=function(e,i,t){var o=this,n=i.id+"-results";e.call(this,i,t),i.on("open",function(){o.$search.attr("aria-owns",n),o.$search.trigger("focus")}),i.on("close",function(){o.$search.val(""),o.$search.removeAttr("aria-activedescendant"),o.$search.removeAttr("aria-owns"),o.$search.trigger("focus")}),i.on("enable",function(){o.$search.prop("disabled",!1),o._transferTabIndex()}),i.on("disable",function(){o.$search.prop("disabled",!0)}),i.on("focus",function(e){o.$search.trigger("focus")}),i.on("results:focus",function(e){o.$search.attr("aria-activedescendant",e.data._resultId)}),this.$selection.on("focusin",".select2-search--inline",function(e){o.trigger("focus",e)}),this.$selection.on("focusout",".select2-search--inline",function(e){o._handleBlur(e)}),this.$selection.on("keydown",".select2-search--inline",function(e){if(e.stopPropagation(),o.trigger("keypress",e),o._keyUpPrevented=e.isDefaultPrevented(),e.which===a.BACKSPACE&&""===o.$search.val()){var t=o.$searchContainer.prev(".select2-selection__choice");if(0this.maximumInputLength?this.trigger("results:message",{message:"inputTooLong",args:{maximum:this.maximumInputLength,input:t.term,params:t}}):e.call(this,t,n)},e}),e.define("select2/data/maximumSelectionLength",[],function(){function e(e,t,n){this.maximumSelectionLength=n.get("maximumSelectionLength"),e.call(this,t,n)}return e.prototype.query=function(n,i,o){var s=this;this.current(function(e){var t=null!=e?e.length:0;0=s.maximumSelectionLength?s.trigger("results:message",{message:"maximumSelected",args:{maximum:s.maximumSelectionLength}}):n.call(s,i,o)})},e}),e.define("select2/dropdown",["jquery","./utils"],function(t,e){function n(e,t){this.$element=e,this.options=t,n.__super__.constructor.call(this)}return e.Extend(n,e.Observable),n.prototype.render=function(){var e=t('');return e.attr("dir",this.options.get("dir")),this.$dropdown=e},n.prototype.bind=function(){},n.prototype.position=function(e,t){},n.prototype.destroy=function(){this.$dropdown.remove()},n}),e.define("select2/dropdown/search",["jquery","../utils"],function(s,e){function t(){}return t.prototype.render=function(e){var t=e.call(this),n=s('');return this.$searchContainer=n,this.$search=n.find("input"),t.prepend(n),t},t.prototype.bind=function(e,t,n){var i=this,o=t.id+"-results";e.call(this,t,n),this.$search.on("keydown",function(e){i.trigger("keypress",e),i._keyUpPrevented=e.isDefaultPrevented()}),this.$search.on("input",function(e){s(this).off("keyup")}),this.$search.on("keyup input",function(e){i.handleSearch(e)}),t.on("open",function(){i.$search.attr("tabindex",0),i.$search.attr("aria-owns",o),i.$search.focus(),window.setTimeout(function(){i.$search.focus()},0)}),t.on("close",function(){i.$search.attr("tabindex",-1),i.$search.removeAttr("aria-activedescendant"),i.$search.removeAttr("aria-owns"),i.$search.val("")}),t.on("focus",function(){t.isOpen()||i.$search.focus()}),t.on("results:all",function(e){null!=e.query.term&&""!==e.query.term||(i.showSearch(e)?i.$searchContainer.removeClass("select2-search--hide"):i.$searchContainer.addClass("select2-search--hide"))}),t.on("results:focus",function(e){i.$search.attr("aria-activedescendant",e.data._resultId)})},t.prototype.handleSearch=function(e){if(!this._keyUpPrevented){var t=this.$search.val();this.trigger("query",{term:t})}this._keyUpPrevented=!1},t.prototype.showSearch=function(e,t){return!0},t}),e.define("select2/dropdown/hidePlaceholder",[],function(){function e(e,t,n,i){this.placeholder=this.normalizePlaceholder(n.get("placeholder")),e.call(this,t,n,i)}return e.prototype.append=function(e,t){t.results=this.removePlaceholder(t.results),e.call(this,t)},e.prototype.normalizePlaceholder=function(e,t){return"string"==typeof t&&(t={id:"",text:t}),t},e.prototype.removePlaceholder=function(e,t){for(var n=t.slice(0),i=t.length-1;0<=i;i--){var o=t[i];this.placeholder.id===o.id&&n.splice(i,1)}return n},e}),e.define("select2/dropdown/infiniteScroll",["jquery"],function(o){function e(e,t,n,i){this.lastParams={},e.call(this,t,n,i),this.$loadingMore=this.createLoadingMore(),this.loading=!1}return e.prototype.append=function(e,t){this.$loadingMore.remove(),this.loading=!1,e.call(this,t),this.showLoadingMore(t)&&this.$results.append(this.$loadingMore)},e.prototype.bind=function(e,t,n){var i=this;e.call(this,t,n),t.on("query",function(e){i.lastParams=e,i.loading=!0}),t.on("query:append",function(e){i.lastParams=e,i.loading=!0}),this.$results.on("scroll",function(){var e=o.contains(document.documentElement,i.$loadingMore[0]);if(!i.loading&&e){var t=i.$results.offset().top+i.$results.outerHeight(!1);i.$loadingMore.offset().top+i.$loadingMore.outerHeight(!1)<=t+50&&i.loadMore()}})},e.prototype.loadMore=function(){this.loading=!0;var e=o.extend({},{page:1},this.lastParams);e.page++,this.trigger("query:append",e)},e.prototype.showLoadingMore=function(e,t){return t.pagination&&t.pagination.more},e.prototype.createLoadingMore=function(){var e=o('
  • '),t=this.options.get("translations").get("loadingMore");return e.html(t(this.lastParams)),e},e}),e.define("select2/dropdown/attachBody",["jquery","../utils"],function(f,a){function e(e,t,n){this.$dropdownParent=n.get("dropdownParent")||f(document.body),e.call(this,t,n)}return e.prototype.bind=function(e,t,n){var i=this,o=!1;e.call(this,t,n),t.on("open",function(){i._showDropdown(),i._attachPositioningHandler(t),o||(o=!0,t.on("results:all",function(){i._positionDropdown(),i._resizeDropdown()}),t.on("results:append",function(){i._positionDropdown(),i._resizeDropdown()}))}),t.on("close",function(){i._hideDropdown(),i._detachPositioningHandler(t)}),this.$dropdownContainer.on("mousedown",function(e){e.stopPropagation()})},e.prototype.destroy=function(e){e.call(this),this.$dropdownContainer.remove()},e.prototype.position=function(e,t,n){t.attr("class",n.attr("class")),t.removeClass("select2"),t.addClass("select2-container--open"),t.css({position:"absolute",top:-999999}),this.$container=n},e.prototype.render=function(e){var t=f(""),n=e.call(this);return t.append(n),this.$dropdownContainer=t},e.prototype._hideDropdown=function(e){this.$dropdownContainer.detach()},e.prototype._attachPositioningHandler=function(e,t){var n=this,i="scroll.select2."+t.id,o="resize.select2."+t.id,s="orientationchange.select2."+t.id,r=this.$container.parents().filter(a.hasScroll);r.each(function(){f(this).data("select2-scroll-position",{x:f(this).scrollLeft(),y:f(this).scrollTop()})}),r.on(i,function(e){var t=f(this).data("select2-scroll-position");f(this).scrollTop(t.y)}),f(window).on(i+" "+o+" "+s,function(e){n._positionDropdown(),n._resizeDropdown()})},e.prototype._detachPositioningHandler=function(e,t){var n="scroll.select2."+t.id,i="resize.select2."+t.id,o="orientationchange.select2."+t.id;this.$container.parents().filter(a.hasScroll).off(n),f(window).off(n+" "+i+" "+o)},e.prototype._positionDropdown=function(){var e=f(window),t=this.$dropdown.hasClass("select2-dropdown--above"),n=this.$dropdown.hasClass("select2-dropdown--below"),i=null,o=this.$container.offset();o.bottom=o.top+this.$container.outerHeight(!1);var s={height:this.$container.outerHeight(!1)};s.top=o.top,s.bottom=o.top+s.height;var r=this.$dropdown.outerHeight(!1),a=e.scrollTop(),l=e.scrollTop()+e.height(),c=ao.bottom+r,d={left:o.left,top:s.bottom},p=this.$dropdownParent;"static"===p.css("position")&&(p=p.offsetParent());var h=p.offset();d.top-=h.top,d.left-=h.left,t||n||(i="below"),u||!c||t?!c&&u&&t&&(i="below"):i="above",("above"==i||t&&"below"!==i)&&(d.top=s.top-h.top-r),null!=i&&(this.$dropdown.removeClass("select2-dropdown--below select2-dropdown--above").addClass("select2-dropdown--"+i),this.$container.removeClass("select2-container--below select2-container--above").addClass("select2-container--"+i)),this.$dropdownContainer.css(d)},e.prototype._resizeDropdown=function(){var e={width:this.$container.outerWidth(!1)+"px"};this.options.get("dropdownAutoWidth")&&(e.minWidth=e.width,e.position="relative",e.width="auto"),this.$dropdown.css(e)},e.prototype._showDropdown=function(e){this.$dropdownContainer.appendTo(this.$dropdownParent),this._positionDropdown(),this._resizeDropdown()},e}),e.define("select2/dropdown/minimumResultsForSearch",[],function(){function e(e,t,n,i){this.minimumResultsForSearch=n.get("minimumResultsForSearch"),this.minimumResultsForSearch<0&&(this.minimumResultsForSearch=Infinity),e.call(this,t,n,i)}return e.prototype.showSearch=function(e,t){return!(function o(e){for(var t=0,n=0;n');return e.attr("dir",this.options.get("dir")),this.$container=e,this.$container.addClass("select2-container--"+this.options.get("theme")),e.data("element",this.$element),e},u}),e.define("select2/compat/utils",["jquery"],function(r){return{syncCssClasses:function a(e,t,n){var i,o,s=[];(i=r.trim(e.attr("class")))&&r((i=""+i).split(/\s+/)).each(function(){0===this.indexOf("select2-")&&s.push(this)}),(i=r.trim(t.attr("class")))&&r((i=""+i).split(/\s+/)).each(function(){0!==this.indexOf("select2-")&&null!=(o=n(this))&&s.push(o)}),e.attr("class",s.join(" "))}}}),e.define("select2/compat/containerCss",["jquery","./utils"],function(r,a){function l(e){return null}function e(){}return e.prototype.render=function(e){var t=e.call(this),n=this.options.get("containerCssClass")||"";r.isFunction(n)&&(n=n(this.$element));var i=this.options.get("adaptContainerCssClass");if(i=i||l,-1!==n.indexOf(":all:")){n=n.replace(":all:","");var o=i;i=function(e){var t=o(e);return null!=t?t+" "+e:e}}var s=this.options.get("containerCss")||{};return r.isFunction(s)&&(s=s(this.$element)),a.syncCssClasses(t,this.$element,i),t.css(s),t.addClass(n),t},e}),e.define("select2/compat/dropdownCss",["jquery","./utils"],function(r,a){function l(e){return null}function e(){}return e.prototype.render=function(e){var t=e.call(this),n=this.options.get("dropdownCssClass")||"";r.isFunction(n)&&(n=n(this.$element));var i=this.options.get("adaptDropdownCssClass");if(i=i||l,-1!==n.indexOf(":all:")){n=n.replace(":all:","");var o=i;i=function(e){var t=o(e);return null!=t?t+" "+e:e}}var s=this.options.get("dropdownCss")||{};return r.isFunction(s)&&(s=s(this.$element)),a.syncCssClasses(t,this.$element,i),t.css(s),t.addClass(n),t},e}),e.define("select2/compat/initSelection",["jquery"],function(i){function e(e,t,n){n.get("debug")&&window.console&&console.warn&&console.warn("Select2: The `initSelection` option has been deprecated in favor of a custom data adapter that overrides the `current` method. This method is now called multiple times instead of a single time when the instance is initialized. Support will be removed for the `initSelection` option in future versions of Select2"),this.initSelection=n.get("initSelection"),this._isInitialized=!1,e.call(this,t,n)}return e.prototype.current=function(e,t){var n=this;this._isInitialized?e.call(this,t):this.initSelection.call(null,this.$element,function(e){n._isInitialized=!0,i.isArray(e)||(e=[e]),t(e)})},e}),e.define("select2/compat/inputData",["jquery"],function(r){function e(e,t,n){this._currentData=[],this._valueSeparator=n.get("valueSeparator")||",","hidden"===t.prop("type")&&n.get("debug")&&console&&console.warn&&console.warn("Select2: Using a hidden input with Select2 is no longer supported and may stop working in the future. It is recommended to use a `');this.$searchContainer=t,this.$search=t.find("input");var n=e.call(this);return this._transferTabIndex(),n},t.prototype.bind=function(e,i,t){var o=this,n=i.id+"-results";e.call(this,i,t),i.on("open",function(){o.$search.attr("aria-owns",n),o.$search.trigger("focus")}),i.on("close",function(){o.$search.val(""),o.$search.removeAttr("aria-activedescendant"),o.$search.removeAttr("aria-owns"),o.$search.trigger("focus")}),i.on("enable",function(){o.$search.prop("disabled",!1),o._transferTabIndex()}),i.on("disable",function(){o.$search.prop("disabled",!0)}),i.on("focus",function(e){o.$search.trigger("focus")}),i.on("results:focus",function(e){o.$search.attr("aria-activedescendant",e.data._resultId)}),this.$selection.on("focusin",".select2-search--inline",function(e){o.trigger("focus",e)}),this.$selection.on("focusout",".select2-search--inline",function(e){o._handleBlur(e)}),this.$selection.on("keydown",".select2-search--inline",function(e){if(e.stopPropagation(),o.trigger("keypress",e),o._keyUpPrevented=e.isDefaultPrevented(),e.which===a.BACKSPACE&&""===o.$search.val()){var t=o.$searchContainer.prev(".select2-selection__choice");if(0this.maximumInputLength?this.trigger("results:message",{message:"inputTooLong",args:{maximum:this.maximumInputLength,input:t.term,params:t}}):e.call(this,t,n)},e}),e.define("select2/data/maximumSelectionLength",[],function(){function e(e,t,n){this.maximumSelectionLength=n.get("maximumSelectionLength"),e.call(this,t,n)}return e.prototype.query=function(n,i,o){var s=this;this.current(function(e){var t=null!=e?e.length:0;0=s.maximumSelectionLength?s.trigger("results:message",{message:"maximumSelected",args:{maximum:s.maximumSelectionLength}}):n.call(s,i,o)})},e}),e.define("select2/dropdown",["jquery","./utils"],function(t,e){function n(e,t){this.$element=e,this.options=t,n.__super__.constructor.call(this)}return e.Extend(n,e.Observable),n.prototype.render=function(){var e=t('');return e.attr("dir",this.options.get("dir")),this.$dropdown=e},n.prototype.bind=function(){},n.prototype.position=function(e,t){},n.prototype.destroy=function(){this.$dropdown.remove()},n}),e.define("select2/dropdown/search",["jquery","../utils"],function(s,e){function t(){}return t.prototype.render=function(e){var t=e.call(this),n=s('');return this.$searchContainer=n,this.$search=n.find("input"),t.prepend(n),t},t.prototype.bind=function(e,t,n){var i=this,o=t.id+"-results";e.call(this,t,n),this.$search.on("keydown",function(e){i.trigger("keypress",e),i._keyUpPrevented=e.isDefaultPrevented()}),this.$search.on("input",function(e){s(this).off("keyup")}),this.$search.on("keyup input",function(e){i.handleSearch(e)}),t.on("open",function(){i.$search.attr("tabindex",0),i.$search.attr("aria-owns",o),i.$search.focus(),window.setTimeout(function(){i.$search.focus()},0)}),t.on("close",function(){i.$search.attr("tabindex",-1),i.$search.removeAttr("aria-activedescendant"),i.$search.removeAttr("aria-owns"),i.$search.val("")}),t.on("focus",function(){t.isOpen()||i.$search.focus()}),t.on("results:all",function(e){null!=e.query.term&&""!==e.query.term||(i.showSearch(e)?i.$searchContainer.removeClass("select2-search--hide"):i.$searchContainer.addClass("select2-search--hide"))}),t.on("results:focus",function(e){i.$search.attr("aria-activedescendant",e.data._resultId)})},t.prototype.handleSearch=function(e){if(!this._keyUpPrevented){var t=this.$search.val();this.trigger("query",{term:t})}this._keyUpPrevented=!1},t.prototype.showSearch=function(e,t){return!0},t}),e.define("select2/dropdown/hidePlaceholder",[],function(){function e(e,t,n,i){this.placeholder=this.normalizePlaceholder(n.get("placeholder")),e.call(this,t,n,i)}return e.prototype.append=function(e,t){t.results=this.removePlaceholder(t.results),e.call(this,t)},e.prototype.normalizePlaceholder=function(e,t){return"string"==typeof t&&(t={id:"",text:t}),t},e.prototype.removePlaceholder=function(e,t){for(var n=t.slice(0),i=t.length-1;0<=i;i--){var o=t[i];this.placeholder.id===o.id&&n.splice(i,1)}return n},e}),e.define("select2/dropdown/infiniteScroll",["jquery"],function(o){function e(e,t,n,i){this.lastParams={},e.call(this,t,n,i),this.$loadingMore=this.createLoadingMore(),this.loading=!1}return e.prototype.append=function(e,t){this.$loadingMore.remove(),this.loading=!1,e.call(this,t),this.showLoadingMore(t)&&this.$results.append(this.$loadingMore)},e.prototype.bind=function(e,t,n){var i=this;e.call(this,t,n),t.on("query",function(e){i.lastParams=e,i.loading=!0}),t.on("query:append",function(e){i.lastParams=e,i.loading=!0}),this.$results.on("scroll",function(){var e=o.contains(document.documentElement,i.$loadingMore[0]);if(!i.loading&&e){var t=i.$results.offset().top+i.$results.outerHeight(!1);i.$loadingMore.offset().top+i.$loadingMore.outerHeight(!1)<=t+50&&i.loadMore()}})},e.prototype.loadMore=function(){this.loading=!0;var e=o.extend({},{page:1},this.lastParams);e.page++,this.trigger("query:append",e)},e.prototype.showLoadingMore=function(e,t){return t.pagination&&t.pagination.more},e.prototype.createLoadingMore=function(){var e=o('
  • '),t=this.options.get("translations").get("loadingMore");return e.html(t(this.lastParams)),e},e}),e.define("select2/dropdown/attachBody",["jquery","../utils"],function(f,a){function e(e,t,n){this.$dropdownParent=n.get("dropdownParent")||f(document.body),e.call(this,t,n)}return e.prototype.bind=function(e,t,n){var i=this,o=!1;e.call(this,t,n),t.on("open",function(){i._showDropdown(),i._attachPositioningHandler(t),o||(o=!0,t.on("results:all",function(){i._positionDropdown(),i._resizeDropdown()}),t.on("results:append",function(){i._positionDropdown(),i._resizeDropdown()}))}),t.on("close",function(){i._hideDropdown(),i._detachPositioningHandler(t)}),this.$dropdownContainer.on("mousedown",function(e){e.stopPropagation()})},e.prototype.destroy=function(e){e.call(this),this.$dropdownContainer.remove()},e.prototype.position=function(e,t,n){t.attr("class",n.attr("class")),t.removeClass("select2"),t.addClass("select2-container--open"),t.css({position:"absolute",top:-999999}),this.$container=n},e.prototype.render=function(e){var t=f(""),n=e.call(this);return t.append(n),this.$dropdownContainer=t},e.prototype._hideDropdown=function(e){this.$dropdownContainer.detach()},e.prototype._attachPositioningHandler=function(e,t){var n=this,i="scroll.select2."+t.id,o="resize.select2."+t.id,s="orientationchange.select2."+t.id,r=this.$container.parents().filter(a.hasScroll);r.each(function(){f(this).data("select2-scroll-position",{x:f(this).scrollLeft(),y:f(this).scrollTop()})}),r.on(i,function(e){var t=f(this).data("select2-scroll-position");f(this).scrollTop(t.y)}),f(window).on(i+" "+o+" "+s,function(e){n._positionDropdown(),n._resizeDropdown()})},e.prototype._detachPositioningHandler=function(e,t){var n="scroll.select2."+t.id,i="resize.select2."+t.id,o="orientationchange.select2."+t.id;this.$container.parents().filter(a.hasScroll).off(n),f(window).off(n+" "+i+" "+o)},e.prototype._positionDropdown=function(){var e=f(window),t=this.$dropdown.hasClass("select2-dropdown--above"),n=this.$dropdown.hasClass("select2-dropdown--below"),i=null,o=this.$container.offset();o.bottom=o.top+this.$container.outerHeight(!1);var s={height:this.$container.outerHeight(!1)};s.top=o.top,s.bottom=o.top+s.height;var r=this.$dropdown.outerHeight(!1),a=e.scrollTop(),l=e.scrollTop()+e.height(),c=ao.bottom+r,d={left:o.left,top:s.bottom},p=this.$dropdownParent;"static"===p.css("position")&&(p=p.offsetParent());var h=p.offset();d.top-=h.top,d.left-=h.left,t||n||(i="below"),u||!c||t?!c&&u&&t&&(i="below"):i="above",("above"==i||t&&"below"!==i)&&(d.top=s.top-h.top-r),null!=i&&(this.$dropdown.removeClass("select2-dropdown--below select2-dropdown--above").addClass("select2-dropdown--"+i),this.$container.removeClass("select2-container--below select2-container--above").addClass("select2-container--"+i)),this.$dropdownContainer.css(d)},e.prototype._resizeDropdown=function(){var e={width:this.$container.outerWidth(!1)+"px"};this.options.get("dropdownAutoWidth")&&(e.minWidth=e.width,e.position="relative",e.width="auto"),this.$dropdown.css(e)},e.prototype._showDropdown=function(e){this.$dropdownContainer.appendTo(this.$dropdownParent),this._positionDropdown(),this._resizeDropdown()},e}),e.define("select2/dropdown/minimumResultsForSearch",[],function(){function e(e,t,n,i){this.minimumResultsForSearch=n.get("minimumResultsForSearch"),this.minimumResultsForSearch<0&&(this.minimumResultsForSearch=Infinity),e.call(this,t,n,i)}return e.prototype.showSearch=function(e,t){return!(function o(e){for(var t=0,n=0;n');return e.attr("dir",this.options.get("dir")),this.$container=e,this.$container.addClass("select2-container--"+this.options.get("theme")),e.data("element",this.$element),e},u}),e.define("select2/compat/utils",["jquery"],function(r){return{syncCssClasses:function a(e,t,n){var i,o,s=[];(i=r.trim(e.attr("class")))&&r((i=""+i).split(/\s+/)).each(function(){0===this.indexOf("select2-")&&s.push(this)}),(i=r.trim(t.attr("class")))&&r((i=""+i).split(/\s+/)).each(function(){0!==this.indexOf("select2-")&&null!=(o=n(this))&&s.push(o)}),e.attr("class",s.join(" "))}}}),e.define("select2/compat/containerCss",["jquery","./utils"],function(r,a){function l(e){return null}function e(){}return e.prototype.render=function(e){var t=e.call(this),n=this.options.get("containerCssClass")||"";r.isFunction(n)&&(n=n(this.$element));var i=this.options.get("adaptContainerCssClass");if(i=i||l,-1!==n.indexOf(":all:")){n=n.replace(":all:","");var o=i;i=function(e){var t=o(e);return null!=t?t+" "+e:e}}var s=this.options.get("containerCss")||{};return r.isFunction(s)&&(s=s(this.$element)),a.syncCssClasses(t,this.$element,i),t.css(s),t.addClass(n),t},e}),e.define("select2/compat/dropdownCss",["jquery","./utils"],function(r,a){function l(e){return null}function e(){}return e.prototype.render=function(e){var t=e.call(this),n=this.options.get("dropdownCssClass")||"";r.isFunction(n)&&(n=n(this.$element));var i=this.options.get("adaptDropdownCssClass");if(i=i||l,-1!==n.indexOf(":all:")){n=n.replace(":all:","");var o=i;i=function(e){var t=o(e);return null!=t?t+" "+e:e}}var s=this.options.get("dropdownCss")||{};return r.isFunction(s)&&(s=s(this.$element)),a.syncCssClasses(t,this.$element,i),t.css(s),t.addClass(n),t},e}),e.define("select2/compat/initSelection",["jquery"],function(i){function e(e,t,n){n.get("debug")&&window.console&&console.warn&&console.warn("Select2: The `initSelection` option has been deprecated in favor of a custom data adapter that overrides the `current` method. This method is now called multiple times instead of a single time when the instance is initialized. Support will be removed for the `initSelection` option in future versions of Select2"),this.initSelection=n.get("initSelection"),this._isInitialized=!1,e.call(this,t,n)}return e.prototype.current=function(e,t){var n=this;this._isInitialized?e.call(this,t):this.initSelection.call(null,this.$element,function(e){n._isInitialized=!0,i.isArray(e)||(e=[e]),t(e)})},e}),e.define("select2/compat/inputData",["jquery"],function(r){function e(e,t,n){this._currentData=[],this._valueSeparator=n.get("valueSeparator")||",","hidden"===t.prop("type")&&n.get("debug")&&console&&console.warn&&console.warn("Select2: Using a hidden input with Select2 is no longer supported and may stop working in the future. It is recommended to use a `');this.$searchContainer=t,this.$search=t.find("input");var n=e.call(this);return this._transferTabIndex(),n},t.prototype.bind=function(e,i,t){var r=this,n=i.id+"-results";e.call(this,i,t),i.on("open",function(){r.$search.attr("aria-owns",n),r.$search.trigger("focus")}),i.on("close",function(){r.$search.val(""),r.$search.removeAttr("aria-activedescendant"),r.$search.removeAttr("aria-owns"),r.$search.trigger("focus")}),i.on("enable",function(){r.$search.prop("disabled",!1),r._transferTabIndex()}),i.on("disable",function(){r.$search.prop("disabled",!0)}),i.on("focus",function(e){r.$search.trigger("focus")}),i.on("results:focus",function(e){r.$search.attr("aria-activedescendant",e.data._resultId)}),this.$selection.on("focusin",".select2-search--inline",function(e){r.trigger("focus",e)}),this.$selection.on("focusout",".select2-search--inline",function(e){r._handleBlur(e)}),this.$selection.on("keydown",".select2-search--inline",function(e){if(e.stopPropagation(),r.trigger("keypress",e),r._keyUpPrevented=e.isDefaultPrevented(),e.which===a.BACKSPACE&&""===r.$search.val()){var t=r.$searchContainer.prev(".select2-selection__choice");if(0this.maximumInputLength?this.trigger("results:message",{message:"inputTooLong",args:{maximum:this.maximumInputLength,input:t.term,params:t}}):e.call(this,t,n)},e}),e.define("select2/data/maximumSelectionLength",[],function(){function e(e,t,n){this.maximumSelectionLength=n.get("maximumSelectionLength"),e.call(this,t,n)}return e.prototype.query=function(n,i,r){var o=this;this.current(function(e){var t=null!=e?e.length:0;0=o.maximumSelectionLength?o.trigger("results:message",{message:"maximumSelected",args:{maximum:o.maximumSelectionLength}}):n.call(o,i,r)})},e}),e.define("select2/dropdown",["jquery","./utils"],function(t,e){function n(e,t){this.$element=e,this.options=t,n.__super__.constructor.call(this)}return e.Extend(n,e.Observable),n.prototype.render=function(){var e=t('');return e.attr("dir",this.options.get("dir")),this.$dropdown=e},n.prototype.bind=function(){},n.prototype.position=function(e,t){},n.prototype.destroy=function(){this.$dropdown.remove()},n}),e.define("select2/dropdown/search",["jquery","../utils"],function(o,e){function t(){}return t.prototype.render=function(e){var t=e.call(this),n=o('');return this.$searchContainer=n,this.$search=n.find("input"),t.prepend(n),t},t.prototype.bind=function(e,t,n){var i=this,r=t.id+"-results";e.call(this,t,n),this.$search.on("keydown",function(e){i.trigger("keypress",e),i._keyUpPrevented=e.isDefaultPrevented()}),this.$search.on("input",function(e){o(this).off("keyup")}),this.$search.on("keyup input",function(e){i.handleSearch(e)}),t.on("open",function(){i.$search.attr("tabindex",0),i.$search.attr("aria-owns",r),i.$search.focus(),window.setTimeout(function(){i.$search.focus()},0)}),t.on("close",function(){i.$search.attr("tabindex",-1),i.$search.removeAttr("aria-activedescendant"),i.$search.removeAttr("aria-owns"),i.$search.val("")}),t.on("focus",function(){t.isOpen()||i.$search.focus()}),t.on("results:all",function(e){null!=e.query.term&&""!==e.query.term||(i.showSearch(e)?i.$searchContainer.removeClass("select2-search--hide"):i.$searchContainer.addClass("select2-search--hide"))}),t.on("results:focus",function(e){i.$search.attr("aria-activedescendant",e.data._resultId)})},t.prototype.handleSearch=function(e){if(!this._keyUpPrevented){var t=this.$search.val();this.trigger("query",{term:t})}this._keyUpPrevented=!1},t.prototype.showSearch=function(e,t){return!0},t}),e.define("select2/dropdown/hidePlaceholder",[],function(){function e(e,t,n,i){this.placeholder=this.normalizePlaceholder(n.get("placeholder")),e.call(this,t,n,i)}return e.prototype.append=function(e,t){t.results=this.removePlaceholder(t.results),e.call(this,t)},e.prototype.normalizePlaceholder=function(e,t){return"string"==typeof t&&(t={id:"",text:t}),t},e.prototype.removePlaceholder=function(e,t){for(var n=t.slice(0),i=t.length-1;0<=i;i--){var r=t[i];this.placeholder.id===r.id&&n.splice(i,1)}return n},e}),e.define("select2/dropdown/infiniteScroll",["jquery"],function(r){function e(e,t,n,i){this.lastParams={},e.call(this,t,n,i),this.$loadingMore=this.createLoadingMore(),this.loading=!1}return e.prototype.append=function(e,t){this.$loadingMore.remove(),this.loading=!1,e.call(this,t),this.showLoadingMore(t)&&this.$results.append(this.$loadingMore)},e.prototype.bind=function(e,t,n){var i=this;e.call(this,t,n),t.on("query",function(e){i.lastParams=e,i.loading=!0}),t.on("query:append",function(e){i.lastParams=e,i.loading=!0}),this.$results.on("scroll",function(){var e=r.contains(document.documentElement,i.$loadingMore[0]);if(!i.loading&&e){var t=i.$results.offset().top+i.$results.outerHeight(!1);i.$loadingMore.offset().top+i.$loadingMore.outerHeight(!1)<=t+50&&i.loadMore()}})},e.prototype.loadMore=function(){this.loading=!0;var e=r.extend({},{page:1},this.lastParams);e.page++,this.trigger("query:append",e)},e.prototype.showLoadingMore=function(e,t){return t.pagination&&t.pagination.more},e.prototype.createLoadingMore=function(){var e=r('
  • '),t=this.options.get("translations").get("loadingMore");return e.html(t(this.lastParams)),e},e}),e.define("select2/dropdown/attachBody",["jquery","../utils"],function(f,a){function e(e,t,n){this.$dropdownParent=n.get("dropdownParent")||f(document.body),e.call(this,t,n)}return e.prototype.bind=function(e,t,n){var i=this,r=!1;e.call(this,t,n),t.on("open",function(){i._showDropdown(),i._attachPositioningHandler(t),r||(r=!0,t.on("results:all",function(){i._positionDropdown(),i._resizeDropdown()}),t.on("results:append",function(){i._positionDropdown(),i._resizeDropdown()}))}),t.on("close",function(){i._hideDropdown(),i._detachPositioningHandler(t)}),this.$dropdownContainer.on("mousedown",function(e){e.stopPropagation()})},e.prototype.destroy=function(e){e.call(this),this.$dropdownContainer.remove()},e.prototype.position=function(e,t,n){t.attr("class",n.attr("class")),t.removeClass("select2"),t.addClass("select2-container--open"),t.css({position:"absolute",top:-999999}),this.$container=n},e.prototype.render=function(e){var t=f(""),n=e.call(this);return t.append(n),this.$dropdownContainer=t},e.prototype._hideDropdown=function(e){this.$dropdownContainer.detach()},e.prototype._attachPositioningHandler=function(e,t){var n=this,i="scroll.select2."+t.id,r="resize.select2."+t.id,o="orientationchange.select2."+t.id,s=this.$container.parents().filter(a.hasScroll);s.each(function(){f(this).data("select2-scroll-position",{x:f(this).scrollLeft(),y:f(this).scrollTop()})}),s.on(i,function(e){var t=f(this).data("select2-scroll-position");f(this).scrollTop(t.y)}),f(window).on(i+" "+r+" "+o,function(e){n._positionDropdown(),n._resizeDropdown()})},e.prototype._detachPositioningHandler=function(e,t){var n="scroll.select2."+t.id,i="resize.select2."+t.id,r="orientationchange.select2."+t.id;this.$container.parents().filter(a.hasScroll).off(n),f(window).off(n+" "+i+" "+r)},e.prototype._positionDropdown=function(){var e=f(window),t=this.$dropdown.hasClass("select2-dropdown--above"),n=this.$dropdown.hasClass("select2-dropdown--below"),i=null,r=this.$container.offset();r.bottom=r.top+this.$container.outerHeight(!1);var o={height:this.$container.outerHeight(!1)};o.top=r.top,o.bottom=r.top+o.height;var s=this.$dropdown.outerHeight(!1),a=e.scrollTop(),l=e.scrollTop()+e.height(),c=ar.bottom+s,d={left:r.left,top:o.bottom},p=this.$dropdownParent;"static"===p.css("position")&&(p=p.offsetParent());var h=p.offset();d.top-=h.top,d.left-=h.left,t||n||(i="below"),u||!c||t?!c&&u&&t&&(i="below"):i="above",("above"==i||t&&"below"!==i)&&(d.top=o.top-h.top-s),null!=i&&(this.$dropdown.removeClass("select2-dropdown--below select2-dropdown--above").addClass("select2-dropdown--"+i),this.$container.removeClass("select2-container--below select2-container--above").addClass("select2-container--"+i)),this.$dropdownContainer.css(d)},e.prototype._resizeDropdown=function(){var e={width:this.$container.outerWidth(!1)+"px"};this.options.get("dropdownAutoWidth")&&(e.minWidth=e.width,e.position="relative",e.width="auto"),this.$dropdown.css(e)},e.prototype._showDropdown=function(e){this.$dropdownContainer.appendTo(this.$dropdownParent),this._positionDropdown(),this._resizeDropdown()},e}),e.define("select2/dropdown/minimumResultsForSearch",[],function(){function e(e,t,n,i){this.minimumResultsForSearch=n.get("minimumResultsForSearch"),this.minimumResultsForSearch<0&&(this.minimumResultsForSearch=Infinity),e.call(this,t,n,i)}return e.prototype.showSearch=function(e,t){return!(function r(e){for(var t=0,n=0;n');return e.attr("dir",this.options.get("dir")),this.$container=e,this.$container.addClass("select2-container--"+this.options.get("theme")),e.data("element",this.$element),e},u}),e.define("jquery-mousewheel",["jquery"],function(e){return e}),e.define("jquery.select2",["jquery","jquery-mousewheel","./select2/core","./select2/defaults"],function(r,e,o,t){if(null==r.fn.selectWoo){var s=["open","close","destroy"];r.fn.selectWoo=function(t){if("object"==typeof(t=t||{}))return this.each(function(){var e=r.extend(!0,{},t);new o(r(this),e)}),this;if("string"!=typeof t)throw new Error("Invalid arguments for Select2: "+t);var n,i=Array.prototype.slice.call(arguments,1);return this.each(function(){var e=r(this).data("select2");null==e&&window.console&&console.error&&console.error("The select2('"+t+"') method was called on an element that is not using Select2."),n=e[t].apply(e,i)}),-1":">",'"':""","'":"'","/":"/"};return"string"!=typeof e?e:String(e).replace(/[&<>"'\/\\]/g,function(e){return t[e]})},e.entityDecode=function(e){var t=document.createElement("textarea");return t.innerHTML=e,t.value},e.appendMany=function(e,t){if("1.7"===o.fn.jquery.substr(0,3)){var n=o();o.map(t,function(e){n=n.add(e)}),t=n}e.append(t)},e.isTouchscreen=function(){return"undefined"==typeof e._isTouchscreenCache&&(e._isTouchscreenCache="ontouchstart"in document.documentElement),e._isTouchscreenCache},e}),e.define("select2/results",["jquery","./utils"],function(h,e){function i(e,t,n){this.$element=e,this.data=n,this.options=t,i.__super__.constructor.call(this)}return e.Extend(i,e.Observable),i.prototype.render=function(){var e=h('
      ');return this.options.get("multiple")&&e.attr("aria-multiselectable","true"),this.$results=e},i.prototype.clear=function(){this.$results.empty()},i.prototype.displayMessage=function(e){var t=this.options.get("escapeMarkup");this.clear(),this.hideLoading();var n=h(''),i=this.options.get("translations").get(e.message);n.append(t(i(e.args))),n[0].className+=" select2-results__message",this.$results.append(n)},i.prototype.hideMessages=function(){this.$results.find(".select2-results__message").remove()},i.prototype.append=function(e){this.hideLoading();var t=[];if(null!=e.results&&0!==e.results.length){e.results=this.sort(e.results);for(var n=0;n",{"class":"select2-results__options select2-results__options--nested",role:"listbox"});p.append(l),o.attr("role","list"),o.append(s),o.append(p)}else this.template(e,t);return h.data(t,"data",e),t},i.prototype.bind=function(t,e){var l=this,n=t.id+"-results";this.$results.attr("id",n),t.on("results:all",function(e){l.clear(),l.append(e.data),t.isOpen()&&(l.setClasses(),l.highlightFirstItem())}),t.on("results:append",function(e){l.append(e.data),t.isOpen()&&l.setClasses()}),t.on("query",function(e){l.hideMessages(),l.showLoading(e)}),t.on("select",function(){t.isOpen()&&(l.setClasses(),l.highlightFirstItem())}),t.on("unselect",function(){t.isOpen()&&(l.setClasses(),l.highlightFirstItem())}),t.on("open",function(){l.$results.attr("aria-expanded","true"),l.$results.attr("aria-hidden","false"),l.setClasses(),l.ensureHighlightVisible()}),t.on("close",function(){l.$results.attr("aria-expanded","false"),l.$results.attr("aria-hidden","true"),l.$results.removeAttr("aria-activedescendant")}),t.on("results:toggle",function(){var e=l.getHighlightedResults();0!==e.length&&e.trigger("mouseup")}),t.on("results:select",function(){var e=l.getHighlightedResults();if(0!==e.length){var t=e.data("data");"true"==e.attr("data-selected")?l.trigger("close",{}):l.trigger("select",{data:t})}}),t.on("results:previous",function(){var e=l.getHighlightedResults(),t=l.$results.find("[data-selected]"),n=t.index(e);if(0!==n){var i=n-1;0===e.length&&(i=0);var r=t.eq(i);r.trigger("mouseenter");var o=l.$results.offset().top,s=r.offset().top,a=l.$results.scrollTop()+(s-o);0===i?l.$results.scrollTop(0):s-o<0&&l.$results.scrollTop(a)}}),t.on("results:next",function(){var e=l.getHighlightedResults(),t=l.$results.find("[data-selected]"),n=t.index(e)+1;if(!(n>=t.length)){var i=t.eq(n);i.trigger("mouseenter");var r=l.$results.offset().top+l.$results.outerHeight(!1),o=i.offset().top+i.outerHeight(!1),s=l.$results.scrollTop()+o-r;0===n?l.$results.scrollTop(0):rthis.$results.outerHeight()||o<0)&&this.$results.scrollTop(r)}},i.prototype.template=function(e,t){var n=this.options.get("templateResult"),i=this.options.get("escapeMarkup"),r=n(e,t);null==r?t.style.display="none":"string"==typeof r?t.innerHTML=i(r):h(t).append(r)},i}),e.define("select2/keys",[],function(){return{BACKSPACE:8,TAB:9,ENTER:13,SHIFT:16,CTRL:17,ALT:18,ESC:27,SPACE:32,PAGE_UP:33,PAGE_DOWN:34,END:35,HOME:36,LEFT:37,UP:38,RIGHT:39,DOWN:40,DELETE:46}}),e.define("select2/selection/base",["jquery","../utils","../keys"],function(i,e,r){function n(e,t){this.$element=e,this.options=t,n.__super__.constructor.call(this)}return e.Extend(n,e.Observable),n.prototype.render=function(){var e=i('');return this._tabindex=0,null!=this.$element.data("old-tabindex")?this._tabindex=this.$element.data("old-tabindex"):null!=this.$element.attr("tabindex")&&(this._tabindex=this.$element.attr("tabindex")),e.attr("title",this.$element.attr("title")),e.attr("tabindex",this._tabindex),this.$selection=e},n.prototype.bind=function(e,t){var n=this,i=(e.id,e.id+"-results");this.options.get("minimumResultsForSearch"),Infinity;this.container=e,this.$selection.on("focus",function(e){n.trigger("focus",e)}),this.$selection.on("blur",function(e){n._handleBlur(e)}),this.$selection.on("keydown",function(e){n.trigger("keypress",e),e.which===r.SPACE&&e.preventDefault()}),e.on("results:focus",function(e){n.$selection.attr("aria-activedescendant",e.data._resultId)}),e.on("selection:update",function(e){n.update(e.data)}),e.on("open",function(){n.$selection.attr("aria-expanded","true"),n.$selection.attr("aria-owns",i),n._attachCloseHandler(e)}),e.on("close",function(){n.$selection.attr("aria-expanded","false"),n.$selection.removeAttr("aria-activedescendant"),n.$selection.removeAttr("aria-owns"),window.setTimeout(function(){n.$selection.focus()},1),n._detachCloseHandler(e)}),e.on("enable",function(){n.$selection.attr("tabindex",n._tabindex)}),e.on("disable",function(){n.$selection.attr("tabindex","-1")})},n.prototype._handleBlur=function(e){var t=this;window.setTimeout(function(){document.activeElement==t.$selection[0]||i.contains(t.$selection[0],document.activeElement)||t.trigger("blur",e)},1)},n.prototype._attachCloseHandler=function(e){i(document.body).on("mousedown.select2."+e.id,function(e){var t=i(e.target),n=t.closest(".select2");i(".select2.select2-container--open").each(function(){var e=i(this);this!=n[0]&&(e.data("element").select2("close"),setTimeout(function(){e.find("*:focus").blur(),t.focus()},1))})})},n.prototype._detachCloseHandler=function(e){i(document.body).off("mousedown.select2."+e.id)},n.prototype.position=function(e,t){t.find(".selection").append(e)},n.prototype.destroy=function(){this._detachCloseHandler(this.container)},n.prototype.update=function(e){throw new Error("The `update` method must be defined in child classes.")},n}),e.define("select2/selection/single",["jquery","./base","../utils","../keys"],function(e,t,r,n){function o(){o.__super__.constructor.apply(this,arguments)}return r.Extend(o,t),o.prototype.render=function(){var e=o.__super__.render.call(this);return e.addClass("select2-selection--single"),e.html(''),e},o.prototype.bind=function(t,e){var n=this;o.__super__.bind.apply(this,arguments);var i=t.id+"-container";this.$selection.find(".select2-selection__rendered").attr("id",i).attr("role","textbox").attr("aria-readonly","true"),this.$selection.attr("aria-labelledby",i),this.$selection.attr("role","combobox"),this.$selection.on("mousedown",function(e){1===e.which&&n.trigger("toggle",{originalEvent:e})}),this.$selection.on("focus",function(e){}),this.$selection.on("keydown",function(e){!t.isOpen()&&48<=e.which&&e.which<=90&&t.open()}),this.$selection.on("blur",function(e){}),t.on("focus",function(e){t.isOpen()||n.$selection.focus()}),t.on("selection:update",function(e){n.update(e.data)})},o.prototype.clear=function(){this.$selection.find(".select2-selection__rendered").empty()},o.prototype.display=function(e,t){var n=this.options.get("templateSelection");return this.options.get("escapeMarkup")(n(e,t))},o.prototype.selectionContainer=function(){return e("")},o.prototype.update=function(e){if(0!==e.length){var t=e[0],n=this.$selection.find(".select2-selection__rendered"),i=r.entityDecode(this.display(t,n));n.empty().text(i),n.prop("title",t.title||t.text)}else this.clear()},o}),e.define("select2/selection/multiple",["jquery","./base","../utils"],function(i,e,a){function r(e,t){r.__super__.constructor.apply(this,arguments)}return a.Extend(r,e),r.prototype.render=function(){var e=r.__super__.render.call(this);return e.addClass("select2-selection--multiple"),e.html('
        '),e},r.prototype.bind=function(t,e){var n=this;r.__super__.bind.apply(this,arguments),this.$selection.on("click",function(e){n.trigger("toggle",{originalEvent:e})}),this.$selection.on("click",".select2-selection__choice__remove",function(e){if(!n.options.get("disabled")){var t=i(this).parent().data("data");n.trigger("unselect",{originalEvent:e,data:t})}}),this.$selection.on("keydown",function(e){!t.isOpen()&&48<=e.which&&e.which<=90&&t.open()}),t.on("focus",function(){n.focusOnSearch()})},r.prototype.clear=function(){this.$selection.find(".select2-selection__rendered").empty()},r.prototype.display=function(e,t){var n=this.options.get("templateSelection");return this.options.get("escapeMarkup")(n(e,t))},r.prototype.selectionContainer=function(){return i('
      • ')},r.prototype.focusOnSearch=function(){var e=this;"undefined"!=typeof e.$search&&setTimeout(function(){e._keyUpPrevented=!0,e.$search.focus()},1)},r.prototype.update=function(e){if(this.clear(),0!==e.length){for(var t=[],n=0;n×');n.data("data",t),this.$selection.find(".select2-selection__rendered").prepend(n)}},e}),e.define("select2/selection/search",["jquery","../utils","../keys"],function(i,e,a){function t(e,t,n){e.call(this,t,n)}return t.prototype.render=function(e){var t=i('');this.$searchContainer=t,this.$search=t.find("input");var n=e.call(this);return this._transferTabIndex(),n},t.prototype.bind=function(e,i,t){var r=this,n=i.id+"-results";e.call(this,i,t),i.on("open",function(){r.$search.attr("aria-owns",n),r.$search.trigger("focus")}),i.on("close",function(){r.$search.val(""),r.$search.removeAttr("aria-activedescendant"),r.$search.removeAttr("aria-owns"),r.$search.trigger("focus")}),i.on("enable",function(){r.$search.prop("disabled",!1),r._transferTabIndex()}),i.on("disable",function(){r.$search.prop("disabled",!0)}),i.on("focus",function(e){r.$search.trigger("focus")}),i.on("results:focus",function(e){r.$search.attr("aria-activedescendant",e.data._resultId)}),this.$selection.on("focusin",".select2-search--inline",function(e){r.trigger("focus",e)}),this.$selection.on("focusout",".select2-search--inline",function(e){r._handleBlur(e)}),this.$selection.on("keydown",".select2-search--inline",function(e){if(e.stopPropagation(),r.trigger("keypress",e),r._keyUpPrevented=e.isDefaultPrevented(),e.which===a.BACKSPACE&&""===r.$search.val()){var t=r.$searchContainer.prev(".select2-selection__choice");if(0this.maximumInputLength?this.trigger("results:message",{message:"inputTooLong",args:{maximum:this.maximumInputLength,input:t.term,params:t}}):e.call(this,t,n)},e}),e.define("select2/data/maximumSelectionLength",[],function(){function e(e,t,n){this.maximumSelectionLength=n.get("maximumSelectionLength"),e.call(this,t,n)}return e.prototype.query=function(n,i,r){var o=this;this.current(function(e){var t=null!=e?e.length:0;0=o.maximumSelectionLength?o.trigger("results:message",{message:"maximumSelected",args:{maximum:o.maximumSelectionLength}}):n.call(o,i,r)})},e}),e.define("select2/dropdown",["jquery","./utils"],function(t,e){function n(e,t){this.$element=e,this.options=t,n.__super__.constructor.call(this)}return e.Extend(n,e.Observable),n.prototype.render=function(){var e=t('');return e.attr("dir",this.options.get("dir")),this.$dropdown=e},n.prototype.bind=function(){},n.prototype.position=function(e,t){},n.prototype.destroy=function(){this.$dropdown.remove()},n}),e.define("select2/dropdown/search",["jquery","../utils"],function(o,e){function t(){}return t.prototype.render=function(e){var t=e.call(this),n=o('');return this.$searchContainer=n,this.$search=n.find("input"),t.prepend(n),t},t.prototype.bind=function(e,t,n){var i=this,r=t.id+"-results";e.call(this,t,n),this.$search.on("keydown",function(e){i.trigger("keypress",e),i._keyUpPrevented=e.isDefaultPrevented()}),this.$search.on("input",function(e){o(this).off("keyup")}),this.$search.on("keyup input",function(e){i.handleSearch(e)}),t.on("open",function(){i.$search.attr("tabindex",0),i.$search.attr("aria-owns",r),i.$search.focus(),window.setTimeout(function(){i.$search.focus()},0)}),t.on("close",function(){i.$search.attr("tabindex",-1),i.$search.removeAttr("aria-activedescendant"),i.$search.removeAttr("aria-owns"),i.$search.val("")}),t.on("focus",function(){t.isOpen()||i.$search.focus()}),t.on("results:all",function(e){null!=e.query.term&&""!==e.query.term||(i.showSearch(e)?i.$searchContainer.removeClass("select2-search--hide"):i.$searchContainer.addClass("select2-search--hide"))}),t.on("results:focus",function(e){i.$search.attr("aria-activedescendant",e.data._resultId)})},t.prototype.handleSearch=function(e){if(!this._keyUpPrevented){var t=this.$search.val();this.trigger("query",{term:t})}this._keyUpPrevented=!1},t.prototype.showSearch=function(e,t){return!0},t}),e.define("select2/dropdown/hidePlaceholder",[],function(){function e(e,t,n,i){this.placeholder=this.normalizePlaceholder(n.get("placeholder")),e.call(this,t,n,i)}return e.prototype.append=function(e,t){t.results=this.removePlaceholder(t.results),e.call(this,t)},e.prototype.normalizePlaceholder=function(e,t){return"string"==typeof t&&(t={id:"",text:t}),t},e.prototype.removePlaceholder=function(e,t){for(var n=t.slice(0),i=t.length-1;0<=i;i--){var r=t[i];this.placeholder.id===r.id&&n.splice(i,1)}return n},e}),e.define("select2/dropdown/infiniteScroll",["jquery"],function(r){function e(e,t,n,i){this.lastParams={},e.call(this,t,n,i),this.$loadingMore=this.createLoadingMore(),this.loading=!1}return e.prototype.append=function(e,t){this.$loadingMore.remove(),this.loading=!1,e.call(this,t),this.showLoadingMore(t)&&this.$results.append(this.$loadingMore)},e.prototype.bind=function(e,t,n){var i=this;e.call(this,t,n),t.on("query",function(e){i.lastParams=e,i.loading=!0}),t.on("query:append",function(e){i.lastParams=e,i.loading=!0}),this.$results.on("scroll",function(){var e=r.contains(document.documentElement,i.$loadingMore[0]);if(!i.loading&&e){var t=i.$results.offset().top+i.$results.outerHeight(!1);i.$loadingMore.offset().top+i.$loadingMore.outerHeight(!1)<=t+50&&i.loadMore()}})},e.prototype.loadMore=function(){this.loading=!0;var e=r.extend({},{page:1},this.lastParams);e.page++,this.trigger("query:append",e)},e.prototype.showLoadingMore=function(e,t){return t.pagination&&t.pagination.more},e.prototype.createLoadingMore=function(){var e=r('
      • '),t=this.options.get("translations").get("loadingMore");return e.html(t(this.lastParams)),e},e}),e.define("select2/dropdown/attachBody",["jquery","../utils"],function(f,a){function e(e,t,n){this.$dropdownParent=n.get("dropdownParent")||f(document.body),e.call(this,t,n)}return e.prototype.bind=function(e,t,n){var i=this,r=!1;e.call(this,t,n),t.on("open",function(){i._showDropdown(),i._attachPositioningHandler(t),r||(r=!0,t.on("results:all",function(){i._positionDropdown(),i._resizeDropdown()}),t.on("results:append",function(){i._positionDropdown(),i._resizeDropdown()}))}),t.on("close",function(){i._hideDropdown(),i._detachPositioningHandler(t)}),this.$dropdownContainer.on("mousedown",function(e){e.stopPropagation()})},e.prototype.destroy=function(e){e.call(this),this.$dropdownContainer.remove()},e.prototype.position=function(e,t,n){t.attr("class",n.attr("class")),t.removeClass("select2"),t.addClass("select2-container--open"),t.css({position:"absolute",top:-999999}),this.$container=n},e.prototype.render=function(e){var t=f(""),n=e.call(this);return t.append(n),this.$dropdownContainer=t},e.prototype._hideDropdown=function(e){this.$dropdownContainer.detach()},e.prototype._attachPositioningHandler=function(e,t){var n=this,i="scroll.select2."+t.id,r="resize.select2."+t.id,o="orientationchange.select2."+t.id,s=this.$container.parents().filter(a.hasScroll);s.each(function(){f(this).data("select2-scroll-position",{x:f(this).scrollLeft(),y:f(this).scrollTop()})}),s.on(i,function(e){var t=f(this).data("select2-scroll-position");f(this).scrollTop(t.y)}),f(window).on(i+" "+r+" "+o,function(e){n._positionDropdown(),n._resizeDropdown()})},e.prototype._detachPositioningHandler=function(e,t){var n="scroll.select2."+t.id,i="resize.select2."+t.id,r="orientationchange.select2."+t.id;this.$container.parents().filter(a.hasScroll).off(n),f(window).off(n+" "+i+" "+r)},e.prototype._positionDropdown=function(){var e=f(window),t=this.$dropdown.hasClass("select2-dropdown--above"),n=this.$dropdown.hasClass("select2-dropdown--below"),i=null,r=this.$container.offset();r.bottom=r.top+this.$container.outerHeight(!1);var o={height:this.$container.outerHeight(!1)};o.top=r.top,o.bottom=r.top+o.height;var s=this.$dropdown.outerHeight(!1),a=e.scrollTop(),l=e.scrollTop()+e.height(),c=ar.bottom+s,d={left:r.left,top:o.bottom},p=this.$dropdownParent;"static"===p.css("position")&&(p=p.offsetParent());var h=p.offset();d.top-=h.top,d.left-=h.left,t||n||(i="below"),u||!c||t?!c&&u&&t&&(i="below"):i="above",("above"==i||t&&"below"!==i)&&(d.top=o.top-h.top-s),null!=i&&(this.$dropdown.removeClass("select2-dropdown--below select2-dropdown--above").addClass("select2-dropdown--"+i),this.$container.removeClass("select2-container--below select2-container--above").addClass("select2-container--"+i)),this.$dropdownContainer.css(d)},e.prototype._resizeDropdown=function(){var e={width:this.$container.outerWidth(!1)+"px"};this.options.get("dropdownAutoWidth")&&(e.minWidth=e.width,e.position="relative",e.width="auto"),this.$dropdown.css(e)},e.prototype._showDropdown=function(e){this.$dropdownContainer.appendTo(this.$dropdownParent),this._positionDropdown(),this._resizeDropdown()},e}),e.define("select2/dropdown/minimumResultsForSearch",[],function(){function e(e,t,n,i){this.minimumResultsForSearch=n.get("minimumResultsForSearch"),this.minimumResultsForSearch<0&&(this.minimumResultsForSearch=Infinity),e.call(this,t,n,i)}return e.prototype.showSearch=function(e,t){return!(function r(e){for(var t=0,n=0;n');return e.attr("dir",this.options.get("dir")),this.$container=e,this.$container.addClass("select2-container--"+this.options.get("theme")),e.data("element",this.$element),e},u}),e.define("jquery-mousewheel",["jquery"],function(e){return e}),e.define("jquery.select2",["jquery","jquery-mousewheel","./select2/core","./select2/defaults"],function(r,e,o,t){if(null==r.fn.selectWoo){var s=["open","close","destroy"];r.fn.selectWoo=function(t){if("object"==typeof(t=t||{}))return this.each(function(){var e=r.extend(!0,{},t);new o(r(this),e)}),this;if("string"!=typeof t)throw new Error("Invalid arguments for Select2: "+t);var n,i=Array.prototype.slice.call(arguments,1);return this.each(function(){var e=r(this).data("select2");null==e&&window.console&&console.error&&console.error("The select2('"+t+"') method was called on an element that is not using Select2."),n=e[t].apply(e,i)}),-1WooCommerce core" > $output_file +echo "Generating contributor list for WC core since $from_date" +./node_modules/.bin/githubcontrib --repo woocommerce $common_arguments >> $output_file + +echo "

        WooCommerce Admin

        " >> $output_file +echo "Generating contributor list for WC Admin since $from_date" +./node_modules/.bin/githubcontrib --repo woocommerce-admin $common_arguments >> $output_file + +echo "

        WooCommerce Blocks

        " >> $output_file +echo "Generating contributor list for WC Blocks since $from_date" +./node_modules/.bin/githubcontrib --repo woocommerce-gutenberg-products-block $common_arguments >> $output_file + +echo "

        Action Scheduler

        " >> $output_file +echo "Generating contributor list for Action Scheduler since $from_date" +./node_modules/.bin/githubcontrib --repo action-scheduler $common_arguments >> $output_file + +echo "

        REST API

        " >> $output_file +echo "Generating contributor list for REST API since $from_date" +./node_modules/.bin/githubcontrib --repo woocommerce-rest-api $common_arguments >> $output_file + +echo "Output generated to $output_file." diff --git a/bin/package-update.sh b/bin/package-update.sh index da83d16e1fa..f3bb1137f81 100755 --- a/bin/package-update.sh +++ b/bin/package-update.sh @@ -34,6 +34,7 @@ output 2 "Done!" output 3 "Updating package JS textdomains..." find ./packages/woocommerce-blocks -iname '*.js' -exec sed -i.bak -e "s/'woo-gutenberg-products-block'/'woocommerce'/g" -e "s/\"woo-gutenberg-products-block\"/'woocommerce'/g" {} \; +find ./packages/woocommerce-blocks -iname '*.js' -exec sed -i.bak -e "s/'woocommerce-admin'/'woocommerce'/g" -e "s/\"woocommerce-admin\"/'woocommerce'/g" {} \; find ./packages/woocommerce-admin -iname '*.js' -exec sed -i.bak -e "s/'woocommerce-admin'/'woocommerce'/g" -e "s/\"woocommerce-admin\"/'woocommerce'/g" {} \; # Cleanup backup files diff --git a/bin/pre-push.sh b/bin/pre-push.sh new file mode 100755 index 00000000000..4f4afd34923 --- /dev/null +++ b/bin/pre-push.sh @@ -0,0 +1,22 @@ +#!/bin/sh + +PROTECTED_BRANCH="master" +REMOTE_REF=$(echo "$HUSKY_GIT_STDIN" | cut -d " " -f 3) + +if [ -n "$REMOTE_REF" ]; then + if [ -z "${REMOTE_REF##*$PROTECTED_BRANCH*}" ]; then + printf "%sYou're about to push to master, is that what you intended? [y/N]: %s" "$(tput setaf 3)" "$(tput sgr0)" + read -r PROCEED < /dev/tty + echo + + if [ "$(echo "${PROCEED:-n}" | tr "[:upper:]" "[:lower:]")" = "y" ]; then + echo "$(tput setaf 2)Brace yourself! Pushing to the master branch...$(tput sgr0)" + echo + exit 0 + fi + + echo "$(tput setaf 2)Push to master cancelled!$(tput sgr0)" + echo + exit 1 + fi +fi diff --git a/composer.json b/composer.json index 04f34d1911d..4fbf8bcb07a 100644 --- a/composer.json +++ b/composer.json @@ -8,15 +8,15 @@ "minimum-stability": "dev", "require": { "php": ">=7.0", - "automattic/jetpack-autoloader": "^1.6.0", + "automattic/jetpack-autoloader": "^1.7.0", "automattic/jetpack-constants": "^1.1", "composer/installers": "1.7.0", "maxmind-db/reader": "1.6.0", "pelago/emogrifier": "^3.1", "woocommerce/action-scheduler": "3.1.6", - "woocommerce/woocommerce-admin": "1.2.0", - "woocommerce/woocommerce-blocks": "2.5.16", - "woocommerce/woocommerce-rest-api": "1.0.8" + "woocommerce/woocommerce-admin": "1.3.0-beta.1", + "woocommerce/woocommerce-blocks": "2.7.1", + "woocommerce/woocommerce-rest-api": "1.0.10" }, "require-dev": { "phpunit/phpunit": "7.5.20", @@ -45,7 +45,8 @@ }, "autoload-dev": { "psr-4": { - "Automattic\\WooCommerce\\Tests\\": "tests/php/src" + "Automattic\\WooCommerce\\Tests\\": "tests/php/src", + "Automattic\\WooCommerce\\Testing\\Tools\\": "tests/Tools" } }, "scripts": { @@ -85,8 +86,8 @@ "test": "Run unit tests", "phpcs": "Analyze code against the WordPress coding standards with PHP_CodeSniffer", "phpcbf": "Fix coding standards warnings/errors automatically with PHP Code Beautifier", - "makepot-audit": "Generate i18n/langauges/woocommerce.pot file and run audit", - "makepot": "Generate i18n/langauges/woocommerce.pot file" + "makepot-audit": "Generate i18n/languages/woocommerce.pot file and run audit", + "makepot": "Generate i18n/languages/woocommerce.pot file" } } } diff --git a/composer.lock b/composer.lock index eabea333cb2..84f84185048 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "9548fdb91087ffaa8f14374698bf402e", + "content-hash": "e1718510b3bc480974ac78bd69e2124a", "packages": [ { "name": "automattic/jetpack-autoloader", @@ -331,7 +331,7 @@ }, { "name": "symfony/css-selector", - "version": "v3.4.40", + "version": "v3.4.42", "source": { "type": "git", "url": "https://github.com/symfony/css-selector.git", @@ -419,16 +419,16 @@ }, { "name": "woocommerce/woocommerce-admin", - "version": "v1.2.0", + "version": "v1.3.0-beta.1", "source": { "type": "git", "url": "https://github.com/woocommerce/woocommerce-admin.git", - "reference": "aa5062218a399843e68160e1b4b884320a7530ae" + "reference": "be22cb889e541caa9a38ec97182a004e9ab1a5c7" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/woocommerce/woocommerce-admin/zipball/aa5062218a399843e68160e1b4b884320a7530ae", - "reference": "aa5062218a399843e68160e1b4b884320a7530ae", + "url": "https://api.github.com/repos/woocommerce/woocommerce-admin/zipball/be22cb889e541caa9a38ec97182a004e9ab1a5c7", + "reference": "be22cb889e541caa9a38ec97182a004e9ab1a5c7", "shasum": "" }, "require": { @@ -462,20 +462,20 @@ ], "description": "A modern, javascript-driven WooCommerce Admin experience.", "homepage": "https://github.com/woocommerce/woocommerce-admin", - "time": "2020-05-08T22:39:16+00:00" + "time": "2020-06-16T02:44:45+00:00" }, { "name": "woocommerce/woocommerce-blocks", - "version": "v2.5.16", + "version": "v2.7.1", "source": { "type": "git", "url": "https://github.com/woocommerce/woocommerce-gutenberg-products-block.git", - "reference": "3bd91b669247000fd3f5277954701d0b148d3f1a" + "reference": "0025c5cda83892c6f566fffd05197006f230d16c" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/woocommerce/woocommerce-gutenberg-products-block/zipball/3bd91b669247000fd3f5277954701d0b148d3f1a", - "reference": "3bd91b669247000fd3f5277954701d0b148d3f1a", + "url": "https://api.github.com/repos/woocommerce/woocommerce-gutenberg-products-block/zipball/0025c5cda83892c6f566fffd05197006f230d16c", + "reference": "0025c5cda83892c6f566fffd05197006f230d16c", "shasum": "" }, "require": { @@ -509,20 +509,20 @@ "gutenberg", "woocommerce" ], - "time": "2020-04-07T11:47:19+00:00" + "time": "2020-06-16T13:34:29+00:00" }, { "name": "woocommerce/woocommerce-rest-api", - "version": "1.0.8", + "version": "1.0.10", "source": { "type": "git", "url": "https://github.com/woocommerce/woocommerce-rest-api.git", - "reference": "0756027c669bb5749554ee58b9416cbdcceaa752" + "reference": "fdcb116b4f5b699b942c01b46fd863c7da8b4b7c" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/woocommerce/woocommerce-rest-api/zipball/0756027c669bb5749554ee58b9416cbdcceaa752", - "reference": "0756027c669bb5749554ee58b9416cbdcceaa752", + "url": "https://api.github.com/repos/woocommerce/woocommerce-rest-api/zipball/fdcb116b4f5b699b942c01b46fd863c7da8b4b7c", + "reference": "fdcb116b4f5b699b942c01b46fd863c7da8b4b7c", "shasum": "" }, "require": { @@ -549,7 +549,7 @@ ], "description": "The WooCommerce core REST API.", "homepage": "https://github.com/woocommerce/woocommerce-rest-api", - "time": "2020-05-11T14:54:30+00:00" + "time": "2020-06-16T09:51:51+00:00" } ], "packages-dev": [ @@ -621,20 +621,20 @@ }, { "name": "doctrine/instantiator", - "version": "1.3.0", + "version": "1.3.1", "source": { "type": "git", "url": "https://github.com/doctrine/instantiator.git", - "reference": "ae466f726242e637cebdd526a7d991b9433bacf1" + "reference": "f350df0268e904597e3bd9c4685c53e0e333feea" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/doctrine/instantiator/zipball/ae466f726242e637cebdd526a7d991b9433bacf1", - "reference": "ae466f726242e637cebdd526a7d991b9433bacf1", + "url": "https://api.github.com/repos/doctrine/instantiator/zipball/f350df0268e904597e3bd9c4685c53e0e333feea", + "reference": "f350df0268e904597e3bd9c4685c53e0e333feea", "shasum": "" }, "require": { - "php": "^7.1" + "php": "^7.1 || ^8.0" }, "require-dev": { "doctrine/coding-standard": "^6.0", @@ -673,7 +673,7 @@ "constructor", "instantiate" ], - "time": "2019-10-21T16:45:58+00:00" + "time": "2020-05-29T17:27:14+00:00" }, { "name": "gettext/gettext", @@ -2414,7 +2414,7 @@ }, { "name": "symfony/finder", - "version": "v3.4.40", + "version": "v3.4.42", "source": { "type": "git", "url": "https://github.com/symfony/finder.git", @@ -2463,16 +2463,16 @@ }, { "name": "symfony/polyfill-ctype", - "version": "v1.16.0", + "version": "v1.17.0", "source": { "type": "git", "url": "https://github.com/symfony/polyfill-ctype.git", - "reference": "1aab00e39cebaef4d8652497f46c15c1b7e45294" + "reference": "e94c8b1bbe2bc77507a1056cdb06451c75b427f9" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/polyfill-ctype/zipball/1aab00e39cebaef4d8652497f46c15c1b7e45294", - "reference": "1aab00e39cebaef4d8652497f46c15c1b7e45294", + "url": "https://api.github.com/repos/symfony/polyfill-ctype/zipball/e94c8b1bbe2bc77507a1056cdb06451c75b427f9", + "reference": "e94c8b1bbe2bc77507a1056cdb06451c75b427f9", "shasum": "" }, "require": { @@ -2484,7 +2484,7 @@ "type": "library", "extra": { "branch-alias": { - "dev-master": "1.16-dev" + "dev-master": "1.17-dev" } }, "autoload": { @@ -2517,7 +2517,7 @@ "polyfill", "portable" ], - "time": "2020-05-08T16:50:20+00:00" + "time": "2020-05-12T16:14:59+00:00" }, { "name": "theseer/tokenizer", @@ -2561,16 +2561,16 @@ }, { "name": "webmozart/assert", - "version": "1.8.0", + "version": "1.9.0", "source": { "type": "git", "url": "https://github.com/webmozart/assert.git", - "reference": "ab2cb0b3b559010b75981b1bdce728da3ee90ad6" + "reference": "9dc4f203e36f2b486149058bade43c851dd97451" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/webmozart/assert/zipball/ab2cb0b3b559010b75981b1bdce728da3ee90ad6", - "reference": "ab2cb0b3b559010b75981b1bdce728da3ee90ad6", + "url": "https://api.github.com/repos/webmozart/assert/zipball/9dc4f203e36f2b486149058bade43c851dd97451", + "reference": "9dc4f203e36f2b486149058bade43c851dd97451", "shasum": "" }, "require": { @@ -2578,6 +2578,7 @@ "symfony/polyfill-ctype": "^1.8" }, "conflict": { + "phpstan/phpstan": "<0.12.20", "vimeo/psalm": "<3.9.1" }, "require-dev": { @@ -2605,7 +2606,7 @@ "check", "validate" ], - "time": "2020-04-18T12:12:48+00:00" + "time": "2020-06-16T10:16:42+00:00" }, { "name": "woocommerce/woocommerce-sniffs", @@ -2649,16 +2650,16 @@ }, { "name": "wp-cli/i18n-command", - "version": "v2.2.2", + "version": "v2.2.3", "source": { "type": "git", "url": "https://github.com/wp-cli/i18n-command.git", - "reference": "2804c5246d9338da59951737b03c54d257be8e47" + "reference": "7a5d483d872dfec1b89d88d348666ecd59454d52" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/wp-cli/i18n-command/zipball/2804c5246d9338da59951737b03c54d257be8e47", - "reference": "2804c5246d9338da59951737b03c54d257be8e47", + "url": "https://api.github.com/repos/wp-cli/i18n-command/zipball/7a5d483d872dfec1b89d88d348666ecd59454d52", + "reference": "7a5d483d872dfec1b89d88d348666ecd59454d52", "shasum": "" }, "require": { @@ -2702,7 +2703,7 @@ ], "description": "Provides internationalization tools for WordPress projects.", "homepage": "https://github.com/wp-cli/i18n-command", - "time": "2019-12-13T09:00:43+00:00" + "time": "2020-06-04T07:07:10+00:00" }, { "name": "wp-cli/mustangostang-spyc", @@ -2921,5 +2922,6 @@ "platform-dev": [], "platform-overrides": { "php": "7.1" - } + }, + "plugin-api-version": "1.1.0" } diff --git a/i18n/states.php b/i18n/states.php index 6361184ccc2..9c2a5ff6876 100644 --- a/i18n/states.php +++ b/i18n/states.php @@ -352,7 +352,6 @@ return array( 'GH' => array( // Ghanaian Regions. 'AF' => __( 'Ahafo', 'woocommerce' ), 'AH' => __( 'Ashanti', 'woocommerce' ), - 'AV' => __( 'Avannaata Kommunia', 'woocommerce' ), 'BA' => __( 'Brong-Ahafo', 'woocommerce' ), 'BO' => __( 'Bono', 'woocommerce' ), 'BE' => __( 'Bono East', 'woocommerce' ), @@ -716,6 +715,55 @@ return array( 'JP46' => __( 'Kagoshima', 'woocommerce' ), 'JP47' => __( 'Okinawa', 'woocommerce' ), ), + 'KE' => array( // Kenya counties. + 'KE01' => __( 'Baringo', 'woocommerce' ), + 'KE02' => __( 'Bomet', 'woocommerce' ), + 'KE03' => __( 'Bungoma', 'woocommerce' ), + 'KE04' => __( 'Busia', 'woocommerce' ), + 'KE05' => __( 'Elgeyo-Marakwet', 'woocommerce' ), + 'KE06' => __( 'Embu', 'woocommerce' ), + 'KE07' => __( 'Garissa', 'woocommerce' ), + 'KE08' => __( 'Homa Bay', 'woocommerce' ), + 'KE09' => __( 'Isiolo', 'woocommerce' ), + 'KE10' => __( 'Kajiado', 'woocommerce' ), + 'KE11' => __( 'Kakamega', 'woocommerce' ), + 'KE12' => __( 'Kericho', 'woocommerce' ), + 'KE13' => __( 'Kiambu', 'woocommerce' ), + 'KE14' => __( 'Kilifi', 'woocommerce' ), + 'KE15' => __( 'Kirinyaga', 'woocommerce' ), + 'KE16' => __( 'Kisii', 'woocommerce' ), + 'KE17' => __( 'Kisumu', 'woocommerce' ), + 'KE18' => __( 'Kitui', 'woocommerce' ), + 'KE19' => __( 'Kwale', 'woocommerce' ), + 'KE20' => __( 'Laikipia', 'woocommerce' ), + 'KE21' => __( 'Lamu', 'woocommerce' ), + 'KE22' => __( 'Machakos', 'woocommerce' ), + 'KE23' => __( 'Makueni', 'woocommerce' ), + 'KE24' => __( 'Mandera', 'woocommerce' ), + 'KE25' => __( 'Marsabit', 'woocommerce' ), + 'KE26' => __( 'Meru', 'woocommerce' ), + 'KE27' => __( 'Migori', 'woocommerce' ), + 'KE28' => __( 'Mombasa', 'woocommerce' ), + 'KE29' => __( 'Murang’a', 'woocommerce' ), + 'KE30' => __( 'Nairobi County', 'woocommerce' ), + 'KE31' => __( 'Nakuru', 'woocommerce' ), + 'KE32' => __( 'Nandi', 'woocommerce' ), + 'KE33' => __( 'Narok', 'woocommerce' ), + 'KE34' => __( 'Nyamira', 'woocommerce' ), + 'KE35' => __( 'Nyandarua', 'woocommerce' ), + 'KE36' => __( 'Nyeri', 'woocommerce' ), + 'KE37' => __( 'Samburu', 'woocommerce' ), + 'KE38' => __( 'Siaya', 'woocommerce' ), + 'KE39' => __( 'Taita-Taveta', 'woocommerce' ), + 'KE40' => __( 'Tana River', 'woocommerce' ), + 'KE41' => __( 'Tharaka-Nithi', 'woocommerce' ), + 'KE42' => __( 'Trans Nzoia', 'woocommerce' ), + 'KE43' => __( 'Turkana', 'woocommerce' ), + 'KE44' => __( 'Uasin Gishu', 'woocommerce' ), + 'KE45' => __( 'Vihiga', 'woocommerce' ), + 'KE46' => __( 'Wajir', 'woocommerce' ), + 'KE47' => __( 'West Pokot', 'woocommerce' ), + ), 'KR' => array(), 'KW' => array(), 'LA' => array( diff --git a/includes/abstracts/abstract-wc-order.php b/includes/abstracts/abstract-wc-order.php index 5e5f38f6d9f..9c0f2618f7e 100644 --- a/includes/abstracts/abstract-wc-order.php +++ b/includes/abstracts/abstract-wc-order.php @@ -437,12 +437,7 @@ abstract class WC_Abstract_Order extends WC_Abstract_Legacy_Order { * @return float */ public function get_subtotal() { - $subtotal = 0; - - foreach ( $this->get_items() as $item ) { - $subtotal += wc_remove_number_precision( self::round_item_subtotal( wc_add_number_precision( $item->get_subtotal() ) ) ); - } - + $subtotal = round( $this->get_cart_subtotal_for_order(), wc_get_price_decimals() ); return apply_filters( 'woocommerce_order_get_subtotal', (float) $subtotal, $this ); } @@ -1672,18 +1667,13 @@ abstract class WC_Abstract_Order extends WC_Abstract_Legacy_Order { public function calculate_totals( $and_taxes = true ) { do_action( 'woocommerce_order_before_calculate_totals', $and_taxes, $this ); - $cart_subtotal = 0; - $cart_total = 0; $fees_total = 0; $shipping_total = 0; $cart_subtotal_tax = 0; $cart_total_tax = 0; - // Sum line item costs without rounding. - foreach ( $this->get_items() as $item ) { - $cart_subtotal += $item->get_subtotal(); - $cart_total += $item->get_total(); - } + $cart_subtotal = $this->get_cart_subtotal_for_order(); + $cart_total = $this->get_cart_total_for_order(); // Sum shipping costs. foreach ( $this->get_shipping_methods() as $shipping ) { diff --git a/includes/abstracts/abstract-wc-settings-api.php b/includes/abstracts/abstract-wc-settings-api.php index 6e844fb4939..4fd19ca7041 100644 --- a/includes/abstracts/abstract-wc-settings-api.php +++ b/includes/abstracts/abstract-wc-settings-api.php @@ -708,7 +708,7 @@ abstract class WC_Settings_API { get_description_html( $data ); // WPCS: XSS ok. ?> @@ -761,11 +761,11 @@ abstract class WC_Settings_API { $option_value_inner ) : ?> - + - + diff --git a/includes/admin/class-wc-admin-dashboard.php b/includes/admin/class-wc-admin-dashboard.php index 9b5ef4941b3..28d1c6b0fe2 100644 --- a/includes/admin/class-wc-admin-dashboard.php +++ b/includes/admin/class-wc-admin-dashboard.php @@ -216,36 +216,61 @@ if ( ! class_exists( 'WC_Admin_Dashboard', false ) ) : $lowinstock_count = get_transient( $transient_name ); if ( false === $lowinstock_count ) { - $lowinstock_count = (int) $wpdb->get_var( - $wpdb->prepare( - "SELECT COUNT( product_id ) - FROM {$wpdb->wc_product_meta_lookup} AS lookup - INNER JOIN {$wpdb->posts} as posts ON lookup.product_id = posts.ID - WHERE stock_quantity <= %d - AND stock_quantity > %d - AND posts.post_status = 'publish'", - $stock, - $nostock - ) - ); - set_transient( $transient_name, $lowinstock_count, DAY_IN_SECONDS * 30 ); + /** + * Status widget low in stock count pre query. + * + * @since 4.3.0 + * @param null|string $low_in_stock_count Low in stock count, by default null. + * @param int $stock Low stock amount. + * @param int $nostock No stock amount + */ + $lowinstock_count = apply_filters( 'woocommerce_status_widget_low_in_stock_count_pre_query', null, $stock, $nostock ); + + if ( is_null( $lowinstock_count ) ) { + $lowinstock_count = $wpdb->get_var( + $wpdb->prepare( + "SELECT COUNT( product_id ) + FROM {$wpdb->wc_product_meta_lookup} AS lookup + INNER JOIN {$wpdb->posts} as posts ON lookup.product_id = posts.ID + WHERE stock_quantity <= %d + AND stock_quantity > %d + AND posts.post_status = 'publish'", + $stock, + $nostock + ) + ); + } + + set_transient( $transient_name, (int) $lowinstock_count, DAY_IN_SECONDS * 30 ); } $transient_name = 'wc_outofstock_count'; $outofstock_count = get_transient( $transient_name ); if ( false === $outofstock_count ) { - $outofstock_count = (int) $wpdb->get_var( - $wpdb->prepare( - "SELECT COUNT( product_id ) - FROM {$wpdb->wc_product_meta_lookup} AS lookup - INNER JOIN {$wpdb->posts} as posts ON lookup.product_id = posts.ID - WHERE stock_quantity <= %d - AND posts.post_status = 'publish'", - $nostock - ) - ); - set_transient( $transient_name, $outofstock_count, DAY_IN_SECONDS * 30 ); + /** + * Status widget out of stock count pre query. + * + * @since 4.3.0 + * @param null|string $outofstock_count Out of stock count, by default null. + * @param int $nostock No stock amount + */ + $outofstock_count = apply_filters( 'woocommerce_status_widget_out_of_stock_count_pre_query', null, $nostock ); + + if ( is_null( $outofstock_count ) ) { + $outofstock_count = (int) $wpdb->get_var( + $wpdb->prepare( + "SELECT COUNT( product_id ) + FROM {$wpdb->wc_product_meta_lookup} AS lookup + INNER JOIN {$wpdb->posts} as posts ON lookup.product_id = posts.ID + WHERE stock_quantity <= %d + AND posts.post_status = 'publish'", + $nostock + ) + ); + } + + set_transient( $transient_name, (int) $outofstock_count, DAY_IN_SECONDS * 30 ); } ?>
      • diff --git a/includes/admin/class-wc-admin-notices.php b/includes/admin/class-wc-admin-notices.php index fd61bf6c388..e6057d91c46 100644 --- a/includes/admin/class-wc-admin-notices.php +++ b/includes/admin/class-wc-admin-notices.php @@ -40,6 +40,7 @@ class WC_Admin_Notices { 'maxmind_license_key' => 'maxmind_missing_license_key_notice', 'redirect_download_method' => 'redirect_download_method_notice', 'uploads_directory_is_unprotected' => 'uploads_directory_is_unprotected_notice', + 'base_tables_missing' => 'base_tables_missing_notice', ); /** @@ -506,6 +507,21 @@ class WC_Admin_Notices { include dirname( __FILE__ ) . '/views/html-notice-uploads-directory-is-unprotected.php'; } + /** + * Notice about base tables missing. + */ + public static function base_tables_missing_notice() { + $notice_dismissed = apply_filters( + 'woocommerce_hide_base_tables_missing_nag', + get_user_meta( get_current_user_id(), 'dismissed_base_tables_missing_notice', true ) + ); + if ( $notice_dismissed ) { + self::remove_notice( 'base_tables_missing' ); + } + + include dirname( __FILE__ ) . '/views/html-notice-base-table-missing.php'; + } + /** * Determine if the store is running SSL. * @@ -568,7 +584,12 @@ class WC_Admin_Notices { $uploads = wp_get_upload_dir(); // Check for the "uploads/woocommerce_uploads" directory. - $response = wp_safe_remote_get( esc_url_raw( $uploads['baseurl'] . '/woocommerce_uploads' ) ); + $response = wp_safe_remote_get( + esc_url_raw( $uploads['baseurl'] . '/woocommerce_uploads/' ), + array( + 'redirection' => 0, + ) + ); $response_code = intval( wp_remote_retrieve_response_code( $response ) ); $response_content = wp_remote_retrieve_body( $response ); diff --git a/includes/admin/class-wc-admin-settings.php b/includes/admin/class-wc-admin-settings.php index d8c9d17b0a7..1d1a49b8311 100644 --- a/includes/admin/class-wc-admin-settings.php +++ b/includes/admin/class-wc-admin-settings.php @@ -869,25 +869,29 @@ if ( ! class_exists( 'WC_Admin_Settings', false ) ) : * If using force or x-sendfile, this ensures the .htaccess is in place. */ public static function check_download_folder_protection() { - $upload_dir = wp_upload_dir(); - $downloads_url = $upload_dir['basedir'] . '/woocommerce_uploads'; + $upload_dir = wp_get_upload_dir(); + $downloads_path = $upload_dir['basedir'] . '/woocommerce_uploads'; $download_method = get_option( 'woocommerce_file_download_method' ); + $file_path = $downloads_path . '/.htaccess'; + $file_content = 'redirect' === $download_method ? 'Options -Indexes' : 'deny from all'; + $create = false; - if ( 'redirect' === $download_method ) { - - // Redirect method - don't protect. - if ( file_exists( $downloads_url . '/.htaccess' ) ) { - unlink( $downloads_url . '/.htaccess' ); // @codingStandardsIgnoreLine - } + if ( wp_mkdir_p( $downloads_path ) && ! file_exists( $file_path ) ) { + $create = true; } else { + $current_content = @file_get_contents( $file_path ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged, WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents - // Force method - protect, add rules to the htaccess file. - if ( ! file_exists( $downloads_url . '/.htaccess' ) ) { - $file_handle = @fopen( $downloads_url . '/.htaccess', 'w' ); // @codingStandardsIgnoreLine - if ( $file_handle ) { - fwrite( $file_handle, 'deny from all' ); // @codingStandardsIgnoreLine - fclose( $file_handle ); // @codingStandardsIgnoreLine - } + if ( $current_content !== $file_content ) { + unlink( $file_path ); + $create = true; + } + } + + if ( $create ) { + $file_handle = @fopen( $file_path, 'wb' ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged, WordPress.WP.AlternativeFunctions.file_system_read_fopen + if ( $file_handle ) { + fwrite( $file_handle, $file_content ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_read_fwrite + fclose( $file_handle ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_read_fclose } } } diff --git a/includes/admin/class-wc-admin-status.php b/includes/admin/class-wc-admin-status.php index be40b97270a..23e670ec8d7 100644 --- a/includes/admin/class-wc-admin-status.php +++ b/includes/admin/class-wc-admin-status.php @@ -339,6 +339,33 @@ class WC_Admin_Status { } } + /** + * Prints table info if a base table is not present. + */ + private static function output_tables_info() { + $missing_tables = WC_Install::verify_base_tables( false ); + if ( 0 === count( $missing_tables ) ) { + return; + } + ?> + +
        + + + + + +

        -

        +

        diff --git a/includes/admin/list-tables/class-wc-admin-list-table-products.php b/includes/admin/list-tables/class-wc-admin-list-table-products.php index f864efa4e4d..8ac403273d5 100644 --- a/includes/admin/list-tables/class-wc-admin-list-table-products.php +++ b/includes/admin/list-tables/class-wc-admin-list-table-products.php @@ -351,7 +351,7 @@ class WC_Admin_List_Table_Products extends WC_Admin_List_Table { */ protected function render_products_type_filter() { $current_product_type = isset( $_REQUEST['product_type'] ) ? wc_clean( wp_unslash( $_REQUEST['product_type'] ) ) : false; // WPCS: input var ok, sanitization ok. - $output = ''; foreach ( wc_get_product_types() as $value => $label ) { $output .= ''; $output .= ''; } } diff --git a/includes/admin/meta-boxes/class-wc-meta-box-coupon-data.php b/includes/admin/meta-boxes/class-wc-meta-box-coupon-data.php index 243e6d1411c..c8b92d10e2a 100644 --- a/includes/admin/meta-boxes/class-wc-meta-box-coupon-data.php +++ b/includes/admin/meta-boxes/class-wc-meta-box-coupon-data.php @@ -194,7 +194,7 @@ class WC_Meta_Box_Coupon_Data { foreach ( $product_ids as $product_id ) { $product = wc_get_product( $product_id ); if ( is_object( $product ) ) { - echo ''; + echo ''; } } ?> @@ -212,7 +212,7 @@ class WC_Meta_Box_Coupon_Data { foreach ( $product_ids as $product_id ) { $product = wc_get_product( $product_id ); if ( is_object( $product ) ) { - echo ''; + echo ''; } } ?> diff --git a/includes/admin/meta-boxes/class-wc-meta-box-order-data.php b/includes/admin/meta-boxes/class-wc-meta-box-order-data.php index 62d929b2670..f5568ddb2d1 100644 --- a/includes/admin/meta-boxes/class-wc-meta-box-order-data.php +++ b/includes/admin/meta-boxes/class-wc-meta-box-order-data.php @@ -404,9 +404,9 @@ class WC_Meta_Box_Order_Data { } if ( ! $found_method && ! empty( $payment_method ) ) { - echo ''; + echo ''; } else { - echo ''; + echo ''; } ?> diff --git a/includes/admin/meta-boxes/class-wc-meta-box-product-data.php b/includes/admin/meta-boxes/class-wc-meta-box-product-data.php index a98b0f6c654..7bbbab50ab2 100644 --- a/includes/admin/meta-boxes/class-wc-meta-box-product-data.php +++ b/includes/admin/meta-boxes/class-wc-meta-box-product-data.php @@ -244,7 +244,7 @@ class WC_Meta_Box_Product_Data { continue; } $attribute_id = 0; - $attribute_name = wc_clean( $attribute_names[ $i ] ); + $attribute_name = wc_clean( esc_html( $attribute_names[ $i ] ) ); if ( 'pa_' === substr( $attribute_name, 0, 3 ) ) { $attribute_id = wc_attribute_taxonomy_id_by_name( $attribute_name ); @@ -257,7 +257,7 @@ class WC_Meta_Box_Product_Data { $options = wp_parse_id_list( $options ); } else { // Terms or text sent in textarea. - $options = 0 < $attribute_id ? wc_sanitize_textarea( wc_sanitize_term_text_based( $options ) ) : wc_sanitize_textarea( $options ); + $options = 0 < $attribute_id ? wc_sanitize_textarea( esc_html( wc_sanitize_term_text_based( $options ) ) ) : wc_sanitize_textarea( esc_html( $options ) ); $options = wc_get_text_attributes( $options ); } diff --git a/includes/admin/meta-boxes/views/html-product-attribute.php b/includes/admin/meta-boxes/views/html-product-attribute.php index d4a7910f2b1..2b987fce19d 100644 --- a/includes/admin/meta-boxes/views/html-product-attribute.php +++ b/includes/admin/meta-boxes/views/html-product-attribute.php @@ -49,7 +49,7 @@ if ( ! defined( 'ABSPATH' ) ) { foreach ( $all_terms as $term ) { $options = $attribute->get_options(); $options = ! empty( $options ) ? $options : array(); - echo ''; + echo ''; } } ?> diff --git a/includes/admin/meta-boxes/views/html-product-data-linked-products.php b/includes/admin/meta-boxes/views/html-product-data-linked-products.php index dfbdd2d17d2..2a7a0938db9 100644 --- a/includes/admin/meta-boxes/views/html-product-data-linked-products.php +++ b/includes/admin/meta-boxes/views/html-product-data-linked-products.php @@ -19,7 +19,7 @@ defined( 'ABSPATH' ) || exit; foreach ( $product_ids as $product_id ) { $product = wc_get_product( $product_id ); if ( is_object( $product ) ) { - echo ''; + echo ''; } } ?> @@ -37,7 +37,7 @@ defined( 'ABSPATH' ) || exit; foreach ( $product_ids as $product_id ) { $product = wc_get_product( $product_id ); if ( is_object( $product ) ) { - echo ''; + echo ''; } } ?> @@ -53,7 +53,7 @@ defined( 'ABSPATH' ) || exit; foreach ( $product_ids as $product_id ) { $product = wc_get_product( $product_id ); if ( is_object( $product ) ) { - echo ''; + echo ''; } } ?> diff --git a/includes/admin/notes/class-wc-notes-run-db-update.php b/includes/admin/notes/class-wc-notes-run-db-update.php index 9d8253640ef..6611f62b6dd 100644 --- a/includes/admin/notes/class-wc-notes-run-db-update.php +++ b/includes/admin/notes/class-wc-notes-run-db-update.php @@ -156,7 +156,6 @@ class WC_Notes_Run_Db_Update { . sprintf( ' ' . esc_html__( 'The database update process runs in the background and may take a little while, so please be patient. Advanced users can alternatively update via %1$sWP CLI%2$s.', 'woocommerce' ), '', '' ) ); $note->set_type( WC_Admin_Note::E_WC_ADMIN_NOTE_UPDATE ); - $note->set_icon( 'info' ); $note->set_name( self::NOTE_NAME ); $note->set_content_data( (object) array() ); $note->set_source( 'woocommerce-core' ); diff --git a/includes/admin/plugin-updates/class-wc-plugin-updates.php b/includes/admin/plugin-updates/class-wc-plugin-updates.php index fb838c726fa..fa64bcce0b4 100644 --- a/includes/admin/plugin-updates/class-wc-plugin-updates.php +++ b/includes/admin/plugin-updates/class-wc-plugin-updates.php @@ -45,13 +45,6 @@ class WC_Plugin_Updates { */ protected $major_untested_plugins = array(); - /** - * Array of plugins lacking testing with the minor version. - * - * @var array - */ - protected $minor_untested_plugins = array(); - /** * Common JS for initializing and managing thickbox-based modals. */ @@ -103,29 +96,6 @@ class WC_Plugin_Updates { | Methods for getting messages. */ - /** - * Get the inline warning notice for minor version updates. - * - * @return string - */ - protected function get_extensions_inline_warning_minor() { - $upgrade_type = 'minor'; - $plugins = ! empty( $this->major_untested_plugins ) ? array_diff_key( $this->minor_untested_plugins, $this->major_untested_plugins ) : $this->minor_untested_plugins; - $version_parts = explode( '.', $this->new_version ); - $new_version = $version_parts[0] . '.' . $version_parts[1]; - - if ( empty( $plugins ) ) { - return; - } - - /* translators: %s: version number */ - $message = sprintf( __( "Heads up! The versions of the following plugins you're running haven't been tested with the latest version of WooCommerce (%s).", 'woocommerce' ), $new_version ); - - ob_start(); - include 'views/html-notice-untested-extensions-inline.php'; - return ob_get_clean(); - } - /** * Get the inline warning notice for major version updates. * diff --git a/includes/admin/plugin-updates/class-wc-plugins-screen-updates.php b/includes/admin/plugin-updates/class-wc-plugins-screen-updates.php index f544f408582..a7a048db15a 100644 --- a/includes/admin/plugin-updates/class-wc-plugins-screen-updates.php +++ b/includes/admin/plugin-updates/class-wc-plugins-screen-updates.php @@ -45,7 +45,6 @@ class WC_Plugins_Screen_Updates extends WC_Plugin_Updates { $this->new_version = $response->new_version; $this->upgrade_notice = $this->get_upgrade_notice( $response->new_version ); $this->major_untested_plugins = $this->get_untested_plugins( $response->new_version, 'major' ); - $this->minor_untested_plugins = $this->get_untested_plugins( $response->new_version, 'minor' ); $current_version_parts = explode( '.', Constants::get_constant( 'WC_VERSION' ) ); $new_version_parts = explode( '.', $this->new_version ); @@ -59,10 +58,6 @@ class WC_Plugins_Screen_Updates extends WC_Plugin_Updates { $this->upgrade_notice .= $this->get_extensions_inline_warning_major(); } - if ( ! empty( $this->minor_untested_plugins ) ) { - $this->upgrade_notice .= $this->get_extensions_inline_warning_minor(); - } - if ( ! empty( $this->major_untested_plugins ) ) { $this->upgrade_notice .= $this->get_extensions_modal_warning(); add_action( 'admin_print_footer_scripts', array( $this, 'plugin_screen_modal_js' ) ); diff --git a/includes/admin/settings/class-wc-settings-advanced.php b/includes/admin/settings/class-wc-settings-advanced.php index 8fbcb5956b6..5056d4fdba8 100644 --- a/includes/admin/settings/class-wc-settings-advanced.php +++ b/includes/admin/settings/class-wc-settings-advanced.php @@ -42,6 +42,7 @@ class WC_Settings_Advanced extends WC_Settings_Page { 'webhooks' => __( 'Webhooks', 'woocommerce' ), 'legacy_api' => __( 'Legacy API', 'woocommerce' ), 'woocommerce_com' => __( 'WooCommerce.com', 'woocommerce' ), + 'features' => __( 'Features', 'woocommerce' ), ); return apply_filters( 'woocommerce_get_sections_' . $this->id, $sections ); @@ -397,6 +398,28 @@ class WC_Settings_Advanced extends WC_Settings_Page { ), ) ); + } elseif ( 'features' === $current_section ) { + $settings = apply_filters( + 'woocommerce_settings_features', + array( + array( + 'title' => __( 'Features', 'woocommerce' ), + 'type' => 'title', + 'desc' => __( 'Start using new features that are being progressively rolled out to improve the store management experience.', 'woocommerce' ), + 'id' => 'features_options', + ), + array( + 'title' => __( 'Home Screen', 'woocommerce' ), + 'desc' => __( 'Displays analytical insights, inbox notifications, and handy shortcuts in a single screen', 'woocommerce' ), + 'id' => 'woocommerce_homescreen_enabled', + 'type' => 'checkbox', + ), + array( + 'type' => 'sectionend', + 'id' => 'features_options', + ), + ) + ); } return apply_filters( 'woocommerce_get_settings_' . $this->id, $settings, $current_section ); diff --git a/includes/admin/settings/class-wc-settings-shipping.php b/includes/admin/settings/class-wc-settings-shipping.php index f34eb287011..11e66d59a5d 100644 --- a/includes/admin/settings/class-wc-settings-shipping.php +++ b/includes/admin/settings/class-wc-settings-shipping.php @@ -286,7 +286,7 @@ class WC_Settings_Shipping extends WC_Settings_Page { * Show zones */ protected function zones_screen() { - $method_count = wc_get_shipping_method_count(); + $method_count = wc_get_shipping_method_count( false, true ); wp_localize_script( 'wc-shipping-zones', diff --git a/includes/admin/settings/views/html-admin-page-shipping-zone-methods.php b/includes/admin/settings/views/html-admin-page-shipping-zone-methods.php index 4512a0adb41..8bc70e58312 100644 --- a/includes/admin/settings/views/html-admin-page-shipping-zone-methods.php +++ b/includes/admin/settings/views/html-admin-page-shipping-zone-methods.php @@ -189,7 +189,7 @@ if ( ! defined( 'ABSPATH' ) ) { if ( ! $method->supports( 'shipping-zones' ) ) { continue; } - echo '
        - +
        - + @@ -792,7 +799,7 @@ if ( 0 < count( $dropins_mu_plugins['mu_plugins'] ) ) : - + diff --git a/includes/admin/views/html-bulk-edit-product.php b/includes/admin/views/html-bulk-edit-product.php index 125fe1c14f9..5e81412b5bd 100644 --- a/includes/admin/views/html-bulk-edit-product.php +++ b/includes/admin/views/html-bulk-edit-product.php @@ -29,7 +29,7 @@ if ( ! defined( 'ABSPATH' ) ) { '3' => __( 'Decrease existing price by (fixed amount or %):', 'woocommerce' ), ); foreach ( $options as $key => $value ) { - echo ''; + echo ''; } ?> @@ -54,7 +54,7 @@ if ( ! defined( 'ABSPATH' ) ) { '4' => __( 'Set to regular price decreased by (fixed amount or %):', 'woocommerce' ), ); foreach ( $options as $key => $value ) { - echo ''; + echo ''; } ?> @@ -78,7 +78,7 @@ if ( ! defined( 'ABSPATH' ) ) { 'none' => _x( 'None', 'Tax status', 'woocommerce' ), ); foreach ( $options as $key => $value ) { - echo ''; + echo ''; } ?> @@ -104,7 +104,7 @@ if ( ! defined( 'ABSPATH' ) ) { } foreach ( $options as $key => $value ) { - echo ''; + echo ''; } ?> @@ -124,7 +124,7 @@ if ( ! defined( 'ABSPATH' ) ) { '1' => __( 'Change to:', 'woocommerce' ), ); foreach ( $options as $key => $value ) { - echo ''; + echo ''; } ?> @@ -148,7 +148,7 @@ if ( ! defined( 'ABSPATH' ) ) { '1' => __( 'Change to:', 'woocommerce' ), ); foreach ( $options as $key => $value ) { - echo ''; + echo ''; } ?> @@ -170,7 +170,7 @@ if ( ! defined( 'ABSPATH' ) ) { $value ) { - echo ''; + echo ''; } ?> @@ -190,7 +190,7 @@ if ( ! defined( 'ABSPATH' ) ) { 'hidden' => __( 'Hidden', 'woocommerce' ), ); foreach ( $options as $key => $value ) { - echo ''; + echo ''; } ?> @@ -207,7 +207,7 @@ if ( ! defined( 'ABSPATH' ) ) { 'no' => __( 'No', 'woocommerce' ), ); foreach ( $options as $key => $value ) { - echo ''; + echo ''; } ?> @@ -222,7 +222,7 @@ if ( ! defined( 'ABSPATH' ) ) { echo ''; foreach ( wc_get_product_stock_status_options() as $key => $value ) { - echo ''; + echo ''; } ?> @@ -241,7 +241,7 @@ if ( ! defined( 'ABSPATH' ) ) { 'no' => __( 'No', 'woocommerce' ), ); foreach ( $options as $key => $value ) { - echo ''; + echo ''; } ?> @@ -261,7 +261,7 @@ if ( ! defined( 'ABSPATH' ) ) { '3' => __( 'Decrease existing stock by:', 'woocommerce' ), ); foreach ( $options as $key => $value ) { - echo ''; + echo ''; } ?> @@ -280,7 +280,7 @@ if ( ! defined( 'ABSPATH' ) ) { echo ''; foreach ( wc_get_product_backorder_options() as $key => $value ) { - echo ''; + echo ''; } ?> diff --git a/includes/admin/views/html-notice-base-table-missing.php b/includes/admin/views/html-notice-base-table-missing.php new file mode 100644 index 00000000000..1a8859b122c --- /dev/null +++ b/includes/admin/views/html-notice-base-table-missing.php @@ -0,0 +1,43 @@ + +
        + + + + +

        + +

        +

        + Check again.', 'woocommerce' ), + esc_html( implode( ', ', $missing_tables ) ), + wp_nonce_url( admin_url( 'admin.php?page=wc-status&tab=tools&action=verify_db_tables' ), 'debug_action' ) + ) + ); + } else { + echo wp_kses_post( + sprintf( + /* translators: %1%s: Missing tables (seperated by ",") */ + __( 'One or more tables required for WooCommerce to function are missing, some features may not work as expected. Missing tables: %1$s.', 'woocommerce' ), + esc_html( implode( ', ', $missing_tables ) ) + ) + ); + } + ?> +

        +
        diff --git a/includes/class-wc-cart.php b/includes/class-wc-cart.php index 17378bfbf1b..4ca59ad0885 100644 --- a/includes/class-wc-cart.php +++ b/includes/class-wc-cart.php @@ -765,7 +765,6 @@ class WC_Cart extends WC_Legacy_Cart { public function check_cart_item_stock() { $error = new WP_Error(); $product_qty_in_cart = $this->get_cart_item_quantities(); - $hold_stock_minutes = (int) get_option( 'woocommerce_hold_stock_minutes', 0 ); $current_session_order_id = isset( WC()->session->order_awaiting_payment ) ? absint( WC()->session->order_awaiting_payment ) : 0; foreach ( $this->get_cart() as $cart_item_key => $values ) { @@ -784,7 +783,7 @@ class WC_Cart extends WC_Legacy_Cart { } // Check stock based on all items in the cart and consider any held stock within pending orders. - $held_stock = ( $hold_stock_minutes > 0 ) ? wc_get_held_stock_quantity( $product, $current_session_order_id ) : 0; + $held_stock = wc_get_held_stock_quantity( $product, $current_session_order_id ); $required_stock = $product_qty_in_cart[ $product->get_stock_managed_by_id() ]; if ( $product->get_stock_quantity() < ( $held_stock + $required_stock ) ) { diff --git a/includes/class-wc-checkout.php b/includes/class-wc-checkout.php index 5477531273d..6645d1f06cf 100644 --- a/includes/class-wc-checkout.php +++ b/includes/class-wc-checkout.php @@ -388,12 +388,30 @@ class WC_Checkout { // Save the order. $order_id = $order->save(); + /** + * Action hook fired after an order is created used to add custom meta to the order. + * + * @since 3.0.0 + */ do_action( 'woocommerce_checkout_update_order_meta', $order_id, $data ); + /** + * Action hook fired after an order is created. + * + * @since 4.3.0 + */ + do_action( 'woocommerce_checkout_order_created', $order ); + return $order_id; } catch ( Exception $e ) { if ( $order && $order instanceof WC_Order ) { $order->get_data_store()->release_held_coupons( $order ); + /** + * Action hook fired when an order is discarded due to Exception. + * + * @since 4.3.0 + */ + do_action( 'woocommerce_checkout_order_exception', $order ); } return new WP_Error( 'checkout-error', $e->getMessage() ); } diff --git a/includes/class-wc-comments.php b/includes/class-wc-comments.php index d39bb7b0a85..ab4e6945f01 100644 --- a/includes/class-wc-comments.php +++ b/includes/class-wc-comments.php @@ -146,7 +146,7 @@ class WC_Comments { */ public static function check_comment_rating( $comment_data ) { // If posting a comment (not trackback etc) and not logged in. - if ( ! is_admin() && isset( $_POST['comment_post_ID'], $_POST['rating'], $comment_data['comment_type'] ) && 'product' === get_post_type( absint( $_POST['comment_post_ID'] ) ) && empty( $_POST['rating'] ) && '' === $comment_data['comment_type'] && wc_review_ratings_enabled() && wc_review_ratings_required() ) { // WPCS: input var ok, CSRF ok. + if ( ! is_admin() && isset( $_POST['comment_post_ID'], $_POST['rating'], $comment_data['comment_type'] ) && 'product' === get_post_type( absint( $_POST['comment_post_ID'] ) ) && empty( $_POST['rating'] ) && self::is_default_comment_type( $comment_data['comment_type'] ) && wc_review_ratings_enabled() && wc_review_ratings_required() ) { // WPCS: input var ok, CSRF ok. wp_die( esc_html__( 'Please rate the product.', 'woocommerce' ) ); exit; } @@ -406,12 +406,26 @@ class WC_Comments { * @return array */ public static function update_comment_type( $comment_data ) { - if ( ! is_admin() && isset( $_POST['comment_post_ID'], $comment_data['comment_type'] ) && '' === $comment_data['comment_type'] && 'product' === get_post_type( absint( $_POST['comment_post_ID'] ) ) ) { // WPCS: input var ok, CSRF ok. + if ( ! is_admin() && isset( $_POST['comment_post_ID'], $comment_data['comment_type'] ) && self::is_default_comment_type( $comment_data['comment_type'] ) && 'product' === get_post_type( absint( $_POST['comment_post_ID'] ) ) ) { // WPCS: input var ok, CSRF ok. $comment_data['comment_type'] = 'review'; } return $comment_data; } + + /** + * Determines if a comment is of the default type. + * + * Prior to WordPress 5.5, '' was the default comment type. + * As of 5.5, the default type is 'comment'. + * + * @since 4.3.0 + * @param string $comment_type Comment type. + * @return bool + */ + private static function is_default_comment_type( $comment_type ) { + return ( '' === $comment_type || 'comment' === $comment_type ); + } } WC_Comments::init(); diff --git a/includes/class-wc-countries.php b/includes/class-wc-countries.php index 405a0d26cc7..7c0bb934c7c 100644 --- a/includes/class-wc-countries.php +++ b/includes/class-wc-countries.php @@ -474,7 +474,7 @@ class WC_Countries { echo ' selected="selected"'; } - echo '>' . esc_html( $value ) . ' — ' . ( $escape ? esc_js( $state_value ) : $state_value ) . ''; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped + echo '>' . esc_html( $value ) . ' — ' . ( $escape ? esc_html( $state_value ) : $state_value ) . ''; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped } echo ''; @@ -483,7 +483,7 @@ class WC_Countries { if ( $selected_country === $key && '*' === $selected_state ) { echo ' selected="selected"'; } - echo ' value="' . esc_attr( $key ) . '">' . ( $escape ? esc_js( $value ) : $value ) . ''; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped + echo ' value="' . esc_attr( $key ) . '">' . ( $escape ? esc_html( $value ) : $value ) . ''; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped } } } diff --git a/includes/class-wc-form-handler.php b/includes/class-wc-form-handler.php index ea62645c57d..80a4336aba5 100644 --- a/includes/class-wc-form-handler.php +++ b/includes/class-wc-form-handler.php @@ -869,11 +869,12 @@ class WC_Form_Handler { */ private static function add_to_cart_handler_variable( $product_id ) { try { - $variation_id = empty( $_REQUEST['variation_id'] ) ? '' : absint( wp_unslash( $_REQUEST['variation_id'] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended - $quantity = empty( $_REQUEST['quantity'] ) ? 1 : wc_stock_amount( wp_unslash( $_REQUEST['quantity'] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended - $missing_attributes = array(); - $variations = array(); - $adding_to_cart = wc_get_product( $product_id ); + $variation_id = empty( $_REQUEST['variation_id'] ) ? '' : absint( wp_unslash( $_REQUEST['variation_id'] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended + $quantity = empty( $_REQUEST['quantity'] ) ? 1 : wc_stock_amount( wp_unslash( $_REQUEST['quantity'] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended + $missing_attributes = array(); + $variations = array(); + $variation_attributes = array(); + $adding_to_cart = wc_get_product( $product_id ); if ( ! $adding_to_cart ) { return false; @@ -881,6 +882,9 @@ class WC_Form_Handler { // If the $product_id was in fact a variation ID, update the variables. if ( $adding_to_cart->is_type( 'variation' ) ) { + $variation_attributes = $adding_to_cart->get_variation_attributes(); + // Filter out 'any' variations, which are empty, as they need to be explicitly specified while adding to cart. + $variation_attributes = array_filter( $variation_attributes ); $variation_id = $product_id; $product_id = $adding_to_cart->get_parent_id(); $adding_to_cart = wc_get_product( $product_id ); @@ -911,6 +915,9 @@ class WC_Form_Handler { } } + // Merge variation attributes and posted attributes. + $posted_and_variation_attributes = array_merge( $variation_attributes, $posted_attributes ); + // If no variation ID is set, attempt to get a variation ID from posted attributes. if ( empty( $variation_id ) ) { $data_store = WC_Data_Store::load( 'product' ); @@ -939,8 +946,8 @@ class WC_Form_Handler { * * If no attribute was posted, only error if the variation has an 'any' attribute which requires a value. */ - if ( isset( $posted_attributes[ $attribute_key ] ) ) { - $value = $posted_attributes[ $attribute_key ]; + if ( isset( $posted_and_variation_attributes[ $attribute_key ] ) ) { + $value = $posted_and_variation_attributes[ $attribute_key ]; // Allow if valid or show error. if ( $valid_value === $value ) { diff --git a/includes/class-wc-install.php b/includes/class-wc-install.php index a219d7d8323..409a5567de4 100644 --- a/includes/class-wc-install.php +++ b/includes/class-wc-install.php @@ -287,6 +287,7 @@ class WC_Install { WC()->wpdb_table_fix(); self::remove_admin_notices(); self::create_tables(); + self::verify_base_tables(); self::create_options(); self::create_roles(); self::setup_environment(); @@ -296,6 +297,7 @@ class WC_Install { self::maybe_enable_setup_wizard(); self::update_wc_version(); self::maybe_update_db_version(); + self::maybe_enable_homescreen(); delete_transient( 'wc_installing' ); @@ -303,6 +305,54 @@ class WC_Install { do_action( 'woocommerce_installed' ); } + /** + * Check if all the base tables are present. + * + * @param bool $modify_notice Whether to modify notice based on if all tables are present. + * @param bool $execute Whether to execute get_schema queries as well. + * + * @return array List of querues. + */ + public static function verify_base_tables( $modify_notice = true, $execute = false ) { + require_once ABSPATH . 'wp-admin/includes/upgrade.php'; + + if ( $execute ) { + self::create_tables(); + } + $queries = dbDelta( self::get_schema(), false ); + $missing_tables = array(); + foreach ( $queries as $table_name => $result ) { + if ( "Created table $table_name" === $result ) { + $missing_tables[] = $table_name; + } + } + + if ( 0 < count( $missing_tables ) ) { + if ( $modify_notice ) { + WC_Admin_Notices::add_notice( 'base_tables_missing' ); + } + update_option( 'woocommerce_schema_missing_tables', $missing_tables ); + } else { + if ( $modify_notice ) { + WC_Admin_Notices::remove_notice( 'base_tables_missing' ); + } + update_option( 'woocommerce_schema_version', WC()->db_version ); + delete_option( 'woocommerce_schema_missing_tables' ); + } + return $missing_tables; + } + + /** + * Check if the homepage should be enabled and set the appropriate option if thats the case. + * + * @since 4.3.0 + */ + private static function maybe_enable_homescreen() { + if ( self::is_new_install() && ! get_option( 'woocommerce_homescreen_enabled' ) ) { + add_option( 'woocommerce_homescreen_enabled', 'yes' ); + } + } + /** * Reset any notices added to admin. * @@ -621,6 +671,11 @@ class WC_Install { /** * Set up the database tables which the plugin needs to function. + * WARNING: If you are modifying this method, make sure that its safe to call regardless of the state of database. + * + * This is called from `install` method and is executed in-sync when WC is installed or updated. This can also be called optionally from `verify_base_tables`. + * + * TODO: Add all crucial tables that we have created from workers in the past. * * Tables: * woocommerce_attribute_taxonomies - Table for storing attribute taxonomies - these are user defined @@ -946,6 +1001,14 @@ CREATE TABLE {$wpdb->prefix}wc_tax_rate_classes ( slug varchar(200) NOT NULL DEFAULT '', PRIMARY KEY (tax_rate_class_id), UNIQUE KEY slug (slug($max_index_length)) +) $collate; +CREATE TABLE {$wpdb->prefix}wc_reserved_stock ( + `order_id` bigint(20) NOT NULL, + `product_id` bigint(20) NOT NULL, + `stock_quantity` double NOT NULL DEFAULT 0, + `timestamp` datetime NOT NULL DEFAULT '0000-00-00 00:00:00', + `expires` datetime NOT NULL DEFAULT '0000-00-00 00:00:00', + PRIMARY KEY (`order_id`, `product_id`) ) $collate; "; @@ -980,6 +1043,7 @@ CREATE TABLE {$wpdb->prefix}wc_tax_rate_classes ( "{$wpdb->prefix}woocommerce_shipping_zones", "{$wpdb->prefix}woocommerce_tax_rate_locations", "{$wpdb->prefix}woocommerce_tax_rates", + "{$wpdb->prefix}wc_reserved_stock", ); /** @@ -1187,7 +1251,7 @@ CREATE TABLE {$wpdb->prefix}wc_tax_rate_classes ( } // Install files and folders for uploading files and prevent hotlinking. - $upload_dir = wp_upload_dir(); + $upload_dir = wp_get_upload_dir(); $download_method = get_option( 'woocommerce_file_download_method', 'force' ); $files = array( @@ -1206,19 +1270,16 @@ CREATE TABLE {$wpdb->prefix}wc_tax_rate_classes ( 'file' => 'index.html', 'content' => '', ), - ); - - if ( 'redirect' !== $download_method ) { - $files[] = array( + array( 'base' => $upload_dir['basedir'] . '/woocommerce_uploads', 'file' => '.htaccess', - 'content' => 'deny from all', - ); - } + 'content' => 'redirect' === $download_method ? 'Options -Indexes' : 'deny from all', + ), + ); foreach ( $files as $file ) { if ( wp_mkdir_p( $file['base'] ) && ! file_exists( trailingslashit( $file['base'] ) . $file['file'] ) ) { - $file_handle = @fopen( trailingslashit( $file['base'] ) . $file['file'], 'w' ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged, WordPress.WP.AlternativeFunctions.file_system_read_fopen + $file_handle = @fopen( trailingslashit( $file['base'] ) . $file['file'], 'wb' ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged, WordPress.WP.AlternativeFunctions.file_system_read_fopen if ( $file_handle ) { fwrite( $file_handle, $file['content'] ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_read_fwrite fclose( $file_handle ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_read_fclose diff --git a/includes/class-wc-post-types.php b/includes/class-wc-post-types.php index 7de16656db5..ab9dcbc07d2 100644 --- a/includes/class-wc-post-types.php +++ b/includes/class-wc-post-types.php @@ -59,6 +59,7 @@ class WC_Post_Types { 'query_var' => is_admin(), 'rewrite' => false, 'public' => false, + 'label' => _x( 'Product type', 'Taxonomy name', 'woocommerce' ), ) ) ); @@ -75,6 +76,7 @@ class WC_Post_Types { 'query_var' => is_admin(), 'rewrite' => false, 'public' => false, + 'label' => _x( 'Product visibility', 'Taxonomy name', 'woocommerce' ), ) ) ); diff --git a/includes/class-wc-shipping.php b/includes/class-wc-shipping.php index 8027b84a693..a803c400f2f 100644 --- a/includes/class-wc-shipping.php +++ b/includes/class-wc-shipping.php @@ -332,7 +332,26 @@ class WC_Shipping { if ( ! is_array( $stored_rates ) || $package_hash !== $stored_rates['package_hash'] || 'yes' === get_option( 'woocommerce_shipping_debug_mode', 'no' ) ) { foreach ( $this->load_shipping_methods( $package ) as $shipping_method ) { if ( ! $shipping_method->supports( 'shipping-zones' ) || $shipping_method->get_instance_id() ) { - $package['rates'] = $package['rates'] + $shipping_method->get_rates_for_package( $package ); // + instead of array_merge maintains numeric keys + /** + * Fires before getting shipping rates for a package. + * + * @since 4.3.0 + * @param array $package Package of cart items. + * @param WC_Shipping_Method $shipping_method Shipping method instance. + */ + do_action( 'woocommerce_before_get_rates_for_package', $package, $shipping_method ); + + // Use + instead of array_merge to maintain numeric keys. + $package['rates'] = $package['rates'] + $shipping_method->get_rates_for_package( $package ); + + /** + * Fires after getting shipping rates for a package. + * + * @since 4.3.0 + * @param array $package Package of cart items. + * @param WC_Shipping_Method $shipping_method Shipping method instance. + */ + do_action( 'woocommerce_after_get_rates_for_package', $package, $shipping_method ); } } diff --git a/includes/class-woocommerce.php b/includes/class-woocommerce.php index 6b1b3334185..42c78cd5c9e 100644 --- a/includes/class-woocommerce.php +++ b/includes/class-woocommerce.php @@ -22,6 +22,15 @@ final class WooCommerce { */ public $version = '4.3.0'; + /** + * WooCommerce Schema version. + * + * @since 4.3 started with version string 430. + * + * @var string + */ + public $db_version = '430'; + /** * The single instance of the class. * @@ -229,7 +238,7 @@ final class WooCommerce { $this->define( 'WC_LOG_DIR', $upload_dir['basedir'] . '/wc-logs/' ); $this->define( 'WC_SESSION_CACHE_GROUP', 'wc_session_id' ); $this->define( 'WC_TEMPLATE_DEBUG_MODE', false ); - $this->define( 'WC_NOTICE_MIN_PHP_VERSION', '7.0' ); + $this->define( 'WC_NOTICE_MIN_PHP_VERSION', '7.2' ); $this->define( 'WC_NOTICE_MIN_WP_VERSION', '5.2' ); $this->define( 'WC_PHP_MIN_REQUIREMENTS_NOTICE', 'wp_php_min_requirements_' . WC_NOTICE_MIN_PHP_VERSION . '_' . WC_NOTICE_MIN_WP_VERSION ); } @@ -246,6 +255,7 @@ final class WooCommerce { 'order_itemmeta' => 'woocommerce_order_itemmeta', 'wc_product_meta_lookup' => 'wc_product_meta_lookup', 'wc_tax_rate_classes' => 'wc_tax_rate_classes', + 'wc_reserved_stock' => 'wc_reserved_stock', ); foreach ( $tables as $name => $table ) { diff --git a/includes/data-stores/class-wc-product-data-store-cpt.php b/includes/data-stores/class-wc-product-data-store-cpt.php index 6c2baf5afff..e417c1d9c6a 100644 --- a/includes/data-stores/class-wc-product-data-store-cpt.php +++ b/includes/data-stores/class-wc-product-data-store-cpt.php @@ -881,8 +881,8 @@ class WC_Product_Data_Store_CPT extends WC_Data_Store_WP implements WC_Object_Da $outofstock_where = ' AND exclude_join.object_id IS NULL'; } + // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared return $wpdb->get_results( - // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared " SELECT posts.ID as id, posts.post_parent as parent_id FROM {$wpdb->posts} AS posts @@ -900,8 +900,8 @@ class WC_Product_Data_Store_CPT extends WC_Data_Store_WP implements WC_Object_Da ) GROUP BY posts.ID " - // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared ); + // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared } /** @@ -1603,7 +1603,7 @@ class WC_Product_Data_Store_CPT extends WC_Data_Store_WP implements WC_Object_Da foreach ( $search_terms as $search_term ) { $like = '%' . $wpdb->esc_like( $search_term ) . '%'; - $term_group_query .= $wpdb->prepare( " {$searchand} ( ( posts.post_title LIKE %s) OR ( posts.post_excerpt LIKE %s) OR ( posts.post_content LIKE %s ) OR ( wc_product_meta_lookup.sku LIKE %s ) )", $like, $like, $like, $like ); // @codingStandardsIgnoreLine. + $term_group_query .= $wpdb->prepare( " {$searchand} ( ( posts.post_title LIKE %s) OR ( posts.post_excerpt LIKE %s) OR ( posts.post_content LIKE %s ) OR ( wc_product_meta_lookup.sku LIKE %s ) )", $like, $like, $like, $like ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared $searchand = ' AND '; } @@ -2062,4 +2062,23 @@ class WC_Product_Data_Store_CPT extends WC_Data_Store_WP implements WC_Object_Da } return ''; } + + /** + * Returns query statement for getting current `_stock` of a product. + * + * @internal MAX function below is used to make sure result is a scalar. + * @param int $product_id Product ID. + * @return string|void Query statement. + */ + public function get_query_for_stock( $product_id ) { + global $wpdb; + return $wpdb->prepare( + " + SELECT COALESCE ( MAX( meta_value ), 0 ) FROM $wpdb->postmeta as meta_table + WHERE meta_table.meta_key = '_stock' + AND meta_table.post_id = %d + ", + $product_id + ); + } } diff --git a/includes/export/class-wc-product-csv-exporter.php b/includes/export/class-wc-product-csv-exporter.php index 78c92c9f857..53b7242251f 100644 --- a/includes/export/class-wc-product-csv-exporter.php +++ b/includes/export/class-wc-product-csv-exporter.php @@ -656,10 +656,10 @@ class WC_Product_CSV_Exporter extends WC_CSV_Batch_Exporter { if ( 0 === strpos( $attribute_name, 'pa_' ) ) { $option_term = get_term_by( 'slug', $attribute, $attribute_name ); // @codingStandardsIgnoreLine. - $row[ 'attributes:value' . $i ] = $option_term && ! is_wp_error( $option_term ) ? str_replace( ',', '\\,', $option_term->name ) : $attribute; + $row[ 'attributes:value' . $i ] = $option_term && ! is_wp_error( $option_term ) ? str_replace( ',', '\\,', $option_term->name ) : str_replace( ',', '\\,', $attribute ); $row[ 'attributes:taxonomy' . $i ] = 1; } else { - $row[ 'attributes:value' . $i ] = $attribute; + $row[ 'attributes:value' . $i ] = str_replace( ',', '\\,', $attribute ); $row[ 'attributes:taxonomy' . $i ] = 0; } diff --git a/includes/import/class-wc-product-csv-importer.php b/includes/import/class-wc-product-csv-importer.php index 14eddea04a1..06a8bb3e8bc 100644 --- a/includes/import/class-wc-product-csv-importer.php +++ b/includes/import/class-wc-product-csv-importer.php @@ -400,21 +400,22 @@ class WC_Product_CSV_Importer extends WC_Product_Importer { $total = count( $_terms ); foreach ( $_terms as $index => $_term ) { - // Check if category exists. Parent must be empty string or null if doesn't exists. - $term = term_exists( $_term, 'product_cat', $parent ); - - if ( is_array( $term ) ) { - $term_id = $term['term_id']; - // Don't allow users without capabilities to create new categories. - } elseif ( ! current_user_can( 'manage_product_terms' ) ) { + // Don't allow users without capabilities to create new categories. + if ( ! current_user_can( 'manage_product_terms' ) ) { break; - } else { - $term = wp_insert_term( $_term, 'product_cat', array( 'parent' => intval( $parent ) ) ); + } - if ( is_wp_error( $term ) ) { - break; // We cannot continue if the term cannot be inserted. + $term = wp_insert_term( $_term, 'product_cat', array( 'parent' => intval( $parent ) ) ); + + if ( is_wp_error( $term ) ) { + if ( $term->get_error_code() === 'term_exists' ) { + // When term exists, error data should contain existing term id. + $term_id = $term->get_error_data(); + } else { + break; // We cannot continue on any other error. } - + } else { + // New term. $term_id = $term['term_id']; } diff --git a/includes/shortcodes/class-wc-shortcode-checkout.php b/includes/shortcodes/class-wc-shortcode-checkout.php index 6316d07e2f8..31413213a72 100644 --- a/includes/shortcodes/class-wc-shortcode-checkout.php +++ b/includes/shortcodes/class-wc-shortcode-checkout.php @@ -84,9 +84,8 @@ class WC_Shortcode_Checkout { // Pay for existing order. if ( isset( $_GET['pay_for_order'], $_GET['key'] ) && $order_id ) { // WPCS: input var ok, CSRF ok. try { - $order_key = isset( $_GET['key'] ) ? wc_clean( wp_unslash( $_GET['key'] ) ) : ''; // WPCS: input var ok, CSRF ok. - $order = wc_get_order( $order_id ); - $hold_stock_minutes = (int) get_option( 'woocommerce_hold_stock_minutes', 0 ); + $order_key = isset( $_GET['key'] ) ? wc_clean( wp_unslash( $_GET['key'] ) ) : ''; // WPCS: input var ok, CSRF ok. + $order = wc_get_order( $order_id ); // Order or payment link is invalid. if ( ! $order || $order->get_id() !== $order_id || ! hash_equals( $order->get_order_key(), $order_key ) ) { @@ -158,7 +157,7 @@ class WC_Shortcode_Checkout { } // Check stock based on all items in the cart and consider any held stock within pending orders. - $held_stock = ( $hold_stock_minutes > 0 ) ? wc_get_held_stock_quantity( $product, $order->get_id() ) : 0; + $held_stock = wc_get_held_stock_quantity( $product, $order->get_id() ); $required_stock = $quantities[ $product->get_stock_managed_by_id() ]; if ( ! apply_filters( 'woocommerce_pay_order_product_has_enough_stock', ( $product->get_stock_quantity() >= ( $held_stock + $required_stock ) ), $product, $order ) ) { diff --git a/includes/shortcodes/class-wc-shortcode-products.php b/includes/shortcodes/class-wc-shortcode-products.php index 4e31f8418ef..b195676a607 100644 --- a/includes/shortcodes/class-wc-shortcode-products.php +++ b/includes/shortcodes/class-wc-shortcode-products.php @@ -507,7 +507,7 @@ class WC_Shortcode_Products { } /** - * Set product as visible when quering for hidden products. + * Set product as visible when querying for hidden products. * * @since 3.2.0 * @param bool $visibility Product visibility. diff --git a/includes/tracks/class-wc-site-tracking.php b/includes/tracks/class-wc-site-tracking.php index 82697a05791..1890045fd9c 100644 --- a/includes/tracks/class-wc-site-tracking.php +++ b/includes/tracks/class-wc-site-tracking.php @@ -44,17 +44,18 @@ class WC_Site_Tracking { return true; } + /** + * Register scripts required to record events from javascript. + */ + public static function register_scripts() { + wp_register_script( 'woo-tracks', 'https://stats.wp.com/w.js', array( 'wp-hooks' ), gmdate( 'YW' ), false ); + } + /** * Add scripts required to record events from javascript. */ public static function enqueue_scripts() { - - // Add w.js to the page. - wp_enqueue_script( 'woo-tracks', 'https://stats.wp.com/w.js', array( 'wp-hooks' ), gmdate( 'YW' ), false ); - - // Expose tracking via a function in the wcTracks global namespace directly before wc_print_js. - add_filter( 'admin_footer', array( __CLASS__, 'add_tracking_function' ), 24 ); - + wp_enqueue_script( 'woo-tracks' ); } /** @@ -65,7 +66,12 @@ class WC_Site_Tracking { customer->get_taxable_address(); /* translators: %s: country name */ $estimated_text = WC()->customer->is_customer_outside_base() && ! WC()->customer->has_calculated_shipping() ? sprintf( ' ' . __( 'estimated for %s', 'woocommerce' ), WC()->countries->estimated_for_prefix( $taxable_address[0] ) . WC()->countries->countries[ $taxable_address[0] ] ) : ''; - /* translators: %s: tax information */ - $value .= '' . sprintf( __( '(includes %s)', 'woocommerce' ), implode( ', ', $tax_string_array ) . $estimated_text ) . ''; + $value .= '(' + /* translators: includes tax information */ + . esc_html__( 'includes', 'woocommerce' ) + . ' ' + . wp_kses_post( implode( ', ', $tax_string_array ) ) + . esc_html( $estimated_text ) + . ')'; } } diff --git a/includes/wc-core-functions.php b/includes/wc-core-functions.php index e197a0ea64c..d8a336ee747 100644 --- a/includes/wc-core-functions.php +++ b/includes/wc-core-functions.php @@ -150,6 +150,86 @@ function wc_update_order( $args ) { return wc_create_order( $args ); } +/** + * Given a path, this will convert any of the subpaths into their corresponding tokens. + * + * @since 4.3.0 + * @param string $path The absolute path to tokenize. + * @param array $path_tokens An array keyed with the token, containing paths that should be replaced. + * @return string The tokenized path. + */ +function wc_tokenize_path( $path, $path_tokens ) { + // Order most to least specific so that the token can encompass as much of the path as possible. + uasort( + $path_tokens, + function ( $a, $b ) { + $a = strlen( $a ); + $b = strlen( $b ); + + if ( $a > $b ) { + return -1; + } + + if ( $b > $a ) { + return 1; + } + + return 0; + } + ); + + foreach ( $path_tokens as $token => $token_path ) { + if ( 0 !== strpos( $path, $token_path ) ) { + continue; + } + + $path = str_replace( $token_path, '{{' . $token . '}}', $path ); + } + + return $path; +} + +/** + * Given a tokenized path, this will expand the tokens to their full path. + * + * @since 4.3.0 + * @param string $path The absolute path to expand. + * @param array $path_tokens An array keyed with the token, containing paths that should be expanded. + * @return string The absolute path. + */ +function wc_untokenize_path( $path, $path_tokens ) { + foreach ( $path_tokens as $token => $token_path ) { + $path = str_replace( '{{' . $token . '}}', $token_path, $path ); + } + + return $path; +} + +/** + * Fetches an array containing all of the configurable path constants to be used in tokenization. + * + * @return array The key is the define and the path is the constant. + */ +function wc_get_path_define_tokens() { + $defines = array( + 'ABSPATH', + 'WP_CONTENT_DIR', + 'WP_PLUGIN_DIR', + 'WPMU_PLUGIN_DIR', + 'PLUGINDIR', + 'WP_THEME_DIR', + ); + + $path_tokens = array(); + foreach ( $defines as $define ) { + if ( defined( $define ) ) { + $path_tokens[ $define ] = constant( $define ); + } + } + + return apply_filters( 'woocommerce_get_path_define_tokens', $path_tokens ); +} + /** * Get template part (for templates like the shop-loop). * @@ -187,7 +267,13 @@ function wc_get_template_part( $slug, $name = '' ) { ); } - wp_cache_set( $cache_key, $template, 'woocommerce' ); + // Don't cache the absolute path so that it can be shared between web servers with different paths. + $cache_path = wc_tokenize_path( $template, wc_get_path_define_tokens() ); + + wc_set_template_cache( $cache_key, $cache_path ); + } else { + // Make sure that the absolute path to the template is resolved. + $template = wc_untokenize_path( $template, wc_get_path_define_tokens() ); } // Allow 3rd party plugins to filter template file from their plugin. @@ -212,7 +298,14 @@ function wc_get_template( $template_name, $args = array(), $template_path = '', if ( ! $template ) { $template = wc_locate_template( $template_name, $template_path, $default_path ); - wp_cache_set( $cache_key, $template, 'woocommerce' ); + + // Don't cache the absolute path so that it can be shared between web servers with different paths. + $cache_path = wc_tokenize_path( $template, wc_get_path_define_tokens() ); + + wc_set_template_cache( $cache_key, $cache_path ); + } else { + // Make sure that the absolute path to the template is resolved. + $template = wc_untokenize_path( $template, wc_get_path_define_tokens() ); } // Allow 3rd party plugin filter template file from their plugin. @@ -310,6 +403,42 @@ function wc_locate_template( $template_name, $template_path = '', $default_path return apply_filters( 'woocommerce_locate_template', $template, $template_name, $template_path ); } +/** + * Add a template to the template cache. + * + * @since 4.3.0 + * @param string $cache_key Object cache key. + * @param string $template Located template. + */ +function wc_set_template_cache( $cache_key, $template ) { + wp_cache_set( $cache_key, $template, 'woocommerce' ); + + $cached_templates = wp_cache_get( 'cached_templates', 'woocommerce' ); + if ( is_array( $cached_templates ) ) { + $cached_templates[] = $cache_key; + } else { + $cached_templates = array( $cache_key ); + } + + wp_cache_set( 'cached_templates', $cached_templates, 'woocommerce' ); +} + +/** + * Clear the template cache. + * + * @since 4.3.0 + */ +function wc_clear_template_cache() { + $cached_templates = wp_cache_get( 'cached_templates', 'woocommerce' ); + if ( is_array( $cached_templates ) ) { + foreach ( $cached_templates as $cache_key ) { + wp_cache_delete( $cache_key, 'woocommerce' ); + } + + wp_cache_delete( 'cached_templates', 'woocommerce' ); + } +} + /** * Get Base Currency Code. * @@ -1493,9 +1622,12 @@ function wc_postcode_location_matcher( $postcode, $objects, $object_id_key, $obj * * @since 2.6.0 * @param bool $include_legacy Count legacy shipping methods too. + * @param bool $enabled_only Whether non-legacy shipping methods should be + * restricted to enabled ones. It doesn't affect + * legacy shipping methods. @since 4.3.0. * @return int */ -function wc_get_shipping_method_count( $include_legacy = false ) { +function wc_get_shipping_method_count( $include_legacy = false, $enabled_only = false ) { global $wpdb; $transient_name = $include_legacy ? 'wc_shipping_method_count_legacy' : 'wc_shipping_method_count'; @@ -1506,7 +1638,8 @@ function wc_get_shipping_method_count( $include_legacy = false ) { return absint( $transient_value['value'] ); } - $method_count = absint( $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->prefix}woocommerce_shipping_zone_methods" ) ); + $where_clause = $enabled_only ? 'WHERE is_enabled=1' : ''; + $method_count = absint( $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->prefix}woocommerce_shipping_zone_methods ${where_clause}" ) ); if ( $include_legacy ) { // Count activated methods that don't support shipping zones. diff --git a/includes/wc-formatting-functions.php b/includes/wc-formatting-functions.php index 967bb207f34..cc5d0f6872d 100644 --- a/includes/wc-formatting-functions.php +++ b/includes/wc-formatting-functions.php @@ -713,6 +713,11 @@ function wc_string_to_datetime( $time_string ) { * @return string PHP timezone string for the site */ function wc_timezone_string() { + // Added in WordPress 5.3 Ref https://developer.wordpress.org/reference/functions/wp_timezone_string/. + if ( function_exists( 'wp_timezone_string' ) ) { + return wp_timezone_string(); + } + // If site timezone string exists, return it. $timezone = get_option( 'timezone_string' ); if ( $timezone ) { @@ -720,13 +725,13 @@ function wc_timezone_string() { } // Get UTC offset, if it isn't set then return UTC. - $utc_offset = intval( get_option( 'gmt_offset', 0 ) ); - if ( 0 === $utc_offset ) { + $utc_offset = floatval( get_option( 'gmt_offset', 0 ) ); + if ( ! is_numeric( $utc_offset ) || 0.0 === $utc_offset ) { return 'UTC'; } // Adjust UTC offset from hours to seconds. - $utc_offset *= 3600; + $utc_offset = (int) ( $utc_offset * 3600 ); // Attempt to guess the timezone string from the UTC offset. $timezone = timezone_name_from_abbr( '', $utc_offset ); diff --git a/includes/wc-stock-functions.php b/includes/wc-stock-functions.php index 2deb1580e4c..d39065cd3d1 100644 --- a/includes/wc-stock-functions.php +++ b/includes/wc-stock-functions.php @@ -299,33 +299,80 @@ function wc_increase_stock_levels( $order_id ) { * @param integer $exclude_order_id Order ID to exclude. * @return int */ -function wc_get_held_stock_quantity( $product, $exclude_order_id = 0 ) { - global $wpdb; +function wc_get_held_stock_quantity( WC_Product $product, $exclude_order_id = 0 ) { + /** + * Filter: woocommerce_hold_stock_for_checkout + * Allows enable/disable hold stock functionality on checkout. + * + * @since 4.3.0 + * @param bool $enabled Default to true if managing stock globally. + */ + if ( ! apply_filters( 'woocommerce_hold_stock_for_checkout', wc_string_to_bool( get_option( 'woocommerce_manage_stock', 'yes' ) ) ) ) { + return 0; + } - return $wpdb->get_var( - $wpdb->prepare( - " - SELECT SUM( order_item_meta.meta_value ) AS held_qty - FROM {$wpdb->posts} AS posts - LEFT JOIN {$wpdb->postmeta} as postmeta ON posts.ID = postmeta.post_id - LEFT JOIN {$wpdb->prefix}woocommerce_order_items as order_items ON posts.ID = order_items.order_id - LEFT JOIN {$wpdb->prefix}woocommerce_order_itemmeta as order_item_meta ON order_items.order_item_id = order_item_meta.order_item_id - LEFT JOIN {$wpdb->prefix}woocommerce_order_itemmeta as order_item_meta2 ON order_items.order_item_id = order_item_meta2.order_item_id - WHERE order_item_meta.meta_key = '_qty' - AND order_item_meta2.meta_key = %s - AND order_item_meta2.meta_value = %d - AND postmeta.meta_key = '_created_via' - AND postmeta.meta_value = 'checkout' - AND posts.post_type IN ( '" . implode( "','", wc_get_order_types() ) . "' ) - AND posts.post_status = 'wc-pending' - AND posts.ID != %d;", - 'product_variation' === get_post_type( $product->get_stock_managed_by_id() ) ? '_variation_id' : '_product_id', - $product->get_stock_managed_by_id(), - $exclude_order_id - ) - ); // WPCS: unprepared SQL ok. + return ( new \Automattic\WooCommerce\Checkout\Helpers\ReserveStock() )->get_reserved_stock( $product, $exclude_order_id ); } +/** + * Hold stock for an order. + * + * @throws ReserveStockException If reserve stock fails. + * + * @since 4.1.0 + * @param \WC_Order|int $order Order ID or instance. + */ +function wc_reserve_stock_for_order( $order ) { + /** + * Filter: woocommerce_hold_stock_for_checkout + * Allows enable/disable hold stock functionality on checkout. + * + * @since @since 4.1.0 + * @param bool $enabled Default to true if managing stock globally. + */ + if ( ! apply_filters( 'woocommerce_hold_stock_for_checkout', wc_string_to_bool( get_option( 'woocommerce_manage_stock', 'yes' ) ) ) ) { + return; + } + + $order = $order instanceof WC_Order ? $order : wc_get_order( $order ); + + if ( $order ) { + ( new \Automattic\WooCommerce\Checkout\Helpers\ReserveStock() )->reserve_stock_for_order( $order ); + } +} +add_action( 'woocommerce_checkout_order_created', 'wc_reserve_stock_for_order' ); + +/** + * Release held stock for an order. + * + * @since 4.3.0 + * @param \WC_Order|int $order Order ID or instance. + */ +function wc_release_stock_for_order( $order ) { + /** + * Filter: woocommerce_hold_stock_for_checkout + * Allows enable/disable hold stock functionality on checkout. + * + * @since 4.3.0 + * @param bool $enabled Default to true if managing stock globally. + */ + if ( ! apply_filters( 'woocommerce_hold_stock_for_checkout', wc_string_to_bool( get_option( 'woocommerce_manage_stock', 'yes' ) ) ) ) { + return; + } + + $order = $order instanceof WC_Order ? $order : wc_get_order( $order ); + + if ( $order ) { + ( new \Automattic\WooCommerce\Checkout\Helpers\ReserveStock() )->release_stock_for_order( $order ); + } +} +add_action( 'woocommerce_checkout_order_exception', 'wc_release_stock_for_order' ); +add_action( 'woocommerce_payment_complete', 'wc_release_stock_for_order', 11 ); +add_action( 'woocommerce_order_status_cancelled', 'wc_release_stock_for_order', 11 ); +add_action( 'woocommerce_order_status_completed', 'wc_release_stock_for_order', 11 ); +add_action( 'woocommerce_order_status_processing', 'wc_release_stock_for_order', 11 ); +add_action( 'woocommerce_order_status_on-hold', 'wc_release_stock_for_order', 11 ); + /** * Return low stock amount to determine if notification needs to be sent * diff --git a/includes/wc-template-functions.php b/includes/wc-template-functions.php index 26a2f26c45a..18f5947bd72 100644 --- a/includes/wc-template-functions.php +++ b/includes/wc-template-functions.php @@ -673,7 +673,7 @@ function wc_get_product_class( $class = '', $product = null ) { * WooCommerce Post Class filter. * * @since 3.6.2 - * @param array $class Array of CSS classes. + * @param array $classes Array of CSS classes. * @param WC_Product $product Product object. */ $classes = apply_filters( 'woocommerce_post_class', $classes, $product ); @@ -2097,7 +2097,7 @@ if ( ! function_exists( 'woocommerce_widget_shopping_cart_subtotal' ) ) { * @since 3.7.0 */ function woocommerce_widget_shopping_cart_subtotal() { - echo '' . esc_html__( 'Subtotal', 'woocommerce' ) . ': ' . WC()->cart->get_cart_subtotal(); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped + echo '' . esc_html__( 'Subtotal:', 'woocommerce' ) . ' ' . WC()->cart->get_cart_subtotal(); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped } } @@ -2706,7 +2706,7 @@ if ( ! function_exists( 'woocommerce_form_field' ) ) { $field = ''; @@ -2733,7 +2733,7 @@ if ( ! function_exists( 'woocommerce_form_field' ) ) { '; foreach ( $states as $ckey => $cvalue ) { - $field .= ''; + $field .= ''; } $field .= ''; @@ -2782,7 +2782,7 @@ if ( ! function_exists( 'woocommerce_form_field' ) ) { } $custom_attributes[] = 'data-allow_clear="true"'; } - $options .= ''; + $options .= ''; } $field .= ''; - $field .= ''; + $field .= ''; } } diff --git a/package-lock.json b/package-lock.json index 50fd94e8c8a..d12e3a21694 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,6 +1,6 @@ { "name": "woocommerce", - "version": "4.1.0", + "version": "4.3.0", "lockfileVersion": 1, "requires": true, "dependencies": { @@ -13563,12 +13563,6 @@ "integrity": "sha1-BjJjj42HfMghB9MKD/8aF8uhzQw=", "dev": true }, - "exit-hook": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/exit-hook/-/exit-hook-1.1.1.tgz", - "integrity": "sha1-8FyiM7SMBdVP/wd2XfhQfpXAL/g=", - "dev": true - }, "expand-brackets": { "version": "2.1.4", "resolved": "https://registry.npmjs.org/expand-brackets/-/expand-brackets-2.1.4.tgz", @@ -16027,161 +16021,6 @@ } } }, - "grunt-prompt": { - "version": "1.3.3", - "resolved": "https://registry.npmjs.org/grunt-prompt/-/grunt-prompt-1.3.3.tgz", - "integrity": "sha1-xbQ77DqimqaWKsZhGolnEvy6Z5E=", - "dev": true, - "requires": { - "inquirer": "^0.11.0", - "lodash": "^3.10.1" - }, - "dependencies": { - "ansi-escapes": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-1.4.0.tgz", - "integrity": "sha1-06ioOzGapneTZisT52HHkRQiMG4=", - "dev": true - }, - "ansi-regex": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", - "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=", - "dev": true - }, - "ansi-styles": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-2.2.1.tgz", - "integrity": "sha1-tDLdM1i2NM914eRmQ2gkBTPB3b4=", - "dev": true - }, - "chalk": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-1.1.3.tgz", - "integrity": "sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg=", - "dev": true, - "requires": { - "ansi-styles": "^2.2.1", - "escape-string-regexp": "^1.0.2", - "has-ansi": "^2.0.0", - "strip-ansi": "^3.0.0", - "supports-color": "^2.0.0" - } - }, - "cli-cursor": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/cli-cursor/-/cli-cursor-1.0.2.tgz", - "integrity": "sha1-ZNo/fValRBLll5S9Ytw1KV6PKYc=", - "dev": true, - "requires": { - "restore-cursor": "^1.0.1" - } - }, - "cli-width": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/cli-width/-/cli-width-1.1.1.tgz", - "integrity": "sha1-pNKT72frt7iNSk1CwMzwDE0eNm0=", - "dev": true - }, - "figures": { - "version": "1.7.0", - "resolved": "https://registry.npmjs.org/figures/-/figures-1.7.0.tgz", - "integrity": "sha1-y+Hjr/zxzUS4DK3+0o3Hk6lwHS4=", - "dev": true, - "requires": { - "escape-string-regexp": "^1.0.5", - "object-assign": "^4.1.0" - } - }, - "inquirer": { - "version": "0.11.4", - "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-0.11.4.tgz", - "integrity": "sha1-geM3ToNhvq/y2XAWIG01nQsy+k0=", - "dev": true, - "requires": { - "ansi-escapes": "^1.1.0", - "ansi-regex": "^2.0.0", - "chalk": "^1.0.0", - "cli-cursor": "^1.0.1", - "cli-width": "^1.0.1", - "figures": "^1.3.5", - "lodash": "^3.3.1", - "readline2": "^1.0.1", - "run-async": "^0.1.0", - "rx-lite": "^3.1.2", - "string-width": "^1.0.1", - "strip-ansi": "^3.0.0", - "through": "^2.3.6" - } - }, - "is-fullwidth-code-point": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-1.0.0.tgz", - "integrity": "sha1-754xOG8DGn8NZDr4L95QxFfvAMs=", - "dev": true, - "requires": { - "number-is-nan": "^1.0.0" - } - }, - "lodash": { - "version": "3.10.1", - "resolved": "https://registry.npmjs.org/lodash/-/lodash-3.10.1.tgz", - "integrity": "sha1-W/Rejkm6QYnhfUgnid/RW9FAt7Y=", - "dev": true - }, - "onetime": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/onetime/-/onetime-1.1.0.tgz", - "integrity": "sha1-ofeDj4MUxRbwXs78vEzP4EtO14k=", - "dev": true - }, - "restore-cursor": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/restore-cursor/-/restore-cursor-1.0.1.tgz", - "integrity": "sha1-NGYfRohjJ/7SmRR5FSJS35LapUE=", - "dev": true, - "requires": { - "exit-hook": "^1.0.0", - "onetime": "^1.0.0" - } - }, - "run-async": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/run-async/-/run-async-0.1.0.tgz", - "integrity": "sha1-yK1KXhEGYeQCp9IbUw4AnyX444k=", - "dev": true, - "requires": { - "once": "^1.3.0" - } - }, - "string-width": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/string-width/-/string-width-1.0.2.tgz", - "integrity": "sha1-EYvfW4zcUaKn5w0hHgfisLmxB9M=", - "dev": true, - "requires": { - "code-point-at": "^1.0.0", - "is-fullwidth-code-point": "^1.0.0", - "strip-ansi": "^3.0.0" - } - }, - "strip-ansi": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", - "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", - "dev": true, - "requires": { - "ansi-regex": "^2.0.0" - } - }, - "supports-color": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-2.0.0.tgz", - "integrity": "sha1-U10EXOa2Nj+kARcIRimZXp3zJMc=", - "dev": true - } - } - }, "grunt-rtlcss": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/grunt-rtlcss/-/grunt-rtlcss-2.0.2.tgz", @@ -16240,34 +16079,6 @@ "integrity": "sha512-90s27H7FoCDcA8C8+R0GwC+ntYD3lG6S/jqcavWm3bn9RiJTmSfOvfbFa1PXx4NbBWuiGQMLfQTj/JvvqT5w6A==", "dev": true }, - "grunt-shell": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/grunt-shell/-/grunt-shell-3.0.1.tgz", - "integrity": "sha512-C8eR4frw/NmIFIwSvzSLS4wOQBUzC+z6QhrKPzwt/tlaIqlzH35i/O2MggVOBj2Sh1tbaAqpASWxGiGsi4JMIQ==", - "dev": true, - "requires": { - "chalk": "^2.4.1", - "npm-run-path": "^2.0.0", - "strip-ansi": "^5.0.0" - }, - "dependencies": { - "ansi-regex": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.0.tgz", - "integrity": "sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg==", - "dev": true - }, - "strip-ansi": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.2.0.tgz", - "integrity": "sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==", - "dev": true, - "requires": { - "ansi-regex": "^4.1.0" - } - } - } - }, "grunt-stylelint": { "version": "0.14.0", "resolved": "https://registry.npmjs.org/grunt-stylelint/-/grunt-stylelint-0.14.0.tgz", @@ -24338,7 +24149,7 @@ } }, "prettier": { - "version": "npm:wp-prettier@1.19.1", + "version": "npm:prettier@1.19.1", "resolved": "https://registry.npmjs.org/wp-prettier/-/wp-prettier-1.19.1.tgz", "integrity": "sha512-mqAC2r1NDmRjG+z3KCJ/i61tycKlmADIjxnDhQab+KBxSAGbF/W7/zwB2guy/ypIeKrrftNsIYkNZZQKf3vJcg==", "dev": true @@ -24844,34 +24655,6 @@ } } }, - "readline2": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/readline2/-/readline2-1.0.1.tgz", - "integrity": "sha1-QQWWCP/BVHV7cV2ZidGZ/783LjU=", - "dev": true, - "requires": { - "code-point-at": "^1.0.0", - "is-fullwidth-code-point": "^1.0.0", - "mute-stream": "0.0.5" - }, - "dependencies": { - "is-fullwidth-code-point": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-1.0.0.tgz", - "integrity": "sha1-754xOG8DGn8NZDr4L95QxFfvAMs=", - "dev": true, - "requires": { - "number-is-nan": "^1.0.0" - } - }, - "mute-stream": { - "version": "0.0.5", - "resolved": "https://registry.npmjs.org/mute-stream/-/mute-stream-0.0.5.tgz", - "integrity": "sha1-j7+rsKmKJT0xhDMfno3rc3L6xsA=", - "dev": true - } - } - }, "realpath-native": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/realpath-native/-/realpath-native-1.1.0.tgz", @@ -25444,12 +25227,6 @@ "integrity": "sha1-pfE/957zt0D+MKqAP7CfmIBdR4I=", "dev": true }, - "rx-lite": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/rx-lite/-/rx-lite-3.1.2.tgz", - "integrity": "sha1-Gc5QLKVyZl87ZHsQk5+X/RYV8QI=", - "dev": true - }, "rxjs": { "version": "6.5.3", "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-6.5.3.tgz", diff --git a/package.json b/package.json index 08308ac74c9..19079f9a231 100644 --- a/package.json +++ b/package.json @@ -56,10 +56,8 @@ "grunt-contrib-watch": "1.1.0", "grunt-phpcs": "0.4.0", "grunt-postcss": "0.9.0", - "grunt-prompt": "1.3.3", "grunt-rtlcss": "2.0.2", "grunt-sass": "3.1.0", - "grunt-shell": "3.0.1", "grunt-stylelint": "0.14.0", "gruntify-eslint": "5.0.0", "husky": "4.2.5", @@ -85,8 +83,9 @@ }, "husky": { "hooks": { + "post-merge": "./bin/post-merge.sh", "pre-commit": "lint-staged", - "post-merge": "./bin/post-merge.sh" + "pre-push": "./bin/pre-push.sh" } }, "lint-staged": { diff --git a/phpcs.xml b/phpcs.xml index b1d14b43537..8075b9d8ccc 100644 --- a/phpcs.xml +++ b/phpcs.xml @@ -59,5 +59,6 @@ i18n/src/tests/php + tests/Tools/ diff --git a/phpunit.xml b/phpunit.xml index 75b6a007d51..94156de9541 100644 --- a/phpunit.xml +++ b/phpunit.xml @@ -49,4 +49,7 @@ + + + diff --git a/readme.txt b/readme.txt index 8255ebeb860..9eeeef44559 100644 --- a/readme.txt +++ b/readme.txt @@ -1,10 +1,10 @@ === WooCommerce === Contributors: automattic, mikejolley, jameskoster, claudiosanches, kloon, rodrigosprimo, peterfabian1000, vedjain, jamosova, obliviousharmony Tags: e-commerce, store, sales, sell, woo, shop, cart, checkout, downloadable, downloads, payments, paypal, storefront, stripe, woo commerce -Requires at least: 5.0 +Requires at least: 5.2 Tested up to: 5.4 Requires PHP: 7.0 -Stable tag: 4.0.1 +Stable tag: 4.1.1 License: GPLv3 License URI: https://www.gnu.org/licenses/gpl-3.0.html @@ -179,48 +179,7 @@ INTERESTED IN DEVELOPMENT? == Changelog == -= 4.1.0 - 2020-05-05 = - -**WooCommerce** -* Enhancement - Update dependency woocommerce/woocommerce-admin to v1.1.0 #26057 -* Enhancement - Updated jetpack-autoloader to 1.6 and woocommerce-blocks to 2.5.16. #26099 -* Enhancement - Added option to ignore discounts from cart's total amount to enable free shipping. #24776 -* Enhancement - Changed show password icon color to a darker grey hue. #25625 -* Enhancement - Use new Setup Wizard for all users. #26016 -* Tweak - Show notice for WP min version to WP 5.2. #26094 -* Tweak - Improve the string for untested WooCommerce extensions in the system status page to avoid confusion. #25904 -* Tweak - Updated KZT (₸) symbol. #25609 -* Tweak - Trim whitespaces and strip slashes from MaxMind License Key. #25466 -* Tweak - Updated "Help" tabs documentation. #25826 -* Tweak - Update serbian currency symbol to рсд from дин. #25885 -* Fix - Password visibility toggle to hide password again from text. #25627 -* Fix - Undefined property error when attempting to modify the coupon post meta. #25755 -* Fix - Remove some of the individual rounding logic to make sure we round at certain places only. #25800 -* Fix - Order totals calculation if the order contains taxable and non-taxable products and percentage coupons. #25092 -* Fix - Wording for cancelled order email. #25316 -* Fix - Removed guided tour videos link on setup wizard (since current link only redirects to the docs). #25823 -* Fix - Add RTL style to the onboarding wizard. #25835 -* Fix - Trigger change and set val to qty on the frontend so that it properly updates event handlers. #25903 -* Fix - Corrected the way percent coupons apply remainders across the order. #25943 -* Fix - Clarified the error messaging for WooCommerce.com package update failures. #26034 -* Fix - Enforce per user usage limit check for a coupon on guest users based on email. #26066 -* Fix - Remove elements with style=display:none explicitly to address a regression causing broken email html. #26075 -* Dev - Added woocommerce_can_restock_refunded_items filter. #25728 -* Dev - Added woocommerce_order_get_tax_location filter. #25727 -* Dev - Updated stock handling to prevent race conditions when orders come in at the same time. #25708 -* Dev - Updated /myaccount/form-login.php to use consistent kebab-case class names for woocommerce-form-row. #25668 -* Dev - Add filter woocommerce_product_upsells_products_heading to allow heading modification without having to override the template file. #25628 -* Dev - Added woocommerce_order_get_tax_location filter. #25727 -* Dev - Added the get_woocommerce_currency_symbols function to allow develops to get an array of all the currency symbol registered with WooCommerce. #25733 -* Dev - Changed string typed label_class to array in checkout fields. -* Dev - Added "woocommerce_emogrifier" action before the content of the emails is "emogrified". #25801 -* Dev - Add Ability to Filter Event Props. #25851 -* Dev - Updated the unit test install script to support paths to MySQL sockets that contain spaces. #25923 -* Dev - Made the default test source folders support the system tmp folder. #25923 -* Dev - Add cart & checkout block/shortcode info to tracker data. #25932 -* Dev - Make WC_Product_Data_Store_CPT::update_product_stock operations atomic. #26039 -* Dev - Adds usage data for the of cart & checkout blocks (currently in development in WooCommmerce Blocks plugin) to the WC Tracker snapshot. #26084 -* Dev - Implement some additional tracks for coupons, orders, and products. #26085 += 4.3.0 - 2020-07-07 = [See changelog for all versions](https://raw.githubusercontent.com/woocommerce/woocommerce/master/CHANGELOG.txt). diff --git a/renovate.json b/renovate.json index 40aaeb69687..e119457e471 100644 --- a/renovate.json +++ b/renovate.json @@ -11,5 +11,11 @@ "depTypeList": ["devDependencies"], "extends": ["schedule:monthly"] } + ], + "ignoreDeps": [ + "woocommerce/action-scheduler", + "woocommerce/woocommerce-admin", + "woocommerce/woocommerce-blocks", + "woocommerce/woocommerce-rest-api" ] } diff --git a/src/Checkout/Helpers/ReserveStock.php b/src/Checkout/Helpers/ReserveStock.php new file mode 100644 index 00000000000..32dff1c5c43 --- /dev/null +++ b/src/Checkout/Helpers/ReserveStock.php @@ -0,0 +1,210 @@ +enabled = get_option( 'woocommerce_schema_version', 0 ) >= 430; + } + + /** + * Is stock reservation enabled? + * + * @return boolean + */ + protected function is_enabled() { + return $this->enabled; + } + + /** + * Query for any existing holds on stock for this item. + * + * @param \WC_Product $product Product to get reserved stock for. + * @param integer $exclude_order_id Optional order to exclude from the results. + * + * @return integer Amount of stock already reserved. + */ + public function get_reserved_stock( \WC_Product $product, $exclude_order_id = 0 ) { + global $wpdb; + + if ( ! $this->is_enabled() ) { + return 0; + } + + // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared + return (int) $wpdb->get_var( $this->get_query_for_reserved_stock( $product->get_stock_managed_by_id(), $exclude_order_id ) ); + } + + /** + * Put a temporary hold on stock for an order if enough is available. + * + * @throws ReserveStockException If stock cannot be reserved. + * + * @param \WC_Order $order Order object. + * @param int $minutes How long to reserve stock in minutes. Defaults to woocommerce_hold_stock_minutes. + */ + public function reserve_stock_for_order( \WC_Order $order, $minutes = 0 ) { + $minutes = $minutes ? $minutes : (int) get_option( 'woocommerce_hold_stock_minutes', 60 ); + + if ( ! $minutes || ! $this->is_enabled() ) { + return; + } + + try { + $items = array_filter( + $order->get_items(), + function( $item ) { + return $item->is_type( 'line_item' ) && $item->get_product() instanceof \WC_Product && $item->get_quantity() > 0; + } + ); + $rows = array(); + + foreach ( $items as $item ) { + $product = $item->get_product(); + + if ( ! $product->is_in_stock() ) { + throw new ReserveStockException( + 'woocommerce_product_out_of_stock', + sprintf( + /* translators: %s: product name */ + __( '"%s" is out of stock and cannot be purchased.', 'woocommerce' ), + $product->get_name() + ), + 403 + ); + } + + // If stock management is off, no need to reserve any stock here. + if ( ! $product->managing_stock() || $product->backorders_allowed() ) { + continue; + } + + $managed_by_id = $product->get_stock_managed_by_id(); + $rows[ $managed_by_id ] = isset( $rows[ $managed_by_id ] ) ? $rows[ $managed_by_id ] + $item->get_quantity() : $item->get_quantity(); + } + + if ( ! empty( $rows ) ) { + foreach ( $rows as $product_id => $quantity ) { + $this->reserve_stock_for_product( $product_id, $quantity, $order, $minutes ); + } + } + } catch ( ReserveStockException $e ) { + $this->release_stock_for_order( $order ); + throw $e; + } + } + + /** + * Release a temporary hold on stock for an order. + * + * @param \WC_Order $order Order object. + */ + public function release_stock_for_order( \WC_Order $order ) { + global $wpdb; + + if ( ! $this->is_enabled() ) { + return; + } + + $wpdb->delete( + $wpdb->wc_reserved_stock, + array( + 'order_id' => $order->get_id(), + ) + ); + } + + /** + * Reserve stock for a product by inserting rows into the DB. + * + * @throws ReserveStockException If a row cannot be inserted. + * + * @param int $product_id Product ID which is having stock reserved. + * @param int $stock_quantity Stock amount to reserve. + * @param \WC_Order $order Order object which contains the product. + * @param int $minutes How long to reserve stock in minutes. + */ + private function reserve_stock_for_product( $product_id, $stock_quantity, \WC_Order $order, $minutes ) { + global $wpdb; + + $product_data_store = \WC_Data_Store::load( 'product' ); + $query_for_stock = $product_data_store->get_query_for_stock( $product_id ); + $query_for_reserved_stock = $this->get_query_for_reserved_stock( $product_id, $order->get_id() ); + + // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared + $result = $wpdb->query( + $wpdb->prepare( + " + INSERT INTO {$wpdb->wc_reserved_stock} ( `order_id`, `product_id`, `stock_quantity`, `timestamp`, `expires` ) + SELECT %d, %d, %d, NOW(), ( NOW() + INTERVAL %d MINUTE ) FROM DUAL + WHERE ( $query_for_stock FOR UPDATE ) - ( $query_for_reserved_stock FOR UPDATE ) >= %d + ON DUPLICATE KEY UPDATE `expires` = VALUES( `expires` ) + ", + $order->get_id(), + $product_id, + $stock_quantity, + $minutes, + $stock_quantity + ) + ); + // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared + + if ( ! $result ) { + $product = wc_get_product( $product_id ); + throw new ReserveStockException( + 'woocommerce_product_not_enough_stock', + sprintf( + /* translators: %s: product name */ + __( 'Not enough units of %s are available in stock to fulfil this order.', 'woocommerce' ), + $product ? $product->get_name() : '#' . $product_id + ), + 403 + ); + } + } + + /** + * Returns query statement for getting reserved stock of a product. + * + * @param int $product_id Product ID. + * @param integer $exclude_order_id Optional order to exclude from the results. + * @return string|void Query statement. + */ + private function get_query_for_reserved_stock( $product_id, $exclude_order_id = 0 ) { + global $wpdb; + return $wpdb->prepare( + " + SELECT COALESCE( SUM( stock_table.`stock_quantity` ), 0 ) FROM $wpdb->wc_reserved_stock stock_table + LEFT JOIN $wpdb->posts posts ON stock_table.`order_id` = posts.ID + WHERE posts.post_status IN ( 'wc-checkout-draft', 'wc-pending' ) + AND stock_table.`expires` > NOW() + AND stock_table.`product_id` = %d + AND stock_table.`order_id` != %d + ", + $product_id, + $exclude_order_id + ); + } +} diff --git a/src/Checkout/Helpers/ReserveStockException.php b/src/Checkout/Helpers/ReserveStockException.php new file mode 100644 index 00000000000..e84409b5f1d --- /dev/null +++ b/src/Checkout/Helpers/ReserveStockException.php @@ -0,0 +1,62 @@ +error_code = $code; + $this->error_data = $data; + + parent::__construct( $message, $http_status_code ); + } + + /** + * Returns the error code. + * + * @return string + */ + public function getErrorCode() { + return $this->error_code; + } + + /** + * Returns error data. + * + * @return array + */ + public function getErrorData() { + return $this->error_data; + } +} diff --git a/templates/auth/form-grant-access.php b/templates/auth/form-grant-access.php index f5ee952ffcf..ecaee458f22 100644 --- a/templates/auth/form-grant-access.php +++ b/templates/auth/form-grant-access.php @@ -50,6 +50,7 @@ defined( 'ABSPATH' ) || exit; printf( esc_html__( 'Logged in as %s', 'woocommerce' ), esc_html( $user->display_name ) ); ?> +

        diff --git a/templates/single-product-reviews.php b/templates/single-product-reviews.php index ecde5dbc72a..5fa9279b8ee 100644 --- a/templates/single-product-reviews.php +++ b/templates/single-product-reviews.php @@ -121,7 +121,7 @@ if ( ! comments_open() ) { } if ( wc_review_ratings_enabled() ) { - $comment_form['comment_field'] = '

        diff --git a/tests/Tools/CodeHacking/CodeHacker.php b/tests/Tools/CodeHacking/CodeHacker.php new file mode 100644 index 00000000000..a22650e20e8 --- /dev/null +++ b/tests/Tools/CodeHacking/CodeHacker.php @@ -0,0 +1,511 @@ +getMethod( 'hack' ); + $has_valid_hack_method = $rm->isPublic() && ! $rm->isStatic() && 2 === $rm->getNumberOfRequiredParameters(); + + $rm = $ro->getMethod( 'reset' ); + $has_valid_reset_method = $rm->isPublic() && ! $rm->isStatic() && 0 === $rm->getNumberOfRequiredParameters(); + + return $has_valid_hack_method && $has_valid_reset_method; + } catch ( ReflectionException $exception ) { + return false; + } + } + + /** + * Initialize the code hacker. + * + * @param array $paths Paths of the directories containing the files to hack. + * @throws \Exception Invalid input. + */ + public static function initialize( array $paths ) { + if ( ! is_array( $paths ) || empty( $paths ) ) { + throw new \Exception( 'CodeHacker::initialize - $paths must be a non-empty array with the directories containing the files to be hacked.' ); + } + self::$paths_with_files_to_hack = array_map( + function( $path ) { + return realpath( $path ); + }, + $paths + ); + } + + /** + * Close directory handle. + */ + public function dir_closedir() { + closedir( $this->handle ); + } + + /** + * Open directory handle. + * + * @param string $path Specifies the URL that was passed to opendir(). + * @param int $options Whether or not to enforce safe_mode (0x04). + * + * @return bool TRUE on success or FALSE on failure. + */ + public function dir_opendir( $path, $options ) { + $this->handle = $this->context + ? $this->native( 'opendir', $path, $this->context ) + : $this->native( 'opendir', $path ); + return (bool) $this->handle; + } + + /** + * Read entry from directory handle. + * + * @return false|string string representing the next filename, or FALSE if there is no next file. + */ + public function dir_readdir() { + return readdir( $this->handle ); + } + + /** + * Rewind directory handle. + * + * @return TRUE on success or FALSE on failure. + */ + public function dir_rewinddir() { + return rewinddir( $this->handle ); + } + + /** + * Create a directory. + * + * @param string $path Directory which should be created. + * @param int $mode The value passed to mkdir(). + * @param int $options A bitwise mask of values, such as STREAM_MKDIR_RECURSIVE. + * + * @return bool TRUE on success or FALSE on failure. + */ + public function mkdir( $path, $mode, $options ) { + $recursive = (bool) ( $options & STREAM_MKDIR_RECURSIVE ); + return $this->native( 'mkdir', $path, $mode, $recursive, $this->context ); + } + + /** + * Renames a file or directory. + * + * @param string $path_from The URL to the current file. + * @param string $path_to The URL which the path_from should be renamed to. + * + * @return bool TRUE on success or FALSE on failure. + */ + public function rename( $path_from, $path_to ) { + return $this->native( 'rename', $path_from, $path_to, $this->context ); + } + + /** + * Removes a directory. + * + * @param string $path The directory URL which should be removed. + * @param int $options A bitwise mask of values, such as STREAM_MKDIR_RECURSIVE. + * + * @return bool TRUE on success or FALSE on failure. + */ + public function rmdir( $path, $options ) { + return $this->native( 'rmdir', $path, $this->context ); + } + + /** + * Retrieve the underlying resource. + * + * @param mixed $cast_as Can be STREAM_CAST_FOR_SELECT when stream_select() is calling stream_cast() or STREAM_CAST_AS_STREAM when stream_cast() is called for other uses. + * + * @return mixed The underlying stream resource used by the wrapper, or FALSE. + */ + public function stream_cast( $cast_as ) { + return $this->handle; + } + + /** + * Close a resource. + */ + public function stream_close() { + fclose( $this->handle ); + } + + /** + * Tests for end-of-file on a file pointer. + * + * @return bool TRUE if the read/write position is at the end of the stream and if no more data is available to be read, or FALSE otherwise. + */ + public function stream_eof() { + return feof( $this->handle ); + } + + /** + * Flushes the output. + * + * @return bool TRUE if the cached data was successfully stored (or if there was no data to store), or FALSE if the data could not be stored. + */ + public function stream_flush() { + return fflush( $this->handle ); + } + + /** + * Advisory file locking. + * + * @param int $operation LOCK_SH, LOCK_EX, LOCK_UN, or LOCK_NB. + * + * @return bool TRUE on success or FALSE on failure. + */ + public function stream_lock( $operation ) { + return $operation + ? flock( $this->handle, $operation ) + : true; + } + + /** + * Change stream metadata. + * + * @param string $path The file path or URL to set metadata. Note that in the case of a URL, it must be a :// delimited URL. Other URL forms are not supported. + * @param int $option STREAM_META_TOUCH, STREAM_META_OWNER_NAME, STREAM_META_OWNER, STREAM_META_GROUP_NAME, STREAM_META_GROUP, or STREAM_META_ACCESS. + * @param mixed $value Depends on $option. + * + * @return bool TRUE on success or FALSE on failure. If option is not implemented, FALSE should be returned. + */ + public function stream_metadata( $path, $option, $value ) { + switch ( $option ) { + case STREAM_META_TOUCH: + $value += array( null, null ); + return $this->native( 'touch', $path, $value[0], $value[1] ); + case STREAM_META_OWNER_NAME: + case STREAM_META_OWNER: + return $this->native( 'chown', $path, $value ); + case STREAM_META_GROUP_NAME: + case STREAM_META_GROUP: + return $this->native( 'chgrp', $path, $value ); + case STREAM_META_ACCESS: + return $this->native( 'chmod', $path, $value ); + } + } + + /** + * Opens file or URL. Note that this is where the hacking actually happens. + * + * @param string $path Specifies the URL that was passed to the original function. + * @param string $mode The mode used to open the file, as detailed for fopen(). + * @param int $options Holds additional flags set by the streams API: STREAM_USE_PATH, STREAM_REPORT_ERRORS. + * @param string $opened_path If the path is opened successfully, and STREAM_USE_PATH is set in options, opened_path should be set to the full path of the file/resource that was actually opened. + * + * @return bool TRUE on success or FALSE on failure. + */ + public function stream_open( $path, $mode, $options, &$opened_path ) { + $use_path = (bool) ( $options & STREAM_USE_PATH ); + if ( 'rb' === $mode && self::path_in_list_of_paths_to_hack( $path ) && 'php' === pathinfo( $path, PATHINFO_EXTENSION ) ) { + $content = $this->native( 'file_get_contents', $path, $use_path, $this->context ); + if ( false === $content ) { + return false; + } + $modified = self::hack( $content, $path ); + if ( $modified !== $content ) { + $this->handle = tmpfile(); + $this->native( 'fwrite', $this->handle, $modified ); + $this->native( 'fseek', $this->handle, 0 ); + return true; + } + } + $this->handle = $this->context + ? $this->native( 'fopen', $path, $mode, $use_path, $this->context ) + : $this->native( 'fopen', $path, $mode, $use_path ); + return (bool) $this->handle; + } + + /** + * Read from stream. + * + * @param int $count How many bytes of data from the current position should be returned. + * + * @return false|string If there are less than count bytes available, return as many as are available. If no more data is available, return either FALSE or an empty string. + */ + public function stream_read( $count ) { + return fread( $this->handle, $count ); + } + + /** + * Seeks to specific location in a stream. + * + * @param int $offset The stream offset to seek to. + * @param int $whence SEEK_SET, SEEK_CUR, or SEEK_END. + * + * @return bool TRUE if the position was updated, FALSE otherwise. + */ + public function stream_seek( $offset, $whence = SEEK_SET ) { + return fseek( $this->handle, $offset, $whence ) === 0; + } + + /** + * Change stream options. + * + * @param int $option STREAM_OPTION_BLOCKING, STREAM_OPTION_READ_TIMEOUT, or STREAM_OPTION_WRITE_BUFFER. + * @param int $arg1 Depends on $option. + * @param int $arg2 Depends on $option. + */ + public function stream_set_option( $option, $arg1, $arg2 ) { + } + + /** + * Retrieve information about a file resource. + * + * @return array See stat(). + */ + public function stream_stat() { + return fstat( $this->handle ); + } + + /** + * Retrieve the current position of a stream. + * + * @return false|int The current position of the stream. + */ + public function stream_tell() { + return ftell( $this->handle ); + } + + /** + * Truncate stream. + * + * @param int $new_size The new size. + * + * @return bool TRUE on success or FALSE on failure. + */ + public function stream_truncate( $new_size ) { + return ftruncate( $this->handle, $new_size ); + } + + /** + * Write to stream. + * + * @param string $data Should be stored into the underlying stream. + * + * @return false|int The number of bytes that were successfully stored, or 0 if none could be stored. + */ + public function stream_write( $data ) { + return fwrite( $this->handle, $data ); + } + + /** + * Delete a file. + * + * @param string $path The file URL which should be deleted. + * + * @return bool TRUE on success or FALSE on failure. + */ + public function unlink( $path ) { + return $this->native( 'unlink', $path ); + } + + /** + * Retrieve information about a file. + * + * @param string $path The file path or URL to stat. Note that in the case of a URL, it must be a :// delimited URL. Other URL forms are not supported. + * @param int $flags Holds additional flags set by the streams API. It can hold one or more of the following values OR'd together. + * + * @return mixed Should return as many elements as stat() does. Unknown or unavailable values should be set to a rational value (usually 0). Pay special attention to mode as documented under stat(). + */ + public function url_stat( $path, $flags ) { + $func = $flags & STREAM_URL_STAT_LINK ? 'lstat' : 'stat'; + return $flags & STREAM_URL_STAT_QUIET + ? @$this->native( $func, $path ) + : $this->native( $func, $path ); + } + + /** + * Executes a native PHP function. + * + * @param string $func Name of the function to execute. Pass the arguments for the PHP function after this one. + * + * @return mixed Return value from the native PHP function. + */ + private function native( $func ) { + stream_wrapper_restore( self::PROTOCOL ); + $res = call_user_func_array( $func, array_slice( func_get_args(), 1 ) ); + stream_wrapper_unregister( self::PROTOCOL ); + stream_wrapper_register( self::PROTOCOL, __CLASS__ ); + return $res; + } + + /** + * Apply the reigstered hacks to the contents of a file. + * + * @param string $code Code content to hack. + * @param string $path Path of the file being hacked. + * + * @return string The code after applying all the registered hacks. + */ + private static function hack( $code, $path ) { + foreach ( self::$hacks as $hack ) { + if ( is_callable( $hack ) ) { + $code = call_user_func( $hack, $code, $path ); + } else { + $code = $hack->hack( $code, $path ); + } + } + + return $code; + } + + /** + * Check if a file path is in the white list. + * + * @param string $path File path to check. + * + * @return bool TRUE if there's an entry in the white list that ends with $path, FALSE otherwise. + * + * @throws \Exception The class is not initialized. + */ + private static function path_in_list_of_paths_to_hack( $path ) { + if ( empty( self::$paths_with_files_to_hack ) ) { + throw new \Exception( "CodeHacker is not initialized, it must initialized by invoking 'initialize'" ); + } + foreach ( self::$paths_with_files_to_hack as $white_list_item ) { + if ( substr( $path, 0, strlen( $white_list_item ) ) === $white_list_item ) { + return true; + } + } + return false; + } +} + +//phpcs:enable WordPress.WP.AlternativeFunctions, WordPress.PHP.NoSilencedErrors.Discouraged + diff --git a/tests/Tools/CodeHacking/CodeHackerTestHook.php b/tests/Tools/CodeHacking/CodeHackerTestHook.php new file mode 100644 index 00000000000..18b0c9aafb6 --- /dev/null +++ b/tests/Tools/CodeHacking/CodeHackerTestHook.php @@ -0,0 +1,32 @@ + + * + * + */ +final class CodeHackerTestHook implements BeforeTestHook { + + /** + * Runs before each test. + * + * @param string $test "TestClass::TestMethod". + * + * @throws \ReflectionException Thrown by execute_before_methods. + */ + public function executeBeforeTest( string $test ): void { + CodeHacker::reset_hacks(); + } +} + diff --git a/tests/Tools/CodeHacking/Hacks/BypassFinalsHack.php b/tests/Tools/CodeHacking/Hacks/BypassFinalsHack.php new file mode 100644 index 00000000000..0d5f0b4e2fb --- /dev/null +++ b/tests/Tools/CodeHacking/Hacks/BypassFinalsHack.php @@ -0,0 +1,42 @@ +tokenize( $code ); + $code = ''; + foreach ( $tokens as $token ) { + $code .= $this->is_token_of_type( $token, T_FINAL ) ? '' : $this->token_to_string( $token ); + } + } + + return $code; + } + + /** + * Revert the hack to its initial state - nothing to do since finals can't be reverted. + */ + public function reset() { + } +} + diff --git a/tests/Tools/CodeHacking/Hacks/CodeHack.php b/tests/Tools/CodeHacking/Hacks/CodeHack.php new file mode 100644 index 00000000000..5f79b652558 --- /dev/null +++ b/tests/Tools/CodeHacking/Hacks/CodeHack.php @@ -0,0 +1,94 @@ + function($name, $default) { + * return 'foo' === $name ? 'bar' : get_option($name, $default); + * } + * ]); + * + * 1 and 2 must be done during the unit testing bootstrap process. + * + * Note that unless the tests directory is included in the hacking via 'CodeHacker::initialize' + * (and they shouldn't!), test code files aren't hacked, therefore the original functions are always + * executed inside tests (and thus the above example won't stack-overflow). + */ +final class FunctionsMockerHack extends CodeHack { + /** + * Tokens that precede a non-standalone-function identifier. + * + * @var array + */ + private static $non_global_function_tokens = array( + T_PAAMAYIM_NEKUDOTAYIM, + T_DOUBLE_COLON, + T_OBJECT_OPERATOR, + T_FUNCTION, + T_CLASS, + T_EXTENDS, + ); + + /** + * @var FunctionsMockerHack Holds the only existing instance of the class. + */ + private static $instance; + + /** + * Initializes the class. + * + * @param array $mockable_functions An array containing the names of the functions that will become mockable. + * + * @throws \Exception $mockable_functions is not an array or is empty. + */ + public static function initialize( $mockable_functions ) { + if ( ! is_array( $mockable_functions ) || empty( $mockable_functions ) ) { + throw new \Exception( 'FunctionsMockeHack::initialize: $mockable_functions must be a non-empty array of function names.' ); + } + + self::$instance = new FunctionsMockerHack( $mockable_functions ); + } + + /** + * FunctionsMockerHack constructor. + * + * @param array $mockable_functions An array containing the names of the functions that will become mockable. + */ + private function __construct( $mockable_functions ) { + $this->mockable_functions = $mockable_functions; + } + + /** + * Hacks code by replacing elegible function invocations with an invocation to this class' static method with the same name. + * + * @param string $code The code to hack. + * @param string $path The path of the file containing the code to hack. + * @return string The hacked code. + */ + public function hack( $code, $path ) { + $tokens = $this->tokenize( $code ); + $code = ''; + $previous_token_is_non_global_function_qualifier = false; + + foreach ( $tokens as $token ) { + $token_type = $this->token_type_of( $token ); + if ( T_WHITESPACE === $token_type ) { + $code .= $this->token_to_string( $token ); + } elseif ( T_STRING === $token_type && ! $previous_token_is_non_global_function_qualifier && in_array( $token[1], $this->mockable_functions, true ) ) { + $code .= __CLASS__ . "::{$token[1]}"; + $previous_token_is_non_global_function_qualifier = false; + } else { + $code .= $this->token_to_string( $token ); + $previous_token_is_non_global_function_qualifier = in_array( $token_type, self::$non_global_function_tokens, true ); + } + } + + return $code; + } + + /** + * @var array Functions that can be mocked, associative array of function name => callback. + */ + private $function_mocks = array(); + + /** + * Register function mocks. + * + * @param array $mocks Mocks as an associative array of function name => mock function with the same arguments as the original function. + * + * @throws \Exception Invalid input. + */ + public function register_function_mocks( $mocks ) { + if ( ! is_array( $mocks ) ) { + throw new \Exception( 'FunctionsMockerHack::add_function_mocks: $mocks must be an associative array of function name => callable.' ); + } + + foreach ( $mocks as $function_name => $mock ) { + if ( ! in_array( $function_name, $this->mockable_functions, true ) ) { + throw new \Exception( "FunctionsMockerHack::add_function_mocks: Can't mock '$function_name' since it isn't in the list of mockable functions supplied to 'initialize'." ); + } + if ( ! is_callable( $mock ) ) { + throw new \Exception( "FunctionsMockerHack::add_function_mocks: The mock supplied for '$function_name' isn't callable." ); + } + } + + $this->function_mocks = array_merge( $this->function_mocks, $mocks ); + } + + /** + * Register function mocks. + * + * @param array $mocks Mocks as an associative array of function name => mock function with the same arguments as the original function. + * + * @throws \Exception Invalid input. + */ + public static function add_function_mocks( $mocks ) { + self::$instance->register_function_mocks( $mocks ); + } + + /** + * Unregister all the registered function mocks. + */ + public function reset() { + $this->function_mocks = array(); + } + + /** + * Handler for undefined static methods on this class, it invokes the mock for the function if registered or the original function if not. + * + * @param string $name Name of the function. + * @param array $arguments Arguments for the function. + * + * @return mixed The return value from the invoked callback or function. + */ + public static function __callStatic( $name, $arguments ) { + if ( array_key_exists( $name, self::$instance->function_mocks ) ) { + return call_user_func_array( self::$instance->function_mocks[ $name ], $arguments ); + } else { + return call_user_func_array( $name, $arguments ); + } + } + + /** + * Get the only existing instance of this class. 'get_instance' is not used to avoid conflicts since that's a widely used method name. + * + * @return FunctionsMockerHack The only existing instance of this class. + */ + public static function get_hack_instance() { + return self::$instance; + } +} diff --git a/tests/Tools/CodeHacking/Hacks/StaticMockerHack.php b/tests/Tools/CodeHacking/Hacks/StaticMockerHack.php new file mode 100644 index 00000000000..9d1709c3b1f --- /dev/null +++ b/tests/Tools/CodeHacking/Hacks/StaticMockerHack.php @@ -0,0 +1,193 @@ + [ + * 'some_method' => function($some_arg) { + * return 'foo' === $some_arg ? 'bar' : SomeClass::some_method($some_arg); + * } + * ] + * ]); + * + * 1 and 2 must be done during the unit testing bootstrap process. + * + * Note that unless the tests directory is included in the hacking via 'CodeHacker::initialize' + * (and they shouldn't!), test code files aren't hacked, therefore the original functions are always + * executed inside tests (and thus the above example won't stack-overflow). + */ +final class StaticMockerHack extends CodeHack { + + /** + * @var StaticMockerHack Holds the only existing instance of the class. + */ + private static $instance; + + /** + * Initializes the class. + * + * @param array $mockable_classes An associative array of class name => array of class methods. + * + * @throws \Exception $mockable_functions is not an array or is empty. + */ + public static function initialize( $mockable_classes ) { + if ( ! is_array( $mockable_classes ) || empty( $mockable_classes ) ) { + throw new \Exception( 'StaticMockerHack::initialize:: $mockable_classes must be a non-empty associative array of class name => array of class methods.' ); + } + + self::$instance = new StaticMockerHack( $mockable_classes ); + } + + /** + * StaticMockerHack constructor. + * + * @param array $mockable_classes An associative array of class name => array of class methods. + */ + private function __construct( $mockable_classes ) { + $this->mockable_classes = $mockable_classes; + } + + /** + * Hacks code by replacing elegible method invocations with an invocation a static method on this class composed from the class and the method names. + * + * @param string $code The code to hack. + * @param string $path The path of the file containing the code to hack. + * @return string The hacked code. + * + */ + public function hack( $code, $path ) { + $last_item = null; + + $tokens = $this->tokenize( $code ); + $code = ''; + $current_token = null; + + // phpcs:ignore WordPress.CodeAnalysis.AssignmentInCondition.FoundInWhileCondition + while ( $current_token = current( $tokens ) ) { + if ( $this->is_token_of_type( $current_token, T_STRING ) && in_array( $current_token[1], $this->mockable_classes, true ) ) { + $class_name = $current_token[1]; + $next_token = next( $tokens ); + if ( $this->is_token_of_type( $next_token, T_DOUBLE_COLON ) ) { + $called_member = next( $tokens )[1]; + $code .= __CLASS__ . "::invoke__{$called_member}__for__{$class_name}"; + } else { + // Reference to source class, but not followed by '::'. + $code .= $this->token_to_string( $current_token ) . $this->token_to_string( $next_token ); + } + } else { + // Not a reference to source class. + $code .= $this->token_to_string( $current_token ); + } + next( $tokens ); + } + + return $code; + } + + /** + * @var array Associative array of class name => associative array of method name => callback. + */ + private $method_mocks = array(); + + /** + * Register method mocks. + * + * @param array $mocks Mocks as an associative array of class name => associative array of method name => mock method with the same arguments as the original method. + * + * @throws \Exception Invalid input. + */ + public function register_method_mocks( $mocks ) { + $exception_text = 'StaticMockerHack::register_method_mocks: $mocks must be an associative array of class name => associative array of method name => callable.'; + + if ( ! is_array( $mocks ) ) { + throw new \Exception( $exception_text ); + } + + foreach ( $mocks as $class_name => $class_mocks ) { + if ( ! is_string( $class_name ) || ! is_array( $class_mocks ) ) { + throw new \Exception( $exception_text ); + } + foreach ( $class_mocks as $method_name => $method_mock ) { + if ( ! is_string( $method_name ) || ! is_callable( $method_mock ) ) { + throw new \Exception( $exception_text ); + } + if ( ! in_array( $class_name, $this->mockable_classes, true ) ) { + throw new \Exception( "FunctionsMockerHack::add_function_mocks: Can't mock methods of the '$class_name' class since it isn't in the list of mockable classes supplied to 'initialize'." ); + } + } + } + + $this->method_mocks = array_merge_recursive( $this->method_mocks, $mocks ); + } + + /** + * Register method mocks. + * + * @param array $mocks Mocks as an associative array of class name => associative array of method name => mock method with the same arguments as the original method. + * + * @throws \Exception Invalid input. + */ + public static function add_method_mocks( $mocks ) { + self::$instance->register_method_mocks( $mocks ); + } + + /** + * Unregister all the registered method mocks. + */ + public function reset() { + $this->method_mocks = array(); + } + + /** + * Handler for undefined static methods on this class, it invokes the mock for the method if both the class and the method are registered, or the original method in the original class if not. + * + * @param string $name Name of the method. + * @param array $arguments Arguments for the function. + * + * @return mixed The return value from the invoked callback or method. + * + * @throws \Exception Invalid method name. + */ + public static function __callStatic( $name, $arguments ) { + preg_match( '/invoke__(.+)__for__(.+)/', $name, $matches ); + if ( empty( $matches ) ) { + throw new \Exception( 'Invalid method ' . __CLASS__ . "::{$name}" ); + } + + $class_name = $matches[2]; + $method_name = $matches[1]; + + if ( array_key_exists( $class_name, self::$instance->method_mocks ) && array_key_exists( $method_name, self::$instance->method_mocks[ $class_name ] ) ) { + return call_user_func_array( self::$instance->method_mocks[ $class_name ][ $method_name ], $arguments ); + } else { + return call_user_func_array( "{$class_name}::{$method_name}", $arguments ); + } + } + + /** + * Get the only existing instance of this class. 'get_instance' is not used to avoid conflicts since that's a widely used method name. + * + * @return StaticMockerHack The only existing instance of this class. + */ + public static function get_hack_instance() { + return self::$instance; + } +} diff --git a/tests/Tools/CodeHacking/README.md b/tests/Tools/CodeHacking/README.md new file mode 100644 index 00000000000..5bd143e14dd --- /dev/null +++ b/tests/Tools/CodeHacking/README.md @@ -0,0 +1,156 @@ +# Code Hacking + +Code hacking is a mechanism that modifies PHP code files while they are loaded. It's intended to ease unit testing code that would otherwise be very difficult or impossible to test (and **only** for this - see [An important note](#an-important-note) about that). + +Currently, the code hacker allows to do the following inside unit tests: + +* Replace standalone functions with custom callbacks. +* Replace invocations to public static methods with custom callbacks. +* Create subclasses of `final` classes. + +## How to use + +Let's go through an example. + +First, create a file named `class-wc-admin-foobar.php` in `includes/admin` with the following code: + +``` + function( $name, $default = false ) { + return "Mocked get_option invoked for '$name'"; + } + ]); + + $expected = "The option returns: Mocked get_option invoked for 'some_option'"; + $actual = $tested->do_something_that_depends_on_an_option(); + $this->assertEquals( $expected, $actual ); + } + + public function test_static_method_mocking() { + $tested = new WC_Admin_Foobar(); + + StaticMockerHack::add_method_mocks([ + 'WC_Some_Legacy_Service' => [ + 'do_something' => function( $what ) { + return "MOCKED do_something invoked for '$what'"; + } + ] + ]); + + $expected = "The legacy service returns: MOCKED do_something invoked for 'foobar'"; + $actual = $tested->do_something_that_depends_on_the_legacy_service( 'foobar' ); + $this->assertEquals( $expected, $actual ); + } +} +``` + +Then run `vendor/bin/phpunit tests/legacy/unit-tests/admin/class-wc-tests-admin-foobar.php` and see the magic happen. + +### Mocking functions + +For a function to be mockable its name needs to be included in the array returned by `tests/legacy/mockable-functions.php`, so if you need to mock a function that is not included in the array, just go and add it. + +Function mocks can be defined by using `FunctionsMockerHack::add_function_mocks`. This method accepts an associative array where keys are function names and values are callbacks with the same signature as the functions they are replacing. + +If you ever need to remove the configured function mocks from inside a test, you can do so by executing `FunctionsMockerHack::get_hack_instance()->reset()`. This is done automatically before each test via PHPUnit's `BeforeTestHook`, so normally you won't need to do that. + +Note that the code hacker is configured so that only the production code files are modified, the tests code itself is **not** modified. This means that you can use the original functions within your tests even if you have mocked them, for example the following would work: + +``` +//Mock get_option but only if the requested option name is 'foo' +FunctionsMockerHack::add_function_mocks([ + 'get_option' => function($name, $default = false) { + return 'foo' === $name ? 'mocked value for option foo' : get_option( $name, $default ); + } +]); +``` + +### Mocking public static methods + +For a public static method to be mockable the name of the class that defines it needs to be included in the array returned by `tests/legacy/classes-with-mockable-static-methods.php`, so if you need to mock a static method for a class that is not included in the array, just go and add it. + +Static method mocks can be defined by using `StaticMockerHack::add_method_mocks`. This method accepts an associative array where keys are class names and values are in turn associative arrays, those having method names as keys and callbacks with the same signature as the methods they are replacing as values. + +If you ever need to remove the configured static method mocks from inside a test, you can do so by executing `StaticMockerHack::get_hack_instance()->reset()`. This is done automatically before each test via PHPUnit's `BeforeTestHook`, so normally you won't need to do that. + +Note that the code hacker is configured so that only the production code files are modified, the tests code itself is **not** modified. This means that you can use the original static methods within your tests even if you have mocked them, for example the following would work: + +``` +StaticMockerHack::add_method_mocks([ + 'WC_Some_Legacy_Service' => [ + //Mock WC_Some_Legacy_Service::do_something but only if the supplied parameter is 'foo' + 'do_something' => function( $what ) { + return 'foo' === $what ? "MOCKED do_something invoked for '$what'" : WC_Some_Legacy_Service::do_something( $what ); + } + ] +]); +``` + +### Subclassing `final` classes + +Inside your test files you can create classes that extend classes marked as `final` thanks to the `BypassFinalsHack` that is registered at bootstrap time. No extra configuration is needed. + +If you want to try it out, mark the `WC_Admin_Foobar` in the previos example as `final`, then add the following to the tests file: `class WC_Admin_Foobar_Subclass extends WC_Admin_Foobar {}`. Without the hack you would get a `Class WC_Admin_Foobar_Subclass may not inherit from final class (WC_Admin_Foobar)` error when trying to run the tests. + +## How it works under the hood + +The core of the code hacker is the `CodeHacker` class, which is based on [the Bypass Finals project](https://github.com/dg/bypass-finals) by David Grudl. This class is actually [a streamWrapper class](https://www.php.net/manual/en/class.streamwrapper.php) for the regular filesystem, most of its methods are just short-circuited to the regular PHP filesystem handling functions but the `stream_open` method contains some code that allows the magic to happen. What it does (for PHP files only) is to read the file contents and apply all the necessary modifications to it, then if the code has been modified it is stored in a temporary file which is then the one that receives any further filesystem operations instead of the original file. That way, for all practical purposes the content of the file is the "hacked" content. + +The files inside `tests/Tools/CodeHacking/Hacks` implement the "hacks" (code file modifications) that are registered via `CodeHacker::add_hack` within `tests/legacy/bootstrap.php`. + +A `BeforeTestHook` is used to reset all hacks to its initial state to ensure that no functions or methods are being mocked when the test starts. + +The functions mocker works by replacing all instances of `the_function(...)` with `FunctionsMockerHack::the_function(...)`, then `FunctionsMockerHack::__call_static` is implemented in a way that invokes the appropriate callback if defined for the invoked function, or reverts to executing the original function if not. The static methods mocker works similarly, but replacing instances of `TheClass::the_method(...)` with `StaticMockerHack::invoke__the_method__for__TheClass(...)`. + +## Creating new hacks + +If you ever need to define a new hack to cover a different kind of code that's difficult to test, that's what you need to do. + +First, implement the hack as a class that contains a `public function hack($code, $path)` method and a `public function reset()` method. The former takes in `$code` a string with the contents of the file pointed by `$path` and returns the modified code, the later reverts the hack to its original state (e.g. for `FunctionsMockerHack` it unregisters all the previously registered function mocks). For convenience you can make your hack a subclass of `CodeHack` but that's not mandatory. + +Second, configure the hack as required inside the `initialize_code_hacker` method in `tests/legacy/bootstrap.php`, and register it using `CodeHacker::add_hack`. + +## Temporarily disabling the code hacker + +In a few rare cases the code hacker will cause problems with tests that do write operations on the local filesystem. In these cases it is possible to temporarily disable the code hacker using `self::disable_code_hacker()` and `self::reenable_code_hacker()` in the test (these methods are defined in `WC_Unit_Test_Case`). These methods are carefully written so that they won't enable the code hacker if it wasn't enabled when the test started, and there's a disabling requests count in place to ensure that the code hacker isn't enabled before it should. + +One of these cases is the usage of the `copy` command to copy files. Since this function is used in a few tests, a convenience `file_copy` method is defined in `WC_Unit_Test_Case`; it just temporarily disables the hacker, does the copy, and reenables the hacker. + +## An important note + +The code hacker is intended to be a **last resort** mechanism to test stuff that it's **really** difficult or impossible to test otherwise - the mechanisms already in place to help testing (e.g. the PHPUnit's mocks or the Woo helpers) should still be used whenever possible. And of course, the code hacker should not be an excuse to write code that's difficult to test. diff --git a/tests/e2e/env/README.md b/tests/e2e/env/README.md index 9f3f514a5b3..2d5f40dbea8 100644 --- a/tests/e2e/env/README.md +++ b/tests/e2e/env/README.md @@ -15,7 +15,7 @@ The `@woocommerce/e2e-environment` package exports configuration objects that ca ### Babel Config -Extend your project's Babel config to contain the expected presets for E2E testing. +Make sure you `npm install @babel/preset-env --save` if you have not already done so. Afterwards, extend your project's `babel.config.js` to contain the expected presets for E2E testing. ```js const { babelConfig: e2eBabelConfig } = require( '@woocommerce/e2e-environment' ); @@ -109,7 +109,7 @@ module.exports = { The E2E environment will look for a `docker-compose.yaml` file in your project root. This will be combined with the base Docker config in the package. This is where you'll map your local project files into the Docker container(s). ```yaml -version: '3.7' +version: '3.3' services: @@ -191,3 +191,7 @@ Stop Docker ```bash npm explore @woocommerce/e2e-environment -- npm run docker:down ``` + +## Additional information + +Refer to [`tests/e2e/specs`](https://github.com/woocommerce/woocommerce/tree/master/tests/e2e/specs) for some test examples, and [`tests/e2e`](https://github.com/woocommerce/woocommerce/tree/master/tests/e2e) for general information on e2e tests. diff --git a/tests/e2e/env/config/default.json b/tests/e2e/env/config/default.json index 13c4c230c8c..19693eece88 100644 --- a/tests/e2e/env/config/default.json +++ b/tests/e2e/env/config/default.json @@ -27,7 +27,7 @@ "country": "United States (US)", "addressfirstline": "addr 1", "addresssecondline": "addr 2", - "countryandstate": "United States (US) -- California", + "countryandstate": "United States (US) — California", "city": "San Francisco", "state": "CA", "postcode": "94107" diff --git a/tests/e2e/specs/activate-and-setup/setup-wizard.test.js b/tests/e2e/specs/activate-and-setup/setup-wizard.test.js index c8770c7ba66..cb0a8205336 100644 --- a/tests/e2e/specs/activate-and-setup/setup-wizard.test.js +++ b/tests/e2e/specs/activate-and-setup/setup-wizard.test.js @@ -6,20 +6,17 @@ * Internal dependencies */ import { StoreOwnerFlow } from '../../utils/flows'; -import { completeOldSetupWizard, completeOnboardingWizard } from '../../utils/components'; +import { completeOnboardingWizard } from '../../utils/components'; import { permalinkSettingsPageSaveChanges, setCheckbox, settingsPageSaveChanges, verifyCheckboxIsSet, - verifyCheckboxIsUnset, verifyValueOfInputField + verifyValueOfInputField } from '../../utils'; -const config = require( 'config' ); - describe( 'Store owner can login and make sure WooCommerce is activated', () => { - - it( 'can login', async () => { + beforeAll( async () => { await StoreOwnerFlow.login(); } ); @@ -56,25 +53,16 @@ describe( 'Store owner can go through setup Task List', () => { it( 'can setup shipping', async () => { // Query for all tasks on the list const taskListItems = await page.$$( '.woocommerce-list__item-title' ); - expect( taskListItems ).toHaveLength( 5 ); + expect( taskListItems ).toHaveLength( 6 ); await Promise.all( [ // Click on "Set up shipping" task to move to the next step - taskListItems[2].click(), + taskListItems[3].click(), // Wait for shipping setup section to load page.waitForNavigation( { waitUntil: 'networkidle0' } ), ] ); - // Query for store location fields - const storeLocationFields = await page.$$( '.components-text-control__input' ); - expect( storeLocationFields ).toHaveLength( 4 ); - - // Wait for "Continue" button to become active - await page.waitForSelector( 'button.is-primary:not(:disabled)' ); - // Click on "Continue" button to move to the shipping cost section - await page.click( 'button.is-primary' ); - // Wait for "Proceed" button to become active await page.waitForSelector( 'button.is-primary:not(:disabled)' ); await page.waitFor( 3000 ); diff --git a/tests/e2e/utils/components.js b/tests/e2e/utils/components.js index 06a7d4a87f2..37b0e99e080 100644 --- a/tests/e2e/utils/components.js +++ b/tests/e2e/utils/components.js @@ -121,11 +121,11 @@ const completeOnboardingWizard = async () => { } // Wait for "Continue" button to become active - await page.waitForSelector( 'button.woocommerce-profile-wizard__continue:not(:disabled)' ); + await page.waitForSelector( 'button.is-primary:not(:disabled)' ); await Promise.all( [ // Click on "Continue" button to move to the next step - page.click( 'button.woocommerce-profile-wizard__continue' ), + page.click( 'button.is-primary' ), // Wait for "Tell us about your business" section to load page.waitForNavigation( { waitUntil: 'networkidle0' } ), @@ -186,9 +186,9 @@ const completeOnboardingWizard = async () => { await page.waitForSelector( '.woocommerce-profile-wizard__header-title' ); // Wait for "No thanks" button to become active - await page.waitForSelector( 'button.is-default:not(:disabled)' ); + await page.waitForSelector( 'button.is-secondary:not(:disabled)' ); // Click on "No thanks" button to move to the next step - await page.click( 'button.is-default' ); + await page.click( 'button.is-secondary' ); // End of onboarding wizard diff --git a/tests/e2e/utils/flows.js b/tests/e2e/utils/flows.js index 50ea2716937..cb72820abb3 100644 --- a/tests/e2e/utils/flows.js +++ b/tests/e2e/utils/flows.js @@ -241,16 +241,15 @@ const StoreOwnerFlow = { }, logout: async () => { - await page.goto(baseUrl + 'wp-login.php?action=logout', { + // Log out link in admin bar is not visible so can't be clicked directly. + const logoutLinks = await page.$$eval( + '#wp-admin-bar-logout a', + ( am ) => am.filter( ( e ) => e.href ).map( ( e ) => e.href ) + ); + + await page.goto( logoutLinks[ 0 ], { waitUntil: 'networkidle0', - }); - - await expect(page).toMatch('You are attempting to log out'); - - await Promise.all([ - page.waitForNavigation({ waitUntil: 'networkidle0' }), - page.click('a'), - ]); + } ); }, openAllOrdersView: async () => { diff --git a/tests/legacy/bootstrap.php b/tests/legacy/bootstrap.php index c0a91df0ec3..9a5513ccebc 100644 --- a/tests/legacy/bootstrap.php +++ b/tests/legacy/bootstrap.php @@ -6,6 +6,12 @@ * @package WooCommerce Tests */ +use Automattic\WooCommerce\Testing\Tools\CodeHacking\CodeHacker; +use Automattic\WooCommerce\Testing\Tools\CodeHacking\Hacks\StaticMockerHack; +use Automattic\WooCommerce\Testing\Tools\CodeHacking\Hacks\FunctionsMockerHack; +use Automattic\WooCommerce\Testing\Tools\CodeHacking\Hacks\BypassFinalsHack; +use Composer\Autoload\ClassLoader; + /** * Class WC_Unit_Tests_Bootstrap */ @@ -29,6 +35,8 @@ class WC_Unit_Tests_Bootstrap { * @since 2.2 */ public function __construct() { + $this->tests_dir = dirname( __FILE__ ); + $this->initialize_code_hacker(); ini_set( 'display_errors', 'on' ); // phpcs:ignore WordPress.PHP.IniSet.display_errors_Blacklisted error_reporting( E_ALL ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.prevent_path_disclosure_error_reporting, WordPress.PHP.DiscouragedPHPFunctions.runtime_configuration_error_reporting @@ -40,8 +48,6 @@ class WC_Unit_Tests_Bootstrap { } // phpcs:enable WordPress.VIP.SuperGlobalInputUsage.AccessDetected - $this->tests_dir = dirname( __FILE__ ); - $this->plugin_dir = dirname( dirname( $this->tests_dir ) ); $this->wp_tests_dir = getenv( 'WP_TESTS_DIR' ) ? getenv( 'WP_TESTS_DIR' ) : sys_get_temp_dir() . '/wordpress-tests-lib'; // load test function so tests_add_filter() is available. @@ -60,6 +66,39 @@ class WC_Unit_Tests_Bootstrap { $this->includes(); } + /** + * Initialize the code hacker. + * + * @throws Exception Error when initializing one of the hacks. + */ + private function initialize_code_hacker() { + $this->plugin_dir = dirname( dirname( $this->tests_dir ) ); + + $hacking_base = $this->plugin_dir . '/tests/Tools/CodeHacking'; + require_once $hacking_base . '/CodeHacker.php'; + require_once $hacking_base . '/Hacks/CodeHack.php'; + require_once $hacking_base . '/Hacks/StaticMockerHack.php'; + require_once $hacking_base . '/Hacks/FunctionsMockerHack.php'; + require_once $hacking_base . '/Hacks/BypassFinalsHack.php'; + + CodeHacker::initialize( array( __DIR__ . '/../../includes/' ) ); + $replaceable_functions = include_once __DIR__ . '/mockable-functions.php'; + if ( ! empty( $replaceable_functions ) ) { + FunctionsMockerHack::initialize( $replaceable_functions ); + CodeHacker::add_hack( FunctionsMockerHack::get_hack_instance() ); + } + + $mockable_static_classes = include_once __DIR__ . '/classes-with-mockable-static-methods.php'; + if ( ! empty( $mockable_static_classes ) ) { + StaticMockerHack::initialize( $mockable_static_classes ); + CodeHacker::add_hack( StaticMockerHack::get_hack_instance() ); + } + + CodeHacker::add_hack( new BypassFinalsHack() ); + + CodeHacker::enable(); + } + /** * Load WooCommerce. * diff --git a/tests/legacy/classes-with-mockable-static-methods.php b/tests/legacy/classes-with-mockable-static-methods.php new file mode 100644 index 00000000000..5c4deecedfb --- /dev/null +++ b/tests/legacy/classes-with-mockable-static-methods.php @@ -0,0 +1,12 @@ + 0 ) { + self::$code_hacker_temporary_disables_requested++; + } + } + + /** + * Decrease the count of Code Hacker disable requests, and effectively re-enable it if the count reaches zero. + * Does nothing if the count is already zero. + */ + protected static function reenable_code_hacker() { + if ( self::$code_hacker_temporary_disables_requested > 0 ) { + self::$code_hacker_temporary_disables_requested--; + if ( 0 === self::$code_hacker_temporary_disables_requested ) { + CodeHacker::enable(); + } + } + } + /** * Setup test case. * @@ -99,4 +132,22 @@ class WC_Unit_Test_Case extends WP_HTTP_TestCase { $message = $message ? $message : "We're all doomed!"; throw new Exception( $message, $code ); } + + + /** + * Copies a file, temporarily disabling the code hacker. + * Use this instead of "copy" in tests for compatibility with the code hacker. + * + * TODO: Investigate why invoking "copy" within a test with the code hacker active causes the test to fail. + * + * @param string $source Path to the source file. + * @param string $dest The destination path. + * @return bool true on success or false on failure. + */ + public static function file_copy( $source, $dest ) { + self::disable_code_hacker(); + $result = copy( $source, $dest ); + self::reenable_code_hacker(); + return $result; + } } diff --git a/tests/legacy/mockable-functions.php b/tests/legacy/mockable-functions.php new file mode 100644 index 00000000000..6d01727f569 --- /dev/null +++ b/tests/legacy/mockable-functions.php @@ -0,0 +1,12 @@ +set_title( 'WooCommerce database update required' ); $note->set_content( 'To keep things running smoothly, we have to update your database to the newest version.' ); $note->set_type( WC_Admin_Note::E_WC_ADMIN_NOTE_UPDATE ); - $note->set_icon( 'info' ); $note->set_name( WC_Notes_Run_Db_Update::NOTE_NAME ); $note->set_content_data( (object) array() ); $note->set_source( 'woocommerce-core' ); diff --git a/tests/legacy/unit-tests/admin/settings.php b/tests/legacy/unit-tests/admin/settings.php new file mode 100644 index 00000000000..585d996e14e --- /dev/null +++ b/tests/legacy/unit-tests/admin/settings.php @@ -0,0 +1,35 @@ +assertEquals( 'deny from all', $file_content ); + + // Test with "redirect" downloads method. + update_option( 'woocommerce_file_download_method', 'redirect' ); + WC_Admin_Settings::check_download_folder_protection(); + $file_content = @file_get_contents( $file_path ); + $this->assertEquals( 'Options -Indexes', $file_content ); + + update_option( 'woocommerce_file_download_method', $default ); + } +} diff --git a/tests/legacy/unit-tests/cart/cart.php b/tests/legacy/unit-tests/cart/cart.php index 52b1df97195..ccfe0074fdf 100644 --- a/tests/legacy/unit-tests/cart/cart.php +++ b/tests/legacy/unit-tests/cart/cart.php @@ -2055,6 +2055,157 @@ class WC_Tests_Cart extends WC_Unit_Test_Case { $this->assertEquals( 70.86, WC()->cart->get_total( 'edit' ) ); } + /** + * Test that adding a variation with URL parameter increases the quantity appropriately + * as described in issue 24000. + */ + public function test_add_variation_by_url() { + add_filter( 'woocommerce_add_to_cart_redirect', '__return_false' ); + update_option( 'woocommerce_cart_redirect_after_add', 'no' ); + WC()->cart->empty_cart(); + WC()->session->set( 'wc_notices', null ); + + $product = WC_Helper_Product::create_variation_product(); + $variations = $product->get_available_variations(); + $variation = array_pop( $variations ); + + // Add variation with add_to_cart_action. + $_REQUEST['add-to-cart'] = $variation['variation_id']; + WC_Form_Handler::add_to_cart_action( false ); + $notices = WC()->session->get( 'wc_notices', array() ); + + // Reset filter / REQUEST variables. + unset( $_REQUEST['add-to-cart'] ); + remove_filter( 'woocommerce_add_to_cart_redirect', '__return_false' ); + + // Check if the item is in the cart. + $this->assertCount( 1, WC()->cart->get_cart_contents() ); + $this->assertEquals( 1, WC()->cart->get_cart_contents_count() ); + + // Check that there are no error notices. + $this->assertArrayNotHasKey( 'error', $notices ); + + // Add variation using parent id. + WC()->cart->add_to_cart( + $product->get_id(), + 1, + $variation['variation_id'], + array( + 'attribute_pa_size' => 'huge', + 'attribute_pa_colour' => 'red', + 'attribute_pa_number' => '2', + ) + ); + $notices = WC()->session->get( 'wc_notices', array() ); + + // Check that the second add to cart call increases the quantity of the existing cart-item. + $this->assertCount( 1, WC()->cart->get_cart_contents() ); + $this->assertEquals( 2, WC()->cart->get_cart_contents_count() ); + + // Check that there are no error notices. + $this->assertArrayNotHasKey( 'error', $notices ); + } + + /** + * Test that adding a variation via URL parameter fails when specifying a value for the attribute + * that differs from a value belonging to that variant. + */ + public function test_add_variation_by_url_with_invalid_attribute() { + add_filter( 'woocommerce_add_to_cart_redirect', '__return_false' ); + update_option( 'woocommerce_cart_redirect_after_add', 'no' ); + WC()->cart->empty_cart(); + WC()->session->set( 'wc_notices', null ); + + $product = WC_Helper_Product::create_variation_product(); + $variations = $product->get_available_variations(); + $variation = array_pop( $variations ); + + // Attempt adding variation with add_to_cart_action, specifying a different colour. + $_REQUEST['add-to-cart'] = $variation['variation_id']; + $_REQUEST['attribute_pa_colour'] = 'green'; + WC_Form_Handler::add_to_cart_action( false ); + $notices = WC()->session->get( 'wc_notices', array() ); + + // Reset filter / REQUEST variables. + unset( $_REQUEST['add-to-cart'] ); + unset( $_REQUEST['attribute_pa_colour'] ); + remove_filter( 'woocommerce_add_to_cart_redirect', '__return_false' ); + + // Check that the notices contain an error message about an invalid colour. + $this->assertArrayHasKey( 'error', $notices ); + $this->assertCount( 1, $notices['error'] ); + $this->assertEquals( 'Invalid value posted for colour', $notices['error'][0]['notice'] ); + } + + /** + * Test that adding a variation via URL parameter succeeds when some attributes belong to the + * variation and others are specificed via URL parameter. + */ + public function test_add_variation_by_url_with_valid_attribute() { + add_filter( 'woocommerce_add_to_cart_redirect', '__return_false' ); + update_option( 'woocommerce_cart_redirect_after_add', 'no' ); + WC()->cart->empty_cart(); + WC()->session->set( 'wc_notices', null ); + + $product = WC_Helper_Product::create_variation_product(); + $variations = $product->get_available_variations(); + $variation = array_shift( $variations ); + + // Attempt adding variation with add_to_cart_action, specifying attributes not defined in the variation. + $_REQUEST['add-to-cart'] = $variation['variation_id']; + $_REQUEST['attribute_pa_colour'] = 'red'; + $_REQUEST['attribute_pa_number'] = '1'; + WC_Form_Handler::add_to_cart_action( false ); + $notices = WC()->session->get( 'wc_notices', array() ); + + // Reset filter / REQUEST variables. + unset( $_REQUEST['add-to-cart'] ); + unset( $_REQUEST['attribute_pa_colour'] ); + unset( $_REQUEST['attribute_pa_number'] ); + remove_filter( 'woocommerce_add_to_cart_redirect', '__return_false' ); + + // Check if the item is in the cart. + $this->assertCount( 1, WC()->cart->get_cart_contents() ); + $this->assertEquals( 1, WC()->cart->get_cart_contents_count() ); + + // Check that there are no error notices. + $this->assertArrayNotHasKey( 'error', $notices ); + } + + /** + * Test that adding a varition via URL parameter fails when an 'any' attribute is missing. + */ + public function test_add_variation_by_url_fails_with_missing_any_attribute() { + add_filter( 'woocommerce_add_to_cart_redirect', '__return_false' ); + update_option( 'woocommerce_cart_redirect_after_add', 'no' ); + WC()->cart->empty_cart(); + WC()->session->set( 'wc_notices', null ); + + $product = WC_Helper_Product::create_variation_product(); + $variations = $product->get_available_variations(); + $variation = array_shift( $variations ); + + // Attempt adding variation with add_to_cart_action, without specifying attribute_pa_colour. + $_REQUEST['add-to-cart'] = $variation['variation_id']; + $_REQUEST['attribute_pa_number'] = '0'; + WC_Form_Handler::add_to_cart_action( false ); + $notices = WC()->session->get( 'wc_notices', array() ); + + // Reset filter / REQUEST variables. + unset( $_REQUEST['add-to-cart'] ); + unset( $_REQUEST['attribute_pa_number'] ); + remove_filter( 'woocommerce_add_to_cart_redirect', '__return_false' ); + + // Verify that there is nothing in the cart. + $this->assertCount( 0, WC()->cart->get_cart_contents() ); + $this->assertEquals( 0, WC()->cart->get_cart_contents_count() ); + + // Check that the notices contain an error message about an invalid colour. + $this->assertArrayHasKey( 'error', $notices ); + $this->assertCount( 1, $notices['error'] ); + $this->assertEquals( 'colour is a required field', $notices['error'][0]['notice'] ); + } + /** * Helper function. Adds 1.5 taxable fees to cart. */ diff --git a/tests/legacy/unit-tests/checkout/checkout.php b/tests/legacy/unit-tests/checkout/checkout.php index fb2ad7ea82d..d6639ec88ab 100644 --- a/tests/legacy/unit-tests/checkout/checkout.php +++ b/tests/legacy/unit-tests/checkout/checkout.php @@ -9,9 +9,8 @@ * Class WC_Checkout */ class WC_Tests_Checkout extends WC_Unit_Test_Case { - /** - * TearDown for tests. + * TearDown. */ public function tearDown() { parent::tearDown(); @@ -19,7 +18,7 @@ class WC_Tests_Checkout extends WC_Unit_Test_Case { } /** - * Setup for tests. + * Setup. */ public function setUp() { parent::setUp(); @@ -32,24 +31,24 @@ class WC_Tests_Checkout extends WC_Unit_Test_Case { * @throws Exception When unable to create order. */ public function test_create_order_with_limited_coupon() { - $coupon_code = 'coupon4one'; + $coupon_code = 'coupon4one'; $coupon_data_store = WC_Data_Store::load( 'coupon' ); - $coupon = WC_Helper_Coupon::create_coupon( + $coupon = WC_Helper_Coupon::create_coupon( $coupon_code, array( 'usage_limit' => 1 ) ); - $product = WC_Helper_Product::create_simple_product( true ); + $product = WC_Helper_Product::create_simple_product( true ); WC()->cart->add_to_cart( $product->get_id(), 1 ); WC()->cart->add_discount( $coupon->get_code() ); $checkout = WC_Checkout::instance(); $order_id = $checkout->create_order( array( - 'billing_email' => 'a@b.com', + 'billing_email' => 'a@b.com', 'payment_method' => 'dummy_payment_gateway', ) ); $this->assertNotWPError( $order_id ); - $order = new WC_Order( $order_id ); + $order = new WC_Order( $order_id ); $coupon_held_key = $order->get_data_store()->get_coupon_held_keys( $order ); $this->assertEquals( count( $coupon_held_key ), 1 ); $this->assertEquals( array_keys( $coupon_held_key )[0], $coupon->get_id() ); @@ -61,7 +60,7 @@ class WC_Tests_Checkout extends WC_Unit_Test_Case { WC()->cart->add_discount( $coupon->get_code() ); $order2_id = $checkout->create_order( array( - 'billing_email' => 'a@c.com', + 'billing_email' => 'a@c.com', 'payment_method' => 'dummy_payment_gateway', ) ); @@ -75,8 +74,8 @@ class WC_Tests_Checkout extends WC_Unit_Test_Case { * @throws Exception When unable to create an order. */ public function test_create_order_with_multiple_limited_coupons() { - $coupon_code1 = 'coupon1'; - $coupon_code2 = 'coupon2'; + $coupon_code1 = 'coupon1'; + $coupon_code2 = 'coupon2'; $coupon_data_store = WC_Data_Store::load( 'coupon' ); $coupon1 = WC_Helper_Coupon::create_coupon( @@ -91,10 +90,10 @@ class WC_Tests_Checkout extends WC_Unit_Test_Case { WC()->cart->add_to_cart( $product->get_id(), 1 ); WC()->cart->add_discount( $coupon_code1 ); WC()->cart->add_discount( $coupon_code2 ); - $checkout = WC_Checkout::instance(); + $checkout = WC_Checkout::instance(); $order_id1 = $checkout->create_order( array( - 'billing_email' => 'a@b.com', + 'billing_email' => 'a@b.com', 'payment_method' => 'dummy_payment_gateway', ) ); @@ -110,7 +109,7 @@ class WC_Tests_Checkout extends WC_Unit_Test_Case { $order2_id = $checkout->create_order( array( - 'billing_email' => 'a@b.com', + 'billing_email' => 'a@b.com', 'payment_method' => 'dummy_payment_gateway', ) ); @@ -188,4 +187,120 @@ class WC_Tests_Checkout extends WC_Unit_Test_Case { return 0.01; } + /** + * Helper method to create a managed product and a order for that product. + * + * @return array + * @throws Exception When unable to create an order . + */ + protected function create_order_for_managed_inventory_product() { + $product = WC_Helper_Product::create_simple_product(); + $product->set_props( array( 'manage_stock' => true ) ); + $product->set_stock_quantity( 10 ); + $product->save(); + + WC()->cart->add_to_cart( $product->get_id(), 9 ); + $this->assertEquals( true, WC()->cart->check_cart_items() ); + + $checkout = WC_Checkout::instance(); + $order_id = $checkout->create_order( + array( + 'payment_method' => 'cod', + 'billing_email' => 'a@b.com', + ) + ); + + // Assertions whether the order was created successfully. + $this->assertNotWPError( $order_id ); + $order = wc_get_order( $order_id ); + + return array( $product, $order ); + } + + /** + * Test when order is out stock because it is held by an order in pending status. + * + * @throws Exception When unable to create order. + */ + public function test_create_order_when_out_of_stock() { + list( $product, $order ) = $this->create_order_for_managed_inventory_product(); + + $this->assertEquals( 9, $order->get_item_count() ); + $this->assertEquals( 'pending', $order->get_status() ); + $this->assertEquals( 9, wc_get_held_stock_quantity( $product ) ); + + WC()->cart->empty_cart(); + WC()->cart->add_to_cart( $product->get_stock_managed_by_id(), 2 ); + + $this->assertEquals( false, WC()->cart->check_cart_items() ); + } + + /** + * Test if pending stock is cleared when order is cancelled. + * + * @throws Exception When unable to create order. + */ + public function test_pending_is_cleared_when_order_is_cancelled() { + list( $product, $order ) = $this->create_order_for_managed_inventory_product(); + + $this->assertEquals( 9, wc_get_held_stock_quantity( $product ) ); + $order->set_status( 'cancelled' ); + $order->save(); + + $this->assertEquals( 0, wc_get_held_stock_quantity( $product ) ); + $this->assertEquals( 10, $product->get_stock_quantity() ); + + } + + /** + * Test if pending stock is cleared when order is processing. + * + * @throws Exception When unable to create order. + */ + public function test_pending_is_cleared_when_order_processed() { + list( $product, $order ) = $this->create_order_for_managed_inventory_product(); + + $this->assertEquals( 9, wc_get_held_stock_quantity( $product ) ); + $order->set_status( 'processing' ); + $order->save(); + + $this->assertEquals( 0, wc_get_held_stock_quantity( $product ) ); + } + + /** + * Test creating order from managed stock for variable product. + * + * @throws Exception When unable to create an order. + */ + public function test_create_order_for_variation_product() { + $parent_product = WC_Helper_Product::create_variation_product(); + $variation = $parent_product->get_available_variations()[0]; + $variation = wc_get_product( $variation['variation_id'] ); + $variation->set_manage_stock( true ); + $variation->set_stock_quantity( 10 ); + $variation->save(); + WC()->cart->add_to_cart( $variation->get_id(), 9 ); + $this->assertEquals( true, WC()->cart->check_cart_items() ); + + $checkout = WC_Checkout::instance(); + $order_id = $checkout->create_order( + array( + 'payment_method' => 'cod', + 'billing_email' => 'a@b.com', + ) + ); + + // Assertions whether the first order was created successfully. + $this->assertNotWPError( $order_id ); + $order = wc_get_order( $order_id ); + + $this->assertEquals( 9, $order->get_item_count() ); + $this->assertEquals( 'pending', $order->get_status() ); + $this->assertEquals( 9, wc_get_held_stock_quantity( $variation ) ); + + WC()->cart->empty_cart(); + WC()->cart->add_to_cart( $variation->get_stock_managed_by_id(), 2 ); + + $this->assertEquals( false, WC()->cart->check_cart_items() ); + } } diff --git a/tests/legacy/unit-tests/formatting/functions.php b/tests/legacy/unit-tests/formatting/functions.php index a2e517dfea4..10c52e4fa2c 100644 --- a/tests/legacy/unit-tests/formatting/functions.php +++ b/tests/legacy/unit-tests/formatting/functions.php @@ -699,15 +699,15 @@ class WC_Tests_Formatting_Functions extends WC_Unit_Test_Case { // Test with missing UTC offset. delete_option( 'gmt_offset' ); - $this->assertEquals( 'UTC', wc_timezone_string() ); + $this->assertContains( wc_timezone_string(), array( '+00:00', 'UTC' ) ); // Test with manually set UTC offset. update_option( 'gmt_offset', -4 ); - $this->assertNotEquals( 'UTC', wc_timezone_string() ); + $this->assertNotContains( wc_timezone_string(), array( '+00:00', 'UTC' ) ); // Test with invalid offset. - update_option( 'gmt_offset', 99 ); - $this->assertEquals( 'UTC', wc_timezone_string() ); + update_option( 'gmt_offset', 'invalid' ); + $this->assertContains( wc_timezone_string(), array( '+00:00', 'UTC' ) ); // Restore default. update_option( 'gmt_offset', '0' ); diff --git a/tests/legacy/unit-tests/importer/product.php b/tests/legacy/unit-tests/importer/product.php index 4a8bad510da..e55fdd79351 100644 --- a/tests/legacy/unit-tests/importer/product.php +++ b/tests/legacy/unit-tests/importer/product.php @@ -147,7 +147,7 @@ class WC_Tests_Product_CSV_Importer extends WC_Unit_Test_Case { * @return void */ public function test_server_file() { - copy( $this->csv_file, ABSPATH . '/sample.csv' ); + self::file_copy( $this->csv_file, ABSPATH . '/sample.csv' ); $_POST['file_url'] = 'sample.csv'; $import_controller = new WC_Product_CSV_Importer_Controller(); $this->assertEquals( ABSPATH . 'sample.csv', $import_controller->handle_upload() ); @@ -644,7 +644,7 @@ class WC_Tests_Product_CSV_Importer extends WC_Unit_Test_Case { if ( false !== strpos( $url, 'http://demo.woothemes.com' ) ) { if ( ! empty( $request['filename'] ) ) { - copy( WC_Unit_Tests_Bootstrap::instance()->tests_dir . '/data/Dr1Bczxq4q.png', $request['filename'] ); + self::file_copy( WC_Unit_Tests_Bootstrap::instance()->tests_dir . '/data/Dr1Bczxq4q.png', $request['filename'] ); } $mocked_response = array( diff --git a/tests/legacy/unit-tests/integrations/maxmind-geolocation/class-wc-tests-maxmind-database.php b/tests/legacy/unit-tests/integrations/maxmind-geolocation/class-wc-tests-maxmind-database.php index e4018d93824..6e424380a33 100644 --- a/tests/legacy/unit-tests/integrations/maxmind-geolocation/class-wc-tests-maxmind-database.php +++ b/tests/legacy/unit-tests/integrations/maxmind-geolocation/class-wc-tests-maxmind-database.php @@ -57,7 +57,12 @@ class WC_Tests_MaxMind_Database extends WC_Unit_Test_Case { $database_service = new WC_Integration_MaxMind_Database_Service( '' ); $expected_database = sys_get_temp_dir() . '/GeoLite2-Country_20200100/GeoLite2-Country.mmdb'; + self::disable_code_hacker(); $result = $database_service->download_database( 'testing_license' ); + self::reenable_code_hacker(); + if ( is_wp_error( $result ) ) { + $this->fail( $result->get_error_message() ); + } $this->assertEquals( $expected_database, $result ); @@ -126,7 +131,7 @@ class WC_Tests_MaxMind_Database extends WC_Unit_Test_Case { if ( 'https://download.maxmind.com/app/geoip_download?edition_id=GeoLite2-Country&license_key=testing_license&suffix=tar.gz' === $url ) { // We need to copy the file to where the request is supposed to have streamed it. - copy( WC_Unit_Tests_Bootstrap::instance()->tests_dir . '/data/GeoLite2-Country.tar.gz', $request['filename'] ); + self::file_copy( WC_Unit_Tests_Bootstrap::instance()->tests_dir . '/data/GeoLite2-Country.tar.gz', $request['filename'] ); $mocked_response = array( 'response' => array( 'code' => 200 ), diff --git a/tests/legacy/unit-tests/order/class-wc-tests-orders.php b/tests/legacy/unit-tests/order/class-wc-tests-orders.php index 20305f95ed1..4877745a592 100644 --- a/tests/legacy/unit-tests/order/class-wc-tests-orders.php +++ b/tests/legacy/unit-tests/order/class-wc-tests-orders.php @@ -8,7 +8,7 @@ /** * Class WC_Tests_Order. */ -class WC_Tests_Order extends WC_Unit_Test_Case { +class WC_Tests_Orders extends WC_Unit_Test_Case { /** * Test for total when round at subtotal is enabled. diff --git a/tests/legacy/unit-tests/order/coupons.php b/tests/legacy/unit-tests/order/coupons.php index 0fdb4fce3e9..dbfbea78180 100644 --- a/tests/legacy/unit-tests/order/coupons.php +++ b/tests/legacy/unit-tests/order/coupons.php @@ -371,6 +371,7 @@ class WC_Tests_Order_Coupons extends WC_Unit_Test_Case { public function test_inclusive_tax_rounding_on_totals() { update_option( 'woocommerce_prices_include_tax', 'yes' ); update_option( 'woocommerce_calc_taxes', 'yes' ); + update_option( 'woocommerce_tax_round_at_subtotal', 'yes' ); WC_Tax::_insert_tax_rate( array( @@ -440,12 +441,9 @@ class WC_Tests_Order_Coupons extends WC_Unit_Test_Case { $order->apply_coupon( $coupon->get_code() ); $applied_coupons = $order->get_items( 'coupon' ); - $applied_coupon = current( $applied_coupons ); $this->assertEquals( '16.95', $order->get_total() ); $this->assertEquals( '1.73', $order->get_total_tax() ); $this->assertEquals( '1.69', $order->get_discount_total() ); - - $this->assertEquals( '1.69', $applied_coupon->get_discount() ); } } diff --git a/tests/legacy/unit-tests/util/api-functions.php b/tests/legacy/unit-tests/util/api-functions.php index bdd1ebf7653..3fb98c57b12 100644 --- a/tests/legacy/unit-tests/util/api-functions.php +++ b/tests/legacy/unit-tests/util/api-functions.php @@ -236,14 +236,14 @@ class WC_Tests_API_Functions extends WC_Unit_Test_Case { } elseif ( 'http://somedomain.com/invalid-image-2.png' === $url ) { // image with an unsupported mime type. // we need to manually copy the file as we are mocking the request. without this an empty file is created. - copy( WC_Unit_Tests_Bootstrap::instance()->tests_dir . '/data/file.txt', $request['filename'] ); + self::file_copy( WC_Unit_Tests_Bootstrap::instance()->tests_dir . '/data/file.txt', $request['filename'] ); $mocked_response = array( 'response' => array( 'code' => 200 ), ); } elseif ( 'http://somedomain.com/' . $this->file_name === $url ) { // we need to manually copy the file as we are mocking the request. without this an empty file is created. - copy( WC_Unit_Tests_Bootstrap::instance()->tests_dir . '/data/Dr1Bczxq4q.png', $request['filename'] ); + self::file_copy( WC_Unit_Tests_Bootstrap::instance()->tests_dir . '/data/Dr1Bczxq4q.png', $request['filename'] ); $mocked_response = array( 'response' => array( 'code' => 200 ), diff --git a/tests/legacy/unit-tests/util/class-wc-tests-core-functions.php b/tests/legacy/unit-tests/util/class-wc-tests-core-functions.php index 9482291d412..5db7b9dfec4 100644 --- a/tests/legacy/unit-tests/util/class-wc-tests-core-functions.php +++ b/tests/legacy/unit-tests/util/class-wc-tests-core-functions.php @@ -283,7 +283,7 @@ class WC_Tests_Core_Functions extends WC_Unit_Test_Case { public function test_wc_get_log_file_path() { $log_dir = trailingslashit( WC_LOG_DIR ); $hash_name = sanitize_file_name( wp_hash( 'unit-tests' ) ); - $date_suffix = date( 'Y-m-d', time() ); + $date_suffix = date( 'Y-m-d', time() ); // phpcs:ignore WordPress.DateTime.RestrictedFunctions.date_date $this->assertEquals( $log_dir . 'unit-tests-' . $date_suffix . '-' . $hash_name . '.log', wc_get_log_file_path( 'unit-tests' ) ); } @@ -569,6 +569,81 @@ class WC_Tests_Core_Functions extends WC_Unit_Test_Case { $this->assertEmpty( wc_get_template_part( 'nothinghere' ) ); } + /** + * Tests the wc_tokenize_path function. + */ + public function test_wc_tokenize_path() { + $path = wc_tokenize_path( ABSPATH . 'test', array() ); + $this->assertEquals( ABSPATH . 'test', $path ); + + $path = wc_tokenize_path( + ABSPATH . 'test', + array( + 'ABSPATH' => ABSPATH, + ) + ); + $this->assertEquals( '{{ABSPATH}}test', $path ); + + $path = wc_tokenize_path( + ABSPATH . 'test', + array( + 'WP_CONTENT_DIR' => WP_CONTENT_DIR, + ) + ); + $this->assertEquals( ABSPATH . 'test', $path ); + + $path = wc_tokenize_path( + WP_CONTENT_DIR . 'test', + array( + 'ABSPATH' => ABSPATH, + 'WP_CONTENT_DIR' => WP_CONTENT_DIR, + ) + ); + $this->assertEquals( '{{WP_CONTENT_DIR}}test', $path ); + } + + /** + * Tests the wc_untokenize_path function. + */ + public function test_wc_untokenize_path() { + $path = wc_untokenize_path( '{{ABSPATH}}test', array() ); + $this->assertEquals( '{{ABSPATH}}test', $path ); + + $path = wc_untokenize_path( + '{{ABSPATH}}test', + array( + 'ABSPATH' => ABSPATH, + ) + ); + $this->assertEquals( ABSPATH . 'test', $path ); + + $path = wc_untokenize_path( + '{{ABSPATH}}test', + array( + 'WP_CONTENT_DIR' => WP_CONTENT_DIR, + ) + ); + $this->assertEquals( '{{ABSPATH}}test', $path ); + + $path = wc_untokenize_path( + '{{WP_CONTENT_DIR}}test', + array( + 'WP_CONTENT_DIR' => WP_CONTENT_DIR, + 'ABSPATH' => ABSPATH, + ) + ); + $this->assertEquals( WP_CONTENT_DIR . 'test', $path ); + } + + /** + * Tests the wc_get_path_define_tokens function. + */ + public function test_wc_get_path_define_tokens() { + $defines = wc_get_path_define_tokens(); + $this->assertArrayHasKey( 'ABSPATH', $defines ); + $this->assertEquals( ABSPATH, $defines['ABSPATH'] ); + } + /** * Test wc_get_template. * @@ -606,6 +681,28 @@ class WC_Tests_Core_Functions extends WC_Unit_Test_Case { $this->assertNotEmpty( $template ); } + /** + * This test ensures that the absolute path to template files is replaced with a token. We do this so + * that the path can be made relative to each installation, and the cache can be shared. + */ + public function test_wc_get_template_cleans_absolute_path() { + add_filter( 'woocommerce_locate_template', array( $this, 'force_template_path' ), 10, 2 ); + + ob_start(); + try { + wc_get_template( 'global/wrapper-start.php' ); + } catch ( \Exception $exception ) { // phpcs:ignore Generic.CodeAnalysis.EmptyStatement.DetectedCatch + // Since the file doesn't really exist this is going to throw an exception (which is fine for our test). + } + ob_end_clean(); + + remove_filter( 'woocommerce_locate_template', array( $this, 'force_template_path' ) ); + + $file_path = wp_cache_get( sanitize_key( 'template-global/wrapper-start.php---' . WC_VERSION ), 'woocommerce' ); + + $this->assertEquals( '{{ABSPATH}}global/wrapper-start.php', $file_path ); + } + /** * Test wc_get_image_size function. * @@ -956,7 +1053,9 @@ class WC_Tests_Core_Functions extends WC_Unit_Test_Case { $this->assertInstanceOf( 'WC_Customer', $this->wc->customer ); $this->assertInstanceOf( 'WC_Session', $this->wc->session ); - $this->wc->cart = $this->wc->customer = $this->wc->session = null; + $this->wc->cart = null; + $this->wc->customer = null; + $this->wc->session = null; $this->assertNull( $this->wc->cart ); $this->assertNull( $this->wc->customer ); $this->assertNull( $this->wc->session ); @@ -967,4 +1066,16 @@ class WC_Tests_Core_Functions extends WC_Unit_Test_Case { $this->assertInstanceOf( 'WC_Session', $this->wc->session ); } + + /** + * Allows us to force the template path. Since the ABSPATH is to /tmp/wordpress in tests, we need to do this + * in order to keep the paths consistent for testing purposes. + * + * @param string $template The path to the template file. + * @param string $template_name The name of the template file. + * @return string The path to be used instead. + */ + public function force_template_path( $template, $template_name ) { + return ABSPATH . $template_name; + } } diff --git a/tests/legacy/unit-tests/util/install.php b/tests/legacy/unit-tests/util/install.php index 44b28b7161e..49e4112d3a5 100644 --- a/tests/legacy/unit-tests/util/install.php +++ b/tests/legacy/unit-tests/util/install.php @@ -38,6 +38,7 @@ class WC_Tests_Install extends WC_Unit_Test_Case { /** * Test - install. */ + /** public function test_install() { // clean existing install first. if ( ! defined( 'WP_UNINSTALL_PLUGIN' ) ) { @@ -52,6 +53,8 @@ class WC_Tests_Install extends WC_Unit_Test_Case { $this->assertEquals( WC()->version, get_option( 'woocommerce_version' ) ); } + * + **/ /** * Test - create pages. diff --git a/tests/php/includes/WCInstallTest.php b/tests/php/includes/WCInstallTest.php new file mode 100644 index 00000000000..063edef6280 --- /dev/null +++ b/tests/php/includes/WCInstallTest.php @@ -0,0 +1,92 @@ +prefix}wc_tax_rate_classes"; + $changed_table_name = "{$wpdb->prefix}wc_tax_rate_classes_2"; + $clear_query = 'DROP TABLE IF EXISTS %s;'; + $rename_table_query = 'RENAME TABLE %s to %s;'; + + // Workaround to call a private function. + $schema = function () { + return static::get_schema(); + }; + + // Rename a base table to simulate it as non-existing. + dbDelta( $schema->call( new \WC_Install() ) ); // Restore correct state. + $wpdb->query( sprintf( $clear_query, $changed_table_name ) ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared + $wpdb->query( sprintf( $rename_table_query, $original_table_name, $changed_table_name ) ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared + + $missing_tables = \WC_Install::verify_base_tables(); + + $wpdb->query( sprintf( $rename_table_query, $changed_table_name, $original_table_name ) ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared + add_filter( 'query', array( $this, '_drop_temporary_tables' ) ); + + $this->assertContains( $original_table_name, $missing_tables ); + $this->assertContains( 'base_tables_missing', \WC_Admin_Notices::get_notices() ); + + // Ideally, no missing table anymore because we have switched back table name. + $missing_tables = \WC_Install::verify_base_tables(); + + $this->assertNotContains( $original_table_name, $missing_tables ); + $this->assertNotContains( 'base_tables_missing', \WC_Admin_Notices::get_notices() ); + } + + + /** + * Test if verify base table can fix the table as well. + */ + public function test_verify_base_tables_fix_tables() { + global $wpdb; + + // Remove drop filter because we do want to drop temp table if it exists. + // This filter was added to only allow dropping temporary tables which will then be rollbacked after the test. + remove_filter( 'query', array( $this, '_drop_temporary_tables' ) ); + + $original_table_name = "{$wpdb->prefix}wc_tax_rate_classes"; + $changed_table_name = "{$wpdb->prefix}wc_tax_rate_classes_2"; + $clear_query = 'DROP TABLE IF EXISTS %s;'; + $rename_table_query = 'RENAME TABLE %s to %s;'; + + // Workaround to call a private function. + $schema = function () { + return static::get_schema(); + }; + + // Rename a base table to simulate it as non-existing. + dbDelta( $schema->call( new \WC_Install() ) ); // Restore correct state. + $wpdb->query( sprintf( $clear_query, $changed_table_name ) ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared + $wpdb->query( sprintf( $rename_table_query, $original_table_name, $changed_table_name ) ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared + + $missing_tables = \WC_Install::verify_base_tables( true, true ); + + $wpdb->query( sprintf( $clear_query, $original_table_name ) ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared + $wpdb->query( sprintf( $rename_table_query, $changed_table_name, $original_table_name ) ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared + add_filter( 'query', array( $this, '_drop_temporary_tables' ) ); + + // Ideally, no missing table because verify base tables created the table as well. + $this->assertNotContains( $original_table_name, $missing_tables ); + $this->assertNotContains( 'base_tables_missing', \WC_Admin_Notices::get_notices() ); + } + +} diff --git a/tests/php/includes/abstracts/class-wc-abstract-order-test.php b/tests/php/includes/abstracts/class-wc-abstract-order-test.php new file mode 100644 index 00000000000..bcb04fa28b5 --- /dev/null +++ b/tests/php/includes/abstracts/class-wc-abstract-order-test.php @@ -0,0 +1,76 @@ + '', + 'tax_rate_state' => '', + 'tax_rate' => '15.0000', + 'tax_rate_name' => 'tax', + 'tax_rate_priority' => '1', + 'tax_rate_order' => '1', + ); + WC_Tax::_insert_tax_rate( $tax_rate ); + + $product1 = WC_Helper_Product::create_simple_product(); + $product1->set_regular_price( 99.48 ); + $product1->save(); + + $product2 = WC_Helper_Product::create_simple_product(); + $product2->set_regular_price( 108.68 ); + $product2->save(); + + $order = new WC_Order(); + $order->add_product( $product1, 6 ); + $order->add_product( $product2, 6 ); + $order->save(); + + $this->order_calculate_rounding_line( $order ); + $this->order_calculate_rounding_subtotal( $order ); + } + + /** + * Helper method to test rounding per line for `test_order_calculate_26582`. + * + * @param WC_Order $order Order object. + */ + private function order_calculate_rounding_line( $order ) { + update_option( 'woocommerce_tax_round_at_subtotal', 'no' ); + + $order->calculate_totals( true ); + + $this->assertEquals( 1086.06, $order->get_subtotal() ); + $this->assertEquals( 162.90, $order->get_total_tax() ); + $this->assertEquals( 1248.96, $order->get_total() ); + } + + /** + * Helper method to test rounding at subtotal for `test_order_calculate_26582`. + * + * @param WC_Order $order Order object. + */ + private function order_calculate_rounding_subtotal( $order ) { + update_option( 'woocommerce_tax_round_at_subtotal', 'yes' ); + + $order->calculate_totals( true ); + + $this->assertEquals( 1086.05, $order->get_subtotal() ); + $this->assertEquals( 162.91, $order->get_total_tax() ); + $this->assertEquals( 1248.96, $order->get_total() ); + } + +} diff --git a/woocommerce.php b/woocommerce.php index 45142ab1df2..47da64854ef 100644 --- a/woocommerce.php +++ b/woocommerce.php @@ -8,6 +8,8 @@ * Author URI: https://woocommerce.com * Text Domain: woocommerce * Domain Path: /i18n/languages/ + * Requires at least: 5.2 + * Requires PHP: 7.0 * * @package WooCommerce */

        +

        + +

        +
        : ' : ''; ?>