Completed
Pull Request — develop (#1484)
by Zack
07:48
created

GravityView_Field_FileUpload   A

Complexity

Total Complexity 35

Size/Duplication

Total Lines 382
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 11

Test Coverage

Coverage 74.63%

Importance

Changes 0
Metric Value
dl 0
loc 382
ccs 103
cts 138
cp 0.7463
rs 9.6
c 0
b 0
f 0
wmc 35
lcom 0
cbo 11

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A field_options() 0 26 2
A get_field_input() 0 8 1
F get_files_array() 0 301 31
1
<?php
2
/**
3
 * @file class-gravityview-field-fileupload.php
4
 * @package GravityView
5
 * @subpackage includes\fields
6
 */
7
8
class GravityView_Field_FileUpload extends GravityView_Field {
9
10
	var $name = 'fileupload';
11
12
	var $_gf_field_class_name = 'GF_Field_FileUpload';
13
14
	var $is_searchable = true;
15
16
	var $search_operators = array( 'contains' );
17
18
	var $group = 'advanced';
19
20
	public function __construct() {
21
		$this->label = esc_html__( 'File Upload', 'gravityview' );
22
		parent::__construct();
23
	}
24
25
	public function field_options( $field_options, $template_id, $field_id, $context, $input_type, $form_id ) {
26
27
		unset( $field_options['search_filter'] );
28
29
		if( 'edit' === $context ) {
30
			return $field_options;
31
		}
32
33
		$add_options['link_to_file'] = array(
0 ignored issues
show
Coding Style Comprehensibility introduced by
$add_options was never initialized. Although not strictly required by PHP, it is generally a good practice to add $add_options = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
34
			'type' => 'checkbox',
35
			'label' => __( 'Display as a Link:', 'gravityview' ),
36
			'desc' => __('Display the uploaded files as links, rather than embedded content.', 'gravityview'),
37
			'value' => false,
38
			'merge_tags' => false,
39
		);
40
41
		$add_options['image_width'] = array(
42
			'type' => 'text',
43
			'label' => __( 'Custom Width:', 'gravityview' ),
44
			'desc' => __( 'Override the default image width (250).', 'gravityview' ),
45
			'value' => '250',
46
			'merge_tags' => false,
47
		);
48
49
		return $add_options + $field_options;
50
	}
51
52
	/**
53
	 * Trick the GF fileupload field to render with the proper HTML ID to enable the plupload JS to work properly
54
	 *
55
	 * @param array               $form  The Form Object currently being processed.
56
	 * @param string|array        $value The field value. From default/dynamic population, $_POST, or a resumed incomplete submission.
0 ignored issues
show
Bug introduced by
There is no parameter named $value. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
57
	 * @param null|array          $entry Null or the Entry Object currently being edited.
58
	 * @param GF_Field_FileUpload $field Gravity Forms field
59
	 *
60
	 * @return string
61
	 */
62 2
	function get_field_input( $form, $field_value, $entry, $field ) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
63
64 2
		$field->_is_entry_detail = true;
65
66 2
		$return = $field->get_field_input( $form, $field_value, $entry );
67
68 2
		return $return;
69
	}
70
71
	/**
72
	 * Return an array of files prepared for output.
73
	 *
74
	 * Processes files by file type and generates unique output for each. Returns array for each file, with the following keys:
75
	 * - `file_path` => The file path of the file, with a line break
76
	 * - `html` => The file output HTML formatted
77
	 *
78
	 * @since  1.2
79
	 * @todo  Support `playlist` shortcode for playlist of video/audio
80
	 * @param  string $value    Field value passed by Gravity Forms. String of file URL, or serialized string of file URL array
81
	 * @param  string $gv_class Field class to add to the output HTML
82
	 *
83
	 * @since 2.0
84
	 * @param \GV\Template_Context The context.
85
	 *
86
	 * @return array           Array of file output, with `file_path` and `html` keys (see comments above)
87
	 */
88 5
	static function get_files_array( $value, $gv_class, $context = null ) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
89
90 5
		if ( $context instanceof \GV\Template_Context ) {
91 5
			$field = $context->field->field;
0 ignored issues
show
Bug introduced by
The property field does not seem to exist in GV\Field.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
92 5
			$field_settings = $context->field->as_configuration();
93 5
			$entry = $context->entry->as_entry();
94 5
			$field_value = $context->value;
95 5
			global $post;
96 5
			$base_id = $post ? $post->ID : $context->view->ID;
97
98 5
			$is_single = $context->request->is_entry();
99 5
			$lightbox = $context->view->settings->get( 'lightbox', false );
100
101
			/** A compatibility array that's required by some of the deprecated filters. */
102
			$field_compat = array(
103 5
				'form' => $context->source->form,
0 ignored issues
show
Bug introduced by
The property form does not seem to exist in GV\Source.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
104 5
				'field_id' => $context->field->ID,
105 5
				'field' => $field,
106 5
				'field_settings' => $field_settings,
107 5
				'value' => $field_value,
108 5
				'display_value' => $context->display_value,
109 5
				'format' => 'html',
110 5
				'entry' => $entry,
111 5
				'field_type' => $context->field->type,
0 ignored issues
show
Documentation introduced by
The property type does not exist on object<GV\Field>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
112 5
				'field_path' => $context->template->located_template,
113
			);
114
		} else {
115
116
			_doing_it_wrong( __METHOD__, '2.0', 'Please pass a \GV\Template_Context object as the 3rd parameter' );
117
118
			$gravityview_view = GravityView_View::getInstance();
119
			/** @deprecated path */
120
			$gv_field_array = $gravityview_view->getCurrentField();
121
122
			/** @var GF_Field_FileUpload $field */
123
			$field = \GV\Utils::get( $gv_field_array, 'field' );
124
			$field_settings = \GV\Utils::get( $gv_field_array, 'field_settings' );
125
			$entry = \GV\Utils::get( $gv_field_array, 'entry' );
126
			$field_value = \GV\Utils::get( $gv_field_array, 'value' );
127
			$base_id = null;
128
129
			$is_single = gravityview_get_context() === 'single';
0 ignored issues
show
Deprecated Code introduced by
The function gravityview_get_context() has been deprecated with message: since 2.0.6.2 Use `gravityview()->request`

This function has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed from the class and what other function to use instead.

Loading history...
130
			$lightbox = ! empty( $gravityview_view->atts['lightbox'] );
0 ignored issues
show
Documentation introduced by
The property $atts is declared protected in GravityView_View. Since you implemented __get(), maybe consider adding a @property or @property-read annotation. This makes it easier for IDEs to provide auto-completion.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
131
			$field_compat = $gravityview_view->getCurrentField();
132
		}
133
134 5
		$output_arr = array();
135
136
		// Get an array of file paths for the field.
137 5
		$file_paths = \GV\Utils::get( $field , 'multipleFiles' ) ? json_decode( $value ) : array( $value );
138
139
		// The $value JSON was probably truncated; let's check lead_detail_long.
140 5
		if ( ! is_array( $file_paths ) ) {
141
			$full_value = RGFormsModel::get_lead_field_value( $entry, $field );
142
			$file_paths = json_decode( $full_value );
143
		}
144
145 5
		if ( ! is_array( $file_paths ) ) {
146
			gravityview()->log->error( 'Field does not have a valid image array. JSON decode may have failed.', array( 'data' => array( '$value' => $value, '$field_value' => $field_value ) ) );
147
			return $output_arr;
148
		}
149
150
		// Process each file path
151 5
		foreach ( $file_paths as $index => $file_path ) {
152
153 5
			$rendered = null;
154
155
			// If the site is HTTPS, use HTTPS
156 5
			if ( function_exists('set_url_scheme') ) {
157 5
				$file_path = set_url_scheme( $file_path );
158
			}
159
160
			// This is from Gravity Forms's code
161 5
			$file_path = esc_attr( str_replace( " ", "%20", $file_path ) );
162
163
			// Get file path information
164 5
			$file_path_info = pathinfo( $file_path );
165
166
			// If pathinfo() gave us the extension of the file, run the switch statement using that.
167 5
			$extension = empty( $file_path_info['extension'] ) ? NULL : strtolower( $file_path_info['extension'] );
168 5
			$basename = $file_path_info['basename'];
169
170
			// Get the secure download URL
171 5
			$is_secure = false;
172 5
			$insecure_file_path = $file_path;
173 5
			$secure_file_path = $field->get_download_url( $file_path );
174 5
			$text = $basename;
175
176 5
			if ( $secure_file_path !== $file_path ) {
177 2
				$basename = basename( $secure_file_path );
178 2
				$file_path = $secure_file_path;
179 2
				$is_secure = true;
180
			}
181
182
			/**
183
			 * @filter `gravityview/fields/fileupload/file_path` Modify the file path before generating a link to it
184
			 * @since 1.22.3
185
			 * @since 2.0 Added $context parameter
186
			 * @since 2.8.2
187
			 * @param string $file_path Path to the file uploaded by Gravity Forms
188
			 * @param array  $field_settings Array of GravityView field settings
189
			 * @param \GV\Template_Context $context The context.
190
			 * @param int $index The current index of the $file_paths array being processed
191
			 */
192 5
			$file_path = apply_filters( 'gravityview/fields/fileupload/file_path', $file_path, $field_settings, $context, $index );
193
194
			// Audio
195 5
			if ( in_array( $extension, wp_get_audio_extensions() ) ) {
196 4
				if ( shortcode_exists( 'audio' ) ) {
197
198
					/**
199
					 * @filter `gravityview_audio_settings` Modify the settings passed to the `wp_video_shortcode()` function
200
					 * @since  1.2
201
					 * @param array $audio_settings Array with `src` and `class` keys
202
					 * @since 2.0
203
					 * @param \GV\Template_Context $context The context.
204
					 */
205 4
					$audio_settings = apply_filters( 'gravityview_audio_settings', array(
206 4
						'src' => $insecure_file_path, // Needs to be insecure path so WP can parse extension
207 4
						'class' => 'wp-audio-shortcode gv-audio gv-field-id-'.$field_settings['id']
208 4
					), $context );
209
210
					/**
211
					 * Generate the audio shortcode
212
					 * @see http://codex.wordpress.org/Audio_Shortcode
213
					 * @see https://developer.wordpress.org/reference/functions/wp_audio_shortcode/
214
					 */
215 4
					$rendered = wp_audio_shortcode( $audio_settings );
216
217 4
					if ( $is_secure ) {
218
219
						// The shortcode adds instance URL args: add_query_arg( '_', $instance, $atts[ $fallback ] )
220
						// these break the path, since we already have "?" in the URL
221 1
						$rendered = str_replace( '?_=', '&_=', $rendered );
222
223 4
						foreach ( array( 'esc_attr', 'esc_html', 'esc_url', 'trim' /** noop */ ) as $f ) {
224 1
							$rendered = str_replace( $f( $insecure_file_path ), $f( $secure_file_path ), $rendered );
225
						}
226
					}
227
				}
228
229
			// Video
230 5
			} else if ( in_array( $extension, wp_get_video_extensions() ) ) {
231
232 1
				if ( shortcode_exists( 'video' ) ) {
233
234
					/**
235
					 * @filter `gravityview_video_settings` Modify the settings passed to the `wp_video_shortcode()` function
236
					 * @since  1.2
237
					 * @param array $video_settings Array with `src` and `class` keys
238
					 * @since 2.0
239
					 * @param \GV\Template_Context $context The context.
240
					 */
241 1
					$video_settings = apply_filters( 'gravityview_video_settings', array(
242 1
						'src' => $insecure_file_path, // Needs to be insecure path so WP can parse extension
243 1
						'class' => 'wp-video-shortcode gv-video gv-field-id-'.$field_settings['id']
244 1
					), $context );
245
246
					/**
247
					 * Generate the video shortcode
248
					 * @see http://codex.wordpress.org/Video_Shortcode
249
					 * @see https://developer.wordpress.org/reference/functions/wp_video_shortcode/
250
					 */
251 1
					$rendered = wp_video_shortcode( $video_settings );
252
253 1
					if ( $is_secure ) {
254
255
						// The shortcode adds instance URL args: add_query_arg( '_', $instance, $atts[ $fallback ] )
256
						// these break the path, since we already have "?" in the URL
257
						$rendered = str_replace( '?_=', '&_=', $rendered );
258
259 1
						foreach ( array( 'esc_attr', 'esc_html', 'esc_url', 'trim' /** noop */ ) as $f ) {
260
							$rendered = str_replace( $f( $insecure_file_path ), $f( $secure_file_path ), $rendered );
261
						}
262
					}
263
				}
264
265
			// PDF
266 5
			} else if ( $extension === 'pdf' ) {
267
268
				// PDF needs to be displayed in an IFRAME
269 1
				$file_path = add_query_arg( array( 'TB_iframe' => 'true' ), $file_path );
270
271
			// Images
272 5
			} else if ( in_array( $extension, array( 'jpg', 'jpeg', 'jpe', 'gif', 'png' ) ) ) {
273 4
				$width = \GV\Utils::get( $field_settings, 'image_width', 250 );
274
				$image_atts = array(
275 4
					'src'   => $file_path,
276 4
					'class' => 'gv-image gv-field-id-' . $field_settings['id'],
277 4
					'alt'   => $field_settings['label'],
278 4
					'width' => ( $is_single ? null : ( $width ? $width: 250 ) )
279
				);
280
281 4
				if ( $is_secure ) {
282 2
					$image_atts['validate_src'] = false;
283
				}
284
285
				/**
286
				 * Modify the default image attributes for uploaded images
287
				 *
288
				 * @since 2.0
289
				 * @see GravityView_Image For the available attributes
290
				 *
291
				 * @param array $image_atts
292
				 */
293 4
				$image_atts = apply_filters( 'gravityview/fields/fileupload/image_atts', $image_atts );
294
295 4
				$image = new GravityView_Image( $image_atts );
296
297 4
				$gv_entry = \GV\GF_Entry::from_entry( $entry );
298
299 4
				$entry_slug = $gv_entry->get_slug();
300
301 4
				unset( $gv_entry );
302
303 4
				if ( $lightbox && empty( $field_settings['show_as_link'] ) ) {
304
					$lightbox_link_atts = array(
305 3
						'rel'   => sprintf( "%s-%s", $gv_class, $entry_slug ),
306 3
						'class' => '',
307
					);
308
309 3
					$lightbox_link_atts = apply_filters( 'gravityview/fields/fileupload/link_atts', $lightbox_link_atts, $field_compat, $context );
310
311 3
					$image_atts['src'] = $insecure_file_path;
312 3
					$image = new GravityView_Image( $image_atts );
313 3
					$file_path = $insecure_file_path;
314
315 3
					$rendered = gravityview_get_link( $file_path, $image->html(), $lightbox_link_atts );
316
				} else {
317 2
					$rendered = $image->html();
318
				}
319
320
				// Show as link should render the image regardless.
321 4
				if ( ! empty( $field_settings['show_as_link'] ) ) {
322 1
					$text = $rendered;
323
				}
324
			}
325
326
			/**
327
			 * @filter `gravityview/fields/fileupload/disable_link` Filter to alter the default behaviour of wrapping images (or image names) with a link to the content object
328
			 * @since 1.5.1
329
			 * @param bool $disable_wrapped_link whether to wrap the content with a link to the content object.
330
			 * @param array $field_compat Current GravityView field array
331
			 * @see GravityView_API:field_value() for info about $gravityview_view->field_data
332
			 * @since 2.0
333
			 * @param \GV\Template_Context $context The context.
334
			 */
335 5
			$disable_wrapped_link = apply_filters( 'gravityview/fields/fileupload/disable_link', false, $field_compat, $context );
336
337
			// Output textualized content where
338 5
			if ( ! $disable_wrapped_link && ( ! empty( $field_settings['link_to_file'] ) || ! empty( $field_settings['show_as_link'] ) ) ) {
339
				/**
340
				 * Modify the link text (defaults to the file name)
341
				 *
342
				 * @since 1.7
343
				 *
344
				 * @param string $content The existing anchor content. Could be `<img>` tag, audio/video embed or the file name
345
				 * @param array $field_compat Current GravityView field array
346
				 * @since 2.0
347
				 * @param \GV\Template_Context $context The context.
348
				 */
349 1
				$content = apply_filters( 'gravityview/fields/fileupload/link_content', $text, $field_compat, $context );
350
351 1
				if ( empty( $field_settings['show_as_link'] ) ) {
352
					/**
353
					 * @filter `gravityview/fields/fileupload/link_atts` Modify the link attributes for a file upload field
354
					 * @param array|string $link_atts Array or attributes string
355
					 * @param array $field_compat Current GravityView field array
356
					 * @since 2.0
357
					 * @param \GV\Template_Context $context The context.
358
					 */
359 1
					$link_atts = apply_filters( 'gravityview/fields/fileupload/link_atts', array( 'target' => '_blank' ), $field_compat, $context );
360
361 1
					$content = gravityview_get_link( $file_path, $content, $link_atts );
362
				}
363
			} else {
364 5
				$content = empty( $rendered ) ? $text : $rendered;
365
			}
366
367 5
			$output_arr[] = array(
368 5
				'file_path' => $file_path,
369 5
				'content' => $content
370
			);
371
372
		} // End foreach loop
373
374
		/**
375
		 * @filter `gravityview/fields/fileupload/files_array` Modify the files array
376
		 * @since 1.7
377
		 * @since 2.0 Added $context
378
		 * @param array $output_arr Associative array of files. {
379
		 *  @type string $file_path The path to the file as stored in Gravity Forms.
380
		 *  @type string $content The generated output for the file.
381
		 * }
382
		 * @param array $field_compat Current GravityView field array.
383
		 * @param \GV\Template_Context $context The context.
384
		 */
385 5
		$output_arr = apply_filters( 'gravityview/fields/fileupload/files_array', $output_arr, $field_compat, $context );
386
387 5
		return $output_arr;
388
	}
389
}
390
391
new GravityView_Field_FileUpload;
392