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

🔨 chore: Update Appsero and refactor with Mozart #55

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

Conversation

devAsadNur
Copy link
Member

@devAsadNur devAsadNur commented Dec 2, 2024

Updated Appsero and integrated Mozart.

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced a new Client class for managing plugin data and updates.
    • Added Insights class for tracking plugin usage with user consent.
    • Implemented License class for managing license activation and validation.
  • Improvements

    • Updated autoloading configuration for better dependency management.
    • Enhanced the init_tracker method for improved encapsulation of dependencies.
  • Bug Fixes

    • Addressed various minor issues related to dependency handling and plugin initialization.

@devAsadNur devAsadNur self-assigned this Dec 2, 2024
Copy link

coderabbitai bot commented Dec 2, 2024

Walkthrough

The changes in this pull request involve significant modifications to the composer.json file, including the addition of an autoload section, updates to package version constraints, and the introduction of new development requirements. Additionally, several new classes (Client, Insights, and License) have been added within the WeDevs_WC_Conversion_Tracking\Dependencies\Appsero namespace to manage various functionalities, including project data, tracking usage, and license management. The init_tracker method in the existing class has also been updated to utilize the new Client class.

Changes

File Change Summary
composer.json - Added autoload section for PSR-4 autoloading.
- Updated version constraint for appsero/client from ^2.0 to ^2.0.4.
- Introduced development requirement for coenjacobs/mozart with version ^0.7.1.
- Expanded scripts section with new commands.
- Added extra section for mozart configuration.
conversion-tracking.php - Updated init_tracker method to instantiate Client from the new namespace WeDevs_WC_Conversion_Tracking\Dependencies\Appsero\Client.
dependencies/Appsero/Client.php - Added Client class with properties for version, hash, name, file path, etc.
- Implemented methods for managing project data, handling updates, and sending requests to a remote endpoint.
dependencies/Appsero/Insights.php - Added Insights class to track plugin usage and manage user consent.
- Implemented methods for data collection, sending tracking data, and managing notices.
dependencies/Appsero/License.php - Added License class for managing license checking, activation, and deactivation.
- Implemented methods for license management, including checking and refreshing license status.

Poem

🐇 In the garden where changes bloom,
New classes sprout, dispelling gloom.
Autoloading paths now neatly align,
With tracking and licenses, all will be fine.
Hooray for the updates, let’s hop and cheer,
For a brighter plugin future, oh so near! 🌼✨


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 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.

@devAsadNur devAsadNur requested a review from mrabbani December 2, 2024 07:47
Copy link

@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 (5)
dependencies/Appsero/Client.php (1)

223-226: Standardize HTTP header keys

In the headers array, 'user-agent' should be capitalized as 'User-Agent' to comply with HTTP standards.

Apply this diff to correct the header key:

$headers = [
-    'user-agent' => 'Appsero/' . md5( esc_url( home_url() ) ) . ';',
+    'User-Agent' => 'Appsero/' . md5( esc_url( home_url() ) ) . ';',
    'Accept'     => 'application/json',
];
dependencies/Appsero/License.php (2)

Line range hint 854-855: Correct typo in error message

There's a typo in the error message: "Nonce vefification failed." It should be "Nonce verification failed."

Apply this diff:

- wp_send_json_error( 'Nonce vefification failed' );
+ wp_send_json_error( 'Nonce verification failed' );

312-345: Improve form data handling and validation

In the license_form_submit() method, consider improving the handling and validation of form data to prevent potential issues.

  • Ensure all $_POST variables are checked with isset() before using them.
  • Use consistent sanitization functions appropriate for the data type.
  • Add error handling for unexpected or missing form data.
dependencies/Appsero/Insights.php (2)

854-855: Correct typo in error message

There's a typo in the error message: "Nonce vefification failed." It should be "Nonce verification failed."

Apply this diff:

- wp_send_json_error( 'Nonce vefification failed' );
+ wp_send_json_error( 'Nonce verification failed' );

365-379: Simplify and secure is_local_server() method

The is_local_server() method could be simplified and made more secure:

  • Use filter_var() with FILTER_VALIDATE_IP to check IP addresses.
  • Use in_array() with strict comparison.
  • Sanitize server variables properly.

Consider refactoring the method for clarity and security.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 81023b9 and 8a43f2c.

⛔ Files ignored due to path filters (1)
  • composer.lock is excluded by !**/*.lock
📒 Files selected for processing (5)
  • composer.json (1 hunks)
  • conversion-tracking.php (1 hunks)
  • dependencies/Appsero/Client.php (1 hunks)
  • dependencies/Appsero/Insights.php (1 hunks)
  • dependencies/Appsero/License.php (1 hunks)
🔇 Additional comments (2)
composer.json (1)

60-60: Verify exclusion of necessary packages

In the excluded_packages section, you have excluded psr/container. Ensure that excluding this package does not affect the functionality of other dependencies.

Run the following script to check for any dependencies requiring psr/container:

If any essential packages depend on psr/container, reconsider excluding it.

✅ Verification successful

Excluding psr/container package is safe in this context

Looking at the composer.json, the exclusion of psr/container is in the Mozart configuration section, which is used for dependency isolation. The package is not directly required by the project (not listed in require or require-dev), and the only packages being processed by Mozart are appsero/updater and appsero/client. Since these are simple client/updater libraries, excluding PSR Container interface won't affect the functionality.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if any required packages depend on psr/container

composer why psr/container

Length of output: 127


Script:

#!/bin/bash
# Let's check the content of composer.json to understand the dependencies and exclusions
cat composer.json

Length of output: 2055


Script:

#!/bin/bash
# Search for any direct usage of PSR Container interfaces or classes in the codebase
rg -l "use Psr\\Container" || rg -l "use Psr/Container"

Length of output: 146


Script:

#!/bin/bash
# Look for Container interface implementations
ast-grep --pattern 'implements ContainerInterface'

Length of output: 52

conversion-tracking.php (1)

Line range hint 249-253: Verify autoloading of namespaced Client class

The init_tracker() method now uses the WeDevs_WC_Conversion_Tracking\Dependencies\Appsero\Client class. Ensure that the new namespace is correctly configured in the autoloader.

Run the following script to confirm that the class is autoloaded properly:

If the class is not found, ensure that the autoload section in composer.json is correctly configured and that you've run composer dump-autoload.

✅ Verification successful

Autoloading configuration is correct and class is properly namespaced

The verification shows that:

  • The Client class exists at dependencies/Appsero/Client.php
  • It's correctly namespaced as WeDevs_WC_Conversion_Tracking\Dependencies\Appsero
  • The composer.json has proper PSR-4 autoloading configuration for the namespace
  • Mozart is correctly configured to prefix the Appsero client package
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify autoloading of the Client class

# Test: Check if the class file exists in the autoload paths
grep -r "class Client" vendor/ | grep "WeDevs_WC_Conversion_Tracking/Dependencies/Appsero/Client.php"

Length of output: 142


Script:

#!/bin/bash
# Let's first check if the class file exists in the repository
fd -t f "Client.php"

# Check composer.json for autoloading configuration
fd -t f "composer.json" --exec cat {}

# Check if there are any PHP files that define this namespace
rg -l "namespace.*WeDevs_WC_Conversion_Tracking\\Dependencies\\Appsero"

Length of output: 2200


Script:

#!/bin/bash
# Let's check the content of the Client.php file to verify namespace
cat dependencies/Appsero/Client.php | head -n 10

# Check if Mozart has properly prefixed the namespace
rg -l "use.*WeDevs_WC_Conversion_Tracking\\Dependencies\\Appsero\\Client"

# Check if the class is being loaded correctly in the main plugin file
rg -A 5 "new WeDevs_WC_Conversion_Tracking\\Dependencies\\Appsero\\Client" 

Length of output: 767

Comment on lines +228 to +242
$response = wp_remote_post(
$url,
[
'method' => 'POST',
'timeout' => 30,
'redirection' => 5,
'httpversion' => '1.0',
'blocking' => $blocking,
'headers' => $headers,
'body' => array_merge( $params, [ 'client' => $this->version ] ),
'cookies' => [],
]
);

return $response;
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add error handling for HTTP requests

In the send_request() method, the response from wp_remote_post() may be a WP_Error on failure. Currently, there is no check for this, which could lead to unexpected behavior.

Add error handling to check if $response is a WP_Error and handle it appropriately.

Apply this diff:

$response = wp_remote_post(
    $url,
    [
        'method'      => 'POST',
        'timeout'     => 30,
        'redirection' => 5,
        'httpversion' => '1.0',
        'blocking'    => $blocking,
        'headers'     => $headers,
        'body'        => array_merge( $params, [ 'client' => $this->version ] ),
        'cookies'     => [],
    ]
);

+ if ( is_wp_error( $response ) ) {
+     return $response;
+ }

return $response;
📝 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
$response = wp_remote_post(
$url,
[
'method' => 'POST',
'timeout' => 30,
'redirection' => 5,
'httpversion' => '1.0',
'blocking' => $blocking,
'headers' => $headers,
'body' => array_merge( $params, [ 'client' => $this->version ] ),
'cookies' => [],
]
);
return $response;
$response = wp_remote_post(
$url,
[
'method' => 'POST',
'timeout' => 30,
'redirection' => 5,
'httpversion' => '1.0',
'blocking' => $blocking,
'headers' => $headers,
'body' => array_merge( $params, [ 'client' => $this->version ] ),
'cookies' => [],
]
);
if ( is_wp_error( $response ) ) {
return $response;
}
return $response;

Comment on lines +190 to +191
list( $this->slug, $mainfile ) = explode( '/', $this->basename );

Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Handle potential Undefined offset when parsing basename

In the set_basename_and_slug() method, you are using explode( '/', $this->basename ) without verifying if $this->basename contains the '/' character. If $this->basename does not contain '/', this could lead to an Undefined offset notice.

Consider adding a check to ensure $this->basename contains '/' before exploding it.

Apply this diff to handle the case:

if ( strpos( $this->basename, '/' ) !== false ) {
    list( $this->slug, $mainfile ) = explode( '/', $this->basename );
} else {
+   $this->slug = $this->basename;
+   $mainfile = '';
}

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +313 to +317
if ( ! isset( $form_data['_nonce'] ) ) {
return;
}

if ( ! wp_verify_nonce( sanitize_key( wp_unslash( $form_data['_nonce'] ) ), $this->client->name ) ) {
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Use appropriate sanitization for nonce verification

In the license_form_submit() method, you are sanitizing the nonce using sanitize_key(). Since nonces are strings that may contain characters not allowed in keys, it's better to use sanitize_text_field().

Apply this diff:

if ( ! wp_verify_nonce( sanitize_key( wp_unslash( $_POST['_nonce'] ) ), $this->client->name ) ) {
    $this->error = $this->client->__trans( 'Nonce vefification failed.' );

+ if ( ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['_nonce'] ) ), $this->client->name ) ) {
+     $this->error = $this->client->__trans( 'Nonce verification failed.' );

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +1049 to +1062
$response = wp_remote_get( 'https://icanhazip.com/' );

if ( is_wp_error( $response ) ) {
return '';
}

$ip = trim( wp_remote_retrieve_body( $response ) );

if ( ! filter_var( $ip, FILTER_VALIDATE_IP ) ) {
return '';
}

return $ip;
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Handle potential failures when retrieving IP address

The get_user_ip_address() method relies on an external service (https://icanhazip.com/) to retrieve the user's IP address. If the service is unavailable or returns an invalid response, it could cause issues.

Consider adding a fallback mechanism or handling for when the remote request fails.

Apply this diff:

$ip = trim( wp_remote_retrieve_body( $response ) );

+ if ( empty( $ip ) || ! filter_var( $ip, FILTER_VALIDATE_IP ) ) {
+     $ip = $_SERVER['REMOTE_ADDR'] ?? '';
+ }
📝 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
$response = wp_remote_get( 'https://icanhazip.com/' );
if ( is_wp_error( $response ) ) {
return '';
}
$ip = trim( wp_remote_retrieve_body( $response ) );
if ( ! filter_var( $ip, FILTER_VALIDATE_IP ) ) {
return '';
}
return $ip;
}
$response = wp_remote_get( 'https://icanhazip.com/' );
if ( is_wp_error( $response ) ) {
return '';
}
$ip = trim( wp_remote_retrieve_body( $response ) );
if ( empty( $ip ) || ! filter_var( $ip, FILTER_VALIDATE_IP ) ) {
$ip = $_SERVER['REMOTE_ADDR'] ?? '';
}
return $ip;
}

Comment on lines +34 to +39
"[ $COMPOSER_DEV_MODE -eq 0 ] || \"vendor/bin/mozart\" compose",
"composer dump-autoload"
],
"post-update-cmd": [
"[ $COMPOSER_DEV_MODE -eq 0 ] || \"vendor/bin/mozart\" compose",
"composer dump-autoload"
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Correct script syntax for Composer hooks

In the post-install-cmd and post-update-cmd scripts, the conditional statements may not execute as intended within Composer's script context.

Consider revising the scripts to ensure they function correctly. Composer scripts don't interpret shell conditionals natively.

Apply this diff:

"post-install-cmd": [
-    "[ $COMPOSER_DEV_MODE -eq 0 ] || \"vendor/bin/mozart\" compose",
+    "@php vendor/bin/mozart compose",
     "composer dump-autoload"
],
"post-update-cmd": [
-    "[ $COMPOSER_DEV_MODE -eq 0 ] || \"vendor/bin/mozart\" compose",
+    "@php vendor/bin/mozart compose",
    "composer dump-autoload"
]

Alternatively, if you want the script to run only in dev mode, use Composer's scripts-dev section or check the COMPOSER_DEV_MODE environment variable within a PHP script.

📝 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
"[ $COMPOSER_DEV_MODE -eq 0 ] || \"vendor/bin/mozart\" compose",
"composer dump-autoload"
],
"post-update-cmd": [
"[ $COMPOSER_DEV_MODE -eq 0 ] || \"vendor/bin/mozart\" compose",
"composer dump-autoload"
"@php vendor/bin/mozart compose",
"composer dump-autoload"
],
"post-update-cmd": [
"@php vendor/bin/mozart compose",
"composer dump-autoload"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant