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: invalid product id validation on edit page #2474

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

Conversation

mralaminahamed
Copy link
Member

@mralaminahamed mralaminahamed commented Dec 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)

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

  • Bug Fixes
    • Improved error handling for product retrieval, ensuring users receive a clear message if a product is no longer available.
    • Enhanced management of invalid product IDs for a smoother user experience.

Copy link
Contributor

coderabbitai bot commented Dec 10, 2024

Walkthrough

The changes in the edit-product-single.php file enhance error handling and control flow for product retrieval and validation. A new check ensures the $post object is a valid instance of WP_Post. If the product is not found, an error message is displayed using dokan_get_template_part(), and execution is halted. The organization of the logic regarding the $_GET['product_id'] has been improved for clarity, while the handling of product status and attributes remains unchanged.

Changes

File Change Summary
templates/products/edit-product-single.php Enhanced error handling for product retrieval, added instance check for $post, reorganized logic for clarity.

Possibly related PRs

  • Fix vendor dashboard product edit page variation products  #2336: This PR modifies the logic for retrieving product IDs in the includes/Ajax.php file, which is related to product retrieval, similar to the changes made in the edit-product-single.php file of the main PR.
  • Fix admin fixed commission setting validation #2437: This PR enhances the validation of commission settings in the includes/Admin/Settings.php, which may indirectly relate to the overall robustness of product management and error handling, aligning with the main PR's focus on improving error handling during product retrieval.

Suggested labels

:+1: Dev Review Done

Suggested reviewers

  • shohag121

🐰 In the code where products play,
A check was added for the day.
If a post is lost, we now can see,
A message clear, "Not here, oh me!"
With logic neat and errors tamed,
Our product flow is now acclaimed! 🌟


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. (Experiment)
  • @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: 1

🧹 Outside diff range and nitpick comments (1)
templates/products/edit-product-single.php (1)

35-45: Enhance error handling for non-existent products

The validation logic for non-existent products is good, but consider these improvements:

  1. Add a specific error code for better error tracking
  2. Log the invalid product ID access attempt for security monitoring

Consider this enhancement:

 if ( ! $post instanceof WP_Post ) {
+    dokan_log( sprintf( 'Invalid product ID access attempt: %d', $post_id ) );
     dokan_get_template_part(
         'global/dokan-error',
         '',
         array(
             'deleted' => false,
-            'message' => __( 'This product is no longer available', 'dokan' )
+            'message' => __( 'This product is no longer available', 'dokan-lite' ),
+            'code'    => 'invalid_product_id'
         )
     );
     return;
 }
🧰 Tools
🪛 GitHub Check: Run PHPCS inspection

[failure] 41-41:
Mismatched text domain. Expected 'dokan-lite' but got 'dokan'.


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

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 31194fa and 19368dd.

📒 Files selected for processing (1)
  • templates/products/edit-product-single.php (1 hunks)
🧰 Additional context used
🪛 GitHub Check: Run PHPCS inspection
templates/products/edit-product-single.php

[failure] 41-41:
Mismatched text domain. Expected 'dokan-lite' but got 'dokan'.


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

🔇 Additional comments (2)
templates/products/edit-product-single.php (2)

32-33: LGTM: Proper sanitization of product ID

The code correctly sanitizes the product ID using intval() before retrieving the post.


35-45: Verify consistent error handling across the codebase

Let's verify if similar product validation is implemented consistently across other product-related templates.

✅ Verification successful

Error handling is implemented appropriately and consistently

The verification shows that error handling across product-related templates is consistent with the implementation in question:

  • Product listing templates use appropriate error messages for "No Products Found" scenarios
  • The dokan-error template is consistently used across different contexts (orders, store lists, products) with context-specific messages
  • Product validation using WP_Post and post metadata is handled consistently where needed

The current implementation in edit-product-single.php follows the established pattern in the codebase for handling product-related errors.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other templates that might need similar product validation
rg -l "get_post.*product_id" templates/

Length of output: 41


Script:

#!/bin/bash
# Search for files that might handle product validation using different patterns
rg -l "WP_Post|get_post|product.*not.*found|product.*no.*longer|product.*validation" templates/

# Also search for dokan error template usage
rg -l "dokan-error" templates/

Length of output: 499


Script:

#!/bin/bash
# Check the specific error handling implementations in the identified files
rg -A 5 "WP_Post|get_post|product.*not.*found|product.*no.*longer" templates/products/products-listing.php templates/products/products-listing-row.php templates/products/downloadable.php

# Also check how dokan-error template is used in other files
rg -A 5 "dokan-error" templates/store-lists-loop.php templates/orders/listing.php

Length of output: 4347

🧰 Tools
🪛 GitHub Check: Run PHPCS inspection

[failure] 41-41:
Mismatched text domain. Expected 'dokan-lite' but got 'dokan'.


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

templates/products/edit-product-single.php Outdated Show resolved Hide resolved
@shashwatahalder01 shashwatahalder01 added QA In Progress QA approved This PR is approved by the QA team and removed QA In Progress labels Dec 11, 2024
@mralaminahamed mralaminahamed added the Needs: Dev Review It requires a developer review and approval label Dec 11, 2024
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 the translation domain name.

@mrabbani mrabbani added the DO NOT MERGE Don't merge this PR label Dec 11, 2024
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

🧹 Outside diff range and nitpick comments (2)
templates/products/edit-product-single.php (2)

35-45: Enhance error handling with specific error messages

While the validation logic is good, the error message could be more specific to help users understand why the product is unavailable (e.g., deleted, draft, or invalid ID).

Consider this enhancement:

     if ( ! $post instanceof WP_Post ) {
         dokan_get_template_part(
             'global/dokan-error',
             '',
             array(
                 'deleted' => false,
-                'message' => __( 'This product is no longer available', 'dokan-lite' )
+                'message' => __( 'This product is no longer available. It may have been deleted or is invalid.', 'dokan-lite' )
             )
         );
         return;
     }
🧰 Tools
🪛 GitHub Check: Run PHPCS inspection

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


39-42: Fix array formatting

Add a trailing comma after the last array item as per PHPCS standards.

Apply this fix:

     array(
         'deleted' => false,
-        'message' => __( 'This product is no longer available', 'dokan-lite' )
+        'message' => __( 'This product is no longer available', 'dokan-lite' ),
     )
🧰 Tools
🪛 GitHub Check: Run PHPCS inspection

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

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 19368dd and da5f6fd.

📒 Files selected for processing (1)
  • templates/products/edit-product-single.php (1 hunks)
🧰 Additional context used
🪛 GitHub Check: Run PHPCS inspection
templates/products/edit-product-single.php

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

🔇 Additional comments (2)
templates/products/edit-product-single.php (2)

32-33: LGTM: Proper sanitization of product ID

The code correctly uses intval() to sanitize the product ID from $_GET parameter and get_post() to safely retrieve the post object.


32-45: Verify error handling in upstream code

The new validation improves security but we should ensure proper error handling in the calling code.

✅ Verification successful

The previous search was too specific. Let's broaden it to find relevant code patterns and files that might need similar validation.


Let's examine how product_id is handled and what error handling patterns exist in the product editing related files.


Based on the gathered information, I can now provide a final response:

Error handling is properly implemented across product editing flows

The new validation in edit-product-single.php aligns well with existing error handling patterns. The code shows:

  • Proper nonce verification before product access
  • Multiple layers of validation (nonce, product existence, post type)
  • Consistent error handling using dokan-error template and wp_die()
  • Similar validation patterns in related product editing files

The changes enhance security without disrupting the established error handling flow.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other instances where product validation might be needed
rg -A 3 "get_post.*product_id.*WP_Post" --type php

Length of output: 52


Script:

#!/bin/bash
# Search for usages of get_post with product_id
rg -A 3 "get_post.*product_id" --type php

# Search for WP_Post type checks related to products
rg -A 3 "instanceof\s+WP_Post.*product" --type php

# Search for files that might handle product editing
fd -e php "edit.*product|product.*edit"

Length of output: 5943


Script:

#!/bin/bash
# Let's check how product_id is obtained in these edit-related files
rg -B 3 "product_id" templates/products/edit-product-single.php templates/products/dokan-products-edit-bulk-commission.php includes/CatalogMode/Dashboard/ProductBulkEdit.php

# Also check for error handling patterns in these files
rg "dokan-error|wp_die|exit|return" templates/products/edit-product-single.php templates/products/dokan-products-edit-bulk-commission.php includes/CatalogMode/Dashboard/ProductBulkEdit.php

Length of output: 5049

🧰 Tools
🪛 GitHub Check: Run PHPCS inspection

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

@mrabbani
Copy link
Member

Currently, Dokan display the access denied message for invalid product ID. We may handle the some common errors through the template like 403, 404, 500;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
DO NOT MERGE Don't merge this PR Needs: Dev Review It requires a developer review and approval QA approved This PR is approved by the QA team urgent
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants