PluginProbe
FileBird – WordPress Media Library Folders & File Manager / 5.5
FileBird – WordPress Media Library Folders & File Manager v5.5
6.5.8 6.5.7 6.5.5 6.5.4 trunk 4.3.1 5.1.6 5.3 5.3.2 5.4.3 5.4.4 5.4.5 5.5 5.5.3 5.5.5 5.5.8 5.5.8.1 5.6 5.6.1 5.6.2 5.6.3 5.6.4 6.2.3 6.2.5 6.3 All 36 releases
filebird / includes / Controller / Folder.php

Folder.php in FileBird – WordPress Media Library Folders & File Manager 5.5, at includes/Controller/Folder.php

872 lines 27.3 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 namespace FileBird\Controller;
4
5 use FileBird\Controller\Convert as ConvertController;
6 use FileBird\Classes\Convert as ConvertModel;
7 use FileBird\Controller\Exclude;
8 use FileBird\Controller\UserSettings;
9 use FileBird\Controller\FolderUser;
10 use FileBird\Controller\Api;
11
12 use FileBird\Model\Folder as FolderModel;
13 use FileBird\Classes\Helpers as Helpers;
14 use FileBird\Classes\Tree;
15 use FileBird\Controller\Attachment\SizeMeta;
16
17 use FileBird\I18n as I18n;
18 use FileBird\Page\Settings;
19
20 defined( 'ABSPATH' ) || exit;
21
22 /**
23 * Folder Controller
24 */
25
26 class Folder extends Controller {
27 protected static $instance = null;
28 private $userSettings = null;
29
30 public static function getInstance() {
31 if ( null == self::$instance ) {
32 self::$instance = new self();
33 self::$instance->doHooks();
34 }
35 return self::$instance;
36 }
37
38 public function __construct() { }
39
40 private function doHooks() {
41 add_filter( 'media_library_infinite_scrolling', '__return_true' );
42 add_filter( 'ajax_query_attachments_args', array( $this, 'ajaxQueryAttachmentsArgs' ), 20 );
43 add_filter( 'mla_media_modal_query_final_terms', array( $this, 'ajaxQueryAttachmentsArgs' ), 20 );
44 add_filter( 'restrict_manage_posts', array( $this, 'restrictManagePosts' ) );
45 add_filter( 'posts_clauses', array( $this, 'postsClauses' ), 10, 2 );
46 add_filter( 'attachment_fields_to_save', array( $this, 'attachment_fields_to_save' ), 10, 2 );
47
48 add_action( 'admin_enqueue_scripts', array( $this, 'enqueueAdminScripts' ), PHP_INT_MAX );
49 add_action( 'rest_api_init', array( $this, 'registerRestFields' ) );
50 add_action( 'add_attachment', array( $this, 'addAttachment' ) );
51 add_action( 'delete_attachment', array( $this, 'deleteAttachment' ) );
52 add_action( 'pre-upload-ui', array( $this, 'actionPluploadUi' ) );
53 add_action( 'wp_ajax_fbv_first_folder_notice', array( $this, 'ajax_first_folder_notice' ) );
54 // add_action( 'wp_ajax_fbv_close_buy_pro_dialog', array($this, 'ajaxCloseBuyProDialog'));
55 add_action( 'admin_notices', array( $this, 'adminNotices' ) );
56 add_action( 'attachment_fields_to_edit', array( $this, 'attachment_fields_to_edit' ), 10, 2 );
57
58 add_filter( 'wp_edited_image_metadata', array( $this, 'edited_image_metadata' ), 10, 3 );
59
60 $this->userSettings = UserSettings::getInstance();
61
62 // MailPoet plugin support
63 SizeMeta::getInstance()->doHooks();
64 new Exclude();
65 new Api();
66 new FolderUser();
67
68 $this->check_update_database();
69
70 add_filter( 'mailpoet_conflict_resolver_whitelist_script', array( $this, 'mailpoet_conflict_resolver_whitelist_script' ), 10, 1 );
71 add_filter( 'mailpoet_conflict_resolver_whitelist_style', array( $this, 'mailpoet_conflict_resolver_whitelist_style' ), 10, 1 );
72
73 add_filter( 'users_have_additional_content', array( $this, 'users_have_additional_content' ), 10, 2 );
74 add_action( 'deleted_user', array( $this, 'deleted_user' ), 10, 3 );
75 }
76
77 public function mailpoet_conflict_resolver_whitelist_script( $scripts ) {
78 $scripts[] = 'filebird';
79 $scripts[] = 'filebird-pro';
80 return $scripts;
81 }
82
83 public function mailpoet_conflict_resolver_whitelist_style( $styles ) {
84 $styles[] = 'filebird';
85 $styles[] = 'filebird-pro';
86 return $styles;
87 }
88
89 public function adminNotices() {
90 global $pagenow;
91
92 $optionFirstFolder = get_option( 'fbv_first_folder_notice' );
93 if ( FolderModel::countFolder() === 0 && $pagenow !== 'upload.php' &&
94 ( $optionFirstFolder === false || time() >= intval( $optionFirstFolder ) ) ) {
95 include NJFB_PLUGIN_PATH . '/views/notices/html-notice-first-folder.php';
96 }
97
98 if ( $pagenow !== 'upload.php' && apply_filters( 'fbv_update_database_notice', false ) ) {
99 include NJFB_PLUGIN_PATH . '/views/notices/html-notice-update-database.php';
100 }
101 }
102
103 public function ajax_first_folder_notice() {
104 check_ajax_referer( 'fbv_nonce', 'nonce', true );
105 update_option( 'fbv_first_folder_notice', time() + 30 * 60 * 60 * 24 ); //After 3 months show
106 wp_send_json_success();
107 }
108
109 public function check_update_database() {
110 if( is_admin() ) {
111 $is_converted = get_option( 'fbv_old_data_updated_to_v4', '0' );
112 if ( $is_converted !== '1' ) {
113 if ( ConvertController::countOldFolders() > 0 && ! isset( $_GET['autorun'] ) ) {
114 add_filter( 'fbv_update_database_notice', '__return_true' );
115 }
116 }
117 }
118 }
119
120 public function registerRestFields() {
121 register_rest_route(
122 NJFB_REST_URL,
123 'get-folders',
124 array(
125 'methods' => 'GET',
126 'callback' => array( $this, 'ajaxGetFolder' ),
127 'permission_callback' => array( $this, 'resPermissionsCheck' ),
128 )
129 );
130 register_rest_route(
131 NJFB_REST_URL,
132 'gutenberg-get-folders',
133 array(
134 'methods' => 'GET',
135 'callback' => array( $this, 'ajaxGutenbergGetFolder' ),
136 'permission_callback' => array( $this, 'resPermissionsCheck' ),
137 )
138 );
139
140 register_rest_route(
141 NJFB_REST_URL,
142 'new-folder',
143 array(
144 'methods' => 'POST',
145 'callback' => array( $this, 'ajaxNewFolder' ),
146 'permission_callback' => array( $this, 'resPermissionsCheck' ),
147 )
148 );
149 register_rest_route(
150 NJFB_REST_URL,
151 'update-folder',
152 array(
153 'methods' => 'POST',
154 'callback' => array( $this, 'ajaxUpdateFolder' ),
155 'permission_callback' => array( $this, 'resPermissionsCheck' ),
156 )
157 );
158 register_rest_route(
159 NJFB_REST_URL,
160 'update-folder-ord',
161 array(
162 'methods' => 'POST',
163 'callback' => array( $this, 'ajaxUpdateFolderOrd' ),
164 'permission_callback' => array( $this, 'resPermissionsCheck' ),
165 )
166 );
167 register_rest_route(
168 NJFB_REST_URL,
169 'delete-folder',
170 array(
171 'methods' => 'POST',
172 'callback' => array( $this, 'ajaxDeleteFolder' ),
173 'permission_callback' => array( $this, 'resPermissionsCheck' ),
174 )
175 );
176 register_rest_route(
177 NJFB_REST_URL,
178 'set-folder-attachments',
179 array(
180 'methods' => 'POST',
181 'callback' => array( $this, 'ajaxSetFolder' ),
182 'permission_callback' => array( $this, 'resPermissionsCheck' ),
183 )
184 );
185 register_rest_route(
186 NJFB_REST_URL,
187 'generate-attachment-size',
188 array(
189 'methods' => \WP_REST_Server::CREATABLE,
190 'callback' => array( SizeMeta::getInstance(), 'apiCallback' ),
191 'permission_callback' => array( $this, 'resPermissionsCheck' ),
192 )
193 );
194 register_rest_route(
195 NJFB_REST_URL,
196 'update-tree',
197 array(
198 'methods' => 'POST',
199 'callback' => array( $this, 'ajaxUpdateTree' ),
200 'permission_callback' => array( $this, 'resPermissionsCheck' ),
201 )
202 );
203 register_rest_route(
204 NJFB_REST_URL,
205 'get-relations',
206 array(
207 'methods' => 'POST',
208 'callback' => array( $this, 'ajaxGetRelations' ),
209 'permission_callback' => array( $this, 'resPermissionsCheck' ),
210 )
211 );
212 register_rest_route(
213 NJFB_REST_URL,
214 'set-settings',
215 array(
216 'methods' => 'POST',
217 'callback' => array( $this, 'ajaxSetSettings' ),
218 'permission_callback' => array( $this, 'resPermissionsCheck' ),
219 )
220 );
221
222 register_rest_route(
223 NJFB_REST_URL,
224 'export-csv',
225 array(
226 'methods' => 'GET',
227 'callback' => array( $this, 'exportCSV' ),
228 'permission_callback' => array( $this, 'resPermissionsCheck' ),
229 )
230 );
231
232 register_rest_route(
233 NJFB_REST_URL,
234 'import-csv',
235 array(
236 'methods' => 'POST',
237 'callback' => array( $this, 'importCSV' ),
238 'permission_callback' => array( $this, 'resPermissionsCheck' ),
239 )
240 );
241
242 register_rest_route(
243 NJFB_REST_URL,
244 'import-csv-detail',
245 array(
246 'methods' => \WP_REST_Server::CREATABLE,
247 'callback' => array( $this, 'getImportCSVDetail' ),
248 'permission_callback' => array( $this, 'resPermissionsCheck' ),
249 )
250 );
251 }
252 public function resPermissionsCheck() {
253 return current_user_can( 'upload_files' );
254 }
255
256 public function enqueueAdminScripts( $screenId ) {
257 if ( function_exists( 'get_current_screen' ) ) {
258 if ( $screenId == 'upload.php' ) {
259 wp_register_script( 'jquery-resizable', NJFB_PLUGIN_URL . 'assets/js/jquery-resizable.min.js' );
260 wp_enqueue_script( 'jquery-resizable' );
261 }
262 }
263
264 if ( $screenId !== 'pagebuilders' ) {
265 wp_enqueue_script( 'fbv-setting', NJFB_PLUGIN_URL . 'assets/js/setting.js', array( 'jquery' ), NJFB_VERSION, false );
266 }
267
268 if ( $screenId === Settings::getInstance()->settingPageSuffix ) {
269 wp_enqueue_style( 'fbv-pro-tippy', NJFB_PLUGIN_URL . 'assets/css/tippy.min.css', array(), NJFB_VERSION );
270 }
271
272 wp_enqueue_script( 'jquery-ui-draggable' );
273 wp_enqueue_script( 'jquery-ui-droppable' );
274
275 if ( wp_is_mobile() ) {
276 wp_enqueue_script( 'jquery-touch-punch-fixed', NJFB_PLUGIN_URL . 'assets/js/jquery.ui.touch-punch.js', array( 'jquery-ui-widget', 'jquery-ui-mouse' ), NJFB_VERSION, false );
277 }
278
279 wp_enqueue_script( 'fbv-folder', NJFB_PLUGIN_URL . 'assets/dist/js/app.js', array(), NJFB_VERSION, false );
280 wp_enqueue_script( 'fbv-lib', NJFB_PLUGIN_URL . 'assets/js/jstree/jstree.min.js', array(), NJFB_VERSION, false );
281
282 wp_enqueue_style( 'fbv-folder', NJFB_PLUGIN_URL . 'assets/dist/css/app.css', array(), NJFB_VERSION );
283 wp_style_add_data( 'fbv-folder', 'rtl', 'replace' );
284
285 wp_localize_script(
286 'fbv-folder',
287 'fbv_data',
288 apply_filters(
289 'fbv_data',
290 array(
291 'nonce' => wp_create_nonce( 'fbv_nonce' ),
292 'rest_nonce' => wp_create_nonce( 'wp_rest' ),
293 'nonce_error' => __( 'Your request can\'t be processed.', 'filebird' ),
294 'current_folder' => ( ( isset( $_GET['fbv'] ) ) ? (int) sanitize_text_field( $_GET['fbv'] ) : -1 ), //-1: all files. 0: uncategorized
295 'folders' => FolderModel::allFolders( 'id as term_id, name as term_name', array( 'term_id', 'term_name' ) ),
296 'relations' => FolderModel::getRelations(),
297 'is_upload_screen' => 'upload.php' === $screenId ? '1' : '0',
298 'i18n' => I18n::getTranslation(),
299 'media_mode' => get_user_option( 'media_library_mode', get_current_user_id() ),
300 'json_url' => apply_filters( 'filebird_json_url', rtrim( rest_url( NJFB_REST_URL ), '/' ) ),
301 'media_url' => admin_url( 'upload.php' ),
302 'asset_url' => NJFB_PLUGIN_URL . 'assets/',
303 'auto_import_url' => esc_url(
304 add_query_arg(
305 array(
306 'page' => 'filebird-settings',
307 'tab' => 'tools',
308 'autorun' => 'true',
309 ),
310 admin_url( 'admin.php' )
311 )
312 ),
313 'pll_lang' => apply_filters( 'fbv_pll_lang', '' ),
314 'is_new_user' => get_option( 'fbv_is_new_user', false ),
315 'import_other_plugins' => ConvertModel::getInstance()->get_plugin3rd_folders_to_import(),
316 'import_other_plugins_url' => esc_url(
317 add_query_arg(
318 array(
319 'page' => 'filebird-settings',
320 'tab' => 'import',
321 ),
322 admin_url( 'admin.php' )
323 )
324 ),
325 'update_database_notice' => apply_filters( 'fbv_update_database_notice', false ),
326 'utils' => new \stdClass(),
327 // 'close_buy_pro_dialog' => time() < get_option('fbv_close_buy_pro_dialog', time())
328 )
329 )
330 );
331 }
332
333 public function restrictManagePosts() {
334 $screen = get_current_screen();
335 if ( $screen->id == 'upload' ) {
336 $fbv = ( ( isset( $_GET['fbv'] ) ) ? (int) sanitize_text_field( $_GET['fbv'] ) : -1 );
337 $folders = FolderModel::allFolders();
338
339 $all = new \stdClass();
340 $all->id = -1;
341 $all->name = __( 'All Folders', 'filebird' );
342
343 $uncategorized = new \stdClass();
344 $uncategorized->id = 0;
345 $uncategorized->name = __( 'Uncategorized', 'filebird' );
346
347 array_unshift( $folders, $all, $uncategorized );
348 echo '<select name="fbv" id="filter-by-fbv" class="fbv-filter attachment-filters fbv">';
349 foreach ( $folders as $k => $folder ) {
350 echo sprintf( '<option value="%1$d" %3$s>%2$s</option>', $folder->id, $folder->name, selected( $folder->id, $fbv, false ) );
351 }
352 echo '</select>';
353 }
354 }
355
356 public function postsClauses( $clauses, $query ) {
357 global $wpdb;
358 if ( $query->get( 'post_type' ) !== 'attachment' ) {
359 return $clauses;
360 }
361
362 if ( Helpers::isListMode() && ! isset( $_GET['fbv'] ) ) {
363 return $clauses;
364 }
365
366 $fbvPropery = $query->get( 'fbv' );
367
368 if ( isset( $_GET['fbv'] ) || $fbvPropery !== '' ) {
369 $fbv = isset( $_GET['fbv'] ) ? (int) sanitize_text_field( $_GET['fbv'] ) : (int) $fbvPropery;
370
371 if ( $fbv === -1 ) {
372 return $clauses;
373 } elseif ( $fbv === 0 ) {
374 $clauses = FolderModel::getRelationsWithFolderUser( $clauses );
375 } else {
376 $clauses['join'] .= $wpdb->prepare( " LEFT JOIN {$wpdb->prefix}fbv_attachment_folder AS fbva ON fbva.attachment_id = {$wpdb->posts}.ID AND fbva.folder_id = %d ", $fbv );
377 $clauses['where'] .= ' AND fbva.folder_id IS NOT NULL';
378 }
379 }
380 return $clauses;
381 }
382 public function addAttachment( $post_id ) {
383 $fbv = ( ( isset( $_REQUEST['fbv'] ) ) ? sanitize_text_field( $_REQUEST['fbv'] ) : '' );
384 if ( $fbv != '' ) {
385 if ( is_numeric( $fbv ) ) {
386 $parent = $fbv;
387 } else {
388 $fbv = explode( '/', ltrim( rtrim( $fbv, '/' ), '/' ) );
389 $parent = (int) $fbv[0];
390 if ( $parent < 0 ) {
391 $parent = 0; //important
392 }
393 if ( apply_filters( 'fbv_auto_create_folders', true ) ) {
394 unset( $fbv[0] );
395 foreach ( $fbv as $k => $v ) {
396 $parent = FolderModel::newOrGet( $v, $parent );
397 }
398 }
399 }
400 FolderModel::setFoldersForPosts( $post_id, $parent );
401 }
402 }
403 public function deleteAttachment( $post_id ) {
404 FolderModel::deleteFoldersOfPost( $post_id );
405 }
406
407 public function ajaxQueryAttachmentsArgs( $query ) {
408 if ( isset( $_REQUEST['query']['fbv'] ) ) {
409 $fbv = $_REQUEST['query']['fbv'];
410 if ( is_array( $fbv ) ) {
411 $fbv = array_map( 'intval', $fbv );
412 } else {
413 $fbv = intval( $fbv );
414 }
415 $query['fbv'] = $fbv;
416 }
417 return $query;
418 }
419 public function ajaxGetFolder( $request ) {
420 $icl_lang = $request->get_param( 'icl_lang' );
421 $pll_lang = $request->get_param( 'pll_lang' );
422 $sort = sanitize_text_field( $request->get_param( 'sort' ) );
423
424 $order_by = null;
425 $sort_option = 'reset';
426
427 $lang = null;
428
429 if ( ! is_null( $icl_lang ) ) {
430 $lang = $icl_lang;
431 }
432 if ( ! is_null( $pll_lang ) ) {
433 $lang = $pll_lang;
434 }
435
436 if ( \in_array( $sort, array( 'name_asc', 'name_desc', 'reset' ) ) ) {
437 if ( 'name_asc' === $sort ) {
438 $order_by = 'LENGTH(name) ASC, name ASC';
439 $sort_option = $sort;
440 } elseif ( 'name_desc' === $sort ) {
441 $order_by = 'LENGTH(name) DESC, name DESC';
442 $sort_option = $sort;
443 }
444 update_option( 'njt_fb_sort_folder', $sort_option );
445 } else {
446 $njt_fb_sort_folder = get_option( 'njt_fb_sort_folder', 'reset' );
447 if ( $njt_fb_sort_folder === 'reset' ) {
448 $order_by = null;
449 } elseif ( $njt_fb_sort_folder === 'name_asc' ) {
450 $order_by = 'name asc';
451 } elseif ( $njt_fb_sort_folder === 'name_desc' ) {
452 $order_by = 'name desc';
453 }
454 }
455
456 $tree = Tree::getFolders( $order_by, false );
457
458 wp_send_json_success(
459 array(
460 'tree' => $tree,
461 'folder_count' => array(
462 'total' => Tree::getCount( -1, $lang ),
463 'folders' => Tree::getAllFoldersAndCount( $lang ),
464 ),
465 )
466 );
467 }
468 public function ajaxGutenbergGetFolder() {
469 $_folders = Tree::getFolders( null, true, 0, true );
470 $folders = array(
471 array(
472 'value' => 0,
473 'label' => __( 'Please choose folder', 'filebird' ),
474 'disabled' => true,
475 ),
476 );
477 foreach ( $_folders as $k => $v ) {
478 $folders[] = array(
479 'value' => $v['id'],
480 'label' => $v['text'],
481 );
482 }
483
484 wp_send_json_success( $folders );
485 }
486 public function ajaxNewFolder( $request ) {
487 $name = $request->get_param( 'name' );
488 $parent = $request->get_param( 'parent' );
489 $name = isset( $name ) ? sanitize_text_field( wp_unslash( $name ) ) : '';
490 $parent = isset( $parent ) ? sanitize_text_field( $parent ) : '';
491 if ( $name != '' && $parent != '' ) {
492 $insert = FolderModel::newOrGet( $name, $parent, false );
493 if ( $insert !== false ) {
494 wp_send_json_success( array( 'id' => $insert ) );
495 } else {
496 wp_send_json_error( array( 'mess' => __( 'A folder with this name already exists. Please choose another one.', 'filebird' ) ) );
497 }
498 } else {
499 wp_send_json_error(
500 array(
501 'mess' => __( 'Validation failed', 'filebird' ),
502 )
503 );
504 }
505 }
506 public function ajaxUpdateFolder( $request ) {
507 $id = $request->get_param( 'id' );
508 $parent = $request->get_param( 'parent' );
509 $name = $request->get_param( 'name' );
510
511 $id = isset( $id ) ? sanitize_text_field( $id ) : '';
512 $parent = isset( $parent ) ? intval( sanitize_text_field( $parent ) ) : '';
513 $name = isset( $name ) ? sanitize_text_field( wp_unslash( $name ) ) : '';
514 if ( is_numeric( $id ) && is_numeric( $parent ) && $name != '' ) {
515 $update = FolderModel::updateFolderName( $name, $parent, $id );
516 if ( $update === true ) {
517 wp_send_json_success();
518 } else {
519 wp_send_json_error( array( 'mess' => __( 'A folder with this name already exists. Please choose another one.', 'filebird' ) ) );
520 }
521 }
522 wp_send_json_error();
523 }
524 public function ajaxUpdateFolderOrd( $request ) {
525 $id = $request->get_param( 'id' );
526 $parent = $request->get_param( 'parent' );
527 $ord = $request->get_param( 'ord' );
528
529 $id = isset( $id ) ? sanitize_text_field( $id ) : '';
530 $parent = isset( $parent ) ? sanitize_text_field( wp_unslash( $parent ) ) : '';
531 $ord = isset( $ord ) ? sanitize_text_field( wp_unslash( $ord ) ) : '';
532 if ( is_numeric( $id ) && is_numeric( $parent ) && is_numeric( $ord ) ) {
533 FolderModel::updateOrdAndParent( $id, $ord, $parent );
534 wp_send_json_success();
535 }
536 wp_send_json_error();
537 }
538 public function ajaxDeleteFolder( $request ) {
539 $ids = $request->get_param( 'ids' );
540 $ids = isset( $ids ) ? Helpers::sanitize_array( $ids ) : '';
541 if ( $ids != '' ) {
542 if ( ! is_array( $ids ) ) {
543 $ids = array( $ids );
544 }
545 $ids = array_map( 'intval', $ids );
546
547 foreach ( $ids as $k => $v ) {
548 if ( $v > 0 ) {
549 FolderModel::deleteFolderAndItsChildren( $v );
550 }
551 }
552 wp_send_json_success();
553 }
554 wp_send_json_error(
555 array(
556 'mess' => __( 'Can\'t delete folder, please try again later', 'filebird' ),
557 )
558 );
559 }
560 public function ajaxSetFolder( $request ) {
561 $ids = $request->get_param( 'ids' );
562 $folder = $request->get_param( 'folder' );
563
564 $ids = isset( $ids ) ? Helpers::sanitize_array( $ids ) : '';
565 $folder = isset( $folder ) ? sanitize_text_field( $folder ) : '';
566 if ( $ids != '' && is_array( $ids ) && is_numeric( $folder ) ) {
567 FolderModel::setFoldersForPosts( $ids, $folder );
568 wp_send_json_success();
569 }
570 wp_send_json_error(
571 array(
572 'mess' => __( 'Validation failed', 'filebird' ),
573 )
574 );
575 }
576 public function ajaxUpdateTree( $request ) {
577 $tree = $request->get_param( 'tree' );
578
579 $tree = isset( $tree ) ? sanitize_text_field( $tree ) : '';
580 if ( $tree != '' ) {
581 $tree = preg_replace( '#[^0-9,()]#', '', $tree );
582 FolderModel::rawInsert( '(id, ord, parent) VALUES ' . $tree . ' ON DUPLICATE KEY UPDATE ord=VALUES(ord),parent=VALUES(parent)' );
583 wp_send_json_success(
584 array(
585 'mess' => __( 'Folder tree has been updated.', 'filebird' ),
586 )
587 );
588 }
589 wp_send_json_error(
590 array(
591 'mess' => __( 'Validation failed', 'filebird' ),
592 )
593 );
594 }
595 public function ajaxGetRelations() {
596 wp_send_json_success(
597 array(
598 'relations' => FolderModel::getRelations(),
599 )
600 );
601 }
602 public function ajaxSetSettings( $request ) {
603 $folder_id = $request->get_param( 'folder_id' );
604
605 $folder_id = isset( $folder_id ) ? intval( $folder_id ) : -1;
606 $this->userSettings->setDefaultSelectedFolder( $folder_id );
607 wp_send_json_success();
608 }
609
610 public function attachment_fields_to_edit( $form_fields, $post ) {
611 $screen = null;
612 if ( function_exists( 'get_current_screen' ) ) {
613 $screen = get_current_screen();
614
615 if ( ! is_null( $screen ) && 'attachment' === $screen->id ) {
616 return $form_fields;
617 }
618 }
619
620 $fbv_folder = FolderModel::getFolderFromPostId( $post->ID );
621 $fbv_folder = count( $fbv_folder ) > 0 ? $fbv_folder[0] : (object) array(
622 'folder_id' => 0,
623 'name' => __( 'Uncategorized', 'filebird' ),
624 );
625 $form_fields['fbv'] = array(
626 'html' => "<div class='fbv-attachment-edit-wrapper' data-folder-id='{$fbv_folder->folder_id}' data-attachment-id='{$post->ID}'><input readonly type='text' value='{$fbv_folder->name}'/></div>",
627 'label' => esc_html__( 'FileBird folder:', 'filebird' ),
628 'helps' => esc_html__( 'Click on the button to move this file to another folder', 'filebird' ),
629 'input' => 'html',
630 );
631
632 return $form_fields;
633 }
634
635 public function attachment_fields_to_save( $post, $attachment ) {
636 if ( isset( $attachment['fbv'] ) ) {
637 FolderModel::setFoldersForPosts( $post['ID'], $attachment['fbv'] );
638 }
639 return $post;
640 }
641
642 public function edited_image_metadata( $new_image_meta, $new_attachment_id, $attachment_id ) {
643 $folder = FolderModel::getFolderFromPostId( $attachment_id );
644 if( is_array( $folder ) && count( $folder ) > 0 ) {
645 if( (int) $folder[0]->folder_id > 0 ) {
646 FolderModel::setFoldersForPosts( $new_attachment_id, (int) $folder[0]->folder_id );
647 }
648 }
649 return $new_image_meta;
650 }
651 private static function addFolderToZip( &$zip, $children, $parent_dir = '' ) {
652 foreach ( $children as $k => $v ) {
653 $folder_name = $v->name;
654 $folder_id = $v->id;
655
656 // $folder_name = sanitize_title( $folder_name );
657
658 $attachment_ids = Helpers::getAttachmentIdsByFolderId( $folder_id );
659 $empty_dir = $parent_dir != '' ? $parent_dir . '/' . $folder_name : $folder_name;
660 $zip->addEmptyDir( $empty_dir );
661
662 foreach ( $attachment_ids as $k => $id ) {
663 $file = get_attached_file( $id );
664 if ( $file ) {
665 $zip->addFile( $file, $empty_dir . '/' . \basename( $file ) );
666 }
667 }
668 if ( \is_array( $v->children ) ) {
669 self::addFolderToZip( $zip, $v->children, $empty_dir );
670 }
671 }
672 }
673 public function actionPluploadUi() {
674 $this->loadView( 'particle/folder_dropdown' );
675 }
676 private function _buildQuery( $tree, $parent ) {
677 $results = array();
678 $ord = 0;
679 foreach ( $tree as $k => $v ) {
680 // if($v['key'] < 1) continue;
681 $results[] = sprintf( '(%1$d, %2$d, %3$d)', $v['id'], $ord, $parent );
682 if ( isset( $v['children'] ) && is_array( $v['children'] ) && count( $v['children'] ) > 0 ) {
683 $children = $this->_buildQuery( $v['children'], $v['id'] );
684 foreach ( $children as $k2 => $v2 ) {
685 $results[] = $v2;
686 }
687 }
688 $ord++;
689 }
690 return $results;
691 }
692
693 public function getFlatTree( $data = array(), $parent = 0, $default = null, $level = 0 ) {
694 $tree = is_null( $default ) ? array() : $default;
695 foreach ( $data as $k => $v ) {
696 if ( $v->parent == $parent ) {
697 $node = array(
698 'title' => str_repeat( '-', $level ) . $v->name,
699 'value' => $v->id,
700 );
701 $tree[] = $node;
702 $children = $this->getFlatTree( $data, $v->id, null, $level + 1 );
703 foreach ( $children as $k2 => $child ) {
704 $tree[] = $child;
705 }
706 }
707 }
708 return $tree;
709 }
710
711 public function exportCSV() {
712 global $wpdb;
713
714 $folders = $wpdb->get_results( "SELECT * FROM {$wpdb->prefix}fbv", ARRAY_A );
715 $attachmentIds = $wpdb->get_results( "SELECT folder_id, GROUP_CONCAT(attachment_id SEPARATOR '|') as attachment_ids FROM {$wpdb->prefix}fbv_attachment_folder GROUP BY (folder_id)", OBJECT_K );
716
717 foreach ( $folders as $key => $folder ) {
718 $folders[ $key ]['attachment_ids'] = $attachmentIds[ $folder['id'] ]->attachment_ids ? $attachmentIds[ $folder['id'] ]->attachment_ids : '';
719 }
720
721 return new \WP_REST_Response( array( 'folders' => $folders ) );
722 }
723
724 public function buildTree( array &$data, $parentId = 0 ) {
725 $tree = array();
726 foreach ( $data as &$node ) {
727 if ( $node['parent'] == $parentId ) {
728 $children = $this->buildTree( $data, $node['id'] );
729 if ( $children ) {
730 $node['children'] = $children;
731 }
732 $tree[] = $node;
733 unset( $node );
734 }
735 }
736 return $tree;
737 }
738
739 public function run_import_folders( $folders, $parent = 0 ) {
740 $folders_created = array();
741
742 foreach ( $folders as $folder ) {
743 $new_folder_id = FolderModel::newOrGet( $folder['name'], $parent );
744 $attachment_ids = ! empty( $folder['attachment_ids'] ) ? explode( '|', $folder['attachment_ids'] ) : false;
745 array_push( $folders_created, $folder['id'] );
746
747 if ( $attachment_ids && false !== $new_folder_id ) {
748 FolderModel::setFoldersForPosts( $attachment_ids, $new_folder_id );
749 }
750
751 if ( isset( $folder['children'] ) && count( $folder['children'] ) > 0 ) {
752 $new_child_folders = $this->run_import_folders( $folder['children'], $new_folder_id );
753 $folders_created = array_merge( $folders_created, $new_child_folders );
754 }
755 }
756
757 return $folders_created;
758 }
759
760 public function restoreFolderStructure( $folders ) {
761 $tree = $this->buildTree( $folders );
762 $folders_created = $this->run_import_folders( $tree );
763
764 $mess = sprintf( __( 'Congratulations! We imported successfully %d folders into <strong>FileBird.</strong>', 'filebird' ), count( $folders_created ) );
765
766 return new \WP_REST_Response( array( 'mess' => $mess ) );
767 }
768
769 public function readCSV( \WP_REST_Request $request ) {
770 $params = $request->get_file_params();
771 $handle = \fopen( $params['file']['tmp_name'], 'r' );
772 $data = array();
773 $columns = array();
774 if ( false !== $handle ) {
775 $count = 1;
776 while ( 1 ) {
777 $row = fgetcsv( $handle, 0 );
778 if ( 1 === $count ) {
779 $columns = $row;
780 $count++;
781 continue;
782 }
783 if ( false === $row ) {
784 break;
785 }
786 foreach ( $columns as $key => $col ) {
787 $tmp[ $col ] = $row[ $key ];
788 }
789 $data[] = $tmp;
790 }
791 }
792 \fclose( $handle );
793
794 $check = array_diff(
795 $columns,
796 array(
797 'id',
798 'name',
799 'parent',
800 'type',
801 'ord',
802 'created_by',
803 'attachment_ids',
804 )
805 );
806
807 if ( count( $check ) > 0 ) {
808 return new \WP_REST_Response(
809 array(
810 'success' => false,
811 'message' => __( 'The uploaded file was not generated by FileBird. Please check again.', 'filebird' ),
812 )
813 );
814 }
815
816 return $data;
817 }
818
819 public function importCSV( \WP_REST_Request $request ) {
820 $data = $this->readCSV( $request );
821 $createdBy = intval( $request->get_param( 'userId' ) );
822
823 if ( $createdBy != '-1' ) {
824 $data = array_filter(
825 $data,
826 function( $item ) use ( $createdBy ) {
827 return $item['created_by'] == $createdBy;
828 }
829 );
830 }
831
832 $result = $this->restoreFolderStructure( $data );
833
834 return new \WP_REST_Response( array( 'success' => $result ) );
835 }
836
837 public function getImportCSVDetail( \WP_REST_Request $request ) {
838 $data = $this->readCSV( $request );
839
840 $users = \get_users(
841 array(
842 'include' => array_unique( array_column( $data, 'created_by' ) ),
843 )
844 );
845
846 $usersReturn = array();
847
848 foreach ( $users as $user ) {
849 $usersReturn[ $user->ID ] = $user->data->display_name . ' ' . __( 'folders', 'filebird' );
850 }
851
852 return new \WP_REST_Response( $usersReturn );
853 }
854
855 public function deleted_user( $id, $reassign, $user ) {
856 if ( $reassign === null ) {
857 FolderModel::deleteByAuthor( $id );
858 } else {
859 FolderModel::updateAuthor( $id, (int) $reassign );
860 }
861 }
862 public function users_have_additional_content( $users_have_content, $userids ) {
863 global $wpdb;
864 if ( $userids && ! $users_have_content ) {
865 if ( $wpdb->get_var( "SELECT id FROM {$wpdb->prefix}fbv WHERE created_by IN( " . implode( ',', $userids ) . ' ) LIMIT 1' ) ) {
866 $users_have_content = true;
867 }
868 }
869 return $users_have_content;
870 }
871 }
872