HEX
Server: LiteSpeed
System: Linux server315.web-hosting.com 4.18.0-553.54.1.lve.el8.x86_64 #1 SMP Wed Jun 4 13:01:13 UTC 2025 x86_64
User: globfdxw (6114)
PHP: 8.1.34
Disabled: NONE
Upload Files
File: //home/globfdxw/www/wp-content/plugins/wpforms-pdf/src/Builder/Ajax/Preview.php
<?php

namespace WPFormsPDF\Builder\Ajax;

use WPFormsPDF\PDF\Renderer;
use Exception;

/**
 * Class Preview.
 *
 * Handles AJAX requests for generating PDF previews in the form builder.
 *
 * @since 1.0.0
 */
class Preview extends Base {

	/**
	 * Register hooks.
	 *
	 * @since 1.0.0
	 */
	protected function hooks(): void {

		add_action( 'wp_ajax_wpforms_pdf_get_preview', [ $this, 'get_preview_html' ] );
	}

	/**
	 * Get PDF preview HTML via AJAX.
	 *
	 * @since 1.0.0
	 */
	public function get_preview_html(): void {

		// Verify the AJAX request.
		$this->verify_ajax_request();
		[ $form_id, $pdf_id, $form_data ] = $this->get_and_sanitize_post_data();

		// Create the renderer.
		$renderer            = new Renderer();
		$form_data['fields'] = $this->get_sample_form_fields();
		$entry_fields        = $this->get_fake_entry_fields();
		$texts               = $this->get_fake_texts( $entry_fields );

		// Render HTML.
		$html = $renderer
			->init_pdf_settings( $pdf_id, $form_data, $entry_fields, 0, true )
			->render_html( $texts );

		// Check for errors.
		if ( empty( $html ) ) {
			// Log the error.
			wpforms_pdf()->helpers->log(
				[
					'message'   => 'An empty PDF preview generated.',
					'form_id'   => $form_id,
					'pdf_id'    => $pdf_id,
					'form_data' => $form_data,
				],
				'error'
			);

			// Send the error.
			wp_send_json_error( esc_html__( 'Something is wrong. An empty PDF preview was generated.', 'wpforms-pdf' ) );
		}

		// Send the response.
		wp_send_json_success( [ 'html' => $html ] );
	}

	/**
	 * Get fake entry fields.
	 *
	 * @since 1.0.0
	 *
	 * @return array
	 */
	private function get_fake_entry_fields(): array {

		$fields       = $this->get_sample_form_fields();
		$count        = 0;
		$max          = 3;
		$entry_fields = [];

		foreach ( $fields as $id => $field ) {

			$entry_fields[ $id ] = [
				'id'    => $id,
				'type'  => $field['type'] ?? 'text',
				'name'  => $field['label'] ?? 'Text',
				'value' => $this->get_fake_value( $field ),
			];

			++$count;

			if ( $count >= $max ) {
				break;
			}
		}

		return $entry_fields;
	}

	/**
	 * Get fake entry fields.
	 *
	 * @since 1.0.0
	 *
	 * @param array $form_data Form data.
	 *
	 * @return array
	 * @noinspection PhpUnusedParameterInspection
	 */
	private function get_fake_texts( array $form_data ): array {

		return [
			'sender_name'  => get_bloginfo( 'name' ),
			'sender_email' => get_option( 'admin_email' ),
		];
	}

	/**
	 * Get sample form fields.
	 *
	 * @since 1.0.0
	 *
	 * @return array Sample form fields.
	 */
	private function get_sample_form_fields(): array {

		return [
			1 => [
				'id'       => '1',
				'type'     => 'name',
				'format'   => 'first-last',
				'label'    => esc_html__( 'Name', 'wpforms-pdf' ),
				'required' => '1',
				'size'     => 'medium',
			],
			2 => [
				'id'       => '2',
				'type'     => 'email',
				'label'    => esc_html__( 'Email', 'wpforms-pdf' ),
				'required' => '1',
				'size'     => 'medium',
			],
			3 => [
				'id'          => '3',
				'type'        => 'textarea',
				'label'       => esc_html__( 'Comment or Message', 'wpforms-pdf' ),
				'size'        => 'medium',
				'placeholder' => '',
				'css'         => '',
			],
		];
	}

	/**
	 * Get fake value.
	 *
	 * @since 1.0.0
	 *
	 * @param array $field Field settings.
	 *
	 * @return string
	 */
	private function get_fake_value( array $field ): string {

		$type = $field['type'] ?? 'text';

		// fake values.
		$values = [
			'name'     => [
				'John Doe',
				'Jane Smith',
				'Bob Johnson',
			],
			'email'    => [
				'1aI2R@example.com',
				'jane@gmail.com',
				'bob@wp.com',
			],
			'text'     => [
				'Lorem ipsum dolor sit amet.',
				'Consectetur adipiscing elit.',
				'Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.',
				'Odio ut sem nulla pharetra diam sit amet.',
			],
			'textarea' => [
				'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Odio ut sem nulla pharetra diam sit amet. Sed risus pretium quam vulputate dignissim suspendisse in est ante. Risus ultricies tristique nulla aliquet enim tortor at auctor. Nisl tincidunt eget nullam non nisi est sit amet facilisis. Duis at tellus at urna condimentum mattis pellentesque id nibh. Curabitur vitae nunc sed velit dignissim.',
				'Amet aliquam purus sit amet luctus venenatis lectus magna fringilla urna porttitor rhoncus dolor purus non enim praesent elementum facilisis leo vel fringilla.',
			],
			'checkbox' => [
				"Lorem ipsum\ndolor sit amet.",
				"Consectetur\nadipiscing elit.",
				"Sed do eiusmod tempor\nincididunt ut labore\net dolore magna aliqua.",
				'Odio ut sem nulla.',
			],
			'address'  => [
				"1234 Fake St\nCity, State, Country\nPostal Code",
				"1234 Sunset Blvd\nLos Angeles,\nCA 90026",
			],
			'tel'      => [
				'+1234567890',
				'123-456-7890',
			],
			'url'      => [
				'https://wpforms.com',
				'https://google.com',
			],
		];

		try {
			$values['number'] = [ random_int( 0, 1000 ) ];
		} catch ( Exception $e ) {
			$values['number'] = 555;
		}

		if ( array_key_exists( $type, $values ) ) {
			$key = $type;
		} else {
			$map = [
				'text'             => 'text',
				'select'           => 'text',
				'checkbox'         => 'checkbox',
				'radio'            => 'checkbox',
				'payment-checkbox' => 'checkbox',
				'payment-multiple' => 'checkbox',
				'textarea'         => 'textarea',
				'content'          => 'textarea',
				'html'             => 'textarea',
				'richtext'         => 'textarea',
				'number'           => 'number',
				'number-slider'    => 'number',
			];

			$key = $map[ $type ] ?? null;
		}

		return empty( $key ) ? '' : $values[ $key ][ array_rand( $values[ $key ] ) ];
	}

	/**
	 * Get and sanitize POST data.
	 *
	 * @since 1.0.0
	 *
	 * @return array
	 */
	private function get_and_sanitize_post_data(): array {

		// Get and sanitize POST data.
		$form_id   = $this->get_post_data( 'form_id', 'int' );
		$pdf_id    = $this->get_post_data( 'pdf_id', 'int' );
		$form_data = $this->get_post_data( 'form_data', 'form_data' );

		$this->validate_ids( $form_id, $pdf_id );

		$settings      = $form_data['settings']['pdfs'][ $pdf_id ] ?? [];
		$theme_slug    = $settings['theme'] ?? '';
		$template_slug = $settings['template_style'] ?? '';

		// Basic check for the required settings.
		if ( empty( $theme_slug ) || empty( $template_slug ) ) {
			wp_send_json_error( esc_html__( 'Invalid settings provided.', 'wpforms-pdf' ) );
		}

		return [ $form_id, $pdf_id, $form_data ];
	}

	/**
	 * Validate form and PDF IDs.
	 *
	 * @since 1.0.0
	 *
	 * @param mixed $form_id Form ID.
	 * @param mixed $pdf_id  PDF ID.
	 *
	 * @return void
	 */
	protected function validate_ids( $form_id, $pdf_id ): void {

		// Validate IDs.
		if ( absint( $form_id ) <= 0 ) {
			wp_send_json_error( esc_html__( 'Invalid Form ID provided.', 'wpforms-pdf' ) );
		}

		if ( absint( $pdf_id ) <= 0 ) {
			wp_send_json_error( esc_html__( 'Invalid PDF ID provided.', 'wpforms-pdf' ) );
		}
	}
}