Completed
Pull Request — 2.x (#3632)
by Scott Kingsley
05:59
created

PodsField_File::input()   C

Complexity

Conditions 31
Paths 6

Size

Total Lines 51
Code Lines 34

Duplication

Lines 24
Ratio 47.06 %

Importance

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

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_' . self::$type . '_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 . '_show_edit_link' => array(
116
                'label' => __( 'Show Edit Link', 'pods' ),
117
                'default' => 0,
118
                'type' => 'boolean'
119
            ),
120
            self::$type . '_linked' => array(
121
                'label' => __( 'Show Download Link', 'pods' ),
122
                'default' => 0,
123
                'type' => 'boolean'
124
            ),
125
            self::$type . '_limit' => array(
126
                'label' => __( 'Max Number of Files', 'pods' ),
127
                'depends-on' => array( self::$type . '_format_type' => 'multi' ),
128
                'default' => 0,
129
                'type' => 'number'
130
            ),
131
            self::$type . '_restrict_filesize' => array(
132
                'label' => __( 'Restrict File Size', 'pods' ),
133
                'depends-on' => array( self::$type . '_uploader' => 'plupload' ),
134
                'default' => '10MB',
135
                'type' => 'text'
136
            ),
137
            self::$type . '_type' => array(
138
                'label' => __( 'Restrict File Types', 'pods' ),
139
                'default' => apply_filters( 'pods_form_ui_field_' . self::$type . '_type_default', 'images' ),
140
                'type' => 'pick',
141
                'data' => apply_filters(
142
                    'pods_form_ui_field_' . self::$type . '_type_options',
143
                    array(
144
                        'images' => __( 'Images (jpg, jpeg, png, gif)', 'pods' ),
145
                        'video' => __( 'Video (mpg, mov, flv, mp4, etc..)', 'pods' ),
146
                        'audio' => __( 'Audio (mp3, m4a, wav, wma, etc..)', 'pods' ),
147
                        'text' => __( 'Text (txt, csv, tsv, rtx, etc..)', 'pods' ),
148
                        'any' => __( 'Any Type (no restriction)', 'pods' ),
149
                        'other' => __( 'Other (customize allowed extensions)', 'pods' )
150
                    )
151
                ),
152
                'dependency' => true
153
            ),
154
            self::$type . '_allowed_extensions' => array(
155
                'label' => __( 'Allowed File Extensions', 'pods' ),
156
                'description' => __( 'Separate file extensions with a comma (ex. jpg,png,mp4,mov)', 'pods' ),
157
                'depends-on' => array( self::$type . '_type' => 'other' ),
158
                'default' => apply_filters( 'pods_form_ui_field_' . self::$type . '_extensions_default', '' ),
159
                'type' => 'text'
160
            ),
161
            self::$type . '_field_template' => array(
162
                'label' => __( 'List Style', 'pods' ),
163
                'help' => __( 'You can choose which style you would like the files to appear within the form.', 'pods' ),
164
                'depends-on' => array( self::$type . '_type' => 'images' ),
165
                'default' => apply_filters( 'pods_form_ui_field_' . self::$type . '_template_default', 'rows' ),
166
                'type' => 'pick',
167
                'data' => apply_filters(
168
                    'pods_form_ui_field_' . self::$type . '_type_templates',
169
                    array(
170
                        'rows' => __( 'Rows', 'pods' ),
171
                        'tiles' => __( 'Tiles', 'pods' ),
172
                    )
173
                ),
174
            ),/*
0 ignored issues
show
Unused Code Comprehensibility introduced by
52% 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...
175
            self::$type . '_image_size' => array(
176
                'label' => __( 'Excluded Image Sizes', 'pods' ),
177
                'description' => __( 'Image sizes not to generate when processing the image', 'pods' ),
178
                'depends-on' => array( self::$type . '_type' => 'images' ),
179
                'default' => 'images',
180
                'type' => 'pick',
181
                'pick_format_type' => 'multi',
182
                'pick_format_multi' => 'checkbox',
183
                'data' => apply_filters(
184
                    'pods_form_ui_field_' . self::$type . '_image_size_options',
185
                    $image_sizes
186
                )
187
            ),*/
188
            self::$type . '_add_button' => array(
189
                'label' => __( 'Add Button Text', 'pods' ),
190
                'default' => __( 'Add File', 'pods' ),
191
                'type' => 'text'
192
            ),
193
            self::$type . '_modal_title' => array(
194
                'label' => __( 'Modal Title', 'pods' ),
195
                'depends-on' => array( self::$type . '_uploader' => 'attachment' ),
196
                'default' => __( 'Attach a file', 'pods' ),
197
                'type' => 'text'
198
            ),
199
            self::$type . '_modal_add_button' => array(
200
                'label' => __( 'Modal Add Button Text', 'pods' ),
201
                'depends-on' => array( self::$type . '_uploader' => 'attachment' ),
202
                'default' => __( 'Add File', 'pods' ),
203
                'type' => 'text'
204
            )
205
        );
206
207 View Code Duplication
        if ( !pods_version_check( 'wp', '3.5' ) ) {
208
            unset( $options[ self::$type . '_linked' ] );
209
            unset( $options[ self::$type . '_modal_title' ] );
210
            unset( $options[ self::$type . '_modal_add_button' ] );
211
212
            $options[ self::$type . '_attachment_tab' ][ 'default' ] = 'type';
213
            $options[ self::$type . '_attachment_tab' ][ 'data' ] = array(
214
                'type' => __( 'Upload File', 'pods' ),
215
                'library' => __( 'Media Library', 'pods' )
216
            );
217
        }
218
219
        return $options;
220
    }
221
222
    /**
223
     * Define the current field's schema for DB table storage
224
     *
225
     * @param array $options
226
     *
227
     * @return array
228
     * @since 2.0
229
     */
230
    public function schema ( $options = null ) {
231
        $schema = false;
232
233
        return $schema;
234
    }
235
236
    /**
237
     * Change the way the value of the field is displayed with Pods::get
238
     *
239
     * @param mixed $value
240
     * @param string $name
241
     * @param array $options
242
     * @param array $pod
243
     * @param int $id
244
     *
245
     * @return mixed|null
246
     * @since 2.0
247
     */
248
    public function display ( $value = null, $name = null, $options = null, $pod = null, $id = null ) {
249
        if ( is_array( $value ) && !empty( $value ) ) {
250
            if ( isset( $value[ 'ID' ] ) )
251
                $value = wp_get_attachment_url( $value[ 'ID' ] );
252
            else {
253
                $attachments = $value;
254
                $value = array();
255
256
                foreach ( $attachments as $v ) {
257
                    if ( !is_array( $v ) )
258
                        $value[] = $v;
259
                    elseif ( isset( $v[ 'ID' ] ) )
260
                        $value[] = wp_get_attachment_url( $v[ 'ID' ] );
261
                }
262
263
                $value = implode( ' ', $value );
264
            }
265
        }
266
267
        return $value;
268
    }
269
270
    /**
271
     * Customize output of the form field
272
     *
273
     * @param string $name
274
     * @param mixed $value
275
     * @param array $options
276
     * @param array $pod
277
     * @param int $id
278
     *
279
     * @since 2.0
280
     */
281
    public function input ( $name, $value = null, $options = null, $pod = null, $id = null ) {
282
        $options = (array) $options;
283
        $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...
284
285 View Code Duplication
        if ( !is_admin() ) {
286
            include_once( ABSPATH . '/wp-admin/includes/template.php' );
287
288
            if ( is_multisite() )
289
                include_once( ABSPATH . '/wp-admin/includes/ms.php' );
290
        }
291
292 View Code Duplication
        if ( ( ( defined( 'PODS_DISABLE_FILE_UPLOAD' ) && true === PODS_DISABLE_FILE_UPLOAD )
293
               || ( defined( 'PODS_UPLOAD_REQUIRE_LOGIN' ) && is_bool( PODS_UPLOAD_REQUIRE_LOGIN ) && true === PODS_UPLOAD_REQUIRE_LOGIN && !is_user_logged_in() )
294
               || ( defined( 'PODS_UPLOAD_REQUIRE_LOGIN' ) && !is_bool( PODS_UPLOAD_REQUIRE_LOGIN ) && ( !is_user_logged_in() || !current_user_can( PODS_UPLOAD_REQUIRE_LOGIN ) ) ) )
295
             && ( ( defined( 'PODS_DISABLE_FILE_BROWSER' ) && true === PODS_DISABLE_FILE_BROWSER )
296
                  || ( defined( 'PODS_FILES_REQUIRE_LOGIN' ) && is_bool( PODS_FILES_REQUIRE_LOGIN ) && true === PODS_FILES_REQUIRE_LOGIN && !is_user_logged_in() )
297
                  || ( defined( 'PODS_FILES_REQUIRE_LOGIN' ) && !is_bool( PODS_FILES_REQUIRE_LOGIN ) && ( !is_user_logged_in() || !current_user_can( PODS_FILES_REQUIRE_LOGIN ) ) ) )
298
        ) {
299
            ?>
300
        <p>You do not have access to upload / browse files. Contact your website admin to resolve.</p>
301
        <?php
302
            return;
303
        }
304
305
        // @todo: Now One Field to Rule Them All
306
        $field_type = 'file-upload';
307
        pods_view( PODS_DIR . 'ui/fields-mv/file-upload.php', compact( array_keys( get_defined_vars() ) ) );
308
        return;
309
310
        // @todo: we're short-circuiting for prototyping above.  The actions below will need to be woven in
311
312
        // Use plupload if attachment isn't available
313
        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...
314
            $field_type = 'plupload';
315
        elseif ( 'plupload' == pods_var( self::$type . '_uploader', $options ) )
316
            $field_type = 'plupload';
317 View Code Duplication
        elseif ( 'attachment' == pods_var( self::$type . '_uploader', $options ) ) {
318
            if ( !pods_version_check( 'wp', '3.5' ) || !is_admin() ) // @todo test frontend media modal
319
                $field_type = 'attachment';
320
            else
321
                $field_type = 'media';
322
        }
323
        else {
324
            // Support custom File Uploader integration
325
            do_action( 'pods_form_ui_field_' . self::$type . '_uploader_' . pods_var( self::$type . '_uploader', $options ), $name, $value, $options, $pod, $id );
326
            do_action( 'pods_form_ui_field_' . self::$type . '_uploader', pods_var( self::$type . '_uploader', $options ), $name, $value, $options, $pod, $id );
327
            return;
328
        }
329
330
        pods_view( PODS_DIR . 'ui/fields/' . $field_type . '.php', compact( array_keys( get_defined_vars() ) ) );
331
    }
332
333
    /**
334
     * Build regex necessary for JS validation
335
     *
336
     * @param mixed $value
337
     * @param string $name
338
     * @param array $options
339
     * @param string $pod
340
     * @param int $id
341
     *
342
     * @return bool
343
     * @since 2.0
344
     */
345
    public function regex ( $value = null, $name = null, $options = null, $pod = null, $id = null ) {
346
        return false;
347
    }
348
349
    /**
350
     * Validate a value before it's saved
351
     *
352
     * @param mixed $value
353
     * @param string $name
354
     * @param array $options
355
     * @param array $fields
356
     * @param array $pod
357
     * @param int $id
358
     * @param null $params
359
     *
360
     * @return bool
361
     * @since 2.0
362
     */
363
    public function validate ( $value, $name = null, $options = null, $fields = null, $pod = null, $id = null, $params = null ) {
364
        // check file size
365
        // check file extensions
366
        return true;
367
    }
368
369
    /**
370
     * Change the value or perform actions after validation but before saving to the DB
371
     *
372
     * @param mixed $value
373
     * @param int $id
374
     * @param string $name
375
     * @param array $options
376
     * @param array $fields
377
     * @param array $pod
378
     * @param object $params
379
     *
380
     * @return mixed
381
     * @since 2.0
382
     */
383
    public function pre_save ( $value, $id = null, $name = null, $options = null, $fields = null, $pod = null, $params = null ) {
384
        return $value;
385
    }
386
387
    /**
388
     * Save the value to the DB
389
     *
390
     * @param mixed $value
391
     * @param int $id
392
     * @param string $name
393
     * @param array $options
394
     * @param array $fields
395
     * @param array $pod
396
     * @param object $params
397
     *
398
     * @since 2.3
399
     */
400
    public function save ( $value, $id = null, $name = null, $options = null, $fields = null, $pod = null, $params = null ) {
401
        if ( empty( self::$api ) )
402
            self::$api = pods_api();
403
404
        // File title / field handling
405
        foreach ( $value as $id ) {
406
            $title = false;
407
408
            if ( is_array( $id ) ) {
409 View Code Duplication
                if ( isset( $id[ 'title' ] ) && 0 < strlen( trim( $id[ 'title' ] ) ) )
410
                    $title = trim( $id[ 'title' ] );
411
412
                if ( isset( $id[ 'id' ] ) )
413
                    $id = (int) $id[ 'id' ];
414
                else
415
                    $id = 0;
416
            }
417
418
            if ( empty( $id ) )
419
                continue;
420
421
            // Update the title if set
422
            if ( false !== $title && 1 == pods_var( self::$type . '_edit_title', $options, 0 ) ) {
423
                $attachment_data = array(
424
                    'ID' => $id,
425
                    'post_title' => $title
426
                );
427
428
                self::$api->save_wp_object( 'media', $attachment_data );
429
            }
430
        }
431
    }
432
433
    /**
434
     * Customize the Pods UI manage table column output
435
     *
436
     * @param int $id
437
     * @param mixed $value
438
     * @param string $name
439
     * @param array $options
440
     * @param array $fields
441
     * @param array $pod
442
     *
443
     * @return mixed|void
444
     * @since 2.0
445
     */
446
    public function ui ( $id, $value, $name = null, $options = null, $fields = null, $pod = null ) {
447
        if ( empty( $value ) )
448
            return;
449
450
        if ( !empty( $value ) && isset( $value[ 'ID' ] ) )
451
            $value = array( $value );
452
453
        $image_size = apply_filters( 'pods_form_ui_field_' . self::$type . '_ui_image_size', 'thumbnail', $id, $value, $name, $options, $pod );
454
455
        return $this->images( $id, $value, $name, $options, $pod, $image_size );
456
    }
457
458
    /**
459
     * Return image(s) markup
460
     *
461
     * @param int $id
462
     * @param mixed $value
463
     * @param string $name
464
     * @param array $options
465
     * @param array $pod
466
     * @param string $image_size
467
     *
468
     * @return string
469
     * @since 2.3
470
     */
471
    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...
472
        $images = '';
473
474
        if ( empty( $value ) || !is_array( $value ) )
475
            return $images;
476
477
        foreach ( $value as $v ) {
478
            $images .= pods_image( $v, $image_size );
479
        }
480
481
        return $images;
482
    }
483
484
    /**
485
     * Handle file row output for uploaders
486
     *
487
     * @param array $attributes
488
     * @param int $limit
489
     * @param bool $editable
490
     * @param int $id
491
     * @param string $icon
492
     * @param string $name
493
     *
494
     * @return string
495
     * @since 2.0
496
     */
497
    public function markup ( $attributes, $limit = 1, $editable = true, $id = null, $icon = null, $name = null, $linked = false, $link = null ) {
498
        // Preserve current file type
499
        $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...
500
501
        ob_start();
502
503
        if ( empty( $id ) )
504
            $id = '{{id}}';
505
506
        if ( empty( $icon ) ) {
507
	        $icon = '{{icon}}';
508
        }else{
509
	        $icon = esc_url( $icon );
510
        }
511
512
513
        if ( empty( $name ) )
514
            $name = '{{name}}';
515
516
        if ( empty( $link ) )
517
            $link = '{{link}}';
518
519
        $editable = (boolean) $editable;
520
        $linked = (boolean) $linked;
521
        ?>
522
    <li class="pods-file hidden" id="pods-file-<?php echo esc_attr( $id ); ?>">
523
        <?php echo PodsForm::field( $attributes[ 'name' ] . '[' . $id . '][id]', $id, 'hidden' ); ?>
524
525
        <ul class="pods-file-meta media-item">
526
            <?php if ( 1 != $limit ) { ?>
527
                <li class="pods-file-col pods-file-handle">Handle</li>
528
            <?php } ?>
529
530
            <li class="pods-file-col pods-file-icon">
531
                <img class="pinkynail" src="<?php echo $icon; ?>" alt="Icon" />
532
            </li>
533
534
            <li class="pods-file-col pods-file-name">
535
                <?php
536
                if ( $editable )
537
                    echo PodsForm::field( $attributes[ 'name' ] . '[' . $id . '][title]', $name, 'text' );
538
                else
539
                    echo ( empty( $name ) ? '{{name}}' : $name );
540
                ?>
541
            </li>
542
543
            <li class="pods-file-col pods-file-actions">
544
                <ul>
545
                    <li class="pods-file-col pods-file-delete"><a href="#delete">Delete</a></li>
546
                    <?php
547
						if ( $linked ) {
548
					?>
549
		                <li class="pods-file-col pods-file-download"><a href="<?php echo esc_url( $link ); ?>" target="_blank">Download</a></li>
550
					<?php
551
						}
552
					?>
553
                </ul>
554
            </li>
555
        </ul>
556
    </li>
557
    <?php
558
        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...
559
560
        return ob_get_clean();
561
    }
562
563
    /**
564
     * Handle plupload AJAX
565
     *
566
     * @since 2.3
567
     */
568
    public function admin_ajax_upload () {
569
		pods_session_start();
570
571
        // Sanitize input
572
        $params = pods_unslash( (array) $_POST );
573
574 View Code Duplication
        foreach ( $params as $key => $value ) {
575
            if ( 'action' == $key )
576
                continue;
577
578
            unset( $params[ $key ] );
579
580
            $params[ str_replace( '_podsfix_', '', $key ) ] = $value;
581
        }
582
583
        $params = (object) $params;
584
585
        $methods = array(
586
            'upload',
587
        );
588
589
        if ( !isset( $params->method ) || !in_array( $params->method, $methods ) || !isset( $params->pod ) || !isset( $params->field ) || !isset( $params->uri ) || empty( $params->uri ) )
590
            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...
591
        elseif ( !empty( $params->pod ) && empty( $params->field ) )
592
            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...
593
        elseif ( empty( $params->pod ) && !current_user_can( 'upload_files' ) )
594
            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...
595
596
        // Flash often fails to send cookies with the POST or upload, so we need to pass it in GET or POST instead
597
        if ( is_ssl() && empty( $_COOKIE[ SECURE_AUTH_COOKIE ] ) && !empty( $_REQUEST[ 'auth_cookie' ] ) )
598
            $_COOKIE[ SECURE_AUTH_COOKIE ] = $_REQUEST[ 'auth_cookie' ];
599
        elseif ( empty( $_COOKIE[ AUTH_COOKIE ] ) && !empty( $_REQUEST[ 'auth_cookie' ] ) )
600
            $_COOKIE[ AUTH_COOKIE ] = $_REQUEST[ 'auth_cookie' ];
601
602
        if ( empty( $_COOKIE[ LOGGED_IN_COOKIE ] ) && !empty( $_REQUEST[ 'logged_in_cookie' ] ) )
603
            $_COOKIE[ LOGGED_IN_COOKIE ] = $_REQUEST[ 'logged_in_cookie' ];
604
605
        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...
606
        unset( $current_user );
607
608
        /**
609
         * Access Checking
610
         */
611
        $upload_disabled = false;
612
613
        if ( defined( 'PODS_DISABLE_FILE_UPLOAD' ) && true === PODS_DISABLE_FILE_UPLOAD )
614
            $upload_disabled = true;
615 View Code Duplication
        elseif ( defined( 'PODS_UPLOAD_REQUIRE_LOGIN' ) && is_bool( PODS_UPLOAD_REQUIRE_LOGIN ) && true === PODS_UPLOAD_REQUIRE_LOGIN && !is_user_logged_in() )
616
            $upload_disabled = true;
617 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 ) ) )
618
            $upload_disabled = true;
619
620
        $uid = @session_id();
621
622
        if ( is_user_logged_in() )
623
            $uid = 'user_' . get_current_user_id();
624
625
        $nonce_check = 'pods_upload_' . (int) $params->pod . '_' . $uid . '_' . $params->uri . '_' . (int) $params->field;
626
627 View Code Duplication
        if ( true === $upload_disabled || !isset( $params->_wpnonce ) || false === wp_verify_nonce( $params->_wpnonce, $nonce_check ) )
628
            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...
629
630
        $pod = array();
631
        $field = array(
632
            'type' => 'file',
633
            'options' => array()
634
        );
635
636
        $api = pods_api();
637
638
	    $api->display_errors = false;
639
640
        if ( !empty( $params->pod ) ) {
641
            $pod = $api->load_pod( array( 'id' => (int) $params->pod ) );
642
            $field = $api->load_field( array( 'id' => (int) $params->field ) );
643
644 View Code Duplication
            if ( empty( $pod ) || empty( $field ) || $pod[ 'id' ] != $field[ 'pod_id' ] || !isset( $pod[ 'fields' ][ $field[ 'name' ] ] ) )
645
                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...
646
647
            if ( !in_array( $field[ 'type' ], PodsForm::file_field_types() ) )
648
                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...
649
        }
650
651
        $method = $params->method;
652
653
        // Cleaning up $params
654
        unset( $params->action );
655
        unset( $params->method );
656
        unset( $params->_wpnonce );
657
658
        $params->post_id = pods_var( 'post_id', $params, 0, null, true );
659
660
        /**
661
         * Upload a new file (advanced - returns URL and ID)
662
         */
663
        if ( 'upload' == $method ) {
664
            $file = $_FILES[ 'Filedata' ];
665
666
            $limit_size = pods_var( $field[ 'type' ] . '_restrict_filesize', $field[ 'options' ] );
667
668
            if ( !empty( $limit_size ) ) {
669
                if ( false !== stripos( $limit_size, 'MB' ) ) {
670
                    $limit_size = (float) trim( str_ireplace( 'MB', '', $limit_size ) );
671
                    $limit_size = $limit_size * 1025 * 1025; // convert to KB to B
672
                }
673 View Code Duplication
                elseif ( false !== stripos( $limit_size, 'KB' ) ) {
674
                    $limit_size = (float) trim( str_ireplace( 'KB', '', $limit_size ) );
675
                    $limit_size = $limit_size * 1025 * 1025; // convert to B
676
                }
677 View Code Duplication
                elseif ( false !== stripos( $limit_size, 'GB' ) ) {
678
                    $limit_size = (float) trim( str_ireplace( 'GB', '', $limit_size ) );
679
                    $limit_size = $limit_size * 1025 * 1025 * 1025; // convert to MB to KB to B
680
                }
681
                elseif ( false !== stripos( $limit_size, 'B' ) )
682
                    $limit_size = (float) trim( str_ireplace( 'B', '', $limit_size ) );
683
                else
684
                    $limit_size = wp_max_upload_size();
685
686
                if ( 0 < $limit_size && $limit_size < $file[ 'size' ] ) {
687
                    $error = __( 'File size too large, max size is %s', 'pods' );
688
                    $error = sprintf( $error, pods_var( $field[ 'type' ] . '_restrict_filesize', $field[ 'options' ] ) );
689
690
                    pods_error( '<div style="color:#FF0000">Error: ' . $error . '</div>' );
691
                }
692
            }
693
694
            $limit_file_type = pods_var( $field[ 'type' ] . '_type', $field[ 'options' ], 'images' );
695
696
            if ( 'images' == $limit_file_type )
697
                $limit_types = 'jpg,jpeg,png,gif';
698
            elseif ( 'video' == $limit_file_type )
699
                $limit_types = 'mpg,mov,flv,mp4';
700
            elseif ( 'audio' == $limit_file_type )
701
                $limit_types = 'mp3,m4a,wav,wma';
702
            elseif ( 'text' == $limit_file_type )
703
                $limit_types = 'txt,rtx,csv,tsv';
704
            elseif ( 'any' == $limit_file_type )
705
                $limit_types = '';
706
            else
707
                $limit_types = pods_var( $field[ 'type' ] . '_allowed_extensions', $field[ 'options' ], '', null, true );
708
709
            $limit_types = trim( str_replace( array( ' ', '.', "\n", "\t", ';' ), array( '', ',', ',', ',' ), $limit_types ), ',' );
710
711 View Code Duplication
            if ( pods_version_check( 'wp', '3.5' ) ) {
712
                $mime_types = wp_get_mime_types();
713
714
                if ( in_array( $limit_file_type, array( 'images', 'audio', 'video' ) ) ) {
715
                    $new_limit_types = array();
716
717
                    foreach ( $mime_types as $type => $mime ) {
718
                        if ( 0 === strpos( $mime, $limit_file_type ) ) {
719
                            $type = explode( '|', $type );
720
721
                            $new_limit_types = array_merge( $new_limit_types, $type );
722
                        }
723
                    }
724
725
                    if ( !empty( $new_limit_types ) )
726
                        $limit_types = implode( ',', $new_limit_types );
727
                }
728
                elseif ( 'any' != $limit_file_type ) {
729
                    $new_limit_types = array();
730
731
                    $limit_types = explode( ',', $limit_types );
732
733
                    foreach ( $limit_types as $k => $limit_type ) {
734
                        $found = false;
735
736
                        foreach ( $mime_types as $type => $mime ) {
737
                            if ( 0 === strpos( $mime, $limit_type ) ) {
738
                                $type = explode( '|', $type );
739
740
                                foreach ( $type as $t ) {
741
                                    if ( !in_array( $t, $new_limit_types ) )
742
                                        $new_limit_types[] = $t;
743
                                }
744
745
                                $found = true;
746
                            }
747
                        }
748
749
                        if ( !$found )
750
                            $new_limit_types[] = $limit_type;
751
                    }
752
753
                    if ( !empty( $new_limit_types ) )
754
                        $limit_types = implode( ',', $new_limit_types );
755
                }
756
            }
757
758
            $limit_types = explode( ',', $limit_types );
759
760
            $limit_types = array_filter( array_unique( $limit_types ) );
761
762
            if ( !empty( $limit_types ) ) {
763
                $ok = false;
764
765
                foreach ( $limit_types as $limit_type ) {
766
                    $limit_type = '.' . trim( $limit_type, ' .' );
767
768
                    $pos = ( strlen( $file[ 'name' ] ) - strlen( $limit_type ) );
769
770
                    if ( $pos === stripos( $file[ 'name' ], $limit_type ) ) {
771
                        $ok = true;
772
773
                        break;
774
                    }
775
                }
776
777
                if ( false === $ok ) {
778
                    $error = __( 'File type not allowed, please use one of the following: %s', 'pods' );
779
                    $error = sprintf( $error, '.' . implode( ', .', $limit_types ) );
780
781
                    pods_error( '<div style="color:#FF0000">Error: ' . $error . '</div>' );
782
                }
783
            }
784
785
            $custom_handler = apply_filters( 'pods_upload_handle', null, 'Filedata', $params->post_id, $params, $field );
786
787
            if ( null === $custom_handler ) {
788
                $attachment_id = media_handle_upload( 'Filedata', $params->post_id );
789
790
                if ( is_object( $attachment_id ) ) {
791
                    $errors = array();
792
793
                    foreach ( $attachment_id->errors[ 'upload_error' ] as $error_code => $error_message ) {
794
                        $errors[] = '[' . $error_code . '] ' . $error_message;
795
                    }
796
797
                    pods_error( '<div style="color:#FF0000">Error: ' . implode( '</div><div>', $errors ) . '</div>' );
798
                }
799
                else {
800
                    $attachment = get_post( $attachment_id, ARRAY_A );
801
802
                    $attachment['filename'] = basename( $attachment['guid'] );
803
804
                    $thumb = wp_get_attachment_image_src( $attachment['ID'], 'thumbnail', true );
805
806
                    $attachment['thumbnail'] = '';
807
808
                    if ( ! empty( $thumb[0] ) ) {
809
                        $attachment['thumbnail'] = $thumb[0];
810
                    }
811
812
                    $attachment['link']      = get_permalink( $attachment['ID'] );
813
                    $attachment['edit_link'] = get_edit_post_link( $attachment['ID'] );
814
                    $attachment['download']  = wp_get_attachment_url( $attachment['ID'] );
815
816
                    $attachment = apply_filters( 'pods_upload_attachment', $attachment, $params->post_id );
817
818
                    wp_send_json( $attachment );
819
                }
820
            }
821
        }
822
823
        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...
824
    }
825
}
826