Rename Uploaded Files

Rename uploaded files for Gravity Forms. You can create a static naming template or using merge tags to base names on user input.

Features:

  • supports single and multi-file upload fields
  • flexible naming template with support for static and dynamic values via GF merge tags

Uses:

  • add a prefix or suffix to file uploads
  • include identifying submitted data in the file name like the user’s first and last name

Instructions

See “Where do I put snippets?” in our documentation for installation instructions.
Read the Walkthrough

Code

Filename: gw-gravity-forms-rename-uploaded-files.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
<?php
/**
 * Gravity Wiz // Gravity Forms // Rename Uploaded Files
 * https://gravitywiz.com/rename-uploaded-files-for-gravity-form/
 *
 * Rename uploaded files for Gravity Forms. You can create a static naming template or using merge tags to base names on user input.
 *
 * Features:
 *  + supports single and multi-file upload fields
 *  + flexible naming template with support for static and dynamic values via GF merge tags
 *
 * Uses:
 *  + add a prefix or suffix to file uploads
 *  + include identifying submitted data in the file name like the user's first and last name
 *
 * @version   2.7
 * @author    David Smith <david@gravitywiz.com>
 * @license   GPL-2.0+
 * @link      https://gravitywiz.com/rename-uploaded-files-for-gravity-form/
 */
class GW_Rename_Uploaded_Files {

	public $_args;

	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,
			'template'         => '',
			'ignore_extension' => 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 ( ! is_callable( array( 'GFFormsModel', 'get_physical_file_path' ) ) ) {
			return;
		}

		add_filter( 'gform_entry_post_save', array( $this, 'rename_uploaded_files' ), 9, 2 );
		add_filter( 'gform_entry_post_save', array( $this, 'stash_uploaded_files' ), 99, 2 );

		add_action( 'gform_after_update_entry', array( $this, 'rename_uploaded_files_after_update' ), 9, 2 );
		add_action( 'gform_after_update_entry', array( $this, 'stash_uploaded_files_after_update' ), 99, 2 );

	}

	function rename_uploaded_files( $entry, $form ) {

		if ( ! $this->is_applicable_form( $form ) ) {
			return $entry;
		}

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

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

			$uploaded_files = rgar( $entry, $field->id );

			if ( empty( $uploaded_files ) ) {
				continue;
			}

			$uploaded_files = $this->parse_files( $uploaded_files, $field );
			$stashed_files  = $this->parse_files( gform_get_meta( $entry['id'], 'gprf_stashed_files' ), $field );
			$renamed_files  = array();

			foreach ( $uploaded_files as $_file ) {

				// Don't rename the same files twice.
				if ( in_array( $_file, $stashed_files ) ) {
					$renamed_files[] = $_file;
					continue;
				}

				$dir  = wp_upload_dir();
				$dir  = $this->get_upload_dir( $form['id'] );
				$file = str_replace( $dir['url'], $dir['path'], $_file );

				if ( ! file_exists( $file ) ) {
					continue;
				}

				$renamed_file = $this->rename_file( $file, $entry );

				if ( ! is_dir( dirname( $renamed_file ) ) ) {
					wp_mkdir_p( dirname( $renamed_file ) );
				}

				$result = rename( $file, $renamed_file );

				if ( ! $result ) {
					$renamed_files[] = $_file;
					continue;
				}

				$renamed_url = $this->get_url_by_path( $renamed_file, $form['id'] );
				$renamed_files[] = $renamed_url;

				// Keep Gravity Forms file-path meta in sync with the renamed URL.
				$root = GF_Field_FileUpload::get_upload_root_info( $form['id'] );
				gform_update_meta(
					$entry['id'],
					GF_Field_FileUpload::get_file_upload_path_meta_key_hash( $renamed_url ),
					array(
						'path'      => trailingslashit( $root['path'] ),
						'url'       => trailingslashit( $root['url'] ),
						'file_name' => wp_basename( $renamed_url ),
					)
				);
			}

			// In cases where 3rd party add-ons offload the image to a remote location, no images can be renamed.
			if ( empty( $renamed_files ) ) {
				continue;
			}

			if ( $field->get_input_type() == 'post_image' ) {
				$value = str_replace( $uploaded_files[0], $renamed_files[0], rgar( $entry, $field->id ) );
			} elseif ( $field->multipleFiles ) {
				$value = json_encode( $renamed_files );
			} else {
				$value = $renamed_files[0];
			}

			GFAPI::update_entry_field( $entry['id'], $field->id, $value );

			$entry[ $field->id ] = $value;

		}

		return $entry;
	}

	function get_upload_dir( $form_id ) {
		$dir         = GFFormsModel::get_file_upload_path( $form_id, 'PLACEHOLDER' );
		$dir['path'] = dirname( $dir['path'] );
		$dir['url']  = dirname( $dir['url'] );
		return $dir;
	}

	function rename_uploaded_files_after_update( $form, $entry_id ) {
		$entry = GFAPI::get_entry( $entry_id );
		$this->rename_uploaded_files( $entry, $form );
	}

	/**
	 * Stash the "final" version of the files after other add-ons have had a chance to interact with them.
	 *
	 * @param $entry
	 * @param $form
	 */
	function stash_uploaded_files( $entry, $form ) {

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

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

			$uploaded_files         = rgar( $entry, $field->id );
			$existing_stashed_files = gform_get_meta( $entry['id'], 'gprf_stashed_files' );

			if ( $this->is_json( $uploaded_files ) ) {
				$uploaded_files = json_decode( $uploaded_files, ARRAY_A );
			}

			if ( $this->is_json( $existing_stashed_files ) ) {
				$existing_stashed_files = json_decode( $existing_stashed_files, ARRAY_A );
			}

			/* Convert single files to array of files. */
			if ( ! is_array( $existing_stashed_files ) ) {
				$existing_stashed_files = $existing_stashed_files ? array( $existing_stashed_files ) : array();
			}

			if ( ! is_array( $uploaded_files ) ) {
				$uploaded_files = $uploaded_files ? array( $uploaded_files ) : array();
			}

			if ( ! empty( $existing_stashed_files ) ) {
				$uploaded_files = array_merge( $existing_stashed_files, $uploaded_files );
			}

			gform_update_meta( $entry['id'], 'gprf_stashed_files', json_encode( $uploaded_files ) );

		}

		return $entry;
	}

	/**
	 * Check whether a string is JSON or not.
	 *
	 * @param $string string String to test.
	 *
	 * @return bool Whether the string is JSON.
	 */
	function is_json( $string ) {
		if ( method_exists( 'GFCommon', 'is_json' ) ) {
			return GFCommon::is_json( $string );
		}

		// Duplicate contents of GFCommon::is_json() here to supports versions of GF older than GF 2.5.
		// phpcs:ignore WordPress.PHP.StrictInArray.MissingTrueStrict
		if ( is_string( $string ) && in_array( substr( $string, 0, 1 ), array( '{', '[' ) ) && is_array( json_decode( $string, ARRAY_A ) ) ) {
			return true;
		}

		return false;
	}

	function stash_uploaded_files_after_update( $form, $entry_id ) {
		$entry = GFAPI::get_entry( $entry_id );
		$this->stash_uploaded_files( $entry, $form );
	}

	function rename_file( $file, $entry ) {

		$new_file = $this->get_renamed_filepath( $this->_args['template'], $file, $entry );
		$new_file = $this->increment_file( $new_file );

		return $new_file;
	}

	function increment_file( $file ) {

		$file_path = GFFormsModel::get_physical_file_path( $file );
		$pathinfo  = pathinfo( $file_path );
		$counter   = 1;

		if ( $this->_args['ignore_extension'] ) {
			while ( glob( str_replace( ".{$pathinfo['extension']}", '.*', $file_path ) ) ) {
				$file_path = str_replace( ".{$pathinfo['extension']}", "{$counter}.{$pathinfo['extension']}", GFFormsModel::get_physical_file_path( $file ) );
				$counter ++;
			}
		} else {
			// increment the filename if it already exists (i.e. balloons.jpg, balloons1.jpg, balloons2.jpg)
			while ( file_exists( $file_path ) ) {
				$file_path = str_replace( ".{$pathinfo['extension']}", "{$counter}.{$pathinfo['extension']}", GFFormsModel::get_physical_file_path( $file ) );
				$counter ++;
			}
		}

		$file = str_replace( basename( $file ), basename( $file_path ), $file );

		return $file;
	}

	function is_path( $filename ) {
		return strpos( $filename, '/' ) !== false;
	}

	function get_renamed_filepath( $template, $file, $entry ) {
		$info = pathinfo( $file );

		// replace our custom "{filename}" psuedo-merge-tag
		$filename = str_replace( '{filename}', $info['filename'], $template );

		// replace merge tags
		$form     = GFAPI::get_form( $entry['form_id'] );
		$filename = GFCommon::replace_variables( $filename, $form, $entry, false, true, false, 'text' );
		// make sure filename is "clean". This includes removing any user inputted items such as "../", "/usr/bin" etc
		$filename = $this->clean( $filename );

		if ( strpos( $template, '/' ) === 0 ) {
			$dir      = wp_upload_dir();
			$filepath = $dir['basedir'];
		} else {
			$filepath = $info['dirname'] . '/';
		}

		$filepath .= $filename . '.' . $info['extension'];

		return $filepath;
	}

	function is_applicable_form( $form ) {

		$form_id = isset( $form['id'] ) ? $form['id'] : $form;

		return $form_id == $this->_args['form_id'];
	}

	function is_applicable_field( $field ) {

		$is_file_upload_field   = in_array( GFFormsModel::get_input_type( $field ), array( 'fileupload', 'post_image' ) );
		$is_applicable_field_id = $this->_args['field_id'] ? $field['id'] == $this->_args['field_id'] : true;

		return $is_file_upload_field && $is_applicable_field_id;
	}

	function clean( $str ) {
		return sanitize_file_name( $str );
	}

	function get_url_by_path( $file, $form_id ) {

		$dir = $this->get_upload_dir( $form_id );
		$url = str_replace( $dir['path'], $dir['url'], $file );

		return $url;
	}

	function parse_files( $files, $field ) {

		if ( empty( $files ) ) {
			return array();
		}

		if ( $this->is_json( $files ) ) {
			$files = json_decode( $files );
		} elseif ( $field->get_input_type() === 'post_image' ) {
			$file_bits = explode( '|:|', $files );
			$files     = array( $file_bits[0] );
		} else {
			$files = array( $files );
		}

		return $files;
	}

}

# Configuration

new GW_Rename_Uploaded_Files( array(
	'form_id'          => 628,
	'field_id'         => 3,
	// most merge tags are supported, original file extension is preserved
	'template'         => '{Name (First):1.3}-{Name (Last):1.6}-{filename}',
	// Ignore extension when renaming files and keep them in sequence (e.g. a.jpg, a1.png, a2.pdf etc.)
	'ignore_extension' => false,
) );

Leave a Reply

Your email address will not be published. Required fields are marked *

  • Trouble installing this snippet? See our troubleshooting tips.
  • Need to include code? Create a gist and link to it in your comment.
  • Reporting a bug? Provide a URL where this issue can be recreated.

By commenting, I understand that I may receive emails related to Gravity Wiz and can unsubscribe at any time.