spivurno of Gravity Wiz
5/6/2014 - 2:52 PM

Gravity Wiz // Gravity Forms // Zip Uploaded Files

Gravity Wiz // Gravity Forms // Zip Uploaded Files

<?php
/**
* Gravity Wiz // Gravity Forms // Zip Uploaded Files
*
* Preview your Gravity forms on the frontend of your website. Adds a "Live Preview" link to the Gravity Forms toolbar.
*
* @version	 1.0
* @author    David Smith <david@gravitywiz.com>
* @license   GPL-2.0+
* @link      http://gravitywiz.com/...
* @copyright 2014 Gravity Wiz
*/
class GW_Zip_Files {

    /**
     * @todo
     *     + add support for auto-attaching to notification
     *     + add support for multiple zip files per form (by field)
     *     + add support for removing file fields from {all_fields}
     *     + add support for linking to specific zip by 'zip_name': {gwzip:zip_name}
     */

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

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

        // ZipArchive must be installed for PHP
        if( ! class_exists( 'ZipArchive' ) )
            return;

        // 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_ids' => false,
            'zip_name'  => 'gf-uploads'
        ) );

        // time for hooks
        add_action( 'gform_entry_created',       array( $this, 'archive_files'            ), 10, 2 );
        add_filter( 'gform_entry_meta',          array( $this, 'register_entry_meta'      ), 10, 2 );
        add_filter( 'gform_entries_field_value', array( $this, 'modify_zip_display_value' ), 10, 3 );
        add_filter( 'gform_replace_merge_tags',  array( $this, 'all_files_merge_tag'      ), 10, 7 );

    }

    public function archive_files( $entry, $form ) {

        if( ! $this->has_applicable_field( $form ) )
            return;

        $archive_files = array();

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

            if( ! $this->is_applicable_field( $field ) )
                continue;

            $files = GFFormsModel::get_lead_field_value( $entry, $field );
            if( $this->is_multi_file( $field ) )
                $files = json_decode( $files );

            if( empty( $files ) )
                continue;

            if( ! is_array( $files ) )
                $files = array( $files );

            foreach( $files as $file ) {
                if( $file_path = $this->convert_url_to_path( $file ) )
                    $archive_files[] = $file_path;
            }

        }

        if( empty( $archive_files ) )
            return;

        $zip = $this->create_zip( $archive_files, $this->get_zip_paths( $entry, 'path' ) );
        if( $zip )
            gform_update_meta( $entry['id'], $this->get_meta_key(), $this->get_zip_paths( $entry, 'url' ) );

    }

    public function register_entry_meta( $entry_meta, $form_id ) {

        if( ! empty( $this->_args['field_ids'] ) )
            return $entry_meta;

        $entry_meta[$this->get_meta_key()] = array(
            'label'             => 'Form Uploads Zip File',
            'is_numeric'        => false,
            'is_default_column' => false
        );

        return $entry_meta;
    }

    public function modify_zip_display_value( $value, $form_id, $field_id ) {

        if( $field_id != $this->get_meta_key() )
            return $value;

        $value = sprintf( '<a href="%s">%s</a>', $value, __( 'Download Zip' ) );

        return $value;
    }

    public function has_applicable_field( $form ) {

        foreach( $form['fields'] as $field ) {
            if( $this->is_applicable_field( $field ) )
                return true;
        }

        return false;
    }

    public function is_applicable_field( $field ) {

        $input_type = GFFormsModel::get_input_type( $field );

        $is_applicable_input_type = in_array( $input_type, array( 'fileupload', 'post_image' ) );
        $is_applicable_field_id   = empty( $this->_args['field_ids'] ) || in_array( $field['id'], $this->_args['field_ids'] );

        return $is_applicable_input_type && $is_applicable_field_id;
    }

    public function is_multi_file( $field ) {
        return rgar( $field, 'multipleFiles' );
    }

    public function convert_url_to_path( $url ) {

        $url = array_shift( explode( '|:|', $url ) );
        if( ! $url )
            return false;

        if( is_multisite() && get_site_option( 'ms_files_rewriting' ) ) {
            $path = preg_replace( '|^(.*?)/files/gravity_forms/|', BLOGUPLOADDIR . 'gravity_forms/', $url );
        } else {
            $path = str_replace( WP_CONTENT_URL, WP_CONTENT_DIR, $url );
        }

        return file_exists( $path ) ? $path : false;
    }

    public function create_zip( $files = array(), $destination = '', $overwrite = false ) {

        if( ! is_array( $files ) )
            return false;

        if( file_exists( $destination ) && ! $overwrite )
            return false;

        $valid_files = array();

        foreach( $files as $file ) {
            if( file_exists( $file ) )
                $valid_files[] = $file;
        }

        if( empty( $valid_files ) )
            return false;

        $zip = new ZipArchive();

        if( $zip->open( $destination, $overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE ) !== true )
            return false;

        foreach( $valid_files as $file ) {
            $zip->addFile( $file, basename( $file ) );
        }

        $zip->close();

        return file_exists( $destination ) ? $destination : false;
    }

    public function get_zip_paths( $entry, $type = false ) {

        $filename = $this->get_zip_filename( $entry['id'] );
        $paths = GFFormsModel::get_file_upload_path( $entry['form_id'], $filename );

        foreach( $paths as &$path ) {
            $path = str_replace( basename( $path ), $filename, $path );
        }

        return $type ? rgar( $paths, $type ) : $paths;
    }

    public function get_zip_filename( $entry_id ) {
        return $this->get_slug( $this->_args['zip_name'], $entry_id, $this->_args['field_ids'] ) . '.zip';
    }

    public function get_meta_key( $entry_id = false ) {
        return $this->get_slug( 'gw_zip', $entry_id, $this->_args['field_ids'] );
    }

    public function get_slug( $name, $entry_id = false, $field_ids = array() ) {

        $bits = array( $name );

        if( $entry_id )
            $bits[] = $entry_id;

        if( ! empty( $field_ids ) )
            $bits[] = md5( implode( $field_ids ) );

        return implode( '_', $bits );
    }

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

        $search = '{all_files}';
        $replace = array( __( 'Uploaded Files:' ) );

        $zip_file = $this->get_zip_paths( $entry, 'path' );
        if( ! $zip_file )
            return $text;

        $zip = new ZipArchive;
        if( ! $zip->open( $zip_file ) )
            return $text;

        $files = array();
        for( $i = 0; $i < $zip->numFiles; $i++ ) {
            $files[] = $zip->getNameIndex( $i );
        }

        $replace = array_merge( $replace, $files );
        $replace[] = sprintf( '<a href="%s">%s</a>', $this->get_zip_paths( $entry, 'url' ), __( 'All Files' ) );

        $replace = implode( '<br />', $replace );

        return str_replace( $search, $replace, $text );
    }

}

# Configuration

new GW_Zip_Files( array(
    'form_id' => 394,
    'zip_name' => 'my-sweet-archive'
) );