-
Notifications
You must be signed in to change notification settings - Fork 52
/
Copy pathfrontend-uploader.php
1552 lines (1298 loc) · 48.8 KB
/
frontend-uploader.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/*
Plugin Name: Frontend Uploader
Description: Allow your visitors to upload content and moderate it.
Author: Rinat Khaziev, Daniel Bachhuber
Version: 1.3.4
Author URI: https://rinat.dev/
Text Domain: frontend-uploader
Requires at least: 4.6
Requires PHP: 7.2
GNU General Public License, Free Software Foundation <http://creativecommons.org/licenses/GPL/2.0/>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
// Define consts and bootstrap and dependencies
define( 'FU_VERSION', '1.3.4' );
define( 'FU_ROOT' , dirname( __FILE__ ) );
define( 'FU_FILE_PATH' , FU_ROOT . '/' . basename( __FILE__ ) );
define( 'FU_URL' , plugins_url( '/', __FILE__ ) );
define( 'FU_NONCE', 'frontend-uploader-upload-media' );
require_once FU_ROOT . '/lib/php/class-html-helper.php';
require_once FU_ROOT . '/lib/php/settings-api/class.settings-api.php';
require_once FU_ROOT . '/lib/php/functions.php';
require_once FU_ROOT . '/lib/php/frontend-uploader-settings.php';
class Frontend_Uploader {
public $allowed_mime_types;
public $html;
public $settings;
public $settings_slug = 'frontend_uploader_settings';
public $is_debug = false;
public $lang = 'en_US';
public $lang_short = 'en';
/**
* Should consist of fields to be proccessed automatically on content submission
*
* Example field:
* array(
* 'name' => '{form name}',
* 'element' => HTML element,
* 'role' => {title|description|content|file|meta|internal} )
*
* @var array
*/
public $form_fields = array();
protected $manage_permissions = array();
/**
* Here we go
*
* Instantiating the plugin, adding actions, filters, and shortcodes
*/
function __construct() {
// Init
add_action( 'init', array( $this, 'action_init' ) );
// HTML helper to render HTML elements
$this->html = new Html_Helper;
register_activation_hook( __FILE__, array( $this, 'activate_plugin' ) );
}
/**
* Load languages and a bit of paranoia
*/
function action_init() {
// Try to gracefully fallback on default values, as well as merge any potentially new settings coming from an upgrade (:
$this->settings = array_merge( $this->settings_defaults(), (array) get_option( $this->settings_slug, [] ) );
load_plugin_textdomain( 'frontend-uploader', false, dirname( plugin_basename( __FILE__ ) ) . '/languages/' );
// Hooking to wp_ajax
add_action( 'wp_ajax_approve_ugc', array( $this, 'approve_media' ) );
add_action( 'wp_ajax_approve_ugc_post', array( $this, 'approve_post' ) );
add_action( 'wp_ajax_delete_ugc', array( $this, 'delete_post' ) );
add_action( 'wp_ajax_upload_ugc', array( $this, 'upload_content' ) );
add_action( 'wp_ajax_nopriv_upload_ugc', array( $this, 'upload_content' ) );
// Adding media submenu
add_action( 'admin_menu', array( $this, 'add_menu_items' ) );
// Currently supported shortcodes
add_shortcode( 'fu-upload-form', array( $this, 'upload_form' ) );
add_shortcode( 'fu-upload-response', array( $this, 'upload_response_shortcode' ) );
// Since 4.01 we need to explicitly disable texturizing of shortcode's inner content
add_filter( 'no_texturize_shortcodes', array( $this, 'filter_no_texturize_shortcodes' ) );
// Static assets
add_action( 'admin_enqueue_scripts', array( $this, 'admin_enqueue_scripts' ) );
// Unautop the shortcode
add_filter( 'the_content', 'shortcode_unautop', 100 );
// Hiding not approved attachments from Media Gallery
// @since core 3.5-beta-1
add_filter( 'posts_where', array( $this, 'filter_posts_where' ) );
$this->allowed_mime_types = $this->_get_mime_types();
// Configuration filter to change manage permissions
$this->manage_permissions = apply_filters( 'fu_manage_permissions', 'edit_posts' );
// Debug mode filter
$this->is_debug = (bool) apply_filters( 'fu_is_debug', defined( 'WP_DEBUG' ) && WP_DEBUG );
add_action( 'fu_after_upload', array( $this, '_maybe_insert_images_into_post' ), 10, 3 );
$this->_set_language();
// Maybe enable Akismet protection
$this->_enable_akismet_protection();
// Maybe enable Recaptcha protection
$this->_enable_recaptcha_protection();
}
/**
* Set current language (used for captcha and jquery validate l18n )
*/
function _set_language() {
// Filter is needed for wordpress.com
$this->lang = apply_filters( 'fu_wplang', get_bloginfo( 'language' ) );
$this->lang_short = substr( $this->lang, 0, 2 );
}
/**
* Handle MIME-types:
*
* First we check what's in the plugin setting (if there's nothing we're falling back to Core list)
* If we're falling back to core value, make sure to remove HTML and JS files.
* Then we also explicitly try to remove any variant of PHP, just in case.
*
* After that we pass the value to the filter,
* so if somebody really wants to shoot in the foot they can do so.
*
* @return array the list of allowed for uploading mime types
*/
function _get_mime_types() {
// $mime_types_orig is needed to re-map the values from the settings lib structure to core WP extension regex => mime-type format.
remove_filter( 'upload_mimes', [ $this, '_get_mime_types' ], 999 );
$mime_types = $mime_types_orig = get_allowed_mime_types();
add_filter( 'upload_mimes', [ $this, '_get_mime_types' ], 999 );
$enabled = isset( $this->settings['enabled_files'] ) && is_array( $this->settings['enabled_files'] ) && $this->settings['enabled_files'] ? $this->settings['enabled_files'] : $mime_types;
foreach ( $enabled as $ext_key => $mime ) {
// Check for PHP.
if ( false !== strpos( $mime, 'php' ) ) {
unset( $enabled[ $ext_key ] );
trigger_error( __( "Frontend Uploader doesn't support PHP uploads for security reasons", 'frontend-uploader' ) );
}
// We need to re-map the value from our settings to the proper MIME-type instead of regex key for mime check to work correctly.
$enabled[ $ext_key ] = $mime_types_orig[ $ext_key ];
}
unset( $enabled['htm|html'] );
unset( $enabled['js'] );
unset( $enabled['svg|svgz'] );
/**
* Configuration filter: fu_allowed_mime_types should return array of allowed mime types (see readme)
* @param array $enabled the list of enabled mime-types in core-compatible [ 'ext|ext2' => 'mime/type' ] format.
*/
$mime_types = apply_filters( 'fu_allowed_mime_types', $enabled );
return $mime_types;
}
/**
* Ensure we're not producing any notices by supplying the defaults to get_option
*
* @return array $defaults
*/
function settings_defaults() {
$defaults = array();
$settings = Frontend_Uploader_Settings::get_settings_fields();
foreach ( $settings[ $this->settings_slug ] as $setting ) {
$defaults[ $setting['name'] ] = $setting['default'];
}
return $defaults;
}
/**
* Activation hook:
*
* Bail if version is less than 3.3, set default settings
*/
function activate_plugin() {
global $wp_version;
if ( version_compare( $wp_version, '3.3', '<' ) ) {
wp_die( esc_html__( 'Frontend Uploader requires WordPress 3.3 or newer. Please upgrade.', 'frontend-uploader' ) );
}
$defaults = $this->settings_defaults();
$existing_settings = (array) get_option( $this->settings_slug, $this->settings_defaults() );
update_option( $this->settings_slug, array_merge( $defaults, (array) $existing_settings ) );
}
/**
* Since 4.01 shortcode contents is texturized by default,
* avoid the behavior by explicitly whitelisting our shortcode
*/
function filter_no_texturize_shortcodes( $shortcodes ) {
$shortcodes[] = 'fu-upload-form';
return $shortcodes;
}
/**
* Since WP 3.5-beta-1 WP Media interface shows private attachments as well
* We don't want that, so we force WHERE statement to post_status = 'inherit'
*
* @since 0.3
*
* @param string $where WHERE statement
* @return string WHERE statement
*/
function filter_posts_where( $where ) {
if ( !is_admin() || !function_exists( 'get_current_screen' ) )
return $where;
$screen = get_current_screen();
if ( ! defined( 'DOING_AJAX' ) && $screen && isset( $screen->base ) && $screen->base === 'upload' && ( !isset( $_GET['page'] ) || $_GET['page'] !== 'manage_frontend_uploader' ) ) {
$where = str_replace( "post_status = 'private'", "post_status = 'inherit'", $where );
}
return $where;
}
/**
* Determine if we should autoapprove the submission or not
*
* @return boolean [description]
*/
function _is_public() {
return ( current_user_can( 'read' ) && 'on' === $this->settings['auto_approve_user_files'] ) || ( 'on' === $this->settings['auto_approve_any_files'] );
}
/**
* Handle uploading of the files
*
* @since 0.4
*
* @uses media_handle_sideload
*
* @param int $post_id Parent post id
* @return array Combined result of media ids and errors if any
*/
function _upload_files( $post_id = 0 ) {
// Only filter mimes just before the upload.
add_filter( 'upload_mimes', array( $this, '_get_mime_types' ), 999 );
$media_ids = $errors = array();
// Bail if there are no files
if ( empty( $_FILES ) )
return array();
// File field name could be user defined, so we just get the first file
$files = current( $_FILES );
// There can be multiple files
// So we need to iterate over each of the files to process
for ( $i = 0; $i < count( $files['name'] ); $i++ ) {
$fields = array( 'name', 'type', 'tmp_name', 'error', 'size' );
foreach ( $fields as $field ) {
$k[$field] = $files[$field][$i];
}
$k['name'] = sanitize_file_name( $k['name'] );
//
if ( $k['error'] === 4 ) {
continue;
}
// Skip to the next file if upload went wrong
if ( $k['error'] !== 0 ) {
$errors['fu-error-media'][] = array( 'name' => $k['name'], 'code' => $k['error'] );
continue;
}
$typecheck = mime_content_type( $k['tmp_name'] );
// Add an error message if MIME-type is not allowed
if ( ! in_array( $typecheck, (array) $this->allowed_mime_types, true ) ) {
$errors['fu-disallowed-mime-type'][] = array( 'name' => $k['name'], 'mime' => $k['type'] );
continue;
}
// Now let's try to catch eval( base64() ) et al
if ( 0 !== $this->_invoke_paranoia_on_file_contents( file_get_contents( $k['tmp_name'] ) ) ) {
$errors['fu-suspicious-file'][] = array( 'name' => $k['name'] );
continue;
}
// Setup some default values
// However, you can make additional changes on 'fu_after_upload' action
$caption = '';
// Try to set post caption if the field is set on request
// Fallback to post_content if the field is not set
if ( isset( $_POST['caption'] ) )
$caption = sanitize_text_field( $_POST['caption'] );
elseif ( isset( $_POST['post_content'] ) )
$caption = sanitize_text_field( $_POST['post_content'] );
$filename = pathinfo( $k['name'], PATHINFO_FILENAME );
$post_overrides = array(
'post_status' => $this->_is_public() ? 'publish' : 'private',
'post_title' => isset( $_POST['post_title'] ) && ! empty( $_POST['post_title'] ) ? sanitize_text_field( $_POST['post_title'] ) : sanitize_text_field( $filename ),
'post_content' => empty( $caption ) ? __( 'Unnamed', 'frontend-uploader' ) : $caption,
'post_excerpt' => empty( $caption ) ? __( 'Unnamed', 'frontend-uploader' ) : $caption,
);
$m = $k;
// Obfuscate filename if setting is present
if ( isset( $this->settings['obfuscate_file_name'] ) && 'on' === $this->settings['obfuscate_file_name'] ){
$fn = explode( '.', $k['name'] );
$m['name'] = uniqid( wp_rand( 1, 1000 ) , true ) . '.' . end( $fn );
}
// Trying to upload the file
$upload_id = media_handle_sideload( $m, (int) $post_id, $post_overrides['post_title'], $post_overrides );
if ( !is_wp_error( $upload_id ) )
$media_ids[] = $upload_id;
else
$errors['fu-error-media'][] = $k['name'];
}
/**
* $success determines the rest of upload flow
* Setting this to true if no errors were produced even if there's was no files to upload
*/
$success = empty( $errors ) ? true : false;
if ( $success ) {
foreach ( $media_ids as $media_id ) {
$this->_save_post_meta_fields( $media_id );
}
}
// Allow additional setup
// Pass array of attachment ids
do_action( 'fu_after_upload', $media_ids, $success, $post_id );
return array( 'success' => $success, 'media_ids' => $media_ids, 'errors' => $errors );
}
/**
* A callback to append uploaded images html to post
*
* @param array $media_ids [description]
* @param bool $success [description]
* @param int $post_id [description]
* @return mixed [description]
*/
function _maybe_insert_images_into_post( $media_ids, $success, $post_id ) {
// Bail if request is failed,
if ( ! $success || !isset( $_POST[ 'append_to_post' ] ) || !$_POST['append_to_post'] )
return;
$post = get_post( $post_id );
$attachments_html = "\n";
foreach( (array) $media_ids as $media_id ) {
$attachments_html .= wp_get_attachment_image( $media_id, 'full' );
}
// add wp_kses_allowed_html filter just in time before we save post
add_filter( 'wp_kses_allowed_html', array( $this, 'wp_kses_add_srcset' ), 10, 2 );
$post->post_content .= $attachments_html;
return wp_update_post( $post, true );
}
/**
* Force adding srcset as allowed attr for repsonsive images
* @param [type] $tags [description]
* @param [type] $context [description]
* @return [type] [description]
*/
function wp_kses_add_srcset( $tags, $context ) {
if ( $context === 'post' )
$tags['img']['srcset'] = true;
return $tags;
}
/**
* Return count of regex matches for common type of upload attack eval(base64($malicious_payload))
* @param string $str [description]
* @return int count of matches
*/
function _invoke_paranoia_on_file_contents( $str = '' ) {
// Not a string, bail
if ( ! is_string( $str ) )
return 0;
return preg_match_all( '/<\?php|eval\s*\(|base64_decode|gzinflate|gzuncompress/imsU', $str, $matches );
}
/**
* Handle post uploads
*
* @since 0.4
*/
function _upload_post() {
$errors = array();
$success = true;
// Sanitize category if present in request
// Allow to supply comma-separated category ids
$category = array();
if ( isset( $_POST['post_category'] ) ) {
foreach ( explode( ',', $_POST['post_category'] ) as $cat_id ) {
$category[] = (int) $cat_id;
}
}
$post_title = isset( $_POST['caption'] ) ? sanitize_text_field( $_POST['caption'] ) : sanitize_text_field( $_POST['post_title'] );
// Construct post array;
$post_array = array(
'post_type' => isset( $_POST['post_type'] ) && $this->is_allowed_post_type( $_POST['post_type'] ) ? sanitize_key( $_POST['post_type'] ) : 'post',
'post_title' => $post_title ? $post_title : __( 'Untitled post submission', 'frontend-uploader' ),
'post_content' => wp_filter_post_kses( $_POST['post_content'] ),
'post_status' => $this->_is_public() ? 'publish' : 'private',
'post_category' => $category,
);
$author = isset( $_POST['post_author'] ) ? sanitize_text_field( $_POST['post_author'] ) : '';
if ( $author ) {
$users = get_users( array(
'search' => $author,
'fields' => 'ID'
) );
if ( isset( $users[0] ) ) {
$post_array['post_author'] = (int) $users[0];
}
}
$post_array = apply_filters( 'fu_before_create_post', $post_array );
$post_id = wp_insert_post( $post_array, true );
// Something went wrong
if ( is_wp_error( $post_id ) ) {
$errors = array( 'fu-error-post' => 1 );
$success = false;
} else {
do_action( 'fu_after_create_post', $post_id );
$this->_save_post_meta_fields( $post_id );
// If the author name is not in registered users
// Save the author name if it was filled and post was created successfully
if ( $author )
add_post_meta( $post_id, 'author_name', $author );
}
return array( 'success' => $success, 'post_id' => $post_id, 'errors' => $errors );
}
private function _save_post_meta_fields( $post_id = 0 ) {
// Post ID not set, bailing
if ( ! $post_id = (int) $post_id )
return false;
// No meta fields in field mapping, bailing
if ( !isset( $this->form_fields['meta'] ) || empty( $this->form_fields['meta'] ) )
return false;
foreach ( $this->form_fields['meta'] as $meta_field ) {
if ( !isset( $_POST[$meta_field] ) )
continue;
$value = $_POST[$meta_field];
// Sanitize array
if ( is_array( $value ) ) {
$value = array_map( array( $this, '_sanitize_array_element_callback' ), $value );
// Sanitize everything else
} else {
$value = sanitize_text_field( $value );
}
add_post_meta( $post_id, $meta_field, $value, true );
}
}
/**
* Handle post, post+media, or just media files
*
* @since 0.4
*/
function upload_content() {
$fields = $result = array();
// Bail if something fishy is going on
if ( !wp_verify_nonce( $_POST['fu_nonce'], FU_NONCE ) ) {
wp_safe_redirect( add_query_arg( array( 'response' => 'fu-error', 'errors' => array( 'fu-nonce-failure' => 1 ) ), wp_get_referer() ) );
exit;
}
// Bail if supplied post type is not allowed
if ( isset( $_POST['post_type'] ) && ! $this->is_allowed_post_type( sanitize_key( $_POST['post_type'] ) ) ) {
wp_safe_redirect( add_query_arg( array( 'response' => 'fu-error', 'errors' => array( 'fu-disallowed-post-type' => sanitize_key( $_POST['post_type'] ) ) ), wp_get_referer() ) );
exit;
}
$form_post_id = isset( $_POST['form_post_id'] ) ? (int) $_POST['form_post_id'] : 0;
$hash = sanitize_text_field( $_POST['ff'] );
$this->form_fields = !empty( $this->form_fields ) ? $this->form_fields : $this->_get_fields_for_form( $form_post_id, $hash );
$layout = isset( $_POST['form_layout'] ) && ! empty( $_POST['form_layout'] ) ? sanitize_text_field( $_POST['form_layout'] ) : 'image';
/**
* Utility hook 'fu_should_process_content_upload': maybe terminate upload early (useful for Akismet integration, etc)
* Defaults to true, upload will be terminated if set to false.
*
* Parameters:
* boolean - whether should process
* string $layout - which form layout is used
*/
if ( false === apply_filters( 'fu_should_process_content_upload', true, $layout ) ) {
wp_safe_redirect( add_query_arg( array( 'response' => 'fu-spam' ), wp_get_referer() ) );
exit;
}
switch ( $layout ) {
// Upload the post
case 'post':
$result = $this->_upload_post();
break;
// Upload the post first, and then upload media and attach to the post
case 'post_image':
case 'post_media';
$result = $this->_upload_post();
if ( ! is_wp_error( $result['post_id'] ) ) {
$media_result = $this->_upload_files( $result['post_id'] );
// Make sure we don't merge a non-array (_upload_files might return null, false or WP_Error)
if ( is_array( $media_result ) )
$result = array_merge( $result, $media_result );
}
break;
// Upload media
case 'image':
case 'media':
$pid = isset( $_POST['post_ID'] ) ? (int) $_POST['post_ID'] : 0;
$result = $this->_upload_files( $pid );
break;
}
/**
* Process result with filter
*
* @param string $layout form layout
* @param array $result assoc array holding $post_id, $media_ids, bool $success, array $errors
*/
do_action( 'fu_upload_result', $layout, $result );
// Notify the admin via email
$this->_notify_admin( $result );
// Handle error and success messages, and redirect
$this->_handle_result( $result );
exit;
}
/**
* Notify site administrator by email
*/
function _notify_admin( $result = array() ) {
// Email notifications are disabled, or upload has failed, bailing
if ( ! ( 'on' === $this->settings['notify_admin'] && $result['success'] ) )
return;
// TODO: It'd be nice to add the list of upload files
$to = !empty( $this->settings['notification_email'] ) && filter_var( $this->settings['notification_email'], FILTER_VALIDATE_EMAIL ) ? $this->settings['notification_email'] : get_option( 'admin_email' );
$subj = __( 'New content was uploaded on your site', 'frontend-uploader' );
add_filter( 'wp_mail_content_type', 'fu_email_content_type' );
wp_mail( $to, $subj, $this->_get_html_email_template( $result ) );
remove_filter( 'wp_mail_content_type', 'fu_email_content_type' );
}
/**
* Get html template
*
* @since 1.2
*
* @param array $result [description]
* @return [type] [description]
*/
function _get_html_email_template( $result = array() ) {
global $fu_result;
$fu_result = $result;
ob_start();
include_once FU_ROOT . "/lib/views/html-email.tpl.php";
return ob_get_clean();
}
/**
* Process response from upload logic
*
* @since 0.4
*/
function _handle_result( $result = array() ) {
// Redirect to referrer if repsonse is malformed
if ( empty( $result ) || !is_array( $result ) ) {
wp_safe_redirect( wp_get_referer() );
exit;
return;
}
// Either redirect to success page if it's set and valid
// Or to referrer
$url = isset( $_POST['success_page'] ) && filter_var( $_POST['success_page'], FILTER_VALIDATE_URL ) ? esc_url_raw( $_POST['success_page'] ) : wp_get_referer();
// $query_args will hold everything that's needed for displaying notices to user
$query_args = array();
// Account for successful uploads
if ( isset( $result['success'] ) && $result['success'] ) {
// If it's a post
if ( isset( $result['post_id'] ) )
$query_args['response'] = 'fu-post-sent';
// If it's media uploads
if ( isset( $result['media_ids'] ) && !isset( $result['post_id'] ) )
$query_args['response'] = 'fu-sent';
}
// Something went wrong, let's indicate it
if ( !empty( $result['errors'] ) ) {
$query_args['response'] = 'fu-error';
$query_args['errors'] = $result['errors'];
}
/**
* Allow to filter query args before doing the redirect after upload
*/
$query_args = apply_filters( 'fu_upload_result_query_args', $query_args, $result );
// Perform a safe redirect and exit
wp_safe_redirect( add_query_arg( $query_args, $url ) );
exit;
}
/**
* Render various admin template files
*
* @param string $view file slug
* @since 0.4
*/
function render( $view = '' ) {
if ( empty( $view ) )
return;
$this->_set_global_query_for_tables( $view );
require_once ABSPATH . '/wp-admin/includes/class-wp-list-table.php';
require_once ABSPATH . '/wp-admin/includes/class-wp-posts-list-table.php';
require_once ABSPATH . '/wp-admin/includes/class-wp-media-list-table.php';
require_once FU_ROOT . '/lib/php/class-frontend-uploader-wp-media-list-table.php';
require_once FU_ROOT . '/lib/php/class-frontend-uploader-wp-posts-list-table.php';
$file = "lib/views/manage-ugc-{$view}.tpl.php";
// Supply relative path to validate_file as it fails to validate absolute paths on Windows (due to colon)
if ( 0 === validate_file( $file ) && file_exists( FU_ROOT . '/' . $file ) ) {
include_once FU_ROOT . '/' . $file;
} else {
wp_die( esc_html__( "Couldn't find template file", 'frontend-uploader' ) );
}
}
/**
* We need to set global $wp_query in order for list tables to work properly
* @param string $type (media|posts)
*/
private function _set_global_query_for_tables( $type = 'posts' ) {
if ( ! in_array( $type, array( 'posts', 'media' ), true ) )
return false;
$args = array(
'post_status' => array( 'private' ),
'posts_per_page' => 20,
'paged' => isset( $_GET['paged'] ) ? (int) $_GET['paged'] : 1,
);
// Tweak query arguments (set proper post type and post status)
switch( $type ) {
case 'posts':
$args['post_type'] = isset( $_GET['post_type'] ) && $this->is_allowed_post_type( $_GET['post_type'] ) ? sanitize_key( $_GET['post_type'] ) : 'post';
break;
case 'media':
$args['post_type'] = 'attachment';
break;
}
query_posts( $args );
}
/**
* Is post type allowed UGC post type?
* @param string $post_type to check
* @return boolean
*/
function is_allowed_post_type( $post_type = 'post' ) {
return in_array( $post_type, $this->settings['enabled_post_types'], true );
}
/**
* Display media list table
*
* @return [type] [description]
*/
function admin_list() {
$this->render( 'media' );
}
/**
* Display posts/custom post types table
*
* @return [type] [description]
*/
function admin_posts_list() {
$this->render( 'posts' );
}
/**
* Add submenu items
*/
function add_menu_items() {
add_media_page( __( 'Manage UGC', 'frontend-uploader' ), __( 'Manage UGC', 'frontend-uploader' ), $this->manage_permissions, 'manage_frontend_uploader', array( $this, 'admin_list' ) );
foreach ( (array) $this->settings['enabled_post_types'] as $cpt ) {
if ( $cpt === 'post' ) {
add_posts_page( __( 'Manage UGC Posts', 'frontend-uploader' ), __( 'Manage UGC', 'frontend-uploader' ), $this->manage_permissions, 'manage_frontend_uploader_posts', array( $this, 'admin_posts_list' ) );
continue;
}
add_submenu_page( "edit.php?post_type={$cpt}", __( 'Manage UGC Posts', 'frontend-uploader' ), __( 'Manage UGC', 'frontend-uploader' ), $this->manage_permissions, "manage_frontend_uploader_{$cpt}s", array( $this, 'admin_posts_list' ) );
}
}
/**
* Approve a media file
*
* @return [type] [description]
*/
function approve_media() {
// Check permissions, attachment ID, and nonce
if ( false === $this->_check_perms_and_nonce() || 0 === (int) $_GET['id'] ) {
wp_safe_redirect( get_admin_url( null, 'upload.php?page=manage_frontend_uploader&error=id_or_perm' ) );
exit;
}
$post = get_post( (int) $_GET['id'] );
if ( is_object( $post ) && $post->post_status === 'private' ) {
$post->post_status = 'inherit';
wp_update_post( $post );
do_action( 'fu_media_approved', $post );
$this->update_gallery_shortcode( $post->post_parent, $post->ID );
wp_safe_redirect( get_admin_url( null, 'upload.php?page=manage_frontend_uploader&approved=1' ) );
exit;
}
wp_safe_redirect( get_admin_url( null, 'upload.php?page=manage_frontend_uploader' ) );
exit;
}
/**
* TODO: refactor in 0.6
*
* @return [type] [description]
*/
function approve_post() {
// check for permissions and id
$url = get_admin_url( null, 'edit.php?page=manage_frontend_uploader_posts&error=id_or_perm' );
if ( !current_user_can( $this->manage_permissions ) || intval( $_GET['id'] ) === 0 ) {
wp_safe_redirect( $url );
exit;
}
$post = get_post( (int) $_GET['id'] );
if ( is_object( $post ) ) {
$post->post_status = 'publish';
wp_update_post( $post );
do_action( 'fu_post_approved', $post );
// Check if there's any UGC attachments
$attachments = get_children( 'post_type=attachment&post_parent=' . $post->ID );
foreach ( (array) $attachments as $image_id => $attachment ) {
$attachment->post_status = "inherit";
wp_update_post( $attachment );
}
// Override query args
$qa = array(
'page' => "manage_frontend_uploader_{$post->post_type}s",
'approved' => 1,
'post_type' => $post->post_type !== 'post' ? $post->post_type : '',
);
$url = add_query_arg( $qa, get_admin_url( null, "edit.php" ) );
}
wp_safe_redirect( $url );
exit;
}
/**
* Delete post and redirect to referrer
*
* @return [type] [description]
*/
function delete_post() {
if ( $this->_check_perms_and_nonce() && 0 !== (int) $_GET['id'] ) {
if ( wp_delete_post( (int) $_GET['id'], true ) )
$args['deleted'] = 1;
}
wp_safe_redirect( add_query_arg( $args, wp_get_referer() ) );
exit;
}
/**
* Handles security checks
*
* @return bool
*/
function _check_perms_and_nonce() {
return current_user_can( $this->manage_permissions ) && wp_verify_nonce( $_REQUEST['fu_nonce'], FU_NONCE );
}
/**
* Shortcode callback for inner content of [fu-upload-form] shortcode
*
* @param array $atts shortcode attributes
* @param unknown $content not used
* @param string $tag
*/
function shortcode_content_parser( $atts, $content = null, $tag ) {
$atts = shortcode_atts( array(
'id' => isset( $atts['name'] ) ? 'ugc-input-' . sanitize_key( $atts['name'] ) : '' ,
'name' => '',
'description' => '',
'help' => '',
'value' => '',
'type' => '',
'class' => '',
'multiple' => false,
'required' => false,
'aria-required' => false,
'values' => '',
'wysiwyg_enabled' => isset( $this->settings['wysiwyg_enabled'] ) && 'on' === $this->settings['wysiwyg_enabled'] ,
'role' => 'meta',
'minlength' => '',
'maxlength' => '',
), $atts );
extract( $atts );
$role = in_array( $role, array( 'meta', 'title', 'description', 'author', 'internal', 'content' ), true ) ? $role : 'meta';
$name = sanitize_text_field( $name );
// Add the field to fields map
$this->form_fields[$role][] = $name;
// Render the element if render callback is available
$callback = array( $this, "_render_{$tag}" );
if ( is_callable( $callback ) )
return call_user_func( $callback, $atts );
}
/**
* Input element callback
*
* @param array shortcode attributes
* @return string formatted html element
*/
function _render_input( $atts ) {
extract( $atts );
// Workaround for HTML5 multiple attribute
if ( (bool) $multiple === false )
unset( $atts['multiple'] );
// Allow multiple file upload by default.
// To do so, we need to add array notation to name field: []
if ( !strpos( $name, '[]' ) && $type === 'file' )
$name = 'files' . '[]';
$input = $this->html->input( $type, $name, $value, $atts );
// No need for wrappers or labels for hidden input
if ( $type === 'hidden' )
return $input;
$label = $this->html->element( 'label', $description , array( 'for' => $id ), false );
$help = isset( $help ) && $help ? $this->html->element( 'p', sanitize_text_field( $help ), array( 'class' => 'ugc-help' ) ) : '';
return $this->html->element( 'div', $label . $input . $help, array( 'class' => 'ugc-input-wrapper' ), false );
}
/**
* Textarea element callback
*
* @param array shortcode attributes
* @return string formatted html elemen
*/
function _render_textarea( $atts ) {
extract( $atts );
$help = isset( $help ) && $help ? $this->html->element( 'p', sanitize_text_field( $help ), array( 'class' => 'ugc-help' ) ) : '';
$label = $this->html->element( 'label', $description , array( 'for' => $id ), false );
// Render WYSIWYG textarea
if ( $wysiwyg_enabled ) {
ob_start();
wp_editor( '', $id, array(
'textarea_name' => $name,
'media_buttons' => false,
'teeny' => true,
'quicktags' => false,
) );
$tiny = ob_get_clean();
return $this->html->element( 'div', $label . $tiny . $help, array( 'class' => 'ugc-input-wrapper' ), false ) ;
}
$element = $this->html->element( 'textarea', '', array( 'name' => $name, 'id' => $id, 'class' => $class, 'minlength' => $minlength, 'maxlength' => $maxlength, 'required' => $required ) );
// Render plain textarea
$label = $this->html->element( 'label', $description, array( 'for' => $id ), false );
return $this->html->element( 'div', $label . $element . $help, array( 'class' => 'ugc-input-wrapper' ), false );
}
/**
* Checkboxes element callback
*
* @param array shortcode attributes
* @return [type] [description]
*/
function _render_checkboxes( $atts ) {
extract( $atts );
$values = explode( ',', $values );
$options = '';
$help = isset( $help ) && $help ? $this->html->element( 'p', sanitize_text_field( $help ), array( 'class' => 'ugc-help' ) ) : '';
// Making sure we're having array of values for checkboxes
if ( false === stristr( '[]', $name ) )
$name = $name . '[]';
//Build options for the list
foreach ( $values as $option ) {
$kv = explode( ":", $option );
$options .= $this->html->_checkbox( $name, isset( $kv[1] ) ? $kv[1] : $kv[0], $kv[0], $atts, array() );
}
$description = $label = $this->html->element( 'label', $description, array(), false );