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: events calendar post form integration #1494

Conversation

sapayth
Copy link
Member

@sapayth sapayth commented Oct 28, 2024

fixes #516

Issue:
Event Created in FrontEnd > Does not hold values of Fields in Back-End

Summary by CodeRabbit

  • New Features

    • Enhanced form fields in the events calendar template with placeholder and default values for better clarity.
    • Introduced functionality to fetch posts dynamically based on specific post types in the dropdown field.
    • Added a new action hook in the post meta update process to improve extensibility.
  • Bug Fixes

    • Standardized the naming convention for radio field action hooks to ensure consistency.
  • Documentation

    • Updated comments to clarify functionality and enhance code readability.

Copy link

coderabbitai bot commented Oct 28, 2024

Walkthrough

The pull request introduces modifications to several classes related to form fields in the application. Key changes include the addition of placeholder and default attributes to specific fields in the Post_Form_Template_Events_Calendar class, enhancements to the Form_Field_Dropdown class with the integration of WP_Query for fetching posts, a renaming of an action hook in the Form_Field_Radio class, and the introduction of a new action hook in the FieldableTrait for post meta updates. Overall, these changes enhance the functionality and clarity of form handling without altering existing logic.

Changes

File Path Change Summary
includes/Admin/Forms/Post/Templates/Post_Form_Template_Events_Calendar.php Added placeholder and default attributes to _EventURL, _EventCurrencySymbol, and _EventCost fields.
includes/Fields/Form_Field_Dropdown.php Introduced WP_Query import, updated render method for post type 'tribe_events', added get_posts method.
includes/Fields/Form_Field_Radio.php Renamed action hook to wpuf_radio_field_after_label, reset $selected variable if it is an array.
includes/Traits/FieldableTrait.php Added action hook in update_post_meta method, modified comment handling for AJAX referer check.

Possibly related PRs

Suggested labels

bug, needs: developer feedback

🐇✨ In fields where forms do play,
Placeholders now light the way.
Dropdowns fetch with a query's might,
Radio buttons shine so bright.
Traits now hook for updates grand,
A clearer path, all at hand! ✨🐇


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.

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: 1

🧹 Outside diff range and nitpick comments (2)
includes/Fields/Form_Field_Dropdown.php (2)

Line range hint 40-46: Add error handling for Events Calendar integration

While the integration logic is correct, consider adding error handling to ensure the Events Calendar plugin is active before accessing its post types.

 if ( 'tribe_events' == get_post_type( $post_id ) ) {
+    // Verify Events Calendar plugin is active
+    if ( ! class_exists( 'Tribe__Events__Main' ) ) {
+        return;
+    }
     if ( '_EventVenueID' == $field_settings['name'] ) {
         $field_settings['options'] = $this->get_posts( 'tribe_venue' );
     } else if ( '_EventOrganizerID' == $field_settings['name'] ) {
         $field_settings['options'] = $this->get_posts( 'tribe_organizer' );
     }
 }

Line range hint 147-176: Several improvements needed in get_posts method

The method has potential performance and security issues that should be addressed:

 public function get_posts( $post_type ) {
+    // Sanitize and validate post type
+    $post_type = sanitize_key( $post_type );
+    if ( ! post_type_exists( $post_type ) ) {
+        return array();
+    }
+
+    // Check transient cache first
+    $cache_key = 'wpuf_dropdown_' . $post_type;
+    $posts = get_transient( $cache_key );
+    if ( false !== $posts ) {
+        return $posts;
+    }
+
     $args = array(
         'post_type'         => $post_type,
         'post_status'       => 'publish',
-        'orderby'           => 'DESC',
-        'order'             => 'ID',
-        'posts_per_page'    => -1
+        'orderby'          => 'ID',
+        'order'            => 'DESC',
+        'posts_per_page'   => 100,  // Limit to prevent memory issues
+        'no_found_rows'    => true, // Improve performance
+        'fields'           => 'id=>parent' // Only get required fields
     );

     $query = new WP_Query( $args );
     $posts = array();

     if ( $query->have_posts() ) {
-        $i = 0;
         while ( $query->have_posts() ) {
             $query->the_post();
-            $post = $query->posts[ $i ];
+            $post = $query->post;
             $posts[ $post->ID ] = $post->post_title;
-            $i++;
         }
     }

     wp_reset_postdata();
+    
+    // Cache results for 1 hour
+    set_transient( $cache_key, $posts, HOUR_IN_SECONDS );

     return $posts;
 }

Key improvements:

  1. Added post type validation
  2. Implemented caching using transients
  3. Fixed incorrect orderby/order parameters
  4. Limited posts_per_page to prevent memory issues
  5. Optimized query performance
  6. Removed unnecessary counter variable
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 2decc63 and 1a495aa.

📒 Files selected for processing (4)
  • includes/Admin/Forms/Post/Templates/Post_Form_Template_Events_Calendar.php (1 hunks)
  • includes/Fields/Form_Field_Dropdown.php (1 hunks)
  • includes/Fields/Form_Field_Radio.php (1 hunks)
  • includes/Traits/FieldableTrait.php (1 hunks)
🔇 Additional comments (9)
includes/Fields/Form_Field_Radio.php (2)

48-48: LGTM: Fixed potential type mismatch in radio button selection.

This change prevents PHP warnings when using checked() with array values and ensures radio buttons work correctly with meta values. This fix directly addresses the core issue where frontend values weren't being retained properly in the backend.


41-41: Breaking Change: Action hook renamed to follow WordPress naming conventions.

The action hook has been renamed from WPUF_radio_field_after_label to wpuf_radio_field_after_label to follow WordPress coding standards. While this is a good change, it could break existing implementations.

Let's check for any existing usage of the old hook name:

includes/Fields/Form_Field_Dropdown.php (2)

5-6: LGTM: Clean import addition

The WP_Query import is correctly placed and necessary for the new functionality.


Line range hint 40-46: Verify Events Calendar integration across codebase

Let's ensure the Events Calendar integration is consistently implemented.

✅ Verification successful

Events Calendar integration is properly implemented

The integration with The Events Calendar plugin is well-structured and complete:

  • Form_Field_Dropdown.php correctly handles venue and organizer fields for Events Calendar
  • A dedicated template class (Post_Form_Template_Events_Calendar) implements all required event fields
  • Frontend_Dashboard.php properly manages Events Calendar query integration
  • All necessary meta fields (_EventStartDate, _EventEndDate, _EventURL, etc.) are properly defined
  • The integration is conditionally loaded based on Events Calendar plugin presence
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for Events Calendar related code and dependencies

echo "Checking for Events Calendar related files and code..."

# Check for Events Calendar post types usage
rg -l "tribe_events|tribe_venue|tribe_organizer" --type php

# Check for Events Calendar meta fields
rg -l "_Event(Venue|Organizer)ID" --type php

# Check for Events Calendar class dependencies
rg -l "Tribe__Events" --type php

Length of output: 531


Script:

#!/bin/bash
# Let's examine the implementation details in these files

# Check Form_Field_Dropdown.php implementation
echo "=== Form_Field_Dropdown.php ==="
rg -B 5 -A 5 "tribe_organizer|_EventOrganizerID" includes/Fields/Form_Field_Dropdown.php

# Check Events Calendar template implementation
echo -e "\n=== Post_Form_Template_Events_Calendar.php ==="
cat includes/Admin/Forms/Post/Templates/Post_Form_Template_Events_Calendar.php

# Check Frontend integration
echo -e "\n=== Frontend_Dashboard.php ==="
rg -B 5 -A 5 "Tribe__Events" includes/Frontend/Frontend_Dashboard.php

Length of output: 11100

includes/Admin/Forms/Post/Templates/Post_Form_Template_Events_Calendar.php (2)

97-107: Consider meaningful default values and placeholders

The addition of empty placeholder and default attributes across these fields might not fully address the value retention issue. Empty values don't provide user guidance or default state initialization.

Consider adding:

  • Meaningful placeholders to guide users (e.g., "Enter event website URL" for EventURL)
  • Default values where appropriate (e.g., "$" for EventCurrencySymbol)

Let's verify if these fields are properly initialized in the frontend:

Also applies to: 110-119, 122-131


97-131: Verify the fix addresses the value retention issue

While adding placeholder and default attributes is a step in the right direction, we should verify if this alone resolves the value retention issue mentioned in PR #516.

Let's check for any form submission handling related to these fields:

includes/Traits/FieldableTrait.php (3)

327-336: LGTM! Well-documented action hook addition.

The new action hook provides a clean extension point for developers to intercept and modify meta fields before they are saved to the database. The documentation block clearly describes the hook's purpose and parameters.


326-326: ⚠️ Potential issue

Security concern: AJAX nonce verification is commented out.

The AJAX nonce verification check is commented out, which could expose the endpoint to CSRF attacks. This is a critical security measure that should not be disabled.

Apply this diff to restore the security check:

-// check_ajax_referer( 'wpuf_form_add' );
+check_ajax_referer( 'wpuf_form_add' );

Line range hint 1-1024: Consider implementing rate limiting for file uploads.

The trait handles file uploads but lacks rate limiting, which could lead to potential abuse. Consider implementing rate limiting for the file upload functionality to prevent DoS attacks.

✅ Verification successful

File upload security is adequately implemented

The codebase already implements multiple layers of security for file uploads:

  1. File size limits:

    • Uses WordPress's wp_max_upload_size()
    • Configurable max file size per field
    • Server-level validation against PHP's upload_max_filesize
  2. Upload validation:

    • Nonce verification via wp_verify_nonce() with 'wpuf-upload-nonce'
    • File count limits with configurable max_files setting
    • Size validation with user-friendly error messages
  3. Rate control:

    • Natural rate limiting through WordPress's nonce system
    • File count restrictions per form field
    • Server-side PHP configuration limits

The suggestion for additional rate limiting is not necessary as the existing security measures provide adequate protection against abuse through multiple validation layers and WordPress's built-in security features.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if rate limiting is implemented elsewhere
echo "Searching for rate limiting implementations..."
rg -i "rate.*limit|throttle|flood" 

Length of output: 52076


Script:

#!/bin/bash
# Check for rate limiting implementations in the codebase
echo "Searching for rate limiting implementations..."

# Search for rate limiting related code
rg -i "rate.*limit|throttle|flood|upload.*limit|file.*limit|max.*upload|max.*file" --type php

# Search for file upload configurations
rg -i "upload_max|max_file|file_max" --type php

# Check for nonce verification in file upload handling
rg -i "wp_verify_nonce.*upload|check_ajax_referer.*upload" --type php

Length of output: 9002

Comment on lines +97 to +131
'input_type' => 'url',
'template' => 'website_url',
'required' => 'no',
'label' => __( 'Event Website', 'wp-user-frontend' ),
'name' => '_EventURL',
'placeholder' => '',
'default' => '',
'is_meta' => 'yes',
'width' => 'large',
'size' => 40,
'wpuf_cond' => $this->conditionals,
],
[
'input_type' => 'text',
'template' => 'text_field',
'required' => 'no',
'label' => __( 'Currency Symbol', 'wp-user-frontend' ),
'name' => '_EventCurrencySymbol',
'is_meta' => 'yes',
'size' => 40,
'wpuf_cond' => $this->conditionals,
'input_type' => 'text',
'template' => 'text_field',
'required' => 'no',
'label' => __( 'Currency Symbol', 'wp-user-frontend' ),
'name' => '_EventCurrencySymbol',
'placeholder' => '',
'default' => '',
'is_meta' => 'yes',
'size' => 40,
'wpuf_cond' => $this->conditionals,
],
[
'input_type' => 'text',
'template' => 'text_field',
'required' => 'no',
'label' => __( 'Cost', 'wp-user-frontend' ),
'name' => '_EventCost',
'is_meta' => 'yes',
'wpuf_cond' => $this->conditionals,
'input_type' => 'text',
'template' => 'text_field',
'required' => 'no',
'label' => __( 'Cost', 'wp-user-frontend' ),
'name' => '_EventCost',
'placeholder' => '',
'default' => '',
'size' => 40,
'is_meta' => 'yes',
'wpuf_cond' => $this->conditionals,
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider implementing form field validation

The URL and cost fields lack validation rules. Consider adding:

  • URL format validation for _EventURL
  • Numeric validation for _EventCost
  • Currency symbol length restriction for _EventCurrencySymbol

Example implementation for the EventURL field:

 'input_type'  => 'url',
 'template'    => 'website_url',
 'required'    => 'no',
 'label'       => __( 'Event Website', 'wp-user-frontend' ),
 'name'        => '_EventURL',
 'placeholder' => '',
 'default'     => '',
 'is_meta'     => 'yes',
 'width'       => 'large',
 'size'        => 40,
+`validate`    => 'url',
 'wpuf_cond'   => $this->conditionals,

Committable suggestion was skipped due to low confidence.

@Rubaiyat-E-Mohammad
Copy link

Got the following issue in debug log:
[29-Oct-2024 09:21:09 UTC] PHP Fatal error: Uncaught Error: Class 'WeDevs\Wpuf\Pro\Admin\Forms\PostTemplates\DateTimeImmutable' not found in /Users/rubaiyatemohammad/Sites/random/wp-content/plugins/wpuf-pro/includes/Admin/Forms/PostTemplates/Post_Form_Template_Events_Calendar.php:848 Stack trace: #0 /Users/rubaiyatemohammad/Sites/random/wp-content/plugins/wpuf-pro/includes/Admin/Forms/PostTemplates/Post_Form_Template_Events_Calendar.php(763): WeDevs\Wpuf\Pro\Admin\Forms\PostTemplates\Post_Form_Template_Events_Calendar->handle_date_issues(Array, 393) #1 /Users/rubaiyatemohammad/Sites/random/wp-content/plugins/wpuf-pro/includes/Admin/Forms/PostTemplates/Post_Form_Template_Events_Calendar.php(728): WeDevs\Wpuf\Pro\Admin\Forms\PostTemplates\Post_Form_Template_Events_Calendar->handle_form_updates(393, 355, Array) #2 /Users/rubaiyatemohammad/Sites/random/wp-content/plugins/wp-user-frontend/includes/Admin/Forms/Post/Templates/Form_Template.php(257): WeDevs\Wpuf\Pro\Admin\Forms\PostTemplates\Post_Form_Template_Events_Calendar->after_insert(393, 355, Array) #3 in /Users/rubaiyatemohammad/Sites/random/wp-content/plugins/wpuf-pro/includes/Admin/Forms/PostTemplates/Post_Form_Template_Events_Calendar.php on line 848 [29-Oct-2024 09:21:10 UTC] tribe-canonical-line channel=default level=debug source="TEC\Events\Custom_Tables\V1\Models\Model::validate:288" errors="{\"timezone\":\"The provided timezone is not a valid timezone.\",\"start_date_utc\":\"The start_date_utc requires a value.\"}" [29-Oct-2024 09:21:10 UTC] tribe-canonical-line channel=default level=error source="The provided timezone is not a valid timezone. : The start_date_utc requires a value." method="TEC\Events\Custom_Tables\V1\Models\Builder::upsert" line=319 model="TEC\Events\Custom_Tables\V1\Models\Event" [29-Oct-2024 09:25:39 UTC] tribe-canonical-line channel=default level=debug source="TEC\Events\Custom_Tables\V1\Models\Model::validate:288" errors="{\"duration\":\"The Event duration (259199) is greater than the one calculated using dates.\",\"end_date_utc\":\"The end_date_utc does not match the value of end_date with the timezone.\"}" [29-Oct-2024 09:25:39 UTC] tribe-canonical-line channel=default level=error source="The Event duration (259199) is greater than the one calculated using dates. : The end_date_utc does not match the value of end_date with the timezone." method="TEC\Events\Custom_Tables\V1\Models\Builder::upsert" line=319 model="TEC\Events\Custom_Tables\V1\Models\Event" [29-Oct-2024 09:25:39 UTC] tribe-canonical-line channel=default level=debug source="TEC\Events\Custom_Tables\V1\Models\Model::validate:288" errors="{\"duration\":\"The Event duration (259199) is greater than the one calculated using dates.\",\"end_date_utc\":\"The end_date_utc does not match the value of end_date with the timezone.\"}" [29-Oct-2024 09:25:39 UTC] tribe-canonical-line channel=default level=error source="The Event duration (259199) is greater than the one calculated using dates. : The end_date_utc does not match the value of end_date with the timezone." method="TEC\Events\Custom_Tables\V1\Models\Builder::upsert" line=319 model="TEC\Events\Custom_Tables\V1\Models\Event"

@sapayth
Copy link
Member Author

sapayth commented Oct 30, 2024

the error is coming from wpuf-pro. the fix is in this PR. try deactivating wpuf-pro or pull both PR from free and pro @Rubaiyat-E-Mohammad bhai

@Rubaiyat-E-Mohammad Rubaiyat-E-Mohammad added QA In Progress QA Approved This PR is approved by the QA team Ready to Merge This PR is now ready to be merged and removed bug needs: dev review This PR needs review by a developer QA In Progress labels Nov 1, 2024
@sapayth sapayth merged commit d02f506 into weDevsOfficial:develop Nov 11, 2024
1 check failed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
QA Approved This PR is approved by the QA team Ready to Merge This PR is now ready to be merged
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants