Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

🎯 fix: DB related PHPCS security issues #2271

Open
wants to merge 24 commits into
base: develop
Choose a base branch
from

Conversation

devAsadNur
Copy link
Member

@devAsadNur devAsadNur commented May 10, 2024

All Submissions:

  • My code follow the WordPress' coding standards
  • My code satisfies feature requirements
  • My code is tested
  • My code passes the PHPCS tests
  • My code has proper inline documentation
  • I've included related pull request(s) (optional)
  • I've included developer documentation (optional)
  • I've added proper labels to this pull request

Changes proposed in this Pull Request:

Related Pull Request(s)

  • Full PR Link

Closes

  • Closes #

How to test the changes in this Pull Request:

  • Steps or issue link

Changelog entry

Title

Detailed Description of the pull request. What was previous behaviour
and what will be changed in this PR.

Before Changes

Describe the issue before changes with screenshots(s).

After Changes

Describe the issue after changes with screenshot(s).

Feature Video (optional)

Link of detailed video if this PR is for a feature.

PR Self Review Checklist:

  • Code is not following code style guidelines
  • Bad naming: make sure you would understand your code if you read it a few months from now.
  • KISS: Keep it simple, Sweetie (not stupid!).
  • DRY: Don't Repeat Yourself.
  • Code that is not readable: too many nested 'if's are a bad sign.
  • Performance issues
  • Complicated constructions that need refactoring or comments: code should almost always be self-explanatory.
  • Grammar errors.

FOR PR REVIEWER ONLY:

As a reviewer, your feedback should be focused on the idea, not the person. Seek to understand, be respectful, and focus on constructive dialog.

As a contributor, your responsibility is to learn from suggestions and iterate your pull request should it be needed based on feedback. Seek to collaborate and produce the best possible contribution to the greater whole.

  • Correct — Does the change do what it’s supposed to? ie: code 100% fulfilling the requirements?
  • Secure — Would a nefarious party find some way to exploit this change? ie: everything is sanitized/escaped appropriately for any SQL or XSS injection possibilities?
  • Readable — Will your future self be able to understand this change months down the road?
  • Elegant — Does the change fit aesthetically within the overall style and architecture?

Summary by CodeRabbit

  • New Features

    • Introduced methods to handle downloadable products, including retrieving, granting, and revoking access to downloads.
    • Added a method to retrieve the total count of reviews for specific stores.
    • Enhanced handling of store categories with commission settings.
  • Bug Fixes

    • Improved error handling in the order download methods to provide robust responses.
  • Refactor

    • Updated conditional logic in product functions to enhance category selection validation and query construction.
    • Restructured code for improved readability and maintainability across several files.
  • Chores

    • Added comments to enable and disable PHP CodeSniffer checks around direct database queries to ensure code compliance.
    • Updated documentation annotations for clarity and compliance with coding standards.

@devAsadNur devAsadNur added the In Progress The issues is being worked on label May 10, 2024
@devAsadNur devAsadNur self-assigned this May 10, 2024
@devAsadNur devAsadNur changed the title fix: DB related PHPCS security issues 🎯 fix: DB related PHPCS security issues May 13, 2024
@devAsadNur devAsadNur requested a review from mrabbani May 13, 2024 06:59
@devAsadNur devAsadNur added Needs: Testing This requires further testing Needs: Dev Review It requires a developer review and approval and removed In Progress The issues is being worked on labels May 13, 2024
Copy link
Contributor

coderabbitai bot commented Jun 26, 2024

Walkthrough

The recent updates primarily modify the Commission, StoreController, Importer, functions, and OrderControllerV2 classes by introducing new functionality and adjusting PHP_CodeSniffer (PHPCS) compliance. The Commission class now includes comments to disable specific PHPCS checks around a database query. The StoreController class adds a method to count total reviews and enhances category handling logic. The Importer class improves code formatting for readability. The OrderControllerV2 class expands API capabilities regarding downloadable products and improves error handling. These changes maintain existing functionality without altering method signatures or introducing additional logic.

Changes

File Change Summary
includes/Commission.php Added phpcs:disable and phpcs:enable comments around a database query for net_amount and order_total.
includes/REST/StoreController.php Added method get_total_review_count for counting reviews, updated get_store_category for category commission handling, and modified parameter name in prepare_links.
includes/DummyData/Importer.php Improved code formatting and readability, added comments to disable PHPCS rules, removed unused $index variable.
includes/Product/functions.php Restructured conditional statements in dokan_save_product for clarity, updated comments for PHPCS compliance.
includes/REST/OrderControllerV2.php Added new methods for handling downloadable products, updated register_routes, enhanced error handling in revoke_order_downloads.

Possibly related PRs

  • Fix decimal and thousand separator for category commission. #2440: The changes in this PR involve modifications to the Commission class, specifically related to the handling of commission values and formatting, which aligns with the changes made in the main PR that also focuses on the Commission class.
  • Fix commission upgrader #2463: This PR addresses issues related to the commission upgrader functionality, which is relevant to the changes in the main PR that involve modifications to the Commission class and its methods.
  • 🎯 fix: Invalid return value for commission rate validate method #2490: This PR focuses on fixing the return value for the commission rate validation method in the Commission class, which directly relates to the changes made in the main PR that also involves modifications to the Commission class and its methods.

Suggested labels

QA approved, Needs: Testing, Upcoming Release

Suggested reviewers

  • mrabbani

Poem

In the world of code so bright,
PHPCS took flight,
Comments added here and there,
Database queries with care.
Code so clean, like morning's dew,
For maintainers old and new.
Updates galore, dokan now anew!


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

Outside diff range and nitpick comments (10)
includes/DummyData/Importer.php (5)

Line range hint 5-5: Remove leading backslash from import statement.

The use statement for WP_Error should not start with a leading backslash as per PHP standards.

- use \WP_Error;
+ use WP_Error;
Tools
GitHub Check: Run PHPCS inspection

[failure] 334-334:
Functions must not contain multiple empty lines in a row; found 2 empty lines


Line range hint 6-6: Remove leading backslash from import statement.

The use statement for WP_Query should not start with a leading backslash.

- use \WP_Query;
+ use WP_Query;
Tools
GitHub Check: Run PHPCS inspection

[failure] 334-334:
Functions must not contain multiple empty lines in a row; found 2 empty lines


Line range hint 8-8: Add file-level docblock after the opening PHP tag.

The file should start with a file-level docblock to describe the purpose and scope of the file, immediately following the <?php tag.

/**
 * Handles importing of dummy data for Dokan plugin.
 */
Tools
GitHub Check: Run PHPCS inspection

[failure] 334-334:
Functions must not contain multiple empty lines in a row; found 2 empty lines


Line range hint 246-246: Use pre-increment instead of post-increment and fix spacing.

Change the post-increment operator to pre-increment for performance optimization and remove the extra space.

- $index ++;
+ ++$index;
Tools
GitHub Check: Run PHPCS inspection

[failure] 334-334:
Functions must not contain multiple empty lines in a row; found 2 empty lines


Line range hint 276-277: Optimize meta key usage and fix array formatting.

Using meta_key directly can lead to slow database queries. Consider using a custom query or indexing. Also, add a comma after the last array item in a multi-line array.

$args = [
    'post_type'      => 'product',
    'posts_per_page' => -1,
    'post_status'    => 'any',
    'fields'         => 'ids',
    'meta_key'       => 'dokan_dummy_data', // Consider optimizing this query
    'meta_value'     => '1',
];
Tools
GitHub Check: Run PHPCS inspection

[failure] 334-334:
Functions must not contain multiple empty lines in a row; found 2 empty lines

includes/Withdraw/Manager.php (1)

Line range hint 535-549: Validate and optimize the summary retrieval method.

The get_user_withdraw_summary method uses a direct database query to compute a summary of withdrawals. While the use of phpcs:disable is necessary, ensure that all input data is properly sanitized and validated. Additionally, consider using more efficient SQL queries or caching mechanisms to optimize performance.

+ $cache_summary = wp_cache_get($cache_key, $cache_group);
+ if (false !== $cache_summary) {
+     return $cache_summary;
+ }
- $results = $wpdb->get_row(...);
+ wp_cache_set($cache_key, $results, $cache_group);
includes/Product/functions.php (1)

Line range hint 402-423: Address incorrect number of replacements in SQL query.

The function dokan_search_seller_products uses a complex SQL query to search for products. The static analysis tool flagged an issue with the incorrect number of replacements passed to $wpdb->prepare(). This needs to be corrected to prevent potential SQL injection vulnerabilities.

- $product_ids = $wpdb->get_col($wpdb->prepare(...));
+ $product_ids = $wpdb->get_col($wpdb->prepare(
+     "SELECT DISTINCT posts.ID FROM {$wpdb->posts} posts
+     LEFT JOIN {$wpdb->postmeta} postmeta ON posts.ID = postmeta.post_id
+     $type_join
+     WHERE (
+         posts.post_title LIKE %s
+         OR posts.post_content LIKE %s
+         OR (
+             postmeta.meta_key = '_sku' AND postmeta.meta_value LIKE %s
+         )
+     )
+     AND posts.post_type IN ('" . implode( "','", $post_types ) . "')
+     AND posts.post_status IN ('" . implode( "','", $post_statuses ) . "')
+     $type_where
+     $users_where
+     ORDER BY posts.post_parent ASC, posts.post_title ASC",
+     $query_args
+ ));
includes/Commission.php (1)

Line range hint 571-571: Avoid using reserved keywords as parameter names

The use of callable as a parameter name should be avoided as it is a reserved keyword in PHP.

- public function prepare_for_calculation( $callable, $product_id = 0, $product_price = 0 )
+ public function prepare_for_calculation( $callback, $product_id = 0, $product_price = 0 )
includes/REST/StoreController.php (2)

Line range hint 608-620: Approve use of PHPCS directives but recommend caching.

The use of phpcs:disable and phpcs:enable is appropriate here to bypass the PHPCS rules for direct database queries. However, consider implementing caching mechanisms to optimize performance and reduce database load, especially if this query is executed frequently.


Line range hint 441-441: Consider renaming the parameter $object.

The use of the reserved keyword "object" as a parameter name might lead to issues in PHP, especially in strict typing contexts. Consider renaming it to something more specific, like $dataObject.

- protected function prepare_links( $object, $request ) {
+ protected function prepare_links( $dataObject, $request ) {
Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between d2a44e3 and cdb9839.

Files selected for processing (11)
  • includes/Commission.php (3 hunks)
  • includes/DummyData/Importer.php (2 hunks)
  • includes/Product/functions.php (5 hunks)
  • includes/REST/OrderControllerV2.php (3 hunks)
  • includes/REST/StoreController.php (2 hunks)
  • includes/Tracker.php (2 hunks)
  • includes/Withdraw/Hooks.php (2 hunks)
  • includes/Withdraw/Manager.php (10 hunks)
  • includes/Withdraw/Withdraw.php (5 hunks)
  • includes/Withdraw/Withdraws.php (1 hunks)
  • uninstall.php (2 hunks)
Files skipped from review due to trivial changes (2)
  • includes/Withdraw/Withdraws.php
  • uninstall.php
Additional context used
GitHub Check: Run PHPCS inspection
includes/REST/OrderControllerV2.php

[warning] 216-216:
Stand-alone post-increment statement found. Use pre-increment instead: ++$file_counter.

includes/DummyData/Importer.php

[failure] 5-5:
An import use statement should never start with a leading backslash


[failure] 6-6:
An import use statement should never start with a leading backslash


[failure] 8-8:
The file-level docblock must follow the opening PHP tag in the file header


[warning] 246-246:
Stand-alone post-increment statement found. Use pre-increment instead: ++$index .


[failure] 246-246:
Expected no spaces between $index and the increment operator; 1 found


[warning] 276-276:
Detected usage of meta_key, possible slow query.


[warning] 277-277:
Detected usage of meta_value, possible slow query.


[failure] 277-277:
There should be a comma after the last array item in a multi-line array.


[warning] 327-327:
When a multi-item array uses associative keys, each value should start on a new line.


[failure] 334-334:
Functions must not contain multiple empty lines in a row; found 2 empty lines

includes/Product/functions.php

[warning] 404-404:
Incorrect number of replacements passed to $wpdb->prepare(). Found 1 replacement parameters, expected 3.

includes/Commission.php

[warning] 571-571:
It is recommended not to use reserved keyword "callable" as function parameter name. Found: $callable

includes/REST/StoreController.php

[warning] 441-441:
It is recommended not to use reserved keyword "object" as function parameter name. Found: $object

Additional comments not posted (16)
includes/Withdraw/Hooks.php (1)

Line range hint 97-133: Verify the necessity of PHPCS suppression directives.

The use of phpcs:disable and phpcs:enable around direct database queries is noted. While this is sometimes necessary, it's important to ensure that there's a valid reason for bypassing these checks, especially concerning database query optimization and security.

includes/REST/OrderControllerV2.php (1)

Line range hint 133-142: Verify the necessity of PHPCS suppression directives.

Similar to previous observations, ensure there's a valid reason for bypassing PHPCS checks around direct database queries. This is crucial for maintaining code quality and security.

Verification successful

Line range hint 133-142: Verified the necessity of PHPCS suppression directives.

The PHPCS suppression directives for WordPress.DB.DirectDatabaseQuery.DirectQuery and WordPress.DB.DirectDatabaseQuery.NoCaching are used consistently across multiple files in the project. This indicates a pattern or necessity for bypassing these specific checks in certain scenarios, likely due to the nature of the operations being performed.

  • includes/Commission.php
  • includes/Withdraw/Hooks.php
  • includes/Withdraw/Withdraw.php
  • includes/Withdraw/Manager.php
  • includes/DummyData/Importer.php
  • includes/REST/StoreController.php
  • includes/REST/OrderControllerV2.php
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Confirm if similar suppressions are used elsewhere in the project for consistency and ensure they are justified.

# Search for similar PHPCS suppressions in PHP files
rg --type php 'phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery'

Length of output: 2209

includes/Tracker.php (1)

68-68: Verify the necessity of PHPCS suppression directive.

The use of phpcs:ignore to suppress warnings for direct database queries is noted. Confirm that this is the best approach and consistent with other similar cases in the codebase.

Verification successful

PHPCS suppression directive is consistent and necessary.

The use of phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery is consistent across the codebase, indicating that direct database queries are a common and necessary practice in this project.

  • uninstall.php
  • includes/Withdraw/Withdraws.php
  • includes/Tracker.php
  • includes/Withdraw/Manager.php
  • includes/functions-compatibility.php
  • includes/Upgrade/Upgrades/V_2_9_13.php
  • includes/Upgrade/Upgrades/V_3_3_1.php
  • includes/ReverseWithdrawal/Manager.php
  • includes/Upgrade/Upgrades/V_3_3_7.php
  • includes/ProductCategory/Hooks.php
  • includes/Product/functions.php
  • includes/Upgrade/Upgrades/BackgroundProcesses/V_2_8_3_VendorBalance.php
  • includes/Upgrade/Upgrades/BackgroundProcesses/V_2_9_4_OrderPostAuthor.php
  • includes/Order/Manager.php
  • includes/Order/MiscHooks.php
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Check for consistency in the use of PHPCS suppression directives across the project.

# Search for similar PHPCS suppressions in PHP files
rg --type php 'phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery'

Length of output: 7159

includes/DummyData/Importer.php (2)

Line range hint 327-327: Format array items on new lines for readability.

When using associative arrays, each item should start on a new line to improve readability.

$args = [
    'task'      => 'clear_dummy_vendors_orders',
    'vendor_id' => $vendor->id,
];
Tools
GitHub Check: Run PHPCS inspection

[failure] 334-334:
Functions must not contain multiple empty lines in a row; found 2 empty lines


Line range hint 336-357: Ensure proper disabling and re-enabling of PHPCS checks.

The use of phpcs:disable and phpcs:enable is correctly placed around direct database operations to suppress PHPCS warnings. Ensure that these directives are necessary and used judiciously.

Tools
GitHub Check: Run PHPCS inspection

[failure] 334-334:
Functions must not contain multiple empty lines in a row; found 2 empty lines

includes/Withdraw/Withdraw.php (3)

Line range hint 451-466: Ensure proper disabling and re-enabling of PHPCS checks.

The use of phpcs:disable and phpcs:enable is correctly placed around direct database operations to suppress PHPCS warnings. Ensure that these directives are necessary and used judiciously.


Line range hint 498-514: Ensure proper disabling and re-enabling of PHPCS checks.

The use of phpcs:disable and phpcs:enable is correctly placed around direct database operations to suppress PHPCS warnings. Ensure that these directives are necessary and used judiciously.


551-557: Ensure proper disabling and re-enabling of PHPCS checks.

The use of phpcs:disable and phpcs:enable is correctly placed around direct database operations to suppress PHPCS warnings. Ensure that these directives are necessary and used judiciously.

includes/Withdraw/Manager.php (4)

100-108: Ensure proper handling of direct database queries.

The phpcs:disable directive is used to bypass the PHPCS checks for direct database queries. While this is necessary for the operation, it's crucial to ensure that these queries do not open up SQL injection vulnerabilities. The usage of $wpdb->prepare is appropriate here, which helps in preventing SQL injection by ensuring that the values are parameterized.


Line range hint 140-158: Validate the handling of status updates in database.

The update_status method correctly uses the phpcs:disable directive to allow direct database queries. The wpdb->update method is used appropriately with parameterization to prevent SQL injection risks. However, ensure that the status values are validated before they are passed to this method to prevent any illegal status updates.


Line range hint 226-235: Review the method for checking pending requests.

The has_pending_request method correctly uses the phpcs:disable directive for a direct database query. The query is parameterized using $wpdb->prepare, which is a good practice to prevent SQL injection. Ensure that the user_id is validated before being used in the query.


409-416: Ensure secure handling of direct database queries.

The method get uses direct database queries to fetch withdrawal details. The use of phpcs:disable is necessary due to the nature of the operation. Ensure that the ID is sanitized and validated before being used in the query to prevent SQL injection.

includes/Product/functions.php (2)

41-42: Review category selection validation logic.

The changes to dokan_save_product include updated logic for category selection validation. This is crucial for ensuring that products are correctly categorized. The use of error handling with WP_Error is appropriate for user feedback. Ensure that the logic covers all possible user inputs to prevent any issues with product saving.


90-91: Ensure robust category handling in product data.

The refactored logic for handling multiple categories in dokan_save_product is a significant improvement. It ensures that all categories are processed and stored correctly, which is crucial for product organization and filtering. Ensure that the array mapping function array_map is used correctly to sanitize and validate all category IDs before use.

includes/Commission.php (2)

Line range hint 92-111: Review of calculate_gateway_fee: Use of PHPCS directives around database queries

The use of phpcs:disable and phpcs:enable is appropriate here due to the direct database queries involved. However, it's crucial to ensure these queries are secure and optimized.

Consider conducting a security audit on these queries to ensure they are safe from SQL injection and other vulnerabilities.


740-747: Review of get_earning_from_order_table: Use of PHPCS directives around database queries

The use of phpcs:disable and phpcs:enable around the SQL query is justified due to the direct database access. However, ensuring the security of this query is essential.

Consider conducting a security audit on this query to ensure it is safe from SQL injection and other vulnerabilities.

// Deleting vendors orders.
foreach ( $orders as $order ) {
$order->delete( true );
}

global $wpdb;

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remove extra empty lines.

Ensure there are no multiple consecutive empty lines within functions.

        global $wpdb;
-
-
        // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
global $wpdb;
// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
Tools
GitHub Check: Run PHPCS inspection

[failure] 334-334:
Functions must not contain multiple empty lines in a row; found 2 empty lines

@@ -211,7 +213,7 @@
$inserted_id = wc_downloadable_file_permission( $download_id, $product_id, $order );

if ( $inserted_id ) {
$file_counter ++;
$file_counter++;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optimize the increment operation.

The static analysis tool has flagged the use of post-increment. Using pre-increment is generally more efficient in PHP.

- $file_counter++;
+ ++$file_counter;
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
$file_counter++;
++$file_counter;
Tools
GitHub Check: Run PHPCS inspection

[warning] 216-216:
Stand-alone post-increment statement found. Use pre-increment instead: ++$file_counter.

Comment on lines +265 to +269
// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
$result = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$wpdb->dokan_withdraw} WHERE status = %d LIMIT %d, %d", $status, $offset, $limit ) );
} else {
$result = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$wpdb->dokan_withdraw} WHERE user_id = %d AND status = %d ORDER BY id DESC LIMIT %d, %d", $user_id, $status, $offset, $limit ) );
//phpcs:enable
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optimize the retrieval of withdrawal requests.

The method get_withdraw_requests uses direct database queries to fetch data. The use of phpcs:disable is appropriate here to bypass the PHPCS checks. Consider caching the results of these queries to improve performance, especially if this method is called frequently.

+ $cache_result = wp_cache_get($cache_key, $cache_group);
+ if (false !== $cache_result) {
+     return $cache_result;
+ }
- $result = $wpdb->get_results(...);
+ wp_cache_set($cache_key, $result, $cache_group);

Committable suggestion was skipped due to low confidence.

@@ -185,7 +189,7 @@

$format = [ '%d', '%f', '%s', '%d', '%s', '%s', '%s', '%s' ];

$inserted = $wpdb->insert( $wpdb->dokan_withdraw, $data, $format );
$inserted = $wpdb->insert( $wpdb->dokan_withdraw, $data, $format ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tip

Codebase Verification

Potential Issue with Direct Database Insertion and Lack of Data Sanitization

The insert_withdraw method directly inserts data into the database using $wpdb->insert without apparent sanitization of the input data. This can lead to SQL injection and other security vulnerabilities.

  • File: includes/Withdraw/Manager.php
  • Line: 192

Please ensure that all data passed to the database is properly sanitized and validated.

Analysis chain

Check for potential issues with direct database insertions.

The method insert_withdraw uses a direct database query without any PHPCS checks. This is indicated by the phpcs:ignore directive. Ensure that all data passed to the database is properly sanitized and validated to prevent SQL injection and other security vulnerabilities.

Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify data sanitization in `insert_withdraw` method.

# Test: Search for the method usage. Expect: Proper sanitization before data is passed.
rg --type php $'insert_withdraw'

Length of output: 113



Script:

#!/bin/bash
# Description: Extract the full implementation of the `insert_withdraw` method to verify data sanitization.

# Searching for the full implementation of the `insert_withdraw` method in the PHP file.
ast-grep --lang php --pattern 'public function insert_withdraw($_) { $$$ }' includes/Withdraw/Manager.php

Length of output: 214



Script:

#!/bin/bash
# Description: Extract the full implementation of the `insert_withdraw` method to verify data sanitization.

# Using ripgrep to search for the full implementation of the `insert_withdraw` method.
rg --context 20 'public function insert_withdraw' includes/Withdraw/Manager.php

Length of output: 1407



Script:

#!/bin/bash
# Description: Search for all instances where `insert_withdraw` is called to verify data sanitization.

# Using ripgrep to find all invocations of the `insert_withdraw` method.
rg 'insert_withdraw\('

Length of output: 106

@@ -189,7 +185,7 @@
}
}

$variations_count = absint( $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(ID) FROM $wpdb->posts WHERE post_parent = %d AND post_type = 'product_variation' AND post_status IN ('publish', 'private', 'pending')", $post->ID ) ) );
$variations_count = absint( $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(ID) FROM $wpdb->posts WHERE post_parent = %d AND post_type = 'product_variation' AND post_status IN ('publish', 'private', 'pending')", $post->ID ) ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optimize the retrieval of product variations.

The method dokan_product_output_variations uses a direct database query to count product variations. While necessary, consider optimizing this query or using caching to improve performance, especially for products with a large number of variations.

+ $variations_count = wp_cache_get('variations_count_' . $post->ID);
+ if (false === $variations_count) {
+     $variations_count = $wpdb->get_var(...);
+     wp_cache_set('variations_count_' . $post->ID, $variations_count);
+ }

Committable suggestion was skipped due to low confidence.

Copy link
Member

@mrabbani mrabbani left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pls fix PHPCS issues.

@mrabbani mrabbani added Needs: Author Reply and removed Needs: Testing This requires further testing labels Aug 21, 2024
@@ -332,6 +332,8 @@ public function delete_dummy_vendor_orders( $args ) {

global $wpdb;


Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pls fix the others PHPCS issues.

@mrabbani mrabbani removed the Needs: Dev Review It requires a developer review and approval label Dec 6, 2024
# Conflicts:
#	includes/Commission.php
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (3)
includes/REST/StoreController.php (3)

Line range hint 608-620: Ensure thorough sanitization of query parameters
Although the query is safely parameterized via $wpdb->prepare(), consider adding explicit sanitization for $status and $post_type (e.g., sanitize_text_field($status)) before using them, to further reinforce security best practices.


Line range hint 608-620: Consider using WP APIs for better maintainability
A direct query with $wpdb->comments and $wpdb->posts can be replaced with a more standardized API (e.g., WP_Comment_Query) if performance or future maintainability becomes a concern. This approach leverages native caching and simplifies compliance with coding standards.


Line range hint 608-620: Gracefully handle potential query failures
If the query fails or returns null, the current code will still pass intval(null) without indicating any error. Consider checking if $total is null before returning, so you can log or handle failures more visibly.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between cdb9839 and 9eb13a2.

📒 Files selected for processing (2)
  • includes/Commission.php (1 hunks)
  • includes/REST/StoreController.php (2 hunks)
✅ Files skipped from review due to trivial changes (1)
  • includes/Commission.php

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (2)
includes/Product/functions.php (1)

188-188: Improve performance with caching
This query directly counts product variations. If products can have many variations, it may impact performance. Consider using transient or object caching to reduce repeated queries.

includes/DummyData/Importer.php (1)

273-274: Consider avoiding PHPCS ignores if feasible.
These lines only define a static meta key and value for use in WP_Query. If you’re ignoring PHPCS solely to bypass potential direct database warnings, it may be unnecessary here since it’s not a raw SQL statement.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9eb13a2 and 303eeb5.

📒 Files selected for processing (4)
  • includes/DummyData/Importer.php (4 hunks)
  • includes/Product/functions.php (5 hunks)
  • includes/REST/OrderControllerV2.php (3 hunks)
  • includes/REST/StoreController.php (3 hunks)
🔇 Additional comments (12)
includes/REST/OrderControllerV2.php (2)

Line range hint 133-142: Consider input validation for direct DB queries
Disabling PHPCS checks around direct queries is acceptable under some circumstances, but ensure that all parameters (especially order_id) are already validated and sanitized. Consider using parameterized queries (such as $wpdb->prepare) for safety, and double-check that no user-generated input can flow unsanitized into the query.


216-216: Great job using pre-increment
Thank you for addressing the previous feedback regarding increment operations. Using ++$file_counter is good for compliance and is also slightly more efficient in PHP.

includes/Product/functions.php (3)

41-42: Properly handle absence of category
The updated check (elseif) reading “Please select at least one category” clarifies the condition. This ensures that a vendor must pick a category. Looks good!


90-91: Good use of array_map('absint', [...]) for product categories
This effectively sanitizes all input category IDs. Remember to confirm that returned categories exist before proceeding with subsequent logic.


402-405: Validate query parameters for increased security
Disabling PHPCS checks is permissible if carefully reviewed. Confirm that $term and $user_ids are always sanitized, and ensure your query logic cannot be manipulated.

Also applies to: 419-419, 423-423

includes/REST/StoreController.php (3)

436-441: Improved parameter naming
Renaming the parameter from $object to $store increases clarity—good practice for maintainability.


444-444: Ensure array structure for $store
You are accessing $store['id']. Double-check $store is consistently an array containing 'id'. If $store can be an object in other calls, this might cause errors.


Line range hint 608-620: Sanitize store ID before the query
You correctly disable PHPCS checks here, but ensure $id and other parameters are sanitized. Even though $wpdb->prepare is used, verifying all parameters remain integer values will help avoid potential injection.

includes/DummyData/Importer.php (4)

5-6: Imports look appropriate and necessary.
It appears that both WP_Error and WP_Query are required for error handling and retrieving posts.


324-330: Validate vendor_id more thoroughly.
Although you check if $vendor_id is empty, consider further validation (e.g., ensuring it’s numeric) to avoid edge cases.


338-338: Direct database queries are parameterized properly.
Using $wpdb->delete() with string format specifiers (%d) is secure. Disabling PHPCS here is acceptable, given the explicit placeholders for prevention of SQL injection.


359-359: Re-enabled PHPCS checks.
Good practice to limit the ignore region as narrowly as possible.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 303eeb5 and 54dcc2e.

📒 Files selected for processing (1)
  • includes/Tracker.php (3 hunks)
🔇 Additional comments (3)
includes/Tracker.php (3)

25-25: Aligns with WordPress PHPDoc standards

Reinstating the @return void annotation is consistent with WordPress coding standards. Good to see the clarity in the docblock.


36-36: Docblock clarity maintained

Likewise, restoring the @return void annotation strengthens the codebase documentation.


74-74: Consistent version annotation

Adding @since 3.0.15 enhances the code’s maintainability and ensures accurate version tracking of newly introduced features.

@@ -65,18 +65,18 @@ function () {
protected function get_order_count() {
global $wpdb;

return (int) $wpdb->get_var( "SELECT count(id) FROM {$wpdb->prefix}dokan_orders WHERE order_status IN ('wc-completed', 'wc-processing', 'wc-on-hold', 'wc-refunded');" );
return (int) $wpdb->get_var( "SELECT count(id) FROM {$wpdb->prefix}dokan_orders WHERE order_status IN ('wc-completed', 'wc-processing', 'wc-on-hold', 'wc-refunded');" ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Use of raw SQL and ignoring PHPCS checks

While the comment clarifies why PHPCS checks are disabled, consider using $wpdb->prepare() to defend against potential SQL injection vulnerabilities, even if the risk appears minimal. Prepared statements also align with best practices and WordPress coding standards.

- return (int) $wpdb->get_var( "SELECT count(id) FROM {$wpdb->prefix}dokan_orders WHERE order_status IN ('wc-completed', 'wc-processing', 'wc-on-hold', 'wc-refunded');" ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
+ $statuses = [ 'wc-completed', 'wc-processing', 'wc-on-hold', 'wc-refunded' ];
+ $placeholders = implode( ', ', array_fill(0, count($statuses), '%s') );
+ $query = $wpdb->prepare(
+     "SELECT COUNT(id) FROM {$wpdb->prefix}dokan_orders WHERE order_status IN ($placeholders)",
+     $statuses
+ );
+ return (int) $wpdb->get_var( $query ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.NoCaching
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
return (int) $wpdb->get_var( "SELECT count(id) FROM {$wpdb->prefix}dokan_orders WHERE order_status IN ('wc-completed', 'wc-processing', 'wc-on-hold', 'wc-refunded');" ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
$statuses = [ 'wc-completed', 'wc-processing', 'wc-on-hold', 'wc-refunded' ];
$placeholders = implode( ', ', array_fill(0, count($statuses), '%s') );
$query = $wpdb->prepare(
"SELECT COUNT(id) FROM {$wpdb->prefix}dokan_orders WHERE order_status IN ($placeholders)",
$statuses
);
return (int) $wpdb->get_var( $query ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.NoCaching

@devAsadNur devAsadNur added Needs: Dev Review It requires a developer review and approval and removed Needs: Author Reply labels Jan 2, 2025
@devAsadNur devAsadNur requested a review from mrabbani January 2, 2025 08:51
@devAsadNur
Copy link
Member Author

@mrabbani Bhai, The PHPCS issues have been fixed based on your PR. Please review once again.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Needs: Dev Review It requires a developer review and approval
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants