spivurno
8/8/2015 - 4:29 AM

Gravity Wiz // Gravity Forms // Print Entry Templates

Gravity Wiz // Gravity Forms // Print Entry Templates

<?php
/**
 * Gravity Wiz // Gravity Forms // Print Entry Templates
 *
 * Provides an easy method for customizing the markup used to generate the Print Entry view in Gravity Forms.
 *
 * @version	  0.9
 * @author    David Smith <david@gravitywiz.com>
 * @license   GPL-2.0+
 * @link      http://gravitywiz.com/...
 * @copyright 2015 Gravity Wiz
 *
 * Plugin Name: Gravity Forms Print Entry Templates
 * Plugin URI: http://gravitywiz.com
 * Description: Provides an easy method for customizing the markup used to generate the Print Entry view in Gravity Forms.
 * Author: David Smith
 * Version: 0.9
 * Author URI: http://gravitywiz.com
 */
class GW_Print_Entry_Templates {

    public function __construct( $args = array() ) {

        // set our default arguments, parse against the provided arguments, and store for use throughout the class
        $this->_args = wp_parse_args( $args, array(
            'form_id'  => false,
            'field_id' => false
        ) );

        // do version check in the init to make sure if GF is going to be loaded, it is already loaded
        add_action( 'init', array( $this, 'init' ) );

    }

    public function init() {

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

        // carry on
	    add_action( 'gform_print_entry_header', array( $this, 'buffer_print_entry_output' ), 1, 2 );
	    add_action( 'gform_print_entry_footer', array( $this, 'clean_print_entry_output_buffer' ), 99, 2 );
	    add_action( 'gform_print_styles',       array( $this, 'maybe_print_scripts' ) );

	    add_filter( 'gform_replace_merge_tags', array( $this, 'replace_notes_merge_tag' ), 10, 3 );
	    add_filter( 'gform_merge_tag_filter', array( $this, 'add_label_modifier_support' ), 10, 5 );

    }

	public function maybe_print_scripts() {

		if( rgget( 'gf_page' ) != 'print-entry' ) {
			return;
		}

		$scripts = new WP_Scripts();
		$scripts->do_items( 'jquery' );

		$template_names = $this->get_available_templates();

		?>

		<style type="text/css">
			#gw-template-select { float: right; margin-top: 4px; }
		</style>

		<script type="text/javascript">

			( function( $ ) {

				var templateNames   = <?php echo json_encode( $template_names ); ?>,
					currentTemplate = '<?php echo $this->get_selected_template(); ?>',
					placeholder     = '<?php _e( 'Default Template' ); ?>';

				$( document ).ready( function( $ ) {
					$( '#print_preview_hdr div:first-child' ).append( generateSelect() );
					$( '#gw-template-select' ).change( function() {
						location.href = removeURLParameter( location.href, 'template' )  + '&template=' + $( this ).val();
					} );
				} );

				function generateSelect() {

					var optionsMarkup = '<option value="">' + placeholder + '</option>';

					for( var i = 0; i < templateNames.length; i++ ) {
						var selected   = templateNames[i].slug == currentTemplate ? 'selected="selected"' : '';
						optionsMarkup += '<option value="' + templateNames[i].slug + '" ' + selected + '>' + templateNames[i].name + '</option>';
					}

					return '<select id="gw-template-select">' + optionsMarkup + '</select>';
				}

				function removeURLParameter( url, parameter ) {
					//prefer to use l.search if you have a location/link object
					var urlparts= url.split('?');
					if (urlparts.length>=2) {

						var prefix= encodeURIComponent(parameter)+'=';
						var pars= urlparts[1].split(/[&;]/g);

						//reverse iteration as may be destructive
						for (var i= pars.length; i-- > 0;) {
							//idiom for string.startsWith
							if (pars[i].lastIndexOf(prefix, 0) !== -1) {
								pars.splice(i, 1);
							}
						}

						url= urlparts[0]+'?'+pars.join('&');
						return url;
					} else {
						return url;
					}
				}

			} )( jQuery );

		</script>

		<?php
	}

	public function buffer_print_entry_output( $form, $entry ) {
		ob_start();
	}

	public function clean_print_entry_output_buffer( $form, $entry ) {
		if( $this->get_selected_template() ) {
			ob_end_clean();
			$content = $this->load_template( sprintf( 'print_entry_%s', $this->get_selected_template() ), null, array( 'form' => $form, 'entry' => $entry ), array( $form['id'] ) );
			echo GFCommon::replace_variables( $content, $form, $entry, false, true, false );

			// output page break between entries
			$page_break = rgget( 'page_break' ) ? 'print-page-break' : false;
			echo sprintf( '<div class="print-hr %s"></div>', $page_break );

		} else {
			echo ob_get_clean();
		}
	}

	public function get_selected_template() {
		return rgget( 'template' );
	}

	public function replace_notes_merge_tag( $text, $form, $entry ) {

		if( strpos( $text, '{notes}' ) === false ) {
			return $text;
		}

		$notes        = GFFormsModel::get_lead_notes( $entry['id'] );
		$notes_markup = '';

		if ( ! empty( $notes ) ) {
			ob_start();
			GFEntryDetail::notes_grid( $notes, false );
			$notes_markup = ob_get_clean();
		}

		return str_replace( '{notes}', $notes_markup, $text );
	}

	public function get_available_templates() {

		$templates = array();
		$paths     = array_unique( $this->get_theme_template_paths() );

		foreach( $paths as $template_path ) {
			$files = glob( $template_path . 'print_entry*.php' );
			if( ! empty( $files ) ) {
				$templates = array_merge( $templates, $files );
			}
		}

		// clean up template data
		foreach( $templates as &$template ) {
			$slug = str_replace( 'print_entry_', '', basename( $template, '.php' ) );
			$template = array(
				'path' => $template,
				'slug' => $slug,
				'name' => ucwords( str_replace( '-', ' ', $slug ) )
			);
		}

		return $templates;
	}

	public function add_label_modifier_support( $value, $input_id, $modifier, $field, $raw_value ) {

		if( $modifier == 'label' ) {
			$value = GFCommon::get_label( $field, $input_id );
		}

		return $value;
	}

    // # TEMPLATE SYSTEM (compliments of EDD) --------------------------------------------------------------------------

    public function load_template( $slug, $name = null, $data = array(), $suffixes = array() ) {
        ob_start();
        extract( $data );
        $template = $this->get_template_part( $slug, $name, false, $suffixes );
        if( ! empty( $template ) ) {
            include( $template );
        }
        $content = ob_get_clean();
        return ! $template ? false : $content;
    }

    public function get_template_part( $slug, $name = null, $load = true, $suffixes = array() ) {

        // Execute code for this part
        do_action( 'get_template_part_' . $slug, $slug, $name, $suffixes );

        // Setup possible parts
        $templates = array();

        if( isset( $name ) ) {
            $suffixes[] = $name;
        }

        foreach( $suffixes as $suffix ) {
            $templates[] = $slug . '-' . $suffix . '.php';
        }

        $templates[] = $slug . '.php';

        // Return the part that is found
        return $this->locate_template( $templates, $load, false );
    }

    public function locate_template( $template_names, $load = false, $require_once = true ) {

        // No file found yet
        $located = false;

        // Try to find a template file
        foreach ( (array) $template_names as $template_name ) {

            // Continue if template is empty
            if ( empty( $template_name ) )
                continue;

            // Trim off any slashes from the template name
            $template_name = ltrim( $template_name, '/' );

            // try locating this template file by looping through the template paths
            foreach( $this->get_theme_template_paths() as $template_path ) {

                if( file_exists( $template_path . $template_name ) ) {
                    $located = $template_path . $template_name;
                    break;
                }
            }

            if( $located ) {
                break;
            }
        }

        if ( ( true == $load ) && ! empty( $located ) )
            load_template( $located, $require_once );

        return $located;
    }

    public function get_theme_template_paths() {

        $template_dir = $this->get_theme_template_dir_name();

        $file_paths = array(
            1 => trailingslashit( get_stylesheet_directory() ) . $template_dir,
            10 => trailingslashit( get_template_directory() ) . $template_dir
        );

        $file_paths = apply_filters( 'edd_template_paths', $file_paths );

        // sort the file paths based on priority
        ksort( $file_paths, SORT_NUMERIC );

        return array_map( 'trailingslashit', $file_paths );
    }

    public function get_theme_template_dir_name() {
        return trailingslashit( 'gravityforms' );
    }

}

# Configuration

new GW_Print_Entry_Templates();