PluginProbe
Booking Manager – Sync WP Booking Calendar – Import Events, Export Bookings to ICS Calendar / trunk
Booking Manager – Sync WP Booking Calendar – Import Events, Export Bookings to ICS Calendar vtrunk
2.1.20 2.1.4 2.1.5 2.1.6 2.1.7 2.1.8 2.1.9 trunk 1.1 2.0 2.0.1 2.0.10.2 2.0.11 2.0.12 2.0.13 2.0.14 2.0.15 2.0.16 2.0.17 2.0.18 2.0.2 2.0.20 2.0.21 2.0.22 2.0.23 All 54 releases
booking-manager / core / wpbm-upload.php

wpbm-upload.php in Booking Manager – Sync WP Booking Calendar – Import Events, Export Bookings to ICS Calendar trunk, at core/wpbm-upload.php

593 lines 19.0 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * @version 1.0
4 * @package File Upload
5 * @subpackage Support Upload Functions
6 * @category Functions
7 *
8 * @author wpdevelop
9 * @link https://oplugins.com/
10 * @email info@oplugins.com
11 *
12 * @modified 2017-04-14
13 */
14
15 if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
16
17
18 /** Code usage in other places for Upload, Selection and Insertion of file URL
19 *
20 <div>
21 <input type="text" value="" wrap="off" placeholder="..." class="wpbm_file_urls" name="wpbm_file_urls" />
22 <a href="javascript:void(0)" class="button wpbm_btn_upload"
23 data-modal_title="<?php echo esc_attr( __( 'Choose file', 'booking-manager' ) ); ?>"
24 data-btn_title="<?php echo esc_attr( __( 'Insert file URL', 'booking-manager' ) ); ?>"
25 ><?php _e( 'Upload File', 'booking-manager' ); ?></a>
26 </div>
27 <?php
28
29 $wpbm_upload = wpbm_upload(); // Get WPBM_Upload obj instance
30
31 $wpbm_upload->set_upload_button( '.wpbm_btn_upload' );
32
33 $wpbm_upload->set_element_insert_url( '.wpbm_file_urls' );
34 ?>
35 *
36 */
37
38 // General Init Class
39 final class WPBM_Upload {
40
41 public $settings = array(
42 'upload_button' => ''
43 , 'element_insert_url' => ''
44 , 'wp_media_uploader_params' => array( 'key' => 'wpbm_type', 'value' => 'wpbm_upload' ) // Required for setting OUR Dir for uploading and set it PROTECTED
45 );
46
47 // Define only one instance of this class
48 static private $instance = NULL;
49
50 public static function init() {
51
52 if ( ! isset( self::$instance ) && ! ( self::$instance instanceof WPBM_Upload ) ) {
53
54 self::$instance = new WPBM_Upload;
55
56
57
58 add_action( 'admin_footer', array( self::$instance, 'js' ), 50 ); // Load JavaScript Code at the footer of the Admin Panel page. Executed in ALL Admin Menu Pages
59
60 //TODO: remove this
61 // add_filter( 'posts_where', array( self::$instance, 'wpbm_filter_posts_where' ) );
62 // add_action('pre_get_posts', array( self::$instance, 'wpbm_pre_get_posts' ) );
63
64 // Uncomment these 2 lines, if need to use protected folder
65 // add_filter( 'upload_dir', array( self::$instance, 'filter_upload_dir' ) );
66 // self::$instance->protect_upload_dir();
67 }
68 return self::$instance;
69 }
70
71
72 /** Get Name of protected DIR name, like wpbm_XXXXX
73 *
74 * @return string
75 */
76 public function get_protected_dir_name() {
77
78 $get_protected_dir_name = get_wpbm_option( 'wpbm_protected_directory_name_level1' );
79
80 if ( empty( $get_protected_dir_name ) ) {
81 $get_protected_dir_name = 'wpbm_' . wp_generate_password( 20, false, false );
82 update_wpbm_option( 'wpbm_protected_directory_name_level1', $get_protected_dir_name );
83 }
84
85 $get_protected_dir_name = untrailingslashit($get_protected_dir_name);
86
87 return $get_protected_dir_name;
88 }
89
90
91 /** Get all settings or specific setting option
92 *
93 * @param string $key
94 * @return mixed
95 */
96 public function get_settings( $key = '' ) {
97
98 if ( '' === $key )
99 return $this->settings;
100
101 if ( isset( $this->settings[ $key ] ) )
102 return $this->settings[ $key ];
103 else
104 return false;
105 }
106
107
108 //TODO: remove this
109 /*
110 function wpbm_pre_get_posts( $query ) {
111 debuge_log( $_POST );
112 if ( is_admin() || ! $query->is_main_query() ) {
113 return;
114 }
115
116 $discount = $query->get( 'discount' );
117
118 if ( ! empty( $discount ) ) {
119
120 // unset ref var from $wp_query
121 $query->set( 'discount', null );
122
123 global $wp;
124
125 // unset ref var from $wp
126 unset( $wp->query_vars[ 'discount' ] );
127
128 // if in home (because $wp->query_vars is empty) and 'show_on_front' is page
129 if ( empty( $wp->query_vars ) && get_option( 'show_on_front' ) === 'page' ) {
130
131 // reset and re-parse query vars
132 $wp->query_vars['page_id'] = get_option( 'page_on_front' );
133 $query->parse_query( $wp->query_vars );
134
135 }
136
137 }
138
139 }
140 */
141
142 //TODO: remove this
143 /**
144 * @param string $where Where clause
145 * @return string $where Modified where clause
146 */
147 /*
148 function wpbm_filter_posts_where( $where = '' ) {
149
150 debuge_log( $_POST );
151 return $where;
152 //debuge( maybe_unserialize( 'a:3:{s:6:"action";s:17:"query-attachments";s:7:"post_id";s:1:"0";s:5:"query";a:4:{s:7:"orderby";s:4:"date";s:5:"order";s:4:"DESC";s:14:"posts_per_page";s:2:"40";s:5:"paged";s:1:"1";}}' ));
153
154 $media_uploader_params = $this->get_settings( 'wp_media_uploader_params' );
155 if ( ( isset( $_POST['query'] ) )
156 && ( isset( $_POST['query'][ $media_uploader_params[ 'key' ] ] ) )
157 && ( $media_uploader_params[ 'value' ] === $_POST['query'][ $media_uploader_params[ 'key' ] ] )
158 ) {
159
160 global $wpdb;
161 $where .= " AND guid LIKE '%".$wpdb->esc_like( untrailingslashit( get_wpbm_option( 'wpbm_protected_directory_name_level1' ) ) )."%'";
162 }
163 return $where;
164 }
165 */
166
167 /** Filters the uploads directory array,
168 * after CLICKING on our Upload Button and USE our wp.media thanks to 'wp_media_uploader_params'
169 *
170 * @param array $uploads Array of upload directory data:
171 array (
172 [path] => Z:\home\new\www/wp-content/uploads/wpbm_lSJacOT1yVLFnrkqt2xR/2017/04
173 [url] => http://new/wp-content/uploads/wpbm_lSJacOT1yVLFnrkqt2xR/2017/04
174
175 [subdir] => /wpbm_lSJacOT1yVLFnrkqt2xR/2017/04
176 [basedir] => Z:\home\new\www/wp-content/uploads
177
178 [baseurl] => http://new/wp-content/uploads
179 [error] =>
180 )
181
182 *$uploads = apply_filters( 'upload_dir', $cache[ $key ] );
183 *
184 * @param type $param
185 */
186 public function filter_upload_dir( $param ) {
187
188 //TODO: here we can create own TAGs and Versioning directory structure in some way.
189
190 $media_uploader_params = $this->get_settings( 'wp_media_uploader_params' );
191
192 if ( isset( $_POST[ $media_uploader_params[ 'key' ] ] ) && $media_uploader_params[ 'value' ] === $_POST[ $media_uploader_params[ 'key' ] ] ) {
193
194 $protected_dir_name = $this->get_protected_dir_name();
195
196 if ( empty( $param['subdir'] ) ) {
197
198 $param['path'] = $param['path'] . '/' . $protected_dir_name;
199 $param['url'] = $param['url'] . '/' . $protected_dir_name;
200 $param['subdir'] = '/' . $protected_dir_name;
201
202 } else {
203 $new_subdir = '/' . $protected_dir_name . $param['subdir'];
204
205 $param['path'] = str_replace( $param['subdir'], $new_subdir, $param['path'] );
206 $param['url'] = str_replace( $param['subdir'], $new_subdir, $param['url'] );
207 $param['subdir'] = str_replace( $param['subdir'], $new_subdir, $param['subdir'] );
208 }
209 }
210
211 return $param;
212 }
213
214
215 /** Get path to protected dir.
216 *
217 * @return type
218 */
219 public function get_protected_dir() {
220
221 // Protected secret name LEVEL 1
222 $dir_level1 = $this->get_protected_dir_name();
223
224 // Install files and folders for uploading files and prevent hotlinking
225 $upload_dir = wp_upload_dir();
226
227 return $upload_dir['basedir'] . '/' . $dir_level1;
228 }
229
230
231 /** Check and Protect upload folder each time
232 *
233 * May be we need to have 2 folders, like /wpbm_xxxxx/XXXXXXXXXXXXX
234 * for prevent of dir listing at previous stage /wpbm_xxxxx with .htaccess file
235 *
236 * Typical Directory structure
237 * /wp-content/uploads/
238 * /wpbm_xxxxx {main dir}
239 * /.htaccess (Deny access and deny dir listing)
240 * /.index.php (Silence is golden)
241 * /XXXXXXXXXXXXX (Secret dir for store files)
242 */
243 function protect_upload_dir() {
244
245 // Protected secret name LEVEL 1
246 $dir_level1 = $this->get_protected_dir_name();
247
248 // Install files and folders for uploading files and prevent hotlinking
249 $upload_dir = wp_upload_dir();
250
251 $files = array(
252 array(
253 'base' => $upload_dir['basedir'] . '/' . $dir_level1,
254 'file' => '.htaccess',
255 'content' => 'Options -Indexes' . "\n"
256 . 'deny from all'
257 )
258 , array(
259 'base' => $upload_dir['basedir'] . '/' . $dir_level1,
260 'file' => 'index.php',
261 'content' => '<?php ' . "\n"
262 . '// Silence is golden.'
263
264 )
265 );
266
267 foreach ( $files as $file ) {
268
269 if ( ( wp_mkdir_p( $file['base'] ) ) // Recursive directory creation based on full path.
270 && ( ! file_exists( trailingslashit( $file['base'] ) . $file['file'] ) ) // If file not exist
271 ) {
272
273 if ( $file_handle = @fopen( trailingslashit( $file['base'] ) . $file['file'], 'w' ) ) {
274
275 fwrite( $file_handle, $file['content'] );
276 fclose( $file_handle );
277 }
278 }
279 }
280 }
281
282
283
284 /** Define element for opening wp media after clicking
285 *
286 * @param string $jq_selector
287 */
288 public function set_upload_button( $jq_selector ) {
289 $this->settings['upload_button'] = $jq_selector;
290 }
291
292
293 /** Define element for inserting URL of file from wp media
294 *
295 * @param type $jq_selector
296 */
297 public function set_element_insert_url( $jq_selector ) {
298 $this->settings['element_insert_url'] = $jq_selector;
299 }
300
301
302 public function js() {
303
304 //set JavaScript only if we set upload button
305 $jq_sel_upload_button = $this->get_settings( 'upload_button' );
306
307 if ( empty( $jq_sel_upload_button ) )
308 return;
309
310
311 ?>
312 <!-- WPBM JavaScript -->
313 <script type="text/javascript">
314 var wpbm_file_frame;
315 (function($){
316 //'use strict';
317 <?php $media_uploader_params = $this->get_settings( 'wp_media_uploader_params' ); ?>
318 // Our wp media frame
319
320
321 jQuery( '<?php echo $this->get_settings('upload_button'); ?>' ).on( 'click', function( event ) {
322
323 var j_btn = jQuery( this );
324 var is_multi_selection = ! true;
325
326 var insert_field_separator = '<?php $wpbm_csv_separator = get_wpbm_option( 'wpbm_csv_separator' ); echo empty( $wpbm_csv_separator ) ? ',' : $wpbm_csv_separator; ?>';
327
328 // Stop the anchor's default behavior
329 event.preventDefault();
330
331 // If frame exist close it
332 if ( wpbm_file_frame ) {
333 wpbm_file_frame.close();
334 }
335
336
337 ///////////////////////////////////////////////////////////////////////
338 // Create Media Frame
339 ///////////////////////////////////////////////////////////////////////
340 wpbm_file_frame = wp.media.frames.wpbm_upload_file_frame = wp.media( { // Check here ../wp-includes/js/media-views.js
341 // Set the title of the modal.
342 title: j_btn.data( 'modal_title' ),
343 library: {
344 type: ''
345 },
346 button: {
347 text: j_btn.data( 'btn_title' ),
348 },
349 multiple: is_multi_selection,
350 states: [
351 new wp.media.controller.Library( {
352 <?php
353 // Add to this libaray custom post parameter: $_POST['query'][ $media_uploader_params['key'] ] = $media_uploader_params['value']
354 // We are checking in functon wpbm_filter_posts_where media files that only relative to this medi Frame opening
355 // And filtering posts (in WHERE) relative custom path to our files.
356 // echo '{' . $media_uploader_params['key'] . ": '" . $media_uploader_params['value'] . "' }";
357 ?>
358 library: wp.media.query(),
359 multiple: is_multi_selection,
360 title: j_btn.data( 'modal_title' ),
361 priority: 15,
362 filterable: 'uploaded',
363 //idealColumnWidth: 125
364 } )
365 ]
366 } );
367
368
369 ///////////////////////////////////////////////////////////////////////
370 // Set custom parameters for uploader -> $_POST['wpbm_type'] - checking in "upload_dir", when filter_upload_dir
371 ///////////////////////////////////////////////////////////////////////
372 wpbm_file_frame.on( 'ready', function () {
373 wpbm_file_frame.uploader.options.uploader.params = {
374 type: 'wpbm_download',
375 <?php
376 echo $media_uploader_params['key'] . ": '" . $media_uploader_params['value'] . "'";
377 ?>
378 };
379 } );
380
381
382 ///////////////////////////////////////////////////////////////////////
383 // When File have selected, do this
384 ///////////////////////////////////////////////////////////////////////
385 wpbm_file_frame.on( 'select', function () {
386
387 if ( ! is_multi_selection ) { // Single file
388
389 var attachment = wpbm_file_frame.state().get('selection').first().toJSON();
390 console.log(attachment);
391 // Put URL of file to text field
392 j_btn.parent().find('<?php echo $this->get_settings('element_insert_url'); ?>').val( attachment.url );
393 console.log( j_btn.parent().find('<?php echo $this->get_settings('element_insert_url'); ?>') );
394
395 } else { // Multiple files.
396
397 var file_paths = '';
398 var csv_data_line = '';
399 wpbm_file_frame.state().get('selection').map( function ( attachment ) {
400
401 // Request new data
402 //attachment.fetch().then(function (data) {
403 // console.log(data);
404 // // preloading finished
405 // // after this you can use your attachment normally
406 // //wp.media.attachment( attachment.id ).get('url');
407 //});
408
409 attachment = attachment.toJSON();
410 //console.log( attachment );
411
412 if ( attachment.url ) {
413 // Insert info from selected files
414 csv_data_line = attachment.id + insert_field_separator + attachment.title + insert_field_separator + attachment.wpbm_version_num + insert_field_separator + attachment.description + insert_field_separator + attachment.url
415 file_paths = file_paths ? file_paths + "\n" + csv_data_line : csv_data_line;
416 }
417
418 // file_paths = file_paths ? file_paths + "\n" + attachment.url : attachment.url;
419 });
420
421 //j_btn.parent().find('<?php echo $this->get_settings('element_insert_url'); ?>').val( file_paths );
422 jQuery( '#wpbm_products_csv_text' ).val( file_paths + "\n\n" + jQuery( '#wpbm_products_csv_text' ).val() );
423 }
424
425 } );
426
427 if (0) {
428 /** Remove Dom element of Media element from Media browser, if the URL not from our settings.
429 *
430 * @param {type} my_model_obj
431 * @returns {undefined}
432 */
433 function wpbm_remove_media_element_from_container( my_model_obj , delay_time ) {
434
435 /** Attributes:
436 'id': 112
437 'title': __71
438 'filename': 71.zip
439 'url': http://server.com/wp-content/uploads/wpbm_lSJacOT1yVLFnrkqt2xR/2017/04/71.zip'
440 'link': http://server.com/__71/'
441 'alt':
442 'author': 1
443 'description':
444 'caption':
445 'name': __71
446 'status': inherit
447 'uploadedTo': 0
448 'date': Mon Apr 17 2017 14:30:32
449 'modified': Mon Apr 17 2017 14:30:32
450 'menuOrder': 0
451 'mime': application/zip
452 'type': application
453 'subtype': zip
454 'icon': http://server.com/wp-includes/images/media/archive.png
455 'dateFormatted': April 17, 2017
456 'nonces': [object Object]
457 'editLink': http://server.com/wp-admin/post.php?post=112&action=edit
458 'meta': false
459 'authorName': admin_name
460 'filesizeInBytes': 324104
461 'filesizeHumanReadable': 317 KB
462 'compat': [object Object]
463 */
464
465 // Sometimes need some delay
466 _.delay( function() {
467
468 if ( my_model_obj.attributes.url != undefined ) {
469 if ( my_model_obj.attributes.url.indexOf('/<?php echo $this->get_protected_dir_name(); ?>/') === -1 ) {
470 //console.log( my_model_obj.attributes.url );
471 //wp.media.model.Attachment.get("collection").collection.remove( my_model_obj );
472
473 jQuery( "li[data-id='" + my_model_obj.attributes.id + "']" ).remove();
474 }
475 }
476
477 }, delay_time );
478
479 }
480
481 wp.media.model.Attachment.get("collection").collection.on( 'change', function( my_model_obj ) {
482 wpbm_remove_media_element_from_container( my_model_obj , 1);
483 });
484
485 // Fires, when Content redraw
486 wpbm_file_frame.on( 'content:activate:browse', function(){
487
488 var wpbm_models = wp.media.model.Attachment.get("collection").collection.models;
489
490 _.each( wpbm_models, function( my_model_obj, ind) {
491
492 wpbm_remove_media_element_from_container( my_model_obj , 1 );
493 });
494 });
495 }
496
497 /*
498 // Fires when a state activates.
499 wpbm_file_frame.on( 'activate', function() { alert('activate'); } );
500
501 // Fires after the frame markup has been built, but not appended to the DOM.
502 // @see wp.media.view.Modal.attach()
503 wpbm_file_frame.on( 'ready', function() { alert('ready'); } );
504
505 // Fires when the frame's $el is appended to its DOM container.
506 // @see media.view.Modal.attach()
507 wpbm_file_frame.on( 'attach', function() { alert('attach'); } );
508
509 // Fires when the modal opens (becomes visible).
510 // @see media.view.Modal.open()
511 wpbm_file_frame.on( 'open', function() { alert('open'); } );
512
513 // Fires when the modal closes via the escape key.
514 // @see media.view.Modal.close()
515 wpbm_file_frame.on( 'escape', function() { alert('escape'); } );
516
517 // Fires when the modal closes.
518 // @see media.view.Modal.close()
519 wpbm_file_frame.on( 'close', function() { alert('close'); } );
520
521 // Fires when a user has selected attachment(s) and clicked the select button.
522 // @see media.view.MediaFrame.Post.mainInsertToolbar()
523 wpbm_file_frame.on( 'select', function() {
524 var selectionCollection = wpbm_file_frame.state().get('select');
525 } );
526
527 // Fires when a mode is deactivated on a region { 'menu' | title | content | toolbar | router }
528 wpbm_file_frame.on( 'content:deactivate', function() { alert('{region}:deactivate'); } );
529 // and a more specific event including the mode.
530 wpbm_file_frame.on( 'content:deactivate:{mode}', function() { alert('{region}:deactivate{mode}'); } );
531
532 // Fires when a region is ready for its view to be created.
533 wpbm_file_frame.on( 'content:create', function() { alert('{region}:create'); } );
534 // and a more specific event including the mode.
535 wpbm_file_frame.on( 'content:create:{mode}', function() { alert('{region}:create{mode}'); } );
536
537 // Fires when a region is ready for its view to be rendered.
538 wpbm_file_frame.on( 'content:render', function() { alert('{region}:render'); } );
539 // and a more specific event including the mode.
540 wpbm_file_frame.on( 'content:render:{mode}', function() { alert('{region}:render{mode}'); } );
541
542 // Fires when a new mode is activated (after it has been rendered) on a region.
543 wpbm_file_frame.on( 'content:activate', function() { alert('{region}:activate'); } );
544 // and a more specific event including the mode.
545 wpbm_file_frame.on( 'content:activate:{mode}', function() { alert('{region}:activate{mode}'); } );
546
547 // Get an object representing the current state.
548 //wpbm_file_frame.state();
549
550 // Get an object representing the previous state.
551 //wpbm_file_frame.lastState();
552 */
553
554 if(0) {
555 // Debuge all events from media Frame!
556 wpbm_file_frame.on("all", function(eventName) {
557 console.log('Frame Event: ' + eventName);
558 });
559
560 // Debuge all events from media Frame!
561 wp.media.model.Attachment.get("collection").collection.on("all", function(eventName) {
562 console.log('[Collection] Event: ' + eventName);
563 });
564 wp.media.model.Attachment.get("models").collection.on( "all", function(eventName) {
565 console.log('[models] Event: ' + eventName);
566 });
567 wp.media.model.Attachment.get("views").collection.on( "all", function(eventName) {
568 console.log('[views] Event: ' + eventName);
569 });
570 }
571 // Open the modal.
572 wpbm_file_frame.open();
573 });
574
575 })(jQuery);
576
577 </script>
578 <!-- End WPBM JavaScript -->
579 <?php
580
581 }
582 }
583
584
585 /**
586 * The main function responsible for returning the one true Instance to functions everywhere.
587 *
588 * Example: <?php $wpbm_upload = wpbm_upload(); ?>
589 */
590 function wpbm_upload() {
591 return WPBM_Upload::init();
592 }
593 wpbm_upload(); // Start