Completed
Push — master ( 21157a...9cf7be )
by Zack
84:58 queued 65:12
created

GravityView_Field_FileUpload::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 3

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 4
rs 10
cc 1
eloc 3
nc 1
nop 0
1
<?php
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 8 and the first side effect is on line 262.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
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';
0 ignored issues
show
Coding Style introduced by
The visibility should be declared for property $name.

The PSR-2 coding standard requires that all properties in a class have their visibility explicitly declared. If you declare a property using

class A {
    var $property;
}

the property is implicitly global.

To learn more about the PSR-2, please see the PHP-FIG site on the PSR-2.

Loading history...
11
12
	var $_gf_field_class_name = 'GF_Field_FileUpload';
0 ignored issues
show
Coding Style introduced by
The visibility should be declared for property $_gf_field_class_name.

The PSR-2 coding standard requires that all properties in a class have their visibility explicitly declared. If you declare a property using

class A {
    var $property;
}

the property is implicitly global.

To learn more about the PSR-2, please see the PHP-FIG site on the PSR-2.

Loading history...
13
14
	var $group = 'advanced';
0 ignored issues
show
Coding Style introduced by
The visibility should be declared for property $group.

The PSR-2 coding standard requires that all properties in a class have their visibility explicitly declared. If you declare a property using

class A {
    var $property;
}

the property is implicitly global.

To learn more about the PSR-2, please see the PHP-FIG site on the PSR-2.

Loading history...
15
16
	public function __construct() {
17
		$this->label = esc_html__( 'File Upload', 'gravityview' );
18
		parent::__construct();
19
	}
20
21
	function field_options( $field_options, $template_id, $field_id, $context, $input_type ) {
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...
22
23
		unset( $field_options['search_filter'] );
24
25
		if( 'edit' === $context ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
26
			return $field_options;
27
		}
28
29
		$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...
30
			'type' => 'checkbox',
31
			'label' => __( 'Display as a Link:', 'gravityview' ),
32
			'desc' => __('Display the uploaded files as links, rather than embedded content.', 'gravityview'),
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after opening bracket; 0 found
Loading history...
Coding Style introduced by
Expected 1 spaces before closing bracket; 0 found
Loading history...
33
			'value' => false,
34
			'merge_tags' => false,
35
		);
36
37
		return $add_options + $field_options;
38
	}
39
40
	/**
41
	 * Return an array of files prepared for output.
42
	 *
43
	 * Processes files by file type and generates unique output for each. Returns array for each file, with the following keys:
44
	 * - `file_path` => The file path of the file, with a line break
45
	 * - `html` => The file output HTML formatted
46
	 *
47
	 * @since  1.2
48
	 * @todo  Support `playlist` shortcode for playlist of video/audio
49
	 * @param  string $value    Field value passed by Gravity Forms. String of file URL, or serialized string of file URL array
50
	 * @param  string $gv_class Field class to add to the output HTML
51
	 * @return array           Array of file output, with `file_path` and `html` keys (see comments above)
52
	 */
53
	static function get_files_array( $value, $gv_class ) {
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...
54
55
		$gravityview_view = GravityView_View::getInstance();
56
57
		extract( $gravityview_view->getCurrentField() );
0 ignored issues
show
introduced by
extract() usage is highly discouraged, due to the complexity and unintended issues it might cause.
Loading history...
58
59
		$output_arr = array();
60
61
		// Get an array of file paths for the field.
62
		$file_paths = rgar( $field , 'multipleFiles' ) ? json_decode( $value ) : array( $value );
63
64
		// Process each file path
65
		foreach( $file_paths as $file_path ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
66
67
			// If the site is HTTPS, use HTTPS
68
			if(function_exists('set_url_scheme')) { $file_path = set_url_scheme($file_path); }
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
introduced by
No space after opening parenthesis is prohibited
Loading history...
Coding Style introduced by
Expected 1 spaces after opening bracket; 0 found
Loading history...
Coding Style introduced by
Expected 1 spaces before closing bracket; 0 found
Loading history...
introduced by
No space before closing parenthesis is prohibited
Loading history...
69
70
			// This is from Gravity Forms's code
71
			$file_path = esc_attr(str_replace(" ", "%20", $file_path));
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after opening bracket; 0 found
Loading history...
Coding Style introduced by
Expected 1 spaces before closing bracket; 0 found
Loading history...
Coding Style Comprehensibility introduced by
The string literal does not require double quotes, as per coding-style, please use single quotes.

PHP provides two ways to mark string literals. Either with single quotes 'literal' or with double quotes "literal". The difference between these is that string literals in double quotes may contain variables with are evaluated at run-time as well as escape sequences.

String literals in single quotes on the other hand are evaluated very literally and the only two characters that needs escaping in the literal are the single quote itself (\') and the backslash (\\). Every other character is displayed as is.

Double quoted string literals may contain other variables or more complex escape sequences.

<?php

$singleQuoted = 'Value';
$doubleQuoted = "\tSingle is $singleQuoted";

print $doubleQuoted;

will print an indented: Single is Value

If your string literal does not contain variables or escape sequences, it should be defined using single quotes to make that fact clear.

For more information on PHP string literals and available escape sequences see the PHP core documentation.

Loading history...
Coding Style Comprehensibility introduced by
The string literal %20 does not require double quotes, as per coding-style, please use single quotes.

PHP provides two ways to mark string literals. Either with single quotes 'literal' or with double quotes "literal". The difference between these is that string literals in double quotes may contain variables with are evaluated at run-time as well as escape sequences.

String literals in single quotes on the other hand are evaluated very literally and the only two characters that needs escaping in the literal are the single quote itself (\') and the backslash (\\). Every other character is displayed as is.

Double quoted string literals may contain other variables or more complex escape sequences.

<?php

$singleQuoted = 'Value';
$doubleQuoted = "\tSingle is $singleQuoted";

print $doubleQuoted;

will print an indented: Single is Value

If your string literal does not contain variables or escape sequences, it should be defined using single quotes to make that fact clear.

For more information on PHP string literals and available escape sequences see the PHP core documentation.

Loading history...
72
73
			// If the field is set to link to the single entry, link to it.
74
			$link = !empty( $field_settings['show_as_link'] ) ? GravityView_API::entry_link( $entry, $field ) : $file_path;
0 ignored issues
show
introduced by
Expected 1 space after "!"; 0 found
Loading history...
75
76
			// Get file path information
77
			$file_path_info = pathinfo($file_path);
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after opening bracket; 0 found
Loading history...
Coding Style introduced by
Expected 1 spaces before closing bracket; 0 found
Loading history...
78
79
			$html_format = NULL;
0 ignored issues
show
Coding Style introduced by
TRUE, FALSE and NULL must be lowercase; expected null, but found NULL.
Loading history...
80
81
			$disable_lightbox = false;
82
83
			$disable_wrapped_link = false;
84
85
			// Is this an image?
86
			$image = new GravityView_Image(array(
87
				'src' => $file_path,
88
				'class' => 'gv-image gv-field-id-'.$field_settings['id'],
89
				'alt' => $field_settings['label'],
90
				'width' => (gravityview_get_context() === 'single' ? NULL : 250)
0 ignored issues
show
Coding Style introduced by
TRUE, FALSE and NULL must be lowercase; expected null, but found NULL.
Loading history...
91
			));
92
93
			$content = $image->html();
94
95
			// The new default content is the image, if it exists. If not, use the file name as the content.
96
			$content = !empty( $content ) ? $content : $file_path_info['basename'];
0 ignored issues
show
introduced by
Expected 1 space after "!"; 0 found
Loading history...
97
98
			// If pathinfo() gave us the extension of the file, run the switch statement using that.
99
			$extension = empty( $file_path_info['extension'] ) ? NULL : strtolower( $file_path_info['extension'] );
0 ignored issues
show
Coding Style introduced by
TRUE, FALSE and NULL must be lowercase; expected null, but found NULL.
Loading history...
100
0 ignored issues
show
Coding Style introduced by
Functions must not contain multiple empty lines in a row; found 2 empty lines
Loading history...
101
102
			switch( true ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
103
104
				// Audio file
105
				case in_array( $extension, wp_get_audio_extensions() ):
106
107
					$disable_lightbox = true;
108
109
					if( shortcode_exists( 'audio' ) ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
110
111
						$disable_wrapped_link = true;
112
113
						/**
114
						 * @filter `gravityview_audio_settings` Modify the settings passed to the `wp_video_shortcode()` function
115
						 * @since  1.2
116
						 * @param array $audio_settings Array with `src` and `class` keys
117
						 */
118
						$audio_settings = apply_filters( 'gravityview_audio_settings', array(
119
							'src' => $file_path,
120
							'class' => 'wp-audio-shortcode gv-audio gv-field-id-'.$field_settings['id']
0 ignored issues
show
introduced by
Each line in an array declaration must end in a comma
Loading history...
121
						));
122
123
						/**
124
						 * Generate the audio shortcode
125
						 * @see http://codex.wordpress.org/Audio_Shortcode
126
						 * @see https://developer.wordpress.org/reference/functions/wp_audio_shortcode/
127
						 */
128
						$content = wp_audio_shortcode( $audio_settings );
129
130
					}
131
132
					break;
133
134
				// Video file
135
				case in_array( $extension, wp_get_video_extensions() ):
136
137
					$disable_lightbox = true;
138
139
					if( shortcode_exists( 'video' ) ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
140
141
						$disable_wrapped_link = true;
142
143
						/**
144
						 * @filter `gravityview_video_settings` Modify the settings passed to the `wp_video_shortcode()` function
145
						 * @since  1.2
146
						 * @param array $video_settings Array with `src` and `class` keys
147
						 */
148
						$video_settings = apply_filters( 'gravityview_video_settings', array(
149
							'src' => $file_path,
150
							'class' => 'wp-video-shortcode gv-video gv-field-id-'.$field_settings['id']
0 ignored issues
show
introduced by
Each line in an array declaration must end in a comma
Loading history...
151
						));
152
153
						/**
154
						 * Generate the video shortcode
155
						 * @see http://codex.wordpress.org/Video_Shortcode
156
						 * @see https://developer.wordpress.org/reference/functions/wp_video_shortcode/
157
						 */
158
						$content = wp_video_shortcode( $video_settings );
159
160
					}
161
162
					break;
163
164
				// PDF
165
				case $extension === 'pdf':
166
167
					// PDF needs to be displayed in an IFRAME
168
					$link = add_query_arg( array( 'TB_iframe' => 'true' ), $link );
169
170
					break;
171
172
				// if not image, do not set the lightbox (@since 1.5.3)
173
				case !in_array( $extension, array( 'jpg', 'jpeg', 'jpe', 'gif', 'png' ) ):
0 ignored issues
show
introduced by
Expected 1 space after "!"; 0 found
Loading history...
174
175
					$disable_lightbox = true;
176
177
					break;
178
179
			}
180
181
			// If using Link to File, override the content.
182
			// (We do this here so that the $disable_lightbox can be set. Yes, there's a little more processing time, but oh well.)
183
			if( !empty( $field_settings['link_to_file'] ) ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
introduced by
Expected 1 space after "!"; 0 found
Loading history...
184
185
				// Force the content to be the file name
186
				$content =  $file_path_info["basename"];
0 ignored issues
show
introduced by
Expected 1 space after "="; 2 found
Loading history...
Coding Style Comprehensibility introduced by
The string literal basename does not require double quotes, as per coding-style, please use single quotes.

PHP provides two ways to mark string literals. Either with single quotes 'literal' or with double quotes "literal". The difference between these is that string literals in double quotes may contain variables with are evaluated at run-time as well as escape sequences.

String literals in single quotes on the other hand are evaluated very literally and the only two characters that needs escaping in the literal are the single quote itself (\') and the backslash (\\). Every other character is displayed as is.

Double quoted string literals may contain other variables or more complex escape sequences.

<?php

$singleQuoted = 'Value';
$doubleQuoted = "\tSingle is $singleQuoted";

print $doubleQuoted;

will print an indented: Single is Value

If your string literal does not contain variables or escape sequences, it should be defined using single quotes to make that fact clear.

For more information on PHP string literals and available escape sequences see the PHP core documentation.

Loading history...
187
188
				// Restore the wrapped link
189
				$disable_wrapped_link = false;
190
191
			}
192
193
			// Whether to use lightbox or not
194
			if( $disable_lightbox || empty( $gravityview_view->atts['lightbox'] ) || !empty( $field_settings['show_as_link'] ) ) {
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...
introduced by
Space after opening control structure is required
Loading history...
introduced by
Expected 1 space after "!"; 0 found
Loading history...
195
196
				$link_atts = empty( $field_settings['show_as_link'] ) ? array( 'target' => '_blank' ) : array();
197
198
			} else {
199
200
				$link_atts = array(
201
					'rel' => sprintf( "%s-%s", $gv_class, $entry['id'] ),
0 ignored issues
show
Coding Style Comprehensibility introduced by
The string literal %s-%s does not require double quotes, as per coding-style, please use single quotes.

PHP provides two ways to mark string literals. Either with single quotes 'literal' or with double quotes "literal". The difference between these is that string literals in double quotes may contain variables with are evaluated at run-time as well as escape sequences.

String literals in single quotes on the other hand are evaluated very literally and the only two characters that needs escaping in the literal are the single quote itself (\') and the backslash (\\). Every other character is displayed as is.

Double quoted string literals may contain other variables or more complex escape sequences.

<?php

$singleQuoted = 'Value';
$doubleQuoted = "\tSingle is $singleQuoted";

print $doubleQuoted;

will print an indented: Single is Value

If your string literal does not contain variables or escape sequences, it should be defined using single quotes to make that fact clear.

For more information on PHP string literals and available escape sequences see the PHP core documentation.

Loading history...
202
					'target' => '_blank',
203
					'class' => 'thickbox',
204
				);
205
206
			}
207
208
			/**
209
			 * @filter `gravityview/fields/fileupload/link_atts` Modify the link attributes for a file upload field
210
			 * @param array|string $link_atts Array or attributes string
211
			 * @param array $field Current GravityView field array
212
			 */
213
			$link_atts = apply_filters( 'gravityview/fields/fileupload/link_atts', $link_atts, $gravityview_view->getCurrentField() );
214
215
			/**
216
			 * @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
217
			 * @since 1.5.1
218
			 * @param bool $disable_wrapped_link whether to wrap the content with a link to the content object.
219
			 * @param array $gravityview_view->field_data
220
			 * @see GravityView_API:field_value() for info about $gravityview_view->field_data
221
			 */
222
			$disable_wrapped_link = apply_filters( 'gravityview/fields/fileupload/disable_link', $disable_wrapped_link, $gravityview_view->getCurrentField() );
223
224
			// If the HTML output hasn't been overridden by the switch statement above, use the default format
225
			if( !empty( $content ) && empty( $disable_wrapped_link ) ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
introduced by
Expected 1 space after "!"; 0 found
Loading history...
226
227
				/**
228
				 * Modify the link text (defaults to the file name)
229
				 *
230
				 * @since 1.7
231
				 *
232
				 * @param string $content The existing anchor content. Could be `<img>` tag, audio/video embed or the file name
233
				 * @param array $field GravityView array of the current field being processed
234
				 */
235
				$content = apply_filters( 'gravityview/fields/fileupload/link_content', $content, $gravityview_view->getCurrentField() );
236
237
                $content = gravityview_get_link( $link, $content, $link_atts );
238
			}
239
240
			$output_arr[] = array(
241
				'file_path' => $file_path,
242
				'content' => $content
0 ignored issues
show
introduced by
Each line in an array declaration must end in a comma
Loading history...
243
			);
244
245
		} // End foreach loop
246
247
		/**
248
		 * @filter `gravityview/fields/fileupload/files_array` Modify the files array
249
		 * @since 1.7
250
		 * @param array $output_arr Associative array of files \n
251
		 *  @type string $file_path The path to the file as stored in Gravity Forms \n
252
		 *  @type string $content The generated output for the file \n
253
		 * @param array $field GravityView array of the current field being processed
254
		 */
255
		$output_arr = apply_filters( 'gravityview/fields/fileupload/files_array', $output_arr, $gravityview_view->getCurrentField() );
256
257
		return $output_arr;
258
	}
259
260
}
261
262
new GravityView_Field_FileUpload;
263