spivurno
4/18/2015 - 7:38 PM

Gravity Wiz // Gravity Forms // File Generator

Gravity Wiz // Gravity Forms // File Generator

<?php
/**
 * Gravity Wiz // Gravity Forms // File Generator
 *
 * Generate a file on submission which will be processed for merge tags.
 *
 * @version   1.0
 * @author    David Smith <david@gravitywiz.com>
 * @license   GPL-2.0+
 * @link      http://gravitywiz.com/...
 * @video     http://www.screencast.com/t/DSr794vPOxxi
 * @copyright 2015 Gravity Wiz
 */
class GW_File_Generator {

    public $_entries          = array();
    public $_registered_files = array();

    private static $instance = null;

    public static function get_instance() {

        if( self::$instance == null )
            self::$instance = new self;

	    return self::$instance;
    }

    function __construct() {

	    add_action( 'init', array( $this, 'init' ) );

    }

	function init() {

		// make sure we're running the required minimum version of Gravity Forms
		if( ! property_exists( 'GFCommon', 'version' ) || ! version_compare( GFCommon::$version, '1.9', '>=' ) ) {
			return;
		}

		$this->listen_for_file_url();

		add_filter( 'gform_replace_merge_tags', array( $this, 'replace_get_file_url_merge_tag' ), 10, 3 );

	}

	function register_file( $filename, $template ) {
		$this->_registered_files[ $filename ] = $template;
	}

	function get_file_url( $entry_id, $filename ) {
		return add_query_arg( array(
			'gw_file_gen' => $filename,
			'eid'         => rawurlencode( GFCommon::encrypt( $entry_id ) )
		), get_site_url() );
	}

	function listen_for_file_url() {

		$filename = rgget( 'gw_file_gen' );
		if( ! $filename || ! array_key_exists( $filename, $this->_registered_files ) ) {
			return;
		}

		$entry_id = $this->get_entry_id();
		if( ! $entry_id ) {
			return;
		}

		$template_url = $this->_registered_files[ $filename ];

		$this->generate_file( $entry_id, $filename, $template_url );

	}

	function generate_file( $entry_id, $filename, $template_url ) {

		$entry = $this->get_entry();
		if( is_wp_error( $entry ) ) {
			return;
		}

		$template = $this->get_template_content( $template_url );
		$content  = $this->replace_merge_tags( $template, $entry );

		header( sprintf( 'Content-Disposition: attachment; filename=%s', basename( $filename ) ) );
		header(          'Content-Type: application/force-download' );
		header( sprintf( 'Content-Length: %d', strlen( $content ) ) );
		header(          'Connection: close' );

		echo $content;

		exit;
	}

	function get_template_content( $template_url) {
		return file_get_contents( $template_url );
	}

    function replace_merge_tags( $content, $entry = false ) {

        $entry = ! $entry ? $this->get_entry() : $entry;
        if( ! $entry ) {
	        return $content;
        }

        $form = GFFormsModel::get_form_meta( $entry['form_id'] );

	    $content = $this->replace_field_label_merge_tags( $content, $form );
	    $content = GFCommon::replace_variables( $content, $form, $entry, false, false, false );

        return $content;
    }

    function replace_field_label_merge_tags( $text, $form ) {

        preg_match_all( '/{([^:]+?)}/', $text, $matches, PREG_SET_ORDER );
        if( empty( $matches ) )
            return $text;

        foreach( $matches as $match ) {

            list( $search, $field_label ) = $match;

            foreach( $form['fields'] as $field ) {

                $full_input_id = false;
                $matches_admin_label = rgar( $field, 'adminLabel' ) == $field_label;
                $matches_field_label = false;

                if( is_array( $field['inputs'] ) ) {
                    foreach( $field['inputs'] as $input ) {
                        if( GFFormsModel::get_label( $field, $input['id'] ) == $field_label ) {
                            $matches_field_label = true;
                            $input_id = $input['id'];
                            break;
                        }
                    }
                } else {
                    $matches_field_label = GFFormsModel::get_label( $field ) == $field_label;
                    $input_id = $field['id'];
                }

                if( ! $matches_admin_label && ! $matches_field_label )
                    continue;

                $replace = sprintf( '{%s:%s}', $field_label, (string) $input_id );
                $text = str_replace( $search, $replace, $text );

                break;
            }

        }

        return $text;
    }

    function prepare_eid( $entry_id ) {

		$eid = rawurlencode( GFCommon::encrypt( $entry_id ) );

        return $eid;
    }

    function get_entry( $entry_id = false ) {

	    $entry_id = ! $entry_id ? $this->get_entry_id() : $entry_id;
	    if( ! $entry_id ) {
		    return new WP_Error( 'no_entry_id', __( 'Entry ID was not provided.' ) );
	    } else if( ! isset( $this->_entries[ $entry_id ] ) ) {
            $this->_entries[ $entry_id ] = GFAPI::get_entry( $entry_id );
        }

        return $this->_entries[ $entry_id ];
    }

    function get_entry_id() {

        $entry_id = rgget( 'eid' );
        if( $entry_id ) {
            return intval( GFCommon::decrypt( $entry_id ) );
        }

        return $entry_id ? $entry_id : false;
    }

	function replace_get_file_url_merge_tag( $text, $form, $entry ) {

		preg_match_all( '/{get_file_url:(.*?)}/', $text, $matches, PREG_SET_ORDER );
		if( empty( $matches ) ) {
			return $text;
		}

		// $entry is not always a "full" entry
		$entry_id = rgar( $entry, 'id' );

		foreach( $matches as $match ) {

			list( $search, $filename ) = $match;

			if( array_key_exists( $filename, $this->_registered_files ) ) {
				$replace = $this->get_file_url( $entry_id, $filename );
				$text    = str_replace( $search, $replace, $text );
			}

		}

		return $text;
	}

}

function gw_file_generator() {
    return GW_File_Generator::get_instance();
}

gw_file_generator()->register_file( 'config.txt', 'http://localhost/wp-content/uploads/2015/04/CONFIG-TEMPLATE.txt' );