Completed
Pull Request — 2.x (#3910)
by Scott Kingsley
12:36 queued 08:00
created

PodsField_File::do_wp_gallery()   C

Complexity

Conditions 11
Paths 96

Size

Total Lines 40
Code Lines 28

Duplication

Lines 7
Ratio 17.5 %

Importance

Changes 0
Metric Value
cc 11
eloc 28
nc 96
nop 2
dl 7
loc 40
rs 5.2653
c 0
b 0
f 0

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * @package Pods\Fields
4
 */
5
class PodsField_File extends PodsField {
6
7
    /**
8
     * Field Type Group
9
     *
10
     * @var string
11
     * @since 2.0
12
     */
13
    public static $group = 'Relationships / Media';
14
15
    /**
16
     * Field Type Identifier
17
     *
18
     * @var string
19
     * @since 2.0
20
     */
21
    public static $type = 'file';
22
23
    /**
24
     * Field Type Label
25
     *
26
     * @var string
27
     * @since 2.0
28
     */
29
    public static $label = 'File / Image / Video';
30
31
    /**
32
     * API caching for fields that need it during validate/save
33
     *
34
     * @var \PodsAPI
35
     * @since 2.3
36
     */
37
    protected static $api = false;
38
39
    /**
40
     * Do things like register/enqueue scripts and stylesheets
41
     *
42
     * @since 2.0
43
     */
44
    public function __construct () {
45
        self::$label = __( 'File / Image / Video', 'pods' );
46
    }
47
48
    /**
49
     * Add admin_init actions
50
     *
51
     * @since 2.3
52
     */
53
    public function admin_init() {
54
        // AJAX for Uploads
55
        add_action( 'wp_ajax_pods_upload', array( $this, 'admin_ajax_upload' ) );
56
        add_action( 'wp_ajax_nopriv_pods_upload', array( $this, 'admin_ajax_upload' ) );
57
    }
58
59
    /**
60
     * Add options and set defaults to
61
     *
62
     * @param array $options
0 ignored issues
show
Bug introduced by
There is no parameter named $options. 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...
63
     *
64
     * @since 2.0
65
     */
66
    public function options () {
67
        $sizes = get_intermediate_image_sizes();
68
69
        $image_sizes = array();
70
71
        foreach ( $sizes as $size ) {
72
            $image_sizes[ $size ] = ucwords( str_replace( '-', ' ', $size ) );
73
        }
74
75
        $options = array(
76
            self::$type . '_format_type' => array(
77
                'label' => __( 'Upload Limit', 'pods' ),
78
                'default' => 'single',
79
                'type' => 'pick',
80
                'data' => array(
81
                    'single' => __( 'Single File', 'pods' ),
82
                    'multi' => __( 'Multiple Files', 'pods' )
83
                ),
84
                'dependency' => true
85
            ),
86
            self::$type . '_uploader' => array(
87
                'label' => __( 'File Uploader', 'pods' ),
88
                'default' => 'attachment',
89
                'type' => 'pick',
90
                'data' => apply_filters(
91
                    'pods_form_ui_field_file_uploader_options',
92
                    array(
93
                        'attachment' => __( 'Attachments (WP Media Library)', 'pods' ),
94
                        'plupload' => __( 'Plupload', 'pods' )
95
                    )
96
                ),
97
                'dependency' => true
98
            ),
99
            self::$type . '_attachment_tab' => array(
100
                'label' => __( 'Attachments Default Tab', 'pods' ),
101
                'depends-on' => array( self::$type . '_uploader' => 'attachment' ),
102
                'default' => 'upload',
103
                'type' => 'pick',
104
                'data' => array(
105
                    // keys MUST match WP's router names
106
                    'upload' => __( 'Upload File', 'pods' ),
107
                    'browse' => __( 'Media Library', 'pods' )
108
                )
109
            ),
110
            self::$type . '_edit_title' => array(
111
                'label' => __( 'Editable Title', 'pods' ),
112
                'default' => 1,
113
                'type' => 'boolean'
114
            ),
115
            self::$type . '_linked' => array(
116
                'label' => __( 'Link to File in editor', 'pods' ),
117
                'default' => 0,
118
                'type' => 'boolean'
119
            ),
120
            self::$type . '_limit' => array(
121
                'label' => __( 'Max Number of Files', 'pods' ),
122
                'depends-on' => array( self::$type . '_format_type' => 'multi' ),
123
                'default' => 0,
124
                'type' => 'number'
125
            ),
126
            self::$type . '_restrict_filesize' => array(
127
                'label' => __( 'Restrict File Size', 'pods' ),
128
                'depends-on' => array( self::$type . '_uploader' => 'plupload' ),
129
                'default' => '10MB',
130
                'type' => 'text'
131
            ),
132
            self::$type . '_type' => array(
133
                'label' => __( 'Restrict File Types', 'pods' ),
134
                'default' => apply_filters( 'pods_form_ui_field_file_type_default', 'images' ),
135
                'type' => 'pick',
136
                'data' => apply_filters(
137
                    'pods_form_ui_field_file_type_options',
138
                    array(
139
                        'images' => __( 'Images (jpg, jpeg, png, gif)', 'pods' ),
140
                        'video' => __( 'Video (mpg, mov, flv, mp4, etc..)', 'pods' ),
141
                        'audio' => __( 'Audio (mp3, m4a, wav, wma, etc..)', 'pods' ),
142
                        'text' => __( 'Text (txt, csv, tsv, rtx, etc..)', 'pods' ),
143
                        'any' => __( 'Any Type (no restriction)', 'pods' ),
144
                        'other' => __( 'Other (customize allowed extensions)', 'pods' )
145
                    )
146
                ),
147
                'dependency' => true
148
            ),
149
            self::$type . '_allowed_extensions' => array(
150
                'label' => __( 'Allowed File Extensions', 'pods' ),
151
                'description' => __( 'Separate file extensions with a comma (ex. jpg,png,mp4,mov)', 'pods' ),
152
                'depends-on' => array( self::$type . '_type' => 'other' ),
153
                'default' => apply_filters( 'pods_form_ui_field_file_extensions_default', '' ),
154
                'type' => 'text'
155
            ),/*
0 ignored issues
show
Unused Code Comprehensibility introduced by
53% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
156
            self::$type . '_field_template' => array(
157
                'label' => __( 'Field template', 'pods' ),
158
                'default' => apply_filters( 'pods_form_ui_field_file_template_default', 'rows' ),
159
                'depends-on' => array( self::$type . '_type' => 'images' ),
160
                'type' => 'pick',
161
                'data' => apply_filters(
162
                    'pods_form_ui_field_file_type_templates',
163
                    array(
164
                        'rows' => __( 'Rows', 'pods' ),
165
                        'tiles' => __( 'Tiles', 'pods' ),
166
                    )
167
                ),
168
                'dependency' => true
169
            ),
170
            self::$type . '_image_size' => array(
171
                'label' => __( 'Excluded Image Sizes', 'pods' ),
172
                'description' => __( 'Image sizes not to generate when processing the image', 'pods' ),
173
                'depends-on' => array( self::$type . '_type' => 'images' ),
174
                'default' => 'images',
175
                'type' => 'pick',
176
                'pick_format_type' => 'multi',
177
                'pick_format_multi' => 'checkbox',
178
                'data' => apply_filters(
179
                    'pods_form_ui_field_file_image_size_options',
180
                    $image_sizes
181
                )
182
            ),*/
183
            self::$type . '_add_button' => array(
184
                'label' => __( 'Add Button Text', 'pods' ),
185
                'default' => __( 'Add File', 'pods' ),
186
                'type' => 'text'
187
            ),
188
            self::$type . '_modal_title' => array(
189
                'label' => __( 'Modal Title', 'pods' ),
190
                'depends-on' => array( self::$type . '_uploader' => 'attachment' ),
191
                'default' => __( 'Attach a file', 'pods' ),
192
                'type' => 'text'
193
            ),
194
            self::$type . '_modal_add_button' => array(
195
                'label' => __( 'Modal Add Button Text', 'pods' ),
196
                'depends-on' => array( self::$type . '_uploader' => 'attachment' ),
197
                'default' => __( 'Add File', 'pods' ),
198
                'type' => 'text'
199
            ),
200
201
            /* WP GALLERY OUTPUT */
202
            self::$type . '_wp_gallery_output' => array(
203
	            'label' => __( 'Output as a WP Gallery', 'pods' ),
204
	            'help' => sprintf(
205
	            	__( '<a href="%s" target="_blank">Click here for more info</a>', 'pods' ),
206
					'https://codex.wordpress.org/The_WordPress_Gallery'
207
				),
208
	            'depends-on' => array( self::$type . '_type' => 'images' ),
209
	            'dependency' => true,
210
	            'type' => 'boolean'
211
            ),
212
            self::$type . '_wp_gallery_link' => array(
213
	            'label' => __( 'Gallery image links', 'pods' ),
214
	            'depends-on' => array( self::$type . '_wp_gallery_output' => 1 ),
215
	            'type' => 'pick',
216
	            'data' => array(
217
		            'post' => __( 'Attachment Page', 'pods' ),
218
		            'file' => __( 'Media File', 'pods' ),
219
		            'none' => __( 'None', 'pods' )
220
	            )
221
            ),
222
            self::$type . '_wp_gallery_columns' => array(
223
	            'label' => __( 'Gallery image columns', 'pods' ),
224
	            'depends-on' => array( self::$type . '_wp_gallery_output' => 1 ),
225
	            'type' => 'pick',
226
	            'data' => array(
227
		            '1' => 1,
228
			    '2' => 2,
229
			    '3' => 3,
230
			    '4' => 4,
231
			    '5' => 5,
232
			    '6' => 6,
233
			    '7' => 7,
234
			    '8' => 8,
235
			    '9' => 9,
236
	            )
237
            ),
238
            self::$type . '_wp_gallery_random_sort' => array(
239
	            'label' => __( 'Gallery randomized order', 'pods' ),
240
	            'depends-on' => array( self::$type . '_wp_gallery_output' => 1 ),
241
	            'type' => 'boolean'
242
            ),
243
            self::$type . '_wp_gallery_size' => array(
244
	            'label' => __( 'Gallery image size', 'pods' ),
245
	            'depends-on' => array( self::$type . '_wp_gallery_output' => 1 ),
246
	            'type' => 'pick',
247
	            'data' => $this->data_image_sizes(),
248
            )
249
        );
250
251 View Code Duplication
        if ( !pods_version_check( 'wp', '3.5' ) ) {
252
            unset( $options[ self::$type . '_linked' ] );
253
            unset( $options[ self::$type . '_modal_title' ] );
254
            unset( $options[ self::$type . '_modal_add_button' ] );
255
256
            $options[ self::$type . '_attachment_tab' ][ 'default' ] = 'type';
257
            $options[ self::$type . '_attachment_tab' ][ 'data' ] = array(
258
                'type' => __( 'Upload File', 'pods' ),
259
                'library' => __( 'Media Library', 'pods' )
260
            );
261
        }
262
263
        return $options;
264
    }
265
266
    /**
267
     * Define the current field's schema for DB table storage
268
     *
269
     * @param array $options
270
     *
271
     * @return array
272
     * @since 2.0
273
     */
274
    public function schema ( $options = null ) {
275
        $schema = false;
276
277
        return $schema;
278
    }
279
280
    /**
281
     * Change the way the value of the field is displayed with Pods::get
282
     *
283
     * @param mixed $value
284
     * @param string $name
285
     * @param array $options
286
     * @param array $pod
287
     * @param int $id
288
     *
289
     * @return mixed|null
290
     * @since 2.0
291
     */
292
    public function display ( $value = null, $name = null, $options = null, $pod = null, $id = null ) {
293
    	if ( 1 == $options[ self::$type . '_wp_gallery_output' ] ) {
294
    		return $this->do_wp_gallery( $value, $options );
295
		}
296
297
        if ( is_array( $value ) && !empty( $value ) ) {
298
            if ( isset( $value[ 'ID' ] ) )
299
                $value = wp_get_attachment_url( $value[ 'ID' ] );
300
            else {
301
                $attachments = $value;
302
                $value = array();
303
304 View Code Duplication
                foreach ( $attachments as $v ) {
305
                    if ( !is_array( $v ) )
306
                        $value[] = $v;
307
                    elseif ( isset( $v[ 'ID' ] ) )
308
                        $value[] = wp_get_attachment_url( $v[ 'ID' ] );
309
                }
310
311
                $value = implode( ' ', $value );
312
            }
313
        }
314
315
        return $value;
316
    }
317
318
    /**
319
     * Customize output of the form field
320
     *
321
     * @param string $name
322
     * @param mixed $value
323
     * @param array $options
324
     * @param array $pod
325
     * @param int $id
326
     *
327
     * @since 2.0
328
     */
329
    public function input ( $name, $value = null, $options = null, $pod = null, $id = null ) {
330
        $options = (array) $options;
331
        $form_field_type = PodsForm::$field_type;
0 ignored issues
show
Bug introduced by
The property field_type cannot be accessed from this context as it is declared private in class PodsForm.

This check looks for access to properties that are not accessible from the current context.

If you need to make a property accessible to another context you can either raise its visibility level or provide an accessible getter in the defining class.

Loading history...
332
333 View Code Duplication
        if ( !is_admin() ) {
334
            include_once( ABSPATH . '/wp-admin/includes/template.php' );
335
336
            if ( is_multisite() )
337
                include_once( ABSPATH . '/wp-admin/includes/ms.php' );
338
        }
339
340 View Code Duplication
        if ( ( ( defined( 'PODS_DISABLE_FILE_UPLOAD' ) && true === PODS_DISABLE_FILE_UPLOAD )
341
               || ( defined( 'PODS_UPLOAD_REQUIRE_LOGIN' ) && is_bool( PODS_UPLOAD_REQUIRE_LOGIN ) && true === PODS_UPLOAD_REQUIRE_LOGIN && !is_user_logged_in() )
342
               || ( defined( 'PODS_UPLOAD_REQUIRE_LOGIN' ) && !is_bool( PODS_UPLOAD_REQUIRE_LOGIN ) && ( !is_user_logged_in() || !current_user_can( PODS_UPLOAD_REQUIRE_LOGIN ) ) ) )
343
             && ( ( defined( 'PODS_DISABLE_FILE_BROWSER' ) && true === PODS_DISABLE_FILE_BROWSER )
344
                  || ( defined( 'PODS_FILES_REQUIRE_LOGIN' ) && is_bool( PODS_FILES_REQUIRE_LOGIN ) && true === PODS_FILES_REQUIRE_LOGIN && !is_user_logged_in() )
345
                  || ( defined( 'PODS_FILES_REQUIRE_LOGIN' ) && !is_bool( PODS_FILES_REQUIRE_LOGIN ) && ( !is_user_logged_in() || !current_user_can( PODS_FILES_REQUIRE_LOGIN ) ) ) )
346
        ) {
347
            ?>
348
        <p>You do not have access to upload / browse files. Contact your website admin to resolve.</p>
349
        <?php
350
            return;
351
        }
352
353
        // Use plupload if attachment isn't available
354
        if ( 'attachment' == pods_var( self::$type . '_uploader', $options ) && ( !is_user_logged_in() || ( !current_user_can( 'upload_files' ) && !current_user_can( 'edit_files' ) ) ) )
355
            $field_type = 'plupload';
356
        elseif ( 'plupload' == pods_var( self::$type . '_uploader', $options ) )
357
            $field_type = 'plupload';
358 View Code Duplication
        elseif ( 'attachment' == pods_var( self::$type . '_uploader', $options ) ) {
359
            if ( !pods_version_check( 'wp', '3.5' ) || !is_admin() ) // @todo test frontend media modal
360
                $field_type = 'attachment';
361
            else
362
                $field_type = 'media';
363
        }
364 View Code Duplication
        else {
365
            // Support custom File Uploader integration
366
            do_action( 'pods_form_ui_field_file_uploader_' . pods_var( self::$type . '_uploader', $options ), $name, $value, $options, $pod, $id );
367
            do_action( 'pods_form_ui_field_file_uploader', pods_var( self::$type . '_uploader', $options ), $name, $value, $options, $pod, $id );
368
            return;
369
        }
370
371
        pods_view( PODS_DIR . 'ui/fields/' . $field_type . '.php', compact( array_keys( get_defined_vars() ) ) );
372
    }
373
374
    /**
375
     * Build regex necessary for JS validation
376
     *
377
     * @param mixed $value
378
     * @param string $name
379
     * @param array $options
380
     * @param string $pod
381
     * @param int $id
382
     *
383
     * @return bool
384
     * @since 2.0
385
     */
386
    public function regex ( $value = null, $name = null, $options = null, $pod = null, $id = null ) {
387
        return false;
388
    }
389
390
    /**
391
     * Validate a value before it's saved
392
     *
393
     * @param mixed $value
394
     * @param string $name
395
     * @param array $options
396
     * @param array $fields
397
     * @param array $pod
398
     * @param int $id
399
     * @param null $params
400
     *
401
     * @return bool
402
     * @since 2.0
403
     */
404
    public function validate ( $value, $name = null, $options = null, $fields = null, $pod = null, $id = null, $params = null ) {
405
        // check file size
406
        // check file extensions
407
        return true;
408
    }
409
410
    /**
411
     * Change the value or perform actions after validation but before saving to the DB
412
     *
413
     * @param mixed $value
414
     * @param int $id
415
     * @param string $name
416
     * @param array $options
417
     * @param array $fields
418
     * @param array $pod
419
     * @param object $params
420
     *
421
     * @return mixed
422
     * @since 2.0
423
     */
424
    public function pre_save ( $value, $id = null, $name = null, $options = null, $fields = null, $pod = null, $params = null ) {
425
        return $value;
426
    }
427
428
    /**
429
     * Save the value to the DB
430
     *
431
     * @param mixed $value
432
     * @param int $id
433
     * @param string $name
434
     * @param array $options
435
     * @param array $fields
436
     * @param array $pod
437
     * @param object $params
438
     *
439
     * @since 2.3
440
     */
441
    public function save ( $value, $id = null, $name = null, $options = null, $fields = null, $pod = null, $params = null ) {
442
        if ( empty( self::$api ) )
443
            self::$api = pods_api();
444
445
        // File title / field handling
446
        foreach ( $value as $id ) {
447
            $title = false;
448
449
            if ( is_array( $id ) ) {
450 View Code Duplication
                if ( isset( $id[ 'title' ] ) && 0 < strlen( trim( $id[ 'title' ] ) ) )
451
                    $title = trim( $id[ 'title' ] );
452
453
                if ( isset( $id[ 'id' ] ) )
454
                    $id = (int) $id[ 'id' ];
455
                else
456
                    $id = 0;
457
            }
458
459
            if ( empty( $id ) )
460
                continue;
461
462
            $attachment_data = array();
463
464
            // Update the title if set
465
            if ( false !== $title && 1 == pods_var( self::$type . '_edit_title', $options, 0 ) ) {
466
                $attachment_data['post_title'] = $title;
467
            }
468
469
            // Update attachment parent if it's not set yet and we're updating a post
470
            if ( ! empty( $params->id ) && ! empty( $pod['type'] ) && 'post_type' == $pod['type'] ) {
471
                $attachment = get_post( $id );
472
                if ( isset( $attachment->post_parent ) && 0 === (int) $attachment->post_parent ) {
473
                    $attachment_data['post_parent'] = (int) $params->id;
474
                }
475
            }
476
477
            // Update the attachment if it the data array is not still empty
478
            if ( ! empty( $attachment_data ) ) {
479
                $attachment_data['ID'] = $id;
480
                self::$api->save_wp_object( 'media', $attachment_data );
481
            }
482
        }
483
    }
484
485
    /**
486
     * Customize the Pods UI manage table column output
487
     *
488
     * @param int $id
489
     * @param mixed $value
490
     * @param string $name
491
     * @param array $options
492
     * @param array $fields
493
     * @param array $pod
494
     *
495
     * @return mixed|void
496
     * @since 2.0
497
     */
498
    public function ui ( $id, $value, $name = null, $options = null, $fields = null, $pod = null ) {
499
        if ( empty( $value ) )
500
            return;
501
502
        if ( !empty( $value ) && isset( $value[ 'ID' ] ) )
503
            $value = array( $value );
504
505
        $image_size = apply_filters( 'pods_form_ui_field_file_ui_image_size', 'thumbnail', $id, $value, $name, $options, $pod );
506
507
        return $this->images( $id, $value, $name, $options, $pod, $image_size );
508
    }
509
510
    /**
511
     * Return image(s) markup
512
     *
513
     * @param int $id
514
     * @param mixed $value
515
     * @param string $name
516
     * @param array $options
517
     * @param array $pod
518
     * @param string $image_size
519
     *
520
     * @return string
521
     * @since 2.3
522
     */
523
    public function images ( $id, $value, $name = null, $options = null, $pod = null, $image_size = null ) {
0 ignored issues
show
Unused Code introduced by
The parameter $id is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $name is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $options is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $pod is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
524
        $images = '';
525
526
        if ( empty( $value ) || !is_array( $value ) )
527
            return $images;
528
529
        foreach ( $value as $v ) {
530
            $images .= pods_image( $v, $image_size );
531
        }
532
533
        return $images;
534
    }
535
536
	/**
537
	 * Data callback for Image Sizes
538
	 *
539
	 * @param string $name The name of the field
540
	 * @param string|array $value The value of the field
541
	 * @param array $options Field options
542
	 * @param array $pod Pod data
543
	 * @param int $id Item ID
544
	 *
545
	 * @return array
546
	 *
547
	 * @since 2.3
548
	 */
549 View Code Duplication
	public function data_image_sizes ( $name = null, $value = null, $options = null, $pod = null, $id = null ) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
550
		$data = array();
551
552
		$image_sizes = get_intermediate_image_sizes();
553
554
		foreach ( $image_sizes as $image_size ) {
555
			$data[ $image_size ] = ucwords( str_replace( '-', ' ', $image_size ) );
556
		}
557
558
		return apply_filters( 'pods_form_ui_field_pick_' . __FUNCTION__, $data, $name, $value, $options, $pod, $id );
559
	}
560
561
	/**
562
	 * Create a WP Gallery from the passed values (need to be attachments)
563
	 *
564
	 * @since  2.7
565
	 * @param  string|array  $value    The value(s)
566
	 * @param  array         $options  The field options
567
	 * @return string
568
	 */
569
	public function do_wp_gallery( $value, $options ) {
570
		$args = array();
571
		if ( ! empty( $options[ self::$type . '_wp_gallery_columns' ] ) ) {
572
			$args['columns'] = $options[ self::$type . '_wp_gallery_columns' ];
573
		}
574
		if ( ! empty( $options[ self::$type . '_wp_gallery_random_sort' ] ) ) {
575
			$args['orderby'] = 'rand';
576
		}
577
		if ( ! empty( $options[ self::$type . '_wp_gallery_link' ] ) ) {
578
			$args['link'] = $options[ self::$type . '_wp_gallery_link' ];
579
		}
580
		if ( ! empty( $options[ self::$type . '_wp_gallery_size' ] ) ) {
581
			$args['size'] = $options[ self::$type . '_wp_gallery_size' ];
582
		}
583
584
		if ( isset( $value[ 'ID' ] ) ) {
585
			$args['ids'] = $value[ 'ID' ];
586
		} else {
587
			$images = array();
588 View Code Duplication
			foreach ( $value as $v ) {
0 ignored issues
show
Bug introduced by
The expression $value of type string|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
589
				if ( ! is_array( $v ) ) {
590
					$images[] = (int) $v;
591
				} elseif ( isset( $v[ 'ID' ] ) ) {
592
					$images[] = (int) $v[ 'ID' ];
593
				}
594
			}
595
			$args['ids'] = implode( ',', $images );
596
		}
597
598
		if ( is_callable( 'gallery_shortcode' ) ) {
599
			return gallery_shortcode( $args );
600
		} else {
601
			$shortcode = '[gallery';
602
			foreach ( $args as $key => $value ) {
603
				$shortcode .= ' ' . $key . '="' . $value . '"';
604
			}
605
			$shortcode .= ']';
606
			return do_shortcode( $shortcode );
607
		}
608
	}
609
610
    /**
611
     * Handle file row output for uploaders
612
     *
613
     * @param array $attributes
614
     * @param int $limit
615
     * @param bool $editable
616
     * @param int $id
617
     * @param string $icon
618
     * @param string $name
619
     *
620
     * @return string
621
     * @since 2.0
622
     */
623
    public function markup ( $attributes, $limit = 1, $editable = true, $id = null, $icon = null, $name = null, $linked = false, $link = null ) {
624
        // Preserve current file type
625
        $field_type = PodsForm::$field_type;
0 ignored issues
show
Bug introduced by
The property field_type cannot be accessed from this context as it is declared private in class PodsForm.

This check looks for access to properties that are not accessible from the current context.

If you need to make a property accessible to another context you can either raise its visibility level or provide an accessible getter in the defining class.

Loading history...
626
627
        ob_start();
628
629
        if ( empty( $id ) )
630
            $id = '{{id}}';
631
632
        if ( empty( $icon ) ) {
633
	        $icon = '{{icon}}';
634
        }else{
635
	        $icon = esc_url( $icon );
636
        }
637
638
639
        if ( empty( $name ) )
640
            $name = '{{name}}';
641
642
        if ( empty( $link ) )
643
            $link = '{{link}}';
644
645
        $editable = (boolean) $editable;
646
        $linked = (boolean) $linked;
647
        ?>
648
    <li class="pods-file hidden" id="pods-file-<?php echo esc_attr( $id ); ?>">
649
        <?php echo PodsForm::field( $attributes[ 'name' ] . '[' . $id . '][id]', $id, 'hidden' ); ?>
650
651
        <ul class="pods-file-meta media-item">
652
            <?php if ( 1 != $limit ) { ?>
653
                <li class="pods-file-col pods-file-handle">Handle</li>
654
            <?php } ?>
655
656
            <li class="pods-file-col pods-file-icon">
657
                <img class="pinkynail" src="<?php echo $icon; ?>" alt="Icon" />
658
            </li>
659
660
            <li class="pods-file-col pods-file-name">
661
                <?php
662
                if ( $editable )
663
                    echo PodsForm::field( $attributes[ 'name' ] . '[' . $id . '][title]', $name, 'text' );
664
                else
665
                    echo ( empty( $name ) ? '{{name}}' : $name );
666
                ?>
667
            </li>
668
669
            <li class="pods-file-col pods-file-delete"><a href="#delete">Delete</a></li>
670
671
			<?php
672
				if ( $linked ) {
673
			?>
674
            	<li class="pods-file-col pods-file-download"><a href="<?php echo esc_url( $link ); ?>" target="_blank">Download</a></li>
675
			<?php
676
				}
677
			?>
678
        </ul>
679
    </li>
680
    <?php
681
        PodsForm::$field_type = $field_type;
0 ignored issues
show
Bug introduced by
The property field_type cannot be accessed from this context as it is declared private in class PodsForm.

This check looks for access to properties that are not accessible from the current context.

If you need to make a property accessible to another context you can either raise its visibility level or provide an accessible getter in the defining class.

Loading history...
682
683
        return ob_get_clean();
684
    }
685
686
    /**
687
     * Handle plupload AJAX
688
     *
689
     * @since 2.3
690
     */
691
    public function admin_ajax_upload () {
692
		pods_session_start();
693
694
        // Sanitize input
695
        $params = pods_unslash( (array) $_POST );
696
697 View Code Duplication
        foreach ( $params as $key => $value ) {
698
            if ( 'action' == $key )
699
                continue;
700
701
            unset( $params[ $key ] );
702
703
            $params[ str_replace( '_podsfix_', '', $key ) ] = $value;
704
        }
705
706
        $params = (object) $params;
707
708
        $methods = array(
709
            'upload',
710
        );
711
712
        if ( !isset( $params->method ) || !in_array( $params->method, $methods ) || !isset( $params->pod ) || !isset( $params->field ) || !isset( $params->uri ) || empty( $params->uri ) )
713
            pods_error( 'Invalid AJAX request', PodsInit::$admin );
0 ignored issues
show
Bug introduced by
The property admin cannot be accessed from this context as it is declared private in class PodsInit.

This check looks for access to properties that are not accessible from the current context.

If you need to make a property accessible to another context you can either raise its visibility level or provide an accessible getter in the defining class.

Loading history...
714
        elseif ( !empty( $params->pod ) && empty( $params->field ) )
715
            pods_error( 'Invalid AJAX request', PodsInit::$admin );
0 ignored issues
show
Bug introduced by
The property admin cannot be accessed from this context as it is declared private in class PodsInit.

This check looks for access to properties that are not accessible from the current context.

If you need to make a property accessible to another context you can either raise its visibility level or provide an accessible getter in the defining class.

Loading history...
716
        elseif ( empty( $params->pod ) && !current_user_can( 'upload_files' ) )
717
            pods_error( 'Invalid AJAX request', PodsInit::$admin );
0 ignored issues
show
Bug introduced by
The property admin cannot be accessed from this context as it is declared private in class PodsInit.

This check looks for access to properties that are not accessible from the current context.

If you need to make a property accessible to another context you can either raise its visibility level or provide an accessible getter in the defining class.

Loading history...
718
719
        // Flash often fails to send cookies with the POST or upload, so we need to pass it in GET or POST instead
720
        if ( is_ssl() && empty( $_COOKIE[ SECURE_AUTH_COOKIE ] ) && !empty( $_REQUEST[ 'auth_cookie' ] ) )
721
            $_COOKIE[ SECURE_AUTH_COOKIE ] = $_REQUEST[ 'auth_cookie' ];
722
        elseif ( empty( $_COOKIE[ AUTH_COOKIE ] ) && !empty( $_REQUEST[ 'auth_cookie' ] ) )
723
            $_COOKIE[ AUTH_COOKIE ] = $_REQUEST[ 'auth_cookie' ];
724
725
        if ( empty( $_COOKIE[ LOGGED_IN_COOKIE ] ) && !empty( $_REQUEST[ 'logged_in_cookie' ] ) )
726
            $_COOKIE[ LOGGED_IN_COOKIE ] = $_REQUEST[ 'logged_in_cookie' ];
727
728
        global $current_user;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
729
        unset( $current_user );
730
731
        /**
732
         * Access Checking
733
         */
734
        $upload_disabled = false;
735
736
        if ( defined( 'PODS_DISABLE_FILE_UPLOAD' ) && true === PODS_DISABLE_FILE_UPLOAD )
737
            $upload_disabled = true;
738 View Code Duplication
        elseif ( defined( 'PODS_UPLOAD_REQUIRE_LOGIN' ) && is_bool( PODS_UPLOAD_REQUIRE_LOGIN ) && true === PODS_UPLOAD_REQUIRE_LOGIN && !is_user_logged_in() )
739
            $upload_disabled = true;
740 View Code Duplication
        elseif ( defined( 'PODS_UPLOAD_REQUIRE_LOGIN' ) && !is_bool( PODS_UPLOAD_REQUIRE_LOGIN ) && ( !is_user_logged_in() || !current_user_can( PODS_UPLOAD_REQUIRE_LOGIN ) ) )
741
            $upload_disabled = true;
742
743
        $uid = @session_id();
744
745
        if ( is_user_logged_in() )
746
            $uid = 'user_' . get_current_user_id();
747
748
        $nonce_check = 'pods_upload_' . (int) $params->pod . '_' . $uid . '_' . $params->uri . '_' . (int) $params->field;
749
750 View Code Duplication
        if ( true === $upload_disabled || !isset( $params->_wpnonce ) || false === wp_verify_nonce( $params->_wpnonce, $nonce_check ) )
751
            pods_error( __( 'Unauthorized request', 'pods' ), PodsInit::$admin );
0 ignored issues
show
Bug introduced by
The property admin cannot be accessed from this context as it is declared private in class PodsInit.

This check looks for access to properties that are not accessible from the current context.

If you need to make a property accessible to another context you can either raise its visibility level or provide an accessible getter in the defining class.

Loading history...
752
753
        $pod = array();
754
        $field = array(
755
            'type' => 'file',
756
            'options' => array()
757
        );
758
759
        $api = pods_api();
760
761
	    $api->display_errors = false;
762
763
        if ( !empty( $params->pod ) ) {
764
            $pod = $api->load_pod( array( 'id' => (int) $params->pod ) );
765
            $field = $api->load_field( array( 'id' => (int) $params->field ) );
766
767 View Code Duplication
            if ( empty( $pod ) || empty( $field ) || $pod[ 'id' ] != $field[ 'pod_id' ] || !isset( $pod[ 'fields' ][ $field[ 'name' ] ] ) )
768
                pods_error( __( 'Invalid field request', 'pods' ), PodsInit::$admin );
0 ignored issues
show
Bug introduced by
The property admin cannot be accessed from this context as it is declared private in class PodsInit.

This check looks for access to properties that are not accessible from the current context.

If you need to make a property accessible to another context you can either raise its visibility level or provide an accessible getter in the defining class.

Loading history...
769
770
            if ( !in_array( $field[ 'type' ], PodsForm::file_field_types() ) )
771
                pods_error( __( 'Invalid field', 'pods' ), PodsInit::$admin );
0 ignored issues
show
Bug introduced by
The property admin cannot be accessed from this context as it is declared private in class PodsInit.

This check looks for access to properties that are not accessible from the current context.

If you need to make a property accessible to another context you can either raise its visibility level or provide an accessible getter in the defining class.

Loading history...
772
        }
773
774
        $method = $params->method;
775
776
        // Cleaning up $params
777
        unset( $params->action );
778
        unset( $params->method );
779
        unset( $params->_wpnonce );
780
781
        $params->post_id = pods_var( 'post_id', $params, 0, null, true );
782
783
        /**
784
         * Upload a new file (advanced - returns URL and ID)
785
         */
786
        if ( 'upload' == $method ) {
787
            $file = $_FILES[ 'Filedata' ];
788
789
            $limit_size = pods_var( $field[ 'type' ] . '_restrict_filesize', $field[ 'options' ] );
790
791
            if ( !empty( $limit_size ) ) {
792
                if ( false !== stripos( $limit_size, 'MB' ) ) {
793
                    $limit_size = (float) trim( str_ireplace( 'MB', '', $limit_size ) );
794
                    $limit_size = $limit_size * 1025 * 1025; // convert to KB to B
795
                }
796 View Code Duplication
                elseif ( false !== stripos( $limit_size, 'KB' ) ) {
797
                    $limit_size = (float) trim( str_ireplace( 'KB', '', $limit_size ) );
798
                    $limit_size = $limit_size * 1025 * 1025; // convert to B
799
                }
800 View Code Duplication
                elseif ( false !== stripos( $limit_size, 'GB' ) ) {
801
                    $limit_size = (float) trim( str_ireplace( 'GB', '', $limit_size ) );
802
                    $limit_size = $limit_size * 1025 * 1025 * 1025; // convert to MB to KB to B
803
                }
804
                elseif ( false !== stripos( $limit_size, 'B' ) )
805
                    $limit_size = (float) trim( str_ireplace( 'B', '', $limit_size ) );
806
                else
807
                    $limit_size = wp_max_upload_size();
808
809
                if ( 0 < $limit_size && $limit_size < $file[ 'size' ] ) {
810
                    $error = __( 'File size too large, max size is %s', 'pods' );
811
                    $error = sprintf( $error, pods_var( $field[ 'type' ] . '_restrict_filesize', $field[ 'options' ] ) );
812
813
                    pods_error( '<div style="color:#FF0000">Error: ' . $error . '</div>' );
814
                }
815
            }
816
817
            $limit_file_type = pods_var( $field[ 'type' ] . '_type', $field[ 'options' ], 'images' );
818
819
            if ( 'images' == $limit_file_type )
820
                $limit_types = 'jpg,jpeg,png,gif';
821
            elseif ( 'video' == $limit_file_type )
822
                $limit_types = 'mpg,mov,flv,mp4';
823
            elseif ( 'audio' == $limit_file_type )
824
                $limit_types = 'mp3,m4a,wav,wma';
825
            elseif ( 'text' == $limit_file_type )
826
                $limit_types = 'txt,rtx,csv,tsv';
827
            elseif ( 'any' == $limit_file_type )
828
                $limit_types = '';
829
            else
830
                $limit_types = pods_var( $field[ 'type' ] . '_allowed_extensions', $field[ 'options' ], '', null, true );
831
832
            $limit_types = trim( str_replace( array( ' ', '.', "\n", "\t", ';' ), array( '', ',', ',', ',' ), $limit_types ), ',' );
833
834 View Code Duplication
            if ( pods_version_check( 'wp', '3.5' ) ) {
835
                $mime_types = wp_get_mime_types();
836
837
                if ( in_array( $limit_file_type, array( 'images', 'audio', 'video' ) ) ) {
838
                    $new_limit_types = array();
839
840
                    foreach ( $mime_types as $type => $mime ) {
841
                        if ( 0 === strpos( $mime, $limit_file_type ) ) {
842
                            $type = explode( '|', $type );
843
844
                            $new_limit_types = array_merge( $new_limit_types, $type );
845
                        }
846
                    }
847
848
                    if ( !empty( $new_limit_types ) )
849
                        $limit_types = implode( ',', $new_limit_types );
850
                }
851
                elseif ( 'any' != $limit_file_type ) {
852
                    $new_limit_types = array();
853
854
                    $limit_types = explode( ',', $limit_types );
855
856
                    foreach ( $limit_types as $k => $limit_type ) {
857
                        $found = false;
858
859
                        foreach ( $mime_types as $type => $mime ) {
860
                            if ( 0 === strpos( $mime, $limit_type ) ) {
861
                                $type = explode( '|', $type );
862
863
                                foreach ( $type as $t ) {
864
                                    if ( !in_array( $t, $new_limit_types ) )
865
                                        $new_limit_types[] = $t;
866
                                }
867
868
                                $found = true;
869
                            }
870
                        }
871
872
                        if ( !$found )
873
                            $new_limit_types[] = $limit_type;
874
                    }
875
876
                    if ( !empty( $new_limit_types ) )
877
                        $limit_types = implode( ',', $new_limit_types );
878
                }
879
            }
880
881
            $limit_types = explode( ',', $limit_types );
882
883
            $limit_types = array_filter( array_unique( $limit_types ) );
884
885
            if ( !empty( $limit_types ) ) {
886
                $ok = false;
887
888
                foreach ( $limit_types as $limit_type ) {
889
                    $limit_type = '.' . trim( $limit_type, ' .' );
890
891
                    $pos = ( strlen( $file[ 'name' ] ) - strlen( $limit_type ) );
892
893
                    if ( $pos === stripos( $file[ 'name' ], $limit_type ) ) {
894
                        $ok = true;
895
896
                        break;
897
                    }
898
                }
899
900
                if ( false === $ok ) {
901
                    $error = __( 'File type not allowed, please use one of the following: %s', 'pods' );
902
                    $error = sprintf( $error, '.' . implode( ', .', $limit_types ) );
903
904
                    pods_error( '<div style="color:#FF0000">Error: ' . $error . '</div>' );
905
                }
906
            }
907
908
            $custom_handler = apply_filters( 'pods_upload_handle', null, 'Filedata', $params->post_id, $params, $field );
909
910
            if ( null === $custom_handler ) {
911
				$linked = pods_var( $field[ 'type' ] . '_linked', $field[ 'options' ], 0 );
912
913
                $attachment_id = media_handle_upload( 'Filedata', $params->post_id );
914
915
                if ( is_object( $attachment_id ) ) {
916
                    $errors = array();
917
918
                    foreach ( $attachment_id->errors[ 'upload_error' ] as $error_code => $error_message ) {
919
                        $errors[] = '[' . $error_code . '] ' . $error_message;
920
                    }
921
922
                    pods_error( '<div style="color:#FF0000">Error: ' . implode( '</div><div>', $errors ) . '</div>' );
923
                }
924
                else {
925
                    $attachment = get_post( $attachment_id, ARRAY_A );
926
927
                    $attachment[ 'filename' ] = basename( $attachment[ 'guid' ] );
928
929
                    $thumb = wp_get_attachment_image_src( $attachment[ 'ID' ], 'thumbnail', true );
930
                    $attachment[ 'thumbnail' ] = $thumb[ 0 ];
931
932
					$attachment[ 'link' ] = '';
933
934
					if ( $linked ) {
935
                    	$attachment[ 'link' ] = wp_get_attachment_url( $attachment[ 'ID' ] );
936
					}
937
938
                    $attachment = apply_filters( 'pods_upload_attachment', $attachment, $params->post_id );
939
940
                    wp_send_json( $attachment );
941
                }
942
            }
943
        }
944
945
        die(); // KBAI!
0 ignored issues
show
Coding Style Compatibility introduced by
The method admin_ajax_upload() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
946
    }
947
}
948