Completed
Pull Request — 2.x (#3397)
by Scott Kingsley
06:16
created

PodsField_File::input()   C

Complexity

Conditions 31
Paths 6

Size

Total Lines 51
Code Lines 34

Duplication

Lines 30
Ratio 58.82 %

Importance

Changes 0
Metric Value
cc 31
eloc 34
nc 6
nop 5
dl 30
loc 51
rs 5.4631
c 0
b 0
f 0

How to fix   Long Method    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
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
            ),
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
            ),/*
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...
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
202 View Code Duplication
        if ( !pods_version_check( 'wp', '3.5' ) ) {
203
            unset( $options[ self::$type . '_linked' ] );
204
            unset( $options[ self::$type . '_modal_title' ] );
205
            unset( $options[ self::$type . '_modal_add_button' ] );
206
207
            $options[ self::$type . '_attachment_tab' ][ 'default' ] = 'type';
208
            $options[ self::$type . '_attachment_tab' ][ 'data' ] = array(
209
                'type' => __( 'Upload File', 'pods' ),
210
                'library' => __( 'Media Library', 'pods' )
211
            );
212
        }
213
214
        return $options;
215
    }
216
217
    /**
218
     * Define the current field's schema for DB table storage
219
     *
220
     * @param array $options
221
     *
222
     * @return array
223
     * @since 2.0
224
     */
225
    public function schema ( $options = null ) {
226
        $schema = false;
227
228
        return $schema;
229
    }
230
231
    /**
232
     * Change the way the value of the field is displayed with Pods::get
233
     *
234
     * @param mixed $value
235
     * @param string $name
236
     * @param array $options
237
     * @param array $pod
238
     * @param int $id
239
     *
240
     * @return mixed|null
241
     * @since 2.0
242
     */
243
    public function display ( $value = null, $name = null, $options = null, $pod = null, $id = null ) {
244
        if ( is_array( $value ) && !empty( $value ) ) {
245
            if ( isset( $value[ 'ID' ] ) )
246
                $value = wp_get_attachment_url( $value[ 'ID' ] );
247
            else {
248
                $attachments = $value;
249
                $value = array();
250
251
                foreach ( $attachments as $v ) {
252
                    if ( !is_array( $v ) )
253
                        $value[] = $v;
254
                    elseif ( isset( $v[ 'ID' ] ) )
255
                        $value[] = wp_get_attachment_url( $v[ 'ID' ] );
256
                }
257
258
                $value = implode( ' ', $value );
259
            }
260
        }
261
262
        return $value;
263
    }
264
265
    /**
266
     * Customize output of the form field
267
     *
268
     * @param string $name
269
     * @param mixed $value
270
     * @param array $options
271
     * @param array $pod
272
     * @param int $id
273
     *
274
     * @since 2.0
275
     */
276
    public function input ( $name, $value = null, $options = null, $pod = null, $id = null ) {
277
        $options = (array) $options;
278
        $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...
279
280 View Code Duplication
        if ( !is_admin() ) {
281
            include_once( ABSPATH . '/wp-admin/includes/template.php' );
282
283
            if ( is_multisite() )
284
                include_once( ABSPATH . '/wp-admin/includes/ms.php' );
285
        }
286
287 View Code Duplication
        if ( ( ( defined( 'PODS_DISABLE_FILE_UPLOAD' ) && true === PODS_DISABLE_FILE_UPLOAD )
288
               || ( defined( 'PODS_UPLOAD_REQUIRE_LOGIN' ) && is_bool( PODS_UPLOAD_REQUIRE_LOGIN ) && true === PODS_UPLOAD_REQUIRE_LOGIN && !is_user_logged_in() )
289
               || ( defined( 'PODS_UPLOAD_REQUIRE_LOGIN' ) && !is_bool( PODS_UPLOAD_REQUIRE_LOGIN ) && ( !is_user_logged_in() || !current_user_can( PODS_UPLOAD_REQUIRE_LOGIN ) ) ) )
290
             && ( ( defined( 'PODS_DISABLE_FILE_BROWSER' ) && true === PODS_DISABLE_FILE_BROWSER )
291
                  || ( defined( 'PODS_FILES_REQUIRE_LOGIN' ) && is_bool( PODS_FILES_REQUIRE_LOGIN ) && true === PODS_FILES_REQUIRE_LOGIN && !is_user_logged_in() )
292
                  || ( defined( 'PODS_FILES_REQUIRE_LOGIN' ) && !is_bool( PODS_FILES_REQUIRE_LOGIN ) && ( !is_user_logged_in() || !current_user_can( PODS_FILES_REQUIRE_LOGIN ) ) ) )
293
        ) {
294
            ?>
295
        <p>You do not have access to upload / browse files. Contact your website admin to resolve.</p>
296
        <?php
297
            return;
298
        }
299
300
        // @todo: Now One Field to Rule Them All
301
        $field_type = 'file-upload';
302
        pods_view( PODS_DIR . 'ui/fields-mv/file-upload.php', compact( array_keys( get_defined_vars() ) ) );
303
        return;
304
305
        // @todo: we're short-circuiting for prototyping above.  The actions below will need to be woven in
306
307
        // Use plupload if attachment isn't available
308
        if ( 'attachment' == pods_var( self::$type . '_uploader', $options ) && ( !is_user_logged_in() || ( !current_user_can( 'upload_files' ) && !current_user_can( 'edit_files' ) ) ) )
0 ignored issues
show
Unused Code introduced by
// @todo: we're short-ci...od, $id); return; } does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
Bug introduced by
The variable $options seems only to be defined at a later point. Did you maybe move this code here without moving the variable definition?

This error can happen if you refactor code and forget to move the variable initialization.

Let’s take a look at a simple example:

function someFunction() {
    $x = 5;
    echo $x;
}

The above code is perfectly fine. Now imagine that we re-order the statements:

function someFunction() {
    echo $x;
    $x = 5;
}

In that case, $x would be read before it is initialized. This was a very basic example, however the principle is the same for the found issue.

Loading history...
309
            $field_type = 'plupload';
310
        elseif ( 'plupload' == pods_var( self::$type . '_uploader', $options ) )
0 ignored issues
show
Bug introduced by
The variable $options seems only to be defined at a later point. Did you maybe move this code here without moving the variable definition?

This error can happen if you refactor code and forget to move the variable initialization.

Let’s take a look at a simple example:

function someFunction() {
    $x = 5;
    echo $x;
}

The above code is perfectly fine. Now imagine that we re-order the statements:

function someFunction() {
    echo $x;
    $x = 5;
}

In that case, $x would be read before it is initialized. This was a very basic example, however the principle is the same for the found issue.

Loading history...
311
            $field_type = 'plupload';
312 View Code Duplication
        elseif ( 'attachment' == pods_var( self::$type . '_uploader', $options ) ) {
0 ignored issues
show
Bug introduced by
The variable $options seems only to be defined at a later point. Did you maybe move this code here without moving the variable definition?

This error can happen if you refactor code and forget to move the variable initialization.

Let’s take a look at a simple example:

function someFunction() {
    $x = 5;
    echo $x;
}

The above code is perfectly fine. Now imagine that we re-order the statements:

function someFunction() {
    echo $x;
    $x = 5;
}

In that case, $x would be read before it is initialized. This was a very basic example, however the principle is the same for the found issue.

Loading history...
313
            if ( !pods_version_check( 'wp', '3.5' ) || !is_admin() ) // @todo test frontend media modal
314
                $field_type = 'attachment';
315
            else
316
                $field_type = 'media';
317
        }
318 View Code Duplication
        else {
319
            // Support custom File Uploader integration
320
            do_action( 'pods_form_ui_field_file_uploader_' . pods_var( self::$type . '_uploader', $options ), $name, $value, $options, $pod, $id );
321
            do_action( 'pods_form_ui_field_file_uploader', pods_var( self::$type . '_uploader', $options ), $name, $value, $options, $pod, $id );
322
            return;
323
        }
324
325
        pods_view( PODS_DIR . 'ui/fields/' . $field_type . '.php', compact( array_keys( get_defined_vars() ) ) );
326
    }
327
328
    /**
329
     * Build regex necessary for JS validation
330
     *
331
     * @param mixed $value
332
     * @param string $name
333
     * @param array $options
334
     * @param string $pod
335
     * @param int $id
336
     *
337
     * @return bool
338
     * @since 2.0
339
     */
340
    public function regex ( $value = null, $name = null, $options = null, $pod = null, $id = null ) {
341
        return false;
342
    }
343
344
    /**
345
     * Validate a value before it's saved
346
     *
347
     * @param mixed $value
348
     * @param string $name
349
     * @param array $options
350
     * @param array $fields
351
     * @param array $pod
352
     * @param int $id
353
     * @param null $params
354
     *
355
     * @return bool
356
     * @since 2.0
357
     */
358
    public function validate ( $value, $name = null, $options = null, $fields = null, $pod = null, $id = null, $params = null ) {
359
        // check file size
360
        // check file extensions
361
        return true;
362
    }
363
364
    /**
365
     * Change the value or perform actions after validation but before saving to the DB
366
     *
367
     * @param mixed $value
368
     * @param int $id
369
     * @param string $name
370
     * @param array $options
371
     * @param array $fields
372
     * @param array $pod
373
     * @param object $params
374
     *
375
     * @return mixed
376
     * @since 2.0
377
     */
378
    public function pre_save ( $value, $id = null, $name = null, $options = null, $fields = null, $pod = null, $params = null ) {
379
        return $value;
380
    }
381
382
    /**
383
     * Save the value to the DB
384
     *
385
     * @param mixed $value
386
     * @param int $id
387
     * @param string $name
388
     * @param array $options
389
     * @param array $fields
390
     * @param array $pod
391
     * @param object $params
392
     *
393
     * @since 2.3
394
     */
395
    public function save ( $value, $id = null, $name = null, $options = null, $fields = null, $pod = null, $params = null ) {
396
        if ( empty( self::$api ) )
397
            self::$api = pods_api();
398
399
        // File title / field handling
400
        foreach ( $value as $id ) {
401
            $title = false;
402
403
            if ( is_array( $id ) ) {
404 View Code Duplication
                if ( isset( $id[ 'title' ] ) && 0 < strlen( trim( $id[ 'title' ] ) ) )
405
                    $title = trim( $id[ 'title' ] );
406
407
                if ( isset( $id[ 'id' ] ) )
408
                    $id = (int) $id[ 'id' ];
409
                else
410
                    $id = 0;
411
            }
412
413
            if ( empty( $id ) )
414
                continue;
415
416
            // Update the title if set
417
            if ( false !== $title && 1 == pods_var( self::$type . '_edit_title', $options, 0 ) ) {
418
                $attachment_data = array(
419
                    'ID' => $id,
420
                    'post_title' => $title
421
                );
422
423
                self::$api->save_wp_object( 'media', $attachment_data );
424
            }
425
        }
426
    }
427
428
    /**
429
     * Customize the Pods UI manage table column output
430
     *
431
     * @param int $id
432
     * @param mixed $value
433
     * @param string $name
434
     * @param array $options
435
     * @param array $fields
436
     * @param array $pod
437
     *
438
     * @return mixed|void
439
     * @since 2.0
440
     */
441
    public function ui ( $id, $value, $name = null, $options = null, $fields = null, $pod = null ) {
442
        if ( empty( $value ) )
443
            return;
444
445
        if ( !empty( $value ) && isset( $value[ 'ID' ] ) )
446
            $value = array( $value );
447
448
        $image_size = apply_filters( 'pods_form_ui_field_file_ui_image_size', 'thumbnail', $id, $value, $name, $options, $pod );
449
450
        return $this->images( $id, $value, $name, $options, $pod, $image_size );
451
    }
452
453
    /**
454
     * Return image(s) markup
455
     *
456
     * @param int $id
457
     * @param mixed $value
458
     * @param string $name
459
     * @param array $options
460
     * @param array $pod
461
     * @param string $image_size
462
     *
463
     * @return string
464
     * @since 2.3
465
     */
466
    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...
467
        $images = '';
468
469
        if ( empty( $value ) || !is_array( $value ) )
470
            return $images;
471
472
        foreach ( $value as $v ) {
473
            $images .= pods_image( $v, $image_size );
474
        }
475
476
        return $images;
477
    }
478
479
    /**
480
     * Handle file row output for uploaders
481
     *
482
     * @param array $attributes
483
     * @param int $limit
484
     * @param bool $editable
485
     * @param int $id
486
     * @param string $icon
487
     * @param string $name
488
     *
489
     * @return string
490
     * @since 2.0
491
     */
492
    public function markup ( $attributes, $limit = 1, $editable = true, $id = null, $icon = null, $name = null, $linked = false, $link = null ) {
493
        // Preserve current file type
494
        $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...
495
496
        ob_start();
497
498
        if ( empty( $id ) )
499
            $id = '{{id}}';
500
501
        if ( empty( $icon ) ) {
502
	        $icon = '{{icon}}';
503
        }else{
504
	        $icon = esc_url( $icon );
505
        }
506
507
508
        if ( empty( $name ) )
509
            $name = '{{name}}';
510
511
        if ( empty( $link ) )
512
            $link = '{{link}}';
513
514
        $editable = (boolean) $editable;
515
        $linked = (boolean) $linked;
516
        ?>
517
    <li class="pods-file hidden" id="pods-file-<?php echo esc_attr( $id ); ?>">
518
        <?php echo PodsForm::field( $attributes[ 'name' ] . '[' . $id . '][id]', $id, 'hidden' ); ?>
519
520
        <ul class="pods-file-meta media-item">
521
            <?php if ( 1 != $limit ) { ?>
522
                <li class="pods-file-col pods-file-handle">Handle</li>
523
            <?php } ?>
524
525
            <li class="pods-file-col pods-file-icon">
526
                <img class="pinkynail" src="<?php echo $icon; ?>" alt="Icon" />
527
            </li>
528
529
            <li class="pods-file-col pods-file-name">
530
                <?php
531
                if ( $editable )
532
                    echo PodsForm::field( $attributes[ 'name' ] . '[' . $id . '][title]', $name, 'text' );
533
                else
534
                    echo ( empty( $name ) ? '{{name}}' : $name );
535
                ?>
536
            </li>
537
538
            <li class="pods-file-col pods-file-delete"><a href="#delete">Delete</a></li>
539
540
			<?php
541
				if ( $linked ) {
542
			?>
543
            	<li class="pods-file-col pods-file-download"><a href="<?php echo esc_url( $link ); ?>" target="_blank">Download</a></li>
544
			<?php
545
				}
546
			?>
547
        </ul>
548
    </li>
549
    <?php
550
        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...
551
552
        return ob_get_clean();
553
    }
554
555
    /**
556
     * Handle plupload AJAX
557
     *
558
     * @since 2.3
559
     */
560
    public function admin_ajax_upload () {
561
		pods_session_start();
562
563
        // Sanitize input
564
        $params = pods_unslash( (array) $_POST );
565
566 View Code Duplication
        foreach ( $params as $key => $value ) {
567
            if ( 'action' == $key )
568
                continue;
569
570
            unset( $params[ $key ] );
571
572
            $params[ str_replace( '_podsfix_', '', $key ) ] = $value;
573
        }
574
575
        $params = (object) $params;
576
577
        $methods = array(
578
            'upload',
579
        );
580
581
        if ( !isset( $params->method ) || !in_array( $params->method, $methods ) || !isset( $params->pod ) || !isset( $params->field ) || !isset( $params->uri ) || empty( $params->uri ) )
582
            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...
583
        elseif ( !empty( $params->pod ) && empty( $params->field ) )
584
            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...
585
        elseif ( empty( $params->pod ) && !current_user_can( 'upload_files' ) )
586
            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...
587
588
        // Flash often fails to send cookies with the POST or upload, so we need to pass it in GET or POST instead
589
        if ( is_ssl() && empty( $_COOKIE[ SECURE_AUTH_COOKIE ] ) && !empty( $_REQUEST[ 'auth_cookie' ] ) )
590
            $_COOKIE[ SECURE_AUTH_COOKIE ] = $_REQUEST[ 'auth_cookie' ];
591
        elseif ( empty( $_COOKIE[ AUTH_COOKIE ] ) && !empty( $_REQUEST[ 'auth_cookie' ] ) )
592
            $_COOKIE[ AUTH_COOKIE ] = $_REQUEST[ 'auth_cookie' ];
593
594
        if ( empty( $_COOKIE[ LOGGED_IN_COOKIE ] ) && !empty( $_REQUEST[ 'logged_in_cookie' ] ) )
595
            $_COOKIE[ LOGGED_IN_COOKIE ] = $_REQUEST[ 'logged_in_cookie' ];
596
597
        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...
598
        unset( $current_user );
599
600
        /**
601
         * Access Checking
602
         */
603
        $upload_disabled = false;
604
605
        if ( defined( 'PODS_DISABLE_FILE_UPLOAD' ) && true === PODS_DISABLE_FILE_UPLOAD )
606
            $upload_disabled = true;
607 View Code Duplication
        elseif ( defined( 'PODS_UPLOAD_REQUIRE_LOGIN' ) && is_bool( PODS_UPLOAD_REQUIRE_LOGIN ) && true === PODS_UPLOAD_REQUIRE_LOGIN && !is_user_logged_in() )
608
            $upload_disabled = true;
609 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 ) ) )
610
            $upload_disabled = true;
611
612
        $uid = @session_id();
613
614
        if ( is_user_logged_in() )
615
            $uid = 'user_' . get_current_user_id();
616
617
        $nonce_check = 'pods_upload_' . (int) $params->pod . '_' . $uid . '_' . $params->uri . '_' . (int) $params->field;
618
619 View Code Duplication
        if ( true === $upload_disabled || !isset( $params->_wpnonce ) || false === wp_verify_nonce( $params->_wpnonce, $nonce_check ) )
620
            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...
621
622
        $pod = array();
623
        $field = array(
624
            'type' => 'file',
625
            'options' => array()
626
        );
627
628
        $api = pods_api();
629
630
	    $api->display_errors = false;
631
632
        if ( !empty( $params->pod ) ) {
633
            $pod = $api->load_pod( array( 'id' => (int) $params->pod ) );
634
            $field = $api->load_field( array( 'id' => (int) $params->field ) );
635
636 View Code Duplication
            if ( empty( $pod ) || empty( $field ) || $pod[ 'id' ] != $field[ 'pod_id' ] || !isset( $pod[ 'fields' ][ $field[ 'name' ] ] ) )
637
                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...
638
639
            if ( !in_array( $field[ 'type' ], PodsForm::file_field_types() ) )
640
                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...
641
        }
642
643
        $method = $params->method;
644
645
        // Cleaning up $params
646
        unset( $params->action );
647
        unset( $params->method );
648
        unset( $params->_wpnonce );
649
650
        $params->post_id = pods_var( 'post_id', $params, 0, null, true );
651
652
        /**
653
         * Upload a new file (advanced - returns URL and ID)
654
         */
655
        if ( 'upload' == $method ) {
656
            $file = $_FILES[ 'Filedata' ];
657
658
            $limit_size = pods_var( $field[ 'type' ] . '_restrict_filesize', $field[ 'options' ] );
659
660
            if ( !empty( $limit_size ) ) {
661
                if ( false !== stripos( $limit_size, 'MB' ) ) {
662
                    $limit_size = (float) trim( str_ireplace( 'MB', '', $limit_size ) );
663
                    $limit_size = $limit_size * 1025 * 1025; // convert to KB to B
664
                }
665 View Code Duplication
                elseif ( false !== stripos( $limit_size, 'KB' ) ) {
666
                    $limit_size = (float) trim( str_ireplace( 'KB', '', $limit_size ) );
667
                    $limit_size = $limit_size * 1025 * 1025; // convert to B
668
                }
669 View Code Duplication
                elseif ( false !== stripos( $limit_size, 'GB' ) ) {
670
                    $limit_size = (float) trim( str_ireplace( 'GB', '', $limit_size ) );
671
                    $limit_size = $limit_size * 1025 * 1025 * 1025; // convert to MB to KB to B
672
                }
673
                elseif ( false !== stripos( $limit_size, 'B' ) )
674
                    $limit_size = (float) trim( str_ireplace( 'B', '', $limit_size ) );
675
                else
676
                    $limit_size = wp_max_upload_size();
677
678
                if ( 0 < $limit_size && $limit_size < $file[ 'size' ] ) {
679
                    $error = __( 'File size too large, max size is %s', 'pods' );
680
                    $error = sprintf( $error, pods_var( $field[ 'type' ] . '_restrict_filesize', $field[ 'options' ] ) );
681
682
                    pods_error( '<div style="color:#FF0000">Error: ' . $error . '</div>' );
683
                }
684
            }
685
686
            $limit_file_type = pods_var( $field[ 'type' ] . '_type', $field[ 'options' ], 'images' );
687
688
            if ( 'images' == $limit_file_type )
689
                $limit_types = 'jpg,jpeg,png,gif';
690
            elseif ( 'video' == $limit_file_type )
691
                $limit_types = 'mpg,mov,flv,mp4';
692
            elseif ( 'audio' == $limit_file_type )
693
                $limit_types = 'mp3,m4a,wav,wma';
694
            elseif ( 'text' == $limit_file_type )
695
                $limit_types = 'txt,rtx,csv,tsv';
696
            elseif ( 'any' == $limit_file_type )
697
                $limit_types = '';
698
            else
699
                $limit_types = pods_var( $field[ 'type' ] . '_allowed_extensions', $field[ 'options' ], '', null, true );
700
701
            $limit_types = trim( str_replace( array( ' ', '.', "\n", "\t", ';' ), array( '', ',', ',', ',' ), $limit_types ), ',' );
702
703 View Code Duplication
            if ( pods_version_check( 'wp', '3.5' ) ) {
704
                $mime_types = wp_get_mime_types();
705
706
                if ( in_array( $limit_file_type, array( 'images', 'audio', 'video' ) ) ) {
707
                    $new_limit_types = array();
708
709
                    foreach ( $mime_types as $type => $mime ) {
710
                        if ( 0 === strpos( $mime, $limit_file_type ) ) {
711
                            $type = explode( '|', $type );
712
713
                            $new_limit_types = array_merge( $new_limit_types, $type );
714
                        }
715
                    }
716
717
                    if ( !empty( $new_limit_types ) )
718
                        $limit_types = implode( ',', $new_limit_types );
719
                }
720
                elseif ( 'any' != $limit_file_type ) {
721
                    $new_limit_types = array();
722
723
                    $limit_types = explode( ',', $limit_types );
724
725
                    foreach ( $limit_types as $k => $limit_type ) {
726
                        $found = false;
727
728
                        foreach ( $mime_types as $type => $mime ) {
729
                            if ( 0 === strpos( $mime, $limit_type ) ) {
730
                                $type = explode( '|', $type );
731
732
                                foreach ( $type as $t ) {
733
                                    if ( !in_array( $t, $new_limit_types ) )
734
                                        $new_limit_types[] = $t;
735
                                }
736
737
                                $found = true;
738
                            }
739
                        }
740
741
                        if ( !$found )
742
                            $new_limit_types[] = $limit_type;
743
                    }
744
745
                    if ( !empty( $new_limit_types ) )
746
                        $limit_types = implode( ',', $new_limit_types );
747
                }
748
            }
749
750
            $limit_types = explode( ',', $limit_types );
751
752
            $limit_types = array_filter( array_unique( $limit_types ) );
753
754
            if ( !empty( $limit_types ) ) {
755
                $ok = false;
756
757
                foreach ( $limit_types as $limit_type ) {
758
                    $limit_type = '.' . trim( $limit_type, ' .' );
759
760
                    $pos = ( strlen( $file[ 'name' ] ) - strlen( $limit_type ) );
761
762
                    if ( $pos === stripos( $file[ 'name' ], $limit_type ) ) {
763
                        $ok = true;
764
765
                        break;
766
                    }
767
                }
768
769
                if ( false === $ok ) {
770
                    $error = __( 'File type not allowed, please use one of the following: %s', 'pods' );
771
                    $error = sprintf( $error, '.' . implode( ', .', $limit_types ) );
772
773
                    pods_error( '<div style="color:#FF0000">Error: ' . $error . '</div>' );
774
                }
775
            }
776
777
            $custom_handler = apply_filters( 'pods_upload_handle', null, 'Filedata', $params->post_id, $params, $field );
778
779
            if ( null === $custom_handler ) {
780
				$linked = pods_var( $field[ 'type' ] . '_linked', $field[ 'options' ], 0 );
781
782
                $attachment_id = media_handle_upload( 'Filedata', $params->post_id );
783
784
                if ( is_object( $attachment_id ) ) {
785
                    $errors = array();
786
787
                    foreach ( $attachment_id->errors[ 'upload_error' ] as $error_code => $error_message ) {
788
                        $errors[] = '[' . $error_code . '] ' . $error_message;
789
                    }
790
791
                    pods_error( '<div style="color:#FF0000">Error: ' . implode( '</div><div>', $errors ) . '</div>' );
792
                }
793
                else {
794
                    $attachment = get_post( $attachment_id, ARRAY_A );
795
796
                    $attachment[ 'filename' ] = basename( $attachment[ 'guid' ] );
797
798
                    $thumb = wp_get_attachment_image_src( $attachment[ 'ID' ], 'thumbnail', true );
799
                    $attachment[ 'thumbnail' ] = $thumb[ 0 ];
800
801
					$attachment[ 'link' ] = '';
802
803
					if ( $linked ) {
804
                    	$attachment[ 'link' ] = wp_get_attachment_url( $attachment[ 'ID' ] );
805
					}
806
807
                    $attachment = apply_filters( 'pods_upload_attachment', $attachment, $params->post_id );
808
809
                    wp_send_json( $attachment );
810
                }
811
            }
812
        }
813
814
        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...
815
    }
816
}
817