PluginProbe
Media Library Folders / trunk
Media Library Folders vtrunk
8.3.9 8.0.6 8.0.7 8.1.0 8.1.1 8.1.2 8.1.3 8.1.4 8.1.5 8.1.6 8.1.7 8.1.8 8.1.9 8.2.0 8.2.1 8.2.2 8.2.3 8.2.4 8.2.5 8.2.6 8.2.7 8.2.8 8.2.9 8.3.0 8.3.1 All 160 releases
media-library-plus / media-library-plus.php

media-library-plus.php in Media Library Folders trunk, at media-library-plus.php

8,234 lines 313.1 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /*
3 Plugin Name: Media Library Folders
4 Plugin URI: https://maxgalleria.com
5 Description: Gives you the ability to adds folders and move files in the WordPress Media Library.
6 Version: 8.3.9
7 Author: Max Foundry
8 Author URI: https://maxfoundry.com
9
10 Copyright 2015-2022 Max Foundry, LLC (https://maxfoundry.com)
11 */
12
13 if(defined('MAXGALLERIA_MEDIA_LIBRARY_VERSION_KEY')) {
14 wp_die(esc_html__('You must deactivate Media Library Folders before activating Media Library Folders Pro', 'maxgalleria-media-library'));
15 }
16
17 include_once(__DIR__ . '/includes/attachments.php');
18
19 class MGMediaLibraryFolders {
20
21 public $upload_dir;
22 public $wp_version;
23 public $theme_mods;
24 public $uploads_folder_name;
25 public $uploads_folder_name_length;
26 public $uploads_folder_ID;
27 public $blog_id;
28 public $base_url_length;
29 public $disable_scaling;
30 public $current_user_can_upload;
31 public $current_user_manage_options;
32 public $sync_skip_webp;
33 public $bda;
34 public $protected_content_dir;
35 public $bda_user_role;
36 public $bda_folder_id;
37 public $bdp_autoprotect;
38 public $capability;
39 public $display_fe_protected_images;
40 public $prevent_right_click;
41
42
43 public function __construct() {
44
45 $this->blog_id = 0;
46 $this->set_global_constants();
47 $this->set_activation_hooks();
48 $this->setup_hooks();
49 $this->upload_dir = wp_upload_dir();
50 $this->wp_version = get_bloginfo('version');
51 $this->base_url_length = strlen($this->upload_dir['baseurl']) + 1;
52
53 $this->uploads_folder_name = get_option(MAXGALLERIA_MEDIA_LIBRARY_UPLOAD_FOLDER_NAME, "uploads");
54 $this->uploads_folder_name_length = strlen($this->uploads_folder_name);
55 $this->uploads_folder_ID = get_option(MAXGALLERIA_MEDIA_LIBRARY_UPLOAD_FOLDER_ID, 0);
56 $this->sync_skip_webp = get_option(MLFP_SKIP_WEBP_FILES, 'off');
57
58 $this->bda = get_option(MLFP_BDA, 'off');
59 $this->protected_content_dir = $this->upload_dir['basedir'] . '/' . MLFP_PROTECTED_DIRECTORY;
60 $this->bda_user_role = get_option(MLFP_BDA_USER_ROLE, 'admins');
61 $this->bdp_autoprotect = get_option(MLFP_BDA_AUTO_PROTECT, 'off');
62 $this->display_fe_protected_images = get_option(MLFP_BDA_DISPLAY_FE_IMAGES, 'off');
63 $this->prevent_right_click = get_option(MLFP_BDA_PREVENT_RIGHT_CLICK, 'off');
64
65 //convert theme mods into an array
66 $theme_mods = get_theme_mods();
67 $this->theme_mods = json_decode(json_encode($theme_mods), true);
68
69 add_option( MAXGALLERIA_MEDIA_LIBRARY_SORT_ORDER, '0' );
70 add_option( MAXGALLERIA_MLF_SORT_TYPE, 'ASC' );
71 add_option( MAXGALLERIA_MEDIA_LIBRARY_MOVE_OR_COPY, 'on' );
72
73 }
74
75
76 public function set_global_constants() {
77 define('MAXGALLERIA_MEDIA_LIBRARY_VERSION_KEY', 'maxgalleria_media_library_version');
78 define('MAXGALLERIA_MEDIA_LIBRARY_VERSION_NUM', '8.3.9');
79 define('MAXGALLERIA_MEDIA_LIBRARY_IGNORE_NOTICE', 'maxgalleria_media_library_ignore_notice');
80 define('MAXGALLERIA_MEDIA_LIBRARY_PLUGIN_NAME', trim(dirname(plugin_basename(__FILE__)), '/'));
81 if(!defined('MAXGALLERIA_MEDIA_LIBRARY_PLUGIN_DIR'))
82 define('MAXGALLERIA_MEDIA_LIBRARY_PLUGIN_DIR', WP_PLUGIN_DIR . '/' . MAXGALLERIA_MEDIA_LIBRARY_PLUGIN_NAME);
83 if(!defined('MAXGALLERIA_MEDIA_LIBRARY_PLUGIN_URL'))
84 define('MAXGALLERIA_MEDIA_LIBRARY_PLUGIN_URL', plugin_dir_url('') . MAXGALLERIA_MEDIA_LIBRARY_PLUGIN_NAME);
85 if(!defined('MAXGALLERIA_MEDIA_LIBRARY_NONCE'))
86 define("MAXGALLERIA_MEDIA_LIBRARY_NONCE", "mgmlp_nonce");
87
88 if(!defined('MLFP_LOAD_IMAGE_NONCE'))
89 define("MLFP_LOAD_IMAGE_NONCE", "mlfp_load_image_nonce");
90
91 if(!defined('MAXGALLERIA_MEDIA_LIBRARY_POST_TYPE'))
92 define("MAXGALLERIA_MEDIA_LIBRARY_POST_TYPE", "mgmlp_media_folder");
93 define("MAXGALLERIA_MEDIA_LIBRARY_UPLOAD_FOLDER_NAME", "mgmlp_upload_folder_name");
94 if(!defined("MAXGALLERIA_MEDIA_LIBRARY_UPLOAD_FOLDER_ID"))
95 define("MAXGALLERIA_MEDIA_LIBRARY_UPLOAD_FOLDER_ID", "mgmlp_upload_folder_id");
96 if(!defined('MAXGALLERIA_MEDIA_LIBRARY_FOLDER_TABLE'))
97 define("MAXGALLERIA_MEDIA_LIBRARY_FOLDER_TABLE", "mgmlp_folders");
98
99 if(!defined('MAXGALLERIA_MEDIA_LIBRARY_SORT_ORDER'))
100 define("MAXGALLERIA_MEDIA_LIBRARY_SORT_ORDER", "mgmlp_sort_order");
101 if(!defined('NEW_MEDIA_LIBRARY_VERSION'))
102 define("NEW_MEDIA_LIBRARY_VERSION", "4.0.0");
103 if(!defined('MAXGALLERIA_MLP_REVIEW_NOTICE'))
104 define("MAXGALLERIA_MLP_REVIEW_NOTICE", "maxgalleria_mlp_review_notice");
105 define("MAXGALLERIA_MLP_FEATURE_NOTICE", "maxgalleria_mlp_feature_notice");
106 if(!defined('MAXGALLERIA_MEDIA_LIBRARY_SRC_FIX'))
107 define("MAXGALLERIA_MEDIA_LIBRARY_SRC_FIX", "mgmlp_src_fix");
108 define("UPGRADE_TO_PRO_LINK", "https://maxgalleria.com/downloads/media-library-plus-pro/");
109 if(!defined('MAXGALLERIA_MEDIA_LIBRARY_MOVE_OR_COPY'))
110 define("MAXGALLERIA_MEDIA_LIBRARY_MOVE_OR_COPY", "mgmlp_move_or_copy");
111 if(!defined('MAXGALLERIA_MEDIA_LIBRARY_IMAGE_SEO'))
112 define("MAXGALLERIA_MEDIA_LIBRARY_IMAGE_SEO", "mgmlp_image_seo");
113 if(!defined('MAXGALLERIA_MEDIA_LIBRARY_ATL_DEFAULT'))
114 define("MAXGALLERIA_MEDIA_LIBRARY_ATL_DEFAULT", "mgmlp_default_alt");
115 if(!defined('MAXGALLERIA_MEDIA_LIBRARY_TITLE_DEFAULT'))
116 define("MAXGALLERIA_MEDIA_LIBRARY_TITLE_DEFAULT", "mgmlp_default_title");
117 //define("MAXGALLERIA_MEDIA_LIBRARY_BACKUP_TABLE", "mgmlp_old_posts");
118 //define("MAXGALLERIA_MEDIA_LIBRARY_POSTMETA_UPDATED", "mgmlp_postmeta_updated");
119
120 define("MLF_TS_URL", "https://wordpress.org/plugins/media-library-plus/faq/");
121 define("MAXGALLERIA_MLP_DISPLAY_INFO", "mlf_display_info");
122 define("MAXGALLERIA_MLP_DISABLE_FT", "mlf_disable_ft");
123 define("MAXG_SYNC_FOLDER_PATH", "mlfp_sync_folder_path");
124 define("MAXG_SYNC_FOLDER_PATH_ID", "mlfp_sync_folder_path_id");
125 define("MAXG_SYNC_FILES", "mlfp_sync_files");
126 define("MAXG_SYNC_FOLDERS", "mlfp_sync_folders");
127 define("MAXG_MC_FILES", "mlfp_move_file_ids");
128 define("MAXG_MC_DESTINATION_FOLDER", "mlfp_move_file_destination");
129 if(!defined('MAXGALLERIA_DISABLE_SCALLING'))
130 define("MAXGALLERIA_DISABLE_SCALLING", "mlfp_disable_scaling");
131 if(!defined('MAXGALLERIA_MLP_ITEMS_PRE_PAGE'))
132 define("MAXGALLERIA_MLP_ITEMS_PRE_PAGE", "mlf_items_per_page");
133 define('MLF_WP_CONTENT_FOLDER_NAME', basename(WP_CONTENT_DIR));
134 if(!defined('MAXGALLERIA_MLF_SORT_TYPE'))
135 define("MAXGALLERIA_MLF_SORT_TYPE", "mlf_sort_order_type");
136 if(!defined('MAXGALLERIA_POSTMETA_INDEX'))
137 define('MAXGALLERIA_POSTMETA_INDEX', 'mgmlp-index');
138 if(!defined('MLFP_SKIP_WEBP_FILES'))
139 define("MLFP_SKIP_WEBP_FILES", "mlfp-skip-webp-files");
140
141 if(!defined('MLFP_BDA'))
142 define("MLFP_BDA", "mlfp-bda");
143 if(!defined('MLFP_PROTECTED_DIR'))
144 define("MLFP_PROTECTED_DIR", "mlfp-protected-content-dir");
145 if(!defined('MLFP_BDA_DIR_LISTING'))
146 define("MLFP_BDA_DIR_LISTING", "mlfp-bda-dir-listing");
147 if(!defined('MLFP_BDA_HOTLINKING'))
148 define("MLFP_BDA_HOTLINKING", "mlfp-bda-hotlinking");
149 if(!defined('MLFP_PROTECTED_DIRECTORY'))
150 define("MLFP_PROTECTED_DIRECTORY", "protected-content");
151 if(!defined('MAXGALLERIA_MEDIA_LIBRARY_BLOCK_ACCESS_TABLE'))
152 define("MAXGALLERIA_MEDIA_LIBRARY_BLOCK_ACCESS_TABLE", "mgmlp_block_access");
153 if(!defined('MLFP_BDA_USER_ROLE'))
154 define("MLFP_BDA_USER_ROLE","mlfp-bda-user-role");
155 if(!defined('MLFP_BDA_MEDIA'))
156 define("MLFP_BDA_MEDIA", "mlfp-bda-media");
157 if(!defined('MLFP_BDA_DOWNLOAD_PAGE'))
158 define("MLFP_BDA_DOWNLOAD_PAGE", "mlfp-download-page");
159 if(!defined('MLFP_BDA_AUTO_PROTECT'))
160 define("MLFP_BDA_AUTO_PROTECT", "mlfp-bda-auto-protect");
161
162 if(!defined('MLFP_BDA_DISPLAY_FE_IMAGES'))
163 define("MLFP_BDA_DISPLAY_FE_IMAGES", "mlfp-bda-display-fe-images");
164 if(!defined('MLFP_BDA_PREVENT_RIGHT_CLICK'))
165 define("MLFP_BDA_PREVENT_RIGHT_CLICK", "mlfp-bda-prevent-right-click");
166 if(!defined('MLFP_BDA_AUTO_PROTECT_DISABLED'))
167 define("MLFP_BDA_AUTO_PROTECT_DISABLED", "mlfp-bda-auto-protect-disabled");
168 if(!defined('MLFP_NO_ACCESS_PAGE_ID'))
169 define("MLFP_NO_ACCESS_PAGE_ID", "mlfp-no-access-page-id");
170 if(!defined('MLFP_NO_ACCESS_PAGE_TITLE'))
171 define("MLFP_NO_ACCESS_PAGE_TITLE", "mlfp-no-access-page-id-title");
172 if(!defined('BLOCKED_IPS_TABLE'))
173 define("BLOCKED_IPS_TABLE","mgmlp_blocked_ips");
174
175 if(!defined('MGMLP_FILTER_SET_UPDATE_TABLE_LINKS'))
176 define('MGMLP_FILTER_SET_UPDATE_TABLE_LINKS', 'mlfp_filter_update_tables_links');
177 if(!defined('MGMLP_FILTER_SET_UPDATE_TABLE_FIELDS'))
178 define('MGMLP_FILTER_SET_UPDATE_TABLE_FIELDS', 'mlfp_filter_update_tables_fields');
179
180
181 // Bring in all the actions and filters
182 require_once 'includes/maxgalleria-media-library-hooks.php';
183
184 }
185
186 public function setup_hooks() {
187
188 global $pagenow;
189
190 add_action('init', array($this, 'load_textdomain'));
191 add_action('init', array($this, 'register_mgmlp_post_type'));
192 add_action('init', array($this, 'get_upload_status'));
193
194 add_action('admin_init', array($this, 'ignore_notice'));
195
196 add_action('admin_print_styles', array($this, 'enqueue_admin_print_styles'));
197 add_action('admin_print_scripts', array($this, 'enqueue_admin_print_scripts'));
198 add_action('admin_menu', array($this, 'setup_mg_media_plus'));
199
200 $this->disable_scaling = get_option( MAXGALLERIA_DISABLE_SCALLING, 'off');
201 if($this->disable_scaling == 'on') {
202 add_filter( 'big_image_size_threshold', '__return_false' );
203 }
204
205 add_action('wp_ajax_nopriv_create_new_folder', array($this, 'create_new_folder'));
206 add_action('wp_ajax_create_new_folder', array($this, 'create_new_folder'));
207
208 add_action('wp_ajax_delete_maxgalleria_media', array($this, 'delete_maxgalleria_media'));
209
210 add_action('wp_ajax_nopriv_upload_attachment', array($this, 'upload_attachment'));
211 add_action('wp_ajax_upload_attachment', array($this, 'upload_attachment'));
212
213 // not used
214 //add_action('wp_ajax_nopriv_copy_media', array($this, 'copy_media'));
215 //add_action('wp_ajax_copy_media', array($this, 'copy_media'));
216
217 //add_action('wp_ajax_nopriv_move_media', array($this, 'move_media'));
218 //add_action('wp_ajax_move_media', array($this, 'move_media'));
219
220 add_action('wp_ajax_nopriv_add_to_max_gallery', array($this, 'add_to_max_gallery'));
221 add_action('wp_ajax_add_to_max_gallery', array($this, 'add_to_max_gallery'));
222
223 add_action('wp_ajax_maxgalleria_rename_image', array($this, 'maxgalleria_rename_image'));
224
225 add_action('wp_ajax_nopriv_sort_contents', array($this, 'sort_contents'));
226 add_action('wp_ajax_sort_contents', array($this, 'sort_contents'));
227
228 add_action('wp_ajax_nopriv_mgmlp_move_copy', array($this, 'mgmlp_move_copy'));
229 add_action('wp_ajax_mgmlp_move_copy', array($this, 'mgmlp_move_copy'));
230
231 add_action( 'new_folder_check', array($this,'admin_check_for_new_folders'));
232
233 add_action('wp_ajax_nopriv_mlf_check_for_new_folders', array($this, 'mlf_check_for_new_folders'));
234 add_action('wp_ajax_mlf_check_for_new_folders', array($this, 'mlf_check_for_new_folders'));
235
236 add_action('wp_ajax_nopriv_mlfp_display_bda_info', array($this, 'mlfp_display_bda_info'));
237 add_action('wp_ajax_mlfp_display_bda_info', array($this, 'mlfp_display_bda_info'));
238
239 //add_action( 'add_attachment', array($this,'add_attachment_to_folder'));
240
241 add_filter( 'wp_generate_attachment_metadata', array($this, 'add_attachment_to_folder2'), 10, 4);
242
243 add_action( 'delete_attachment', array($this,'delete_folder_attachment'));
244
245 //add_action('wp_ajax_nopriv_max_sync_contents', array($this, 'max_sync_contents'));
246 //add_action('wp_ajax_max_sync_contents', array($this, 'max_sync_contents'));
247
248 add_action('wp_ajax_nopriv_mlp_load_folder', array($this, 'mlp_load_folder'));
249 add_action('wp_ajax_mlp_load_folder', array($this, 'mlp_load_folder'));
250
251 //add_action('wp_ajax_nopriv_mlp_display_folder_ajax', array($this, 'mlp_display_folder_contents_ajax'));
252 add_action('wp_ajax_nopriv_mlp_display_folder_contents_ajax', array($this, 'mlp_display_folder_contents_ajax'));
253 add_action('wp_ajax_mlp_display_folder_contents_ajax', array($this, 'mlp_display_folder_contents_ajax'));
254
255 add_action('wp_ajax_nopriv_mlp_display_folder_contents_images_ajax', array($this, 'mlp_display_folder_contents_images_ajax'));
256 add_action('wp_ajax_mlp_display_folder_contents_images_ajax', array($this, 'mlp_display_folder_contents_images_ajax'));
257
258 add_action('wp_ajax_nopriv_mlpp_hide_template_ad', array($this, 'mlpp_hide_template_ad'));
259 add_action('wp_ajax_mlpp_hide_template_ad', array($this, 'mlpp_hide_template_ad'));
260
261 add_action('wp_ajax_nopriv_mlpp_create_new_ng_gallery', array($this, 'mlpp_create_new_ng_gallery'));
262 add_action('wp_ajax_mlpp_create_new_ng_gallery', array($this, 'mlpp_create_new_ng_gallery'));
263
264 add_action('wp_ajax_nopriv_display_folder_nav_ajax', array($this, 'display_folder_nav_ajax'));
265 add_action('wp_ajax_mgmlp_display_folder_nav_ajax', array($this, 'display_folder_nav_ajax'));
266
267 add_action('wp_ajax_nopriv_mlp_get_folder_data', array($this, 'mlp_get_folder_data'));
268 add_action('wp_ajax_mlp_get_folder_data', array($this, 'mlp_get_folder_data'));
269
270 add_action('wp_ajax_nopriv_regen_mlp_thumbnails', array($this, 'regen_mlp_thumbnails'));
271 add_action('wp_ajax_regen_mlp_thumbnails', array($this, 'regen_mlp_thumbnails'));
272
273 add_action( 'wp_ajax_regeneratethumbnail', array( $this, 'ajax_process_image' ) );
274 $this->capability = apply_filters( 'regenerate_thumbs_cap', 'manage_options' );
275
276 add_action('wp_ajax_nopriv_mlp_image_seo_change', array($this, 'mlp_image_seo_change'));
277 add_action('wp_ajax_mlp_image_seo_change', array($this, 'mlp_image_seo_change'));
278
279 add_action('wp_ajax_nopriv_hide_maxgalleria_media', array($this, 'hide_maxgalleria_media'));
280 add_action('wp_ajax_hide_maxgalleria_media', array($this, 'hide_maxgalleria_media'));
281
282 add_filter( 'body_class', array($this, 'mlf_body_classes'));
283 add_filter( 'admin_body_class', array($this, 'mlf_body_classes'));
284
285 add_action('wp_ajax_nopriv_mlf_hide_info', array($this, 'mlf_hide_info'));
286 add_action('wp_ajax_mlf_hide_info', array($this, 'mlf_hide_info'));
287
288 add_action('wp_ajax_nopriv_mlfp_set_scaling', array($this, 'mlfp_set_scaling'));
289 add_action('wp_ajax_mlfp_set_scaling', array($this, 'mlfp_set_scaling'));
290
291 add_action('wp_ajax_nopriv_mlfp_run_sync_process', array($this, 'mlfp_run_sync_process'));
292 add_action('wp_ajax_mlfp_run_sync_process', array($this, 'mlfp_run_sync_process'));
293
294 add_action('wp_ajax_nopriv_mlfp_process_mc_data', array($this, 'mlfp_process_mc_data'));
295 add_action('wp_ajax_mlfp_process_mc_data', array($this, 'mlfp_process_mc_data'));
296
297 add_action('wp_ajax_nopriv_mlf_change_sort_type', array($this, 'mlf_change_sort_type'));
298 add_action('wp_ajax_mlf_change_sort_type', array($this, 'mlf_change_sort_type'));
299
300 add_action('wp_ajax_nopriv_mlfp_process_bdp', array($this, 'mlfp_process_bdp'));
301 add_action('wp_ajax_mlfp_process_bdp', array($this, 'mlfp_process_bdp'));
302
303 add_action('wp_ajax_nopriv_mlfp_save_noaccess_page', array($this, 'mlfp_save_noaccess_page'));
304 add_action('wp_ajax_mlfp_save_noaccess_page', array($this, 'mlfp_save_noaccess_page'));
305
306 add_action('wp_ajax_nopriv_mlfp_bdp_report', array($this, 'mlfp_bdp_report'));
307 add_action('wp_ajax_mlfp_bdp_report', array($this, 'mlfp_bdp_report'));
308
309 add_action('wp_ajax_nopriv_mlfp_block_new_ip', array($this, 'mlfp_block_new_ip'));
310 add_action('wp_ajax_mlfp_block_new_ip', array($this, 'mlfp_block_new_ip'));
311
312 add_action('wp_ajax_nopriv_mlfp_unblock_ips', array($this, 'mlfp_unblock_ips'));
313 add_action('wp_ajax_mlfp_unblock_ips', array($this, 'mlfp_unblock_ips'));
314
315 add_action('wp_ajax_nopriv_mlfp_get_block_ips', array($this, 'mlfp_get_block_ips'));
316 add_action('wp_ajax_mlfp_get_block_ips', array($this, 'mlfp_get_block_ips'));
317
318 add_action('wp_ajax_nopriv_mlfp_load_image', array($this, 'mlfp_load_image'));
319 add_action('wp_ajax_mlfp_load_image', array($this, 'mlfp_load_image'));
320
321 add_action('wp_ajax_nopriv_mlfp_load_fe_image', array($this, 'mlfp_load_fe_image'));
322 add_action('wp_ajax_mlfp_load_fe_image', array($this, 'mlfp_load_fe_image'));
323
324 add_action('wp_ajax_nopriv_mlfp_toggle_file_access', array($this, 'mlfp_toggle_file_access'));
325 add_action('wp_ajax_mlfp_toggle_file_access', array($this, 'mlfp_toggle_file_access'));
326
327 add_action('wp_ajax_nopriv_mlfp_update_bda_record', array($this, 'mlfp_update_bda_record'));
328 add_action('wp_ajax_mlfp_update_bda_record', array($this, 'mlfp_update_bda_record'));
329
330 add_action('wp_ajax_nopriv_mflp_enable_auto_protect', array($this, 'mflp_enable_auto_protect'));
331 add_action('wp_ajax_mflp_enable_auto_protect', array($this, 'mflp_enable_auto_protect'));
332
333 add_action('wp_enqueue_media', array($this, 'mlfp_enqueue_media'), 99, 1);
334 add_filter('wp_prepare_attachment_for_js', array($this, 'bda_prepare_attachment_for_js'), 10, 3);
335 add_action('admin_enqueue_scripts', array($this, 'bda_add_class_to_media_library_grid_elements'));
336
337 //add_action( 'admin_menu', array($this, 'hide_mlf_menu_items'));
338
339 $this->bda = get_option(MLFP_BDA, 'off');
340 if($this->bda == 'on') {
341 add_action('wp_enqueue_scripts', array($this, 'bda_enqueue_scripts'));
342 add_action('wp_footer', array($this, 'mlfp_display_protected_file'));
343 add_action('admin_enqueue_scripts', array($this, 'bda_load_protected_file'));
344 }
345
346 }
347
348 // public function hide_mlf_menu_items() {
349 // // Remove the submenu item
350 // remove_submenu_page('mlf-folders8', 'search-library');
351 // }
352
353 public function bda_enqueue_scripts() {
354 wp_enqueue_script('jquery');
355 }
356
357 // loades javascript file for displaying a protected image on the image edit page
358 public function bda_load_protected_file() {
359 global $pagenow;
360
361 if($pagenow == 'post.php') {
362
363 wp_enqueue_script('jquery');
364
365 wp_register_script('mlfp-lpf', MAXGALLERIA_MEDIA_LIBRARY_PLUGIN_URL . '/js/mlfp-lpf.js', array('jquery'), '', true );
366
367 wp_localize_script('mlfp-lpf', 'lpf_ajax',
368 array('ajaxurl' => admin_url( 'admin-ajax.php'),
369 'nonce'=> wp_create_nonce(MAXGALLERIA_MEDIA_LIBRARY_NONCE))
370 );
371
372 wp_enqueue_script('mlfp-lpf');
373
374 }
375 }
376
377 public function mlfp_display_protected_file() {
378 ?>
379 <script type="text/javascript">
380
381 jQuery(document).ready(function(){
382
383 var display_protected_images = '<?php echo esc_js($this->display_fe_protected_images) ?>';
384 var prevent_right_click = '<?php echo esc_js($this->prevent_right_click) ?>';
385
386 if(prevent_right_click == 'on') {
387 jQuery("img").mousedown(function(e){
388 e.preventDefault();
389 });
390
391 // this will disable right-click on all images
392 jQuery("body").on("contextmenu", function(e){
393 return false;
394 });
395 }
396
397 if(display_protected_images == 'on') {
398 //console.log("display_protected_images on");
399 var image_index = 1;
400 jQuery("img").each(function () {
401 var element = jQuery(this);
402 var src = jQuery(this).attr('src');
403 var clone = jQuery(this).clone();
404 console.log(image_index,src);
405
406 jQuery.ajax({
407 url:src,
408 type:'GET',
409 async: false,
410 error:function(response){
411 console.log('error src', src);
412 var image_id = 'image' + image_index;
413 jQuery(clone).attr('id', image_id);
414 jQuery(clone).attr('src', '');
415 jQuery(clone).removeAttr('srcset');
416 // replace with new element in order to load the image
417 jQuery(element).replaceWith(clone);
418
419 jQuery.ajax({
420 type: "POST",
421 async: false,
422 data: { action: "mlfp_load_image", src: src, nonce: '<?php echo wp_create_nonce(MLFP_LOAD_IMAGE_NONCE) ?>' },
423 url: '<?php echo admin_url('admin-ajax.php') ?>',
424 success: function (data) {
425 if(data.length > 0)
426 jQuery('#'+image_id).attr("src", data);
427 },
428 error: function (err){
429 alert(err.responseText);
430 }
431 });
432 }
433 });
434 image_index++;
435 });
436 }
437 });
438 </script>
439 <?php
440 }
441
442 /* manually loads an image file */
443 public function mlfp_load_image () {
444
445 if ( !wp_verify_nonce( $_POST['nonce'], MLFP_LOAD_IMAGE_NONCE)) {
446 exit(esc_html__('Missing nonce! Please refresh this page.','maxgalleria-media-library'));
447 }
448
449 // Check if the current user has the capability to upload files
450 if(!current_user_can('upload_files')){
451 exit(esc_html__('You do not have the capability to upload files.','maxgalleria-media-library'));
452 }
453
454 if ((isset($_POST['src'])) && (strlen(trim($_POST['src'])) > 0))
455 $download_file = trim(sanitize_url($_POST['src']));
456 else
457 $download_file = "";
458
459 if(!empty($download_file)) {
460
461 $file_path = $this->get_absolute_path($download_file);
462
463 if($this->is_path_inside($this->protected_content_dir, $file_path)) {
464 if(file_exists($file_path)) {
465 $type = pathinfo($file_path, PATHINFO_EXTENSION);
466 $data = file_get_contents($file_path);
467 $base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
468 echo $base64;
469 }
470 }
471 }
472
473 die();
474 }
475
476 public function is_path_inside($potential_parent, $potential_child) {
477 // Get the real, absolute paths
478 $parent_path = realpath($potential_parent);
479 $child_path = realpath($potential_child);
480
481 // Check if both paths are valid
482 if ($parent_path === false || $child_path === false) {
483 return false;
484 }
485
486 $parent_path = rtrim($parent_path, DIRECTORY_SEPARATOR);
487 $child_path = rtrim($child_path, DIRECTORY_SEPARATOR);
488
489 return $child_path === $parent_path || strpos($child_path, $parent_path . DIRECTORY_SEPARATOR) === 0;
490 }
491
492 /* manually load image on the front end of the site */
493 public function mlfp_load_fe_image () {
494
495 if ( !wp_verify_nonce( $_POST['nonce'], MLFP_LOAD_IMAGE_NONCE)) {
496 exit(esc_html__('Missing nonce! Please refresh this page.','maxgalleria-media-library'));
497 }
498
499 // Check if the current user has the capability to upload files
500 if(!current_user_can('upload_files')){
501 exit(esc_html__('You do not have the capability to upload files.','maxgalleria-media-library'));
502 }
503
504 if ((isset($_POST['src'])) && (strlen(trim($_POST['src'])) > 0))
505 $download_file = trim(sanitize_url($_POST['src']));
506 else
507 $download_file = "";
508
509 if ((isset($_POST['image_id'])) && (strlen(trim($_POST['image_id'])) > 0))
510 $image_id = intval(trim(sanitize_text_field($_POST['image_id'])));
511 else
512 $image_id = "";
513
514 if(!empty($download_file)) {
515 $file_path = $this->get_absolute_path($download_file);
516
517 if($this->is_path_inside($this->protected_content_dir, $file_path)) {
518
519 if(file_exists($file_path)) {
520 $type = pathinfo($file_path, PATHINFO_EXTENSION);
521 $data = file_get_contents($file_path);
522 $base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
523 echo $base64;
524 }
525 }
526 } else {
527 echo null;
528 }
529
530 die();
531 }
532
533 public function mlfp_remove_protected_folders() {
534
535 if ( !wp_verify_nonce( $_POST['nonce'], MAXGALLERIA_MEDIA_LIBRARY_NONCE)) {
536 exit(esc_html__('Missing nonce! Please refresh this page.','maxgalleria-media-library'));
537 }
538
539 // Check if the current user has the capability to manage options
540 if(!current_user_can('manage_options')){
541 exit(esc_html__('You do not have the capability to manage options.','maxgalleria-media-library'));
542 }
543
544
545 $this->remove_protected_folders();
546
547 die();
548 }
549
550 public function remove_protected_folders() {
551
552 $folders = array();
553
554 $protected_content_path = $this->get_absolute_path($this->protected_content_dir);
555
556 $iterator = new RecursiveDirectoryIterator($protected_content_path);
557
558 $iterator->setFlags(RecursiveDirectoryIterator::SKIP_DOTS);
559
560 $directories = new ParentIterator($iterator);
561
562 // check for empty folders
563 foreach (new RecursiveIteratorIterator($directories, RecursiveIteratorIterator::SELF_FIRST) as $dir) {
564 $folder_path = $dir->getPathname();
565 $sub_iterator = new FilesystemIterator($folder_path);
566 if(!$sub_iterator->valid()) {
567 $folders[] = $folder_path;
568 }
569 }
570
571 // delete the empty folders
572 foreach($folders as $folder) {
573 if(file_exists($folder)) {
574 rmdir($folder);
575 }
576 }
577 }
578
579
580
581 public function set_activation_hooks() {
582 register_activation_hook(__FILE__, array($this, 'do_activation'));
583 register_deactivation_hook(__FILE__, array($this, 'do_deactivation'));
584 }
585
586 public function do_activation($network_wide) {
587 $this->activate();
588 }
589
590 public function do_deactivation($network_wide) {
591 $this->deactivate();
592 }
593
594 public function activate() {
595 update_option(MAXGALLERIA_MEDIA_LIBRARY_VERSION_KEY, MAXGALLERIA_MEDIA_LIBRARY_VERSION_NUM);
596 //update_option('uploads_use_yearmonth_folders', 1);
597 $this->add_folder_table();
598 $this->add_block_access_table();
599 $this->add_blocked_ips_table();
600 //update_option('mgmlp_database_checked', 'off', true);
601
602 if ( 'impossible_default_value_1234' === get_option( MAXGALLERIA_MEDIA_LIBRARY_UPLOAD_FOLDER_NAME, 'impossible_default_value_1234' ) ) {
603 $this->scan_attachments();
604 $this->admin_check_for_new_folders(true);
605 update_option(MAXGALLERIA_MEDIA_LIBRARY_SRC_FIX, true);
606 }
607
608 $current_user_id = get_current_user_id();
609 $havemeta = get_user_meta( $current_user_id, MAXGALLERIA_MLP_FEATURE_NOTICE, true );
610 if ($havemeta === '') {
611 $review_date = date('Y-m-d', strtotime("+1 days"));
612 update_user_meta( $current_user_id, MAXGALLERIA_MLP_FEATURE_NOTICE, $review_date );
613 }
614
615 if($this->bda == 'on') {
616 add_filter('mod_rewrite_rules', array( $this, 'mlfp_update_htaccess'));
617 flush_rewrite_rules();
618 }
619
620 if ( ! wp_next_scheduled( 'new_folder_check' ) )
621 wp_schedule_event( time(), 'daily', 'new_folder_check' );
622
623 }
624
625 public function deactivate() {
626
627 }
628
629 public function check_for_old_multisite() {
630
631 $content_folder = apply_filters( 'mlfp_content_folder', 'wp-content');
632 $upload_sites = ABSPATH . $content_folder . DIRECTORY_SEPARATOR . "uploads";
633
634 if(!file_exists($upload_sites))
635 return false;
636 else
637 return true;
638 }
639
640
641 public function enqueue_admin_print_styles() {
642
643 //error_log("enqueue_admin_print_styles");
644
645 global $pagenow;
646
647 if(isset($_REQUEST['page'])) {
648
649 //error_log("page " . $_REQUEST['page']);
650
651 // on these pages load our styles and scripts
652 if($_REQUEST['page'] == 'mlf-folders8'
653 || $_REQUEST['page'] == 'search-library'
654 || $_REQUEST['page'] == 'mlf-thumbnails'
655 || $_REQUEST['page'] == 'mlf-image-seo'
656 || $_REQUEST['page'] == 'mlf-settings8'
657 || $_REQUEST['page'] == 'mlf-support8') {
658
659 wp_enqueue_style('mlf8', MAXGALLERIA_MEDIA_LIBRARY_PLUGIN_URL . '/css/mlf.css');
660 wp_enqueue_style('mlfp-fontawesome', MAXGALLERIA_MEDIA_LIBRARY_PLUGIN_URL . '/libs/fontawesome-free-6.0.0-web/css/all.min.css');
661
662 if($_REQUEST['page'] === 'mlf-folders8' ||
663 $_REQUEST['page'] === 'mlf-thumbnails' ||
664 $_REQUEST['page'] === 'search-library') {
665
666 //wp_enqueue_style('jstree-style', esc_url(MAXGALLERIA_MEDIA_LIBRARY_PLUGIN_URL . '/js/jstree/themes/default/style.css'));
667 wp_enqueue_style('mlf8-jstree-style', MAXGALLERIA_MEDIA_LIBRARY_PLUGIN_URL . '/js/jstree/themes/default/style.min.css');
668
669 wp_enqueue_script('jquery');
670
671 wp_enqueue_script('jquery-ui');
672 wp_enqueue_script('jquery-ui-core');
673 wp_enqueue_script('jquery-ui-progressbar');
674 wp_enqueue_script('jquery-ui-draggable');
675 wp_enqueue_script('jquery-ui-droppable');
676
677 wp_enqueue_script('jquery-ui-widget');
678 wp_enqueue_script('jquery-ui-mouse');
679 wp_enqueue_script('jquery-ui-position');
680 wp_enqueue_script('jquery-ui-resizable');
681 wp_enqueue_script('jquery-ui-selectable');
682 wp_enqueue_script('jquery-ui-sortable');
683
684 wp_register_script('jstree', MAXGALLERIA_MEDIA_LIBRARY_PLUGIN_URL . '/js/jstree/jstree.min.js', array('jquery'));
685 wp_enqueue_script('jstree');
686 }
687
688 if($_REQUEST['page'] == 'mlf-settings8' && isset($_REQUEST['tab']) && $_REQUEST['tab'] == 'access') {
689 wp_enqueue_script('jquery');
690 wp_enqueue_style('select2', MAXGALLERIA_MEDIA_LIBRARY_PLUGIN_URL . '/js/select2/css/select2.min.css', false, null );
691 wp_enqueue_script('select2', MAXGALLERIA_MEDIA_LIBRARY_PLUGIN_URL . '/js/select2/js/select2.min.js');
692 }
693
694 } else if ($_REQUEST['page'] === 'mlp-upgrade-to-pro') {
695 wp_enqueue_style('media-library-upgrade-to-pro', esc_url(MAXGALLERIA_MEDIA_LIBRARY_PLUGIN_URL . '/css/upgrade-to-pro.css'));
696 }
697
698 }
699
700 }
701
702 public function enqueue_admin_print_scripts() {
703
704 global $pagenow, $current_screen;
705
706 if(isset($_REQUEST['page'])) {
707
708 // error_log("page " . $_REQUEST['page']);
709
710 // on these pages load our styles and scripts
711 if($_REQUEST['page'] == 'mlf-folders8'
712 || $_REQUEST['page'] == 'search-library'
713 || $_REQUEST['page'] == 'mlf-thumbnails'
714 || $_REQUEST['page'] == 'mlf-image-seo'
715 || $_REQUEST['page'] == 'mlf-settings8'
716 || $_REQUEST['page'] == 'mlf-support8') {
717
718 wp_enqueue_script('jquery');
719 wp_enqueue_script('jquery-migrate', esc_url(ABSPATH . WPINC . '/js/jquery/jquery-migrate.min.js'), array('jquery'));
720
721 wp_register_script( 'loader-folders', esc_url(MAXGALLERIA_MEDIA_LIBRARY_PLUGIN_URL . '/js/mgmlp-loader.js'), array( 'jquery' ), '', true );
722
723 wp_localize_script( 'loader-folders', 'mgmlp_ajax',
724 array( 'ajaxurl' => admin_url( 'admin-ajax.php' ),
725 'confirm_file_delete' => esc_html__('Are you sure you want to delete the selected files?', 'maxgalleria-media-library' ),
726 'nothing_selected' => esc_html__('No items were selected.', 'maxgalleria-media-library' ),
727 'no_images_selected' => esc_html__('No images were selected.', 'maxgalleria-media-library' ),
728 'no_quotes' => esc_html__('Folder names cannot contain single or double quotes.', 'maxgalleria-media-library' ),
729 'no_spaces' => esc_html__('Folder names cannot contain spaces.', 'maxgalleria-media-library' ),
730 'no_punctuation' => __('Folder names may only include the following punctuation marks: period, dash, underscore, and tilde.', 'maxgalleria-media-library' ),
731 'no_blank' => esc_html__('The folder name cannot be blank.' ),
732 'no_blank_filename' => esc_html__('The new file name cannot be blank.' ),
733 'valid_file_name' => esc_html__('Please enter a valid file name with no spaces.', 'maxgalleria-media-library' ),
734 'move_mode' => esc_html__('Drag and drop is set for moving files', 'maxgalleria-media-library' ),
735 'copy_mode' => esc_html__('Drag and drop is set for copying files', 'maxgalleria-media-library' ),
736 'folder_check' => esc_html__('Checking for new folders...', 'maxgalleria-media-library' ),
737 'bda_user_role' => $this->bda_user_role,
738 'link_copied' => esc_html__('download link has been copied to the clipboard', 'maxgalleria-media-library'),
739 'lin_nonce'=> wp_create_nonce(MLFP_LOAD_IMAGE_NONCE),
740 'nonce'=> wp_create_nonce(MAXGALLERIA_MEDIA_LIBRARY_NONCE))
741 );
742
743 wp_enqueue_script('loader-folders');
744
745 //error_log("loader-folders loaded");
746 }
747 }
748
749 if (isset( $current_screen ) && 'upload' === $current_screen->base) {
750 $uploads_js_ver = date("ymd-Gis", filemtime(MAXGALLERIA_MEDIA_LIBRARY_PLUGIN_DIR . '/js/uploads-media.js'));
751 wp_register_script( 'uploads-media', MAXGALLERIA_MEDIA_LIBRARY_PLUGIN_URL . '/js/uploads-media.js', array( 'jquery', 'media-models', ), $uploads_js_ver, true );
752 wp_enqueue_script('uploads-media');
753 }
754 }
755
756 public function mlfp_enqueue_media() {
757
758 wp_enqueue_style('bda-media', MAXGALLERIA_MEDIA_LIBRARY_PLUGIN_URL . '/css/bda-media.css');
759
760 $media_js_ver = date("ymd-Gis", filemtime(MAXGALLERIA_MEDIA_LIBRARY_PLUGIN_DIR . '/js/mlfp-media.js'));
761 wp_register_script( 'mlfp-media', MAXGALLERIA_MEDIA_LIBRARY_PLUGIN_URL . '/js/mlfp-media.js', array( 'jquery', 'media-models', ), $media_js_ver, true );
762
763 wp_localize_script( 'mlfp-media', 'mlfpmedia', $this->media_localize());
764
765 wp_enqueue_script('mlfp-media');
766
767 if($this->bda == 'on') {
768 wp_enqueue_script('jquery');
769 wp_enqueue_script('bda-media', MAXGALLERIA_MEDIA_LIBRARY_PLUGIN_URL . '/js/bda-media.js', array('jquery'));
770 }
771
772 }
773
774 public function media_localize() {
775
776 $upload_id = get_option(MAXGALLERIA_MEDIA_LIBRARY_UPLOAD_FOLDER_ID );
777 $theme = get_option('template');
778 $user = wp_get_current_user();
779
780 return array(
781 'ajaxurl' => admin_url( 'admin-ajax.php' ),
782 'nonce'=> wp_create_nonce(MAXGALLERIA_MEDIA_LIBRARY_NONCE),
783 'lin_nonce'=> wp_create_nonce(MLFP_LOAD_IMAGE_NONCE),
784 'upload_message' => esc_html__('Select the folder where you wish to view or upload files.', 'maxgalleria-media-library'),
785 'uploads_folder_id' => $upload_id,
786 'bda' => $this->bda,
787 'bda_user_role' => $this->bda_user_role,
788 'display_btn_text' => esc_html__('Display Blocked Files', 'maxgalleria-media-library'),
789 'theme' => get_option('template'),
790 'gutenberg' => $this->gutenberg_active(),
791 'location' => esc_html__('Location: ', 'maxgalleria-media-library')
792 );
793
794 }
795
796 public function gutenberg_active() {
797 // Gutenberg plugin is installed and activated.
798 $gutenberg = ! ( false === has_filter( 'replace_editor', 'gutenberg_init' ) );
799
800 // Block editor since 5.0.
801 $block_editor = version_compare( $GLOBALS['wp_version'], '5.0-beta', '>' );
802
803 if ( ! $gutenberg && ! $block_editor ) {
804 return false;
805 }
806
807 if ( $this->classic_editor_plugin_active() ) {
808 $editor_option = get_option( 'classic-editor-replace' );
809 $block_editor_active = array( 'no-replace', 'block' );
810
811 return in_array( $editor_option, $block_editor_active, true );
812 }
813
814 return true;
815 }
816
817 public function classic_editor_plugin_active() {
818 if ( ! function_exists( 'is_plugin_active' ) ) {
819 include_once ABSPATH . 'wp-admin/includes/plugin.php';
820 }
821 }
822
823 public function setup_mg_media_plus() {
824 add_menu_page(esc_html__('Media Library Folders','maxgalleria-media-library'), esc_html__('Media Library Folders','maxgalleria-media-library'), 'upload_files', 'mlf-folders8', array($this, 'mlf_folders'), 'dashicons-admin-media', 11 );
825 add_submenu_page('mlf-folders8', esc_html__('Folders & Files','maxgalleria-media-library'), esc_html__('Folders & Files','maxgalleria-media-library'), 'upload_files', 'mlf-folders8' );
826 add_submenu_page('mlf-folders8', esc_html__('Thumbnails','maxgalleria-media-library'), esc_html__('Thumbnails','maxgalleria-media-library'), 'manage_options', 'mlf-thumbnails', array($this, 'mlfp_thumbnails'));
827 add_submenu_page('mlf-folders8', esc_html__('Image SEO','maxgalleria-media-library'), esc_html__('Image SEO','maxgalleria-media-library'), 'upload_files', 'mlf-image-seo', array($this, 'mlfp_image_seo'));
828 add_submenu_page('mlf-folders8', esc_html__('Settings','maxgalleria-media-library'), esc_html__('Settings','maxgalleria-media-library'), 'manage_options', 'mlf-settings8', array($this, 'mlfp_settings8'));
829 add_submenu_page('mlf-folders8', esc_html__('Support','maxgalleria-media-library'), esc_html__('Support','maxgalleria-media-library'), 'manage_options', 'mlf-support8', array($this, 'mlfp_support'));
830 add_submenu_page('mlf-folders8', esc_html__('Upgrade to Pro','maxgalleria-media-library'), esc_html__('Upgrade to Pro','maxgalleria-media-library'), 'upload_files', 'mlp-upgrade-to-pro', array($this, 'mlp_upgrade_to_pro'));
831 add_submenu_page('not-visible', esc_html__('Search Library','maxgalleria-media-library'), esc_html__('Search Library','maxgalleria-media-library'), 'upload_files', 'search-library', array($this, 'search_library'));
832 }
833
834 public function mlf_folders() {
835 require_once 'includes/media-folders.php';
836 }
837
838 public function mlfp_thumbnails() {
839 require_once 'includes/mlf-thumbnails.php';
840 }
841
842 public function mlfp_image_seo() {
843 require_once 'includes/mlf-image-seo.php';
844 }
845
846 public function mlfp_settings8() {
847 require_once 'includes/mlf-settings.php';
848 }
849
850 public function mlfp_support() {
851 require_once 'includes/mlf-support.php';
852 }
853
854 public function media_library() {
855 require_once 'includes/media-library.php';
856 }
857
858 public function support_tips() {
859 require_once 'includes/mlf-support-tips.php';
860 }
861
862 public function support_articles() {
863 require_once 'includes/mlf-support-articles.php';
864 }
865
866 public function support_sys_info() {
867 require_once 'includes/mlf-support-sys-info.php';
868 }
869
870 public function block_access_settings() {
871 require_once 'includes/mlfp-bda-options.php';
872 }
873
874
875 public function display_mlfp_header() {
876
877 $html = '';
878
879 $html .= '<div class="mgmlp-header">' . PHP_EOL;
880
881 $html .= ' <div id="mlfp-logo-container">' . PHP_EOL;
882 $html .= ' <img id="mlpf-logo" src="' . esc_url(MAXGALLERIA_MEDIA_LIBRARY_PLUGIN_URL . '/images/mlp_logo.png') . '" alt="media library folders pro logo" width="100" height="100">' . PHP_EOL;
883 $html .= ' </div>' . PHP_EOL;
884
885 $html .= ' <div id="mlfp-link-container">' . PHP_EOL;
886 $html .= ' <div id="mlfp-links">' . PHP_EOL;
887 $html .= ' <div>' . esc_html__('Brought to you by ', 'maxgalleria-media-library') .' <a target="_blank" href="https://maxfoundry.com">MaxFoundry</a></div>' . PHP_EOL;
888 $html .= ' <div>' . esc_html__('Makers of', 'maxgalleria-media-library') . ' <a target="_blank" href="https://maxbuttons.com/">MaxButtons</a>, <a target="_blank" href="https://maxbuttons.com/product-category/button-packs/">WordPress Buttons</a> ' . esc_html__('and', 'maxgalleria-media-library') . ' <a target="_blank" href="https://maxgalleria.com/">MaxGalleria</a></div>' . PHP_EOL;
889 $html .= ' </div>' . PHP_EOL;
890
891 $html .= ' <div id="mlfp-support">' . PHP_EOL;
892 $html .= ' <div><strong>Quick Support</strong></div>' . PHP_EOL;
893 $html .= ' <div>' . esc_html__('Click here to', 'maxgalleria-media-library') . '&nbsp;<a href="' . MLF_TS_URL . '" target="_blank">' . esc_html__('Fix Common Problems', 'maxgalleria-media-library') . '</a></div>' . PHP_EOL;
894 $html .= ' <div>' . esc_html__('Need more help? Check out our ', 'maxgalleria-media-library') . ' <a href="https://wordpress.org/support/plugin/media-library-plus" target="_blank">' . esc_html__('Support Forums', 'maxgalleria-media-library') . '</a></div>' . PHP_EOL;
895 $html .= ' <div>' . esc_html__('Or Email Us at', 'maxgalleria-media-library' ) . ' <a href="mailto:support@maxfoundry.com">support@maxfoundry.com</a></div>' . PHP_EOL;
896 $html .= ' </div>' . PHP_EOL;
897
898 $html .= ' </div>' . PHP_EOL;
899
900
901 $html .= '</div>' . PHP_EOL;
902
903 return $html;
904
905 }
906
907 function mlf_body_classes( $classes ) {
908 $locale = "locale-" . str_replace('_','-', strtolower(get_locale()));
909 if(is_array($classes))
910 $classes[] = $locale;
911 else
912 $classes .= " " . $locale;
913 return $classes;
914 }
915
916 public function delete_folder_attachment ($postid) {
917 global $wpdb;
918 $postid = intval($postid);
919 $table = $wpdb->prefix . MAXGALLERIA_MEDIA_LIBRARY_FOLDER_TABLE;
920 $where = array( 'post_id' => $postid );
921 $wpdb->delete( $table, $where );
922 }
923
924 // in case an image is uploaded in the WP media library we
925 // need to add a record to the mgmlp_folders table
926 public function add_attachment_to_folder ($post_id) {
927
928 $folder_id = $this->get_default_folder($post_id); //for non pro version
929 if($folder_id !== false) {
930 $this->add_new_folder_parent($post_id, $folder_id);
931 }
932 }
933
934 public function add_attachment_to_folder2( $metadata, $attachment_id ) {
935
936 $folder_id = $this->get_default_folder($attachment_id);
937 if($folder_id !== false && $folder_id != null) {
938 $this->add_new_folder_parent($attachment_id, $folder_id);
939
940 //error_log("bdp_autoprotect " . $this->bdp_autoprotect);
941 if($this->bda == 'on' && $this->bdp_autoprotect == 'on') {
942 $message = $this->move_to_protected_folder($attachment_id, $folder_id, 0);
943 }
944
945 }
946 return $metadata;
947 }
948
949 public function get_parent_by_name($sub_folder) {
950
951 global $wpdb;
952
953 $sql = "SELECT post_id FROM {$wpdb->prefix}postmeta where meta_key = '_wp_attached_file' and `meta_value` = '$sub_folder'";
954
955 return $wpdb->get_var($sql);
956 }
957
958 public function get_default_folder($post_id) {
959
960 $attached_file = get_post_meta($post_id, '_wp_attached_file', true);
961 $folder_path = dirname($attached_file);
962
963 $upload_folder_id = get_option(MAXGALLERIA_MEDIA_LIBRARY_UPLOAD_FOLDER_ID);
964
965 if($folder_path == '.') {
966 $folder_id = $upload_folder_id;
967 } else {
968 $folder_id = $this->get_parent_by_name($folder_path);
969 }
970 return $folder_id;
971 }
972
973 public function register_mgmlp_post_type() {
974
975 $args = apply_filters(MGMLP_FILTER_POST_TYPE_ARGS, array(
976 'public' => false,
977 'publicly_queryable' => false,
978 'show_ui' => false,
979 'show_in_nav_menus' => false,
980 'show_in_admin_bar' => false,
981 'show_in_menu' => false,
982 'query_var' => true,
983 'hierarchical' => true,
984 'supports' => false,
985 'exclude_from_search' => true
986 ));
987
988 register_post_type(MAXGALLERIA_MEDIA_LIBRARY_POST_TYPE, $args);
989
990 }
991
992 public function add_folder_table () {
993 global $wpdb;
994 require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
995
996 $table = $wpdb->prefix . MAXGALLERIA_MEDIA_LIBRARY_FOLDER_TABLE;
997 $sql = "CREATE TABLE IF NOT EXISTS " . $table . " (
998 `post_id` bigint(20) NOT NULL,
999 `folder_id` bigint(20) NOT NULL,
1000 PRIMARY KEY (`post_id`)
1001 ) DEFAULT CHARSET=utf8;";
1002
1003 dbDelta($sql);
1004
1005 }
1006
1007 public function add_block_access_table() {
1008 global $wpdb;
1009 require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
1010
1011 $table = $wpdb->prefix . MAXGALLERIA_MEDIA_LIBRARY_BLOCK_ACCESS_TABLE;
1012 $sql = "CREATE TABLE IF NOT EXISTS `" . $table . "` (
1013 `attachment_id` bigint(20) NOT NULL,
1014 `hash_id` varchar(256) NULL,
1015 `time` datetime NULL,
1016 `block` tinyint(4) NULL,
1017 `count` mediumint(9) NULL,
1018 `download_limit` mediumint(9) NULL,
1019 `expiration_date` date NULL,
1020 PRIMARY KEY (`attachment_id`)
1021 ) DEFAULT CHARSET=utf8;";
1022
1023 dbDelta($sql);
1024
1025 }
1026
1027 public function add_blocked_ips_table() {
1028 global $wpdb;
1029 require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
1030
1031 $table = $wpdb->prefix . BLOCKED_IPS_TABLE;
1032 $sql = "CREATE TABLE IF NOT EXISTS `" . $table . "` (
1033 `ip_id` bigint(20) NOT NULL AUTO_INCREMENT,
1034 `address` varchar(16) NOT NULL,
1035 PRIMARY KEY (`ip_id`)
1036 ) DEFAULT CHARSET=utf8;";
1037
1038 dbDelta($sql);
1039
1040 }
1041
1042 public function upload_attachment () {
1043 global $is_IIS;
1044
1045 if ( !wp_verify_nonce( $_POST['nonce'], MAXGALLERIA_MEDIA_LIBRARY_NONCE)) {
1046 exit(esc_html__('missing nonce!','maxgalleria-media-library'));
1047 }
1048
1049 // Check if the current user has the capability to upload files
1050 if(!current_user_can('upload_files')){
1051 exit(esc_html__('You do not have the capability to upload files.','maxgalleria-media-library'));
1052 }
1053
1054 if ((isset($_POST['folder_id'])) && (strlen(trim($_POST['folder_id'])) > 0))
1055 $folder_id = intval(trim(sanitize_text_field($_POST['folder_id'])));
1056 else
1057 $folder_id = 0;
1058
1059 if ((isset($_POST['title_text'])) && (strlen(trim($_POST['title_text'])) > 0))
1060 $seo_title_text = trim(sanitize_text_field($_POST['title_text']));
1061 else
1062 $seo_title_text = "";
1063
1064 if ((isset($_POST['alt_text'])) && (strlen(trim($_POST['alt_text'])) > 0))
1065 $alt_text = trim(sanitize_text_field($_POST['alt_text']));
1066 else
1067 $alt_text = "";
1068
1069 $destination = $this->get_folder_path($folder_id);
1070
1071 if(isset($_FILES['file'])){
1072 if ( 0 < $_FILES['file']['error'] ) {
1073 echo esc_html('Error: ' . $_FILES['file']['error'] . '<br>');
1074 } else {
1075
1076
1077 if(!defined('ALLOW_UNFILTERED_UPLOADS')) {
1078 $wp_filetype = wp_check_filetype_and_ext($_FILES['file']['tmp_name'], $_FILES['file']['name'] );
1079
1080 //error_log(print_r($wp_filetype,true));
1081
1082 if ($wp_filetype['ext'] === false) {
1083 ?>
1084 <script>
1085 jQuery("#folder-message").html("<span class='mlp-warning'><?php echo esc_html($_FILES['file']['name'] . esc_html__(' file\'s type is invalid.', 'maxgalleria-media-library')); ?></span>");
1086 </script>
1087 <?php
1088 exit;
1089 }
1090 }
1091
1092 // insure it has a unique name
1093 $title_text = $_FILES['file']['name'];
1094 $new_filename = wp_unique_filename( $destination, $_FILES['file']['name'], null );
1095
1096 if ($is_IIS || strtoupper(substr(PHP_OS, 0, 3)) == 'WIN' || strtoupper(substr(PHP_OS, 0, 13)) == 'MICROSOFT-IIS' )
1097 $destination = rtrim($destination, '\\');
1098
1099 $filename = $destination . DIRECTORY_SEPARATOR . $new_filename;
1100
1101 if(file_exists($destination)) {
1102 if( move_uploaded_file($_FILES['file']['tmp_name'], $filename) ) {
1103
1104 // Set correct file permissions.
1105 $stat = stat( dirname( $filename ));
1106 $perms = $stat['mode'] & 0000664;
1107 @chmod( $filename, $perms );
1108
1109 $attach_id = $this->add_new_attachment($filename, $folder_id, $title_text, $alt_text, $seo_title_text);
1110
1111 //error_log("bdp_autoprotect " . $this->bdp_autoprotect);
1112 if($this->bda == 'on' && $this->bdp_autoprotect == 'on') {
1113 $message = $this->move_to_protected_folder($attach_id, $folder_id, 0);
1114 }
1115
1116 $this->display_folder_contents ($folder_id);
1117
1118 }
1119 } else {
1120 ?>
1121 <script>
1122 jQuery("#folder-message").html("<span class='mlp-warning'><?php esc_html__(' Unable to move the file to the destination folder; the folder may not exist.', 'maxgalleria-media-library') ?></span>");
1123 </script>
1124 <?php
1125 }
1126 }
1127 }
1128 die();
1129 }
1130
1131 public function add_new_attachment($filename, $folder_id, $title_text="", $alt_text="", $seo_title_text="") {
1132
1133 global $is_IIS;
1134 $parent_post_id = 0;
1135 $exif_data = array();
1136 $ImageDescription = "";
1137
1138 // prevent unauthorized users from uploading
1139 if (!current_user_can('upload_files')) {
1140 wp_die(__('You do not have permission to upload files.', 'maxgalleria-media-library'));
1141 }
1142
1143 //error_log("add_new_attachment, add_new_attachment, $folder_id");
1144
1145 //remove_action( 'add_attachment', array($this,'add_attachment_to_folder'));
1146 remove_filter( 'wp_generate_attachment_metadata', array($this, 'add_attachment_to_folder2'));
1147
1148 // Check the type of file. We'll use this as the 'post_mime_type'.
1149 $filetype = wp_check_filetype( basename( $filename ), null );
1150
1151 if(isset($filetype['type'])) {
1152 if($filetype['type'] == 'image/jpeg') {
1153 if(extension_loaded("exif")) {
1154 $exif_data = exif_read_data($filename);
1155 }
1156 }
1157 }
1158
1159 // Get the path to the upload directory.
1160 $wp_upload_dir = wp_upload_dir();
1161
1162 $file_url = $this->get_file_url_for_copy($filename);
1163
1164 $image_seo = get_option(MAXGALLERIA_MEDIA_LIBRARY_IMAGE_SEO, 'off');
1165
1166 if(isset($filetype['type']) && $filetype['type'] == 'image/jpeg') {
1167 if(isset($exif_data['FileName'])) {
1168 $title_text = $exif_data['FileName'];
1169 }
1170 if(isset($exif_data['ImageDescription'])) {
1171 $ImageDescription = $exif_data['ImageDescription'];
1172 }
1173 }
1174
1175 // remove the extention from the file name
1176 $position = strrpos($title_text, '.');
1177 if($position)
1178 $title_text = substr ($title_text, 0, $position);
1179
1180 if($image_seo === 'on') {
1181
1182 $folder_name = $this->get_folder_name($folder_id);
1183
1184 $file_name = $this->remove_extension(basename($filename));
1185
1186 $file_name = str_replace('-', ' ', $file_name);
1187
1188 $new_file_title = $seo_title_text;
1189
1190 $new_file_title = str_replace('%foldername', $folder_name, $new_file_title );
1191
1192 $new_file_title = str_replace('%filename', $file_name, $new_file_title );
1193
1194 $default_alt = $alt_text;
1195
1196 $default_alt = str_replace('%foldername', $folder_name, $default_alt );
1197
1198 $default_alt = str_replace('%filename', $file_name, $default_alt );
1199
1200 } else {
1201 //$new_file_title = preg_replace( '/\.[^.]+$/', '', basename( $filename ) );
1202 $new_file_title = $title_text;
1203 }
1204
1205 // Prepare an array of post data for the attachment.
1206 $attachment = array(
1207 'guid' => $file_url,
1208 'post_mime_type' => $filetype['type'],
1209 'post_title' => $new_file_title,
1210 'post_parent' => 0,
1211 'post_content' => '',
1212 'post_excerpt' => $ImageDescription,
1213 'post_status' => 'inherit'
1214 );
1215
1216 // Insert the attachment.
1217 if (! ($attach_id = get_file_attachment_id($filename))) {
1218 $attach_id = wp_insert_attachment( $attachment, $filename, $parent_post_id );
1219 }
1220
1221 if($image_seo == 'on')
1222 update_post_meta($attach_id, '_wp_attachment_image_alt', $default_alt);
1223
1224 // Make sure that this file is included, as wp_generate_attachment_metadata() depends on it.
1225 require_once( ABSPATH . 'wp-admin/includes/image.php' );
1226
1227 // Generate the metadata for the attachment (if it doesn't already exist), and update the database record.
1228 if (! wp_get_attachment_metadata($attach_id, TRUE)) {
1229 if ($is_IIS || strtoupper(substr(PHP_OS, 0, 3)) == 'WIN' || strtoupper(substr(PHP_OS, 0, 13)) == 'MICROSOFT-IIS' )
1230 $attach_data = wp_generate_attachment_metadata( $attach_id, addslashes($filename));
1231 else
1232 $attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
1233
1234 wp_update_attachment_metadata( $attach_id, $attach_data );
1235 }
1236
1237 if($this->is_windows()) {
1238
1239 // get the uploads dir name
1240 $basedir = $this->upload_dir['baseurl'];
1241 $uploads_dir_name_pos = strrpos($basedir, '/');
1242 $uploads_dir_name = substr($basedir, $uploads_dir_name_pos+1);
1243
1244 //find the name and cut off the part with the uploads path
1245 $string_position = strpos($filename, $uploads_dir_name);
1246 $uploads_dir_length = strlen($uploads_dir_name) + 1;
1247 $uploads_location = substr($filename, $string_position+$uploads_dir_length);
1248 $uploads_location = str_replace('\\','/', $uploads_location);
1249 $uploads_location = ltrim($uploads_location, '/');
1250
1251 // put the short path into postmeta
1252 $media_file = get_post_meta( $attach_id, '_wp_attached_file', true );
1253
1254 if($media_file !== $uploads_location )
1255 update_post_meta( $attach_id, '_wp_attached_file', $uploads_location );
1256 }
1257
1258 $this->add_new_folder_parent($attach_id, $folder_id );
1259 //add_action( 'add_attachment', array($this,'add_attachment_to_folder'));
1260 add_filter( 'wp_generate_attachment_metadata', array($this, 'add_attachment_to_folder2'), 10, 4);
1261
1262 return $attach_id;
1263
1264 }
1265
1266 public function update_links($rename_image_location, $rename_destination) {
1267
1268 global $wpdb;
1269
1270 $table_list = apply_filters( MGMLP_FILTER_SET_UPDATE_TABLE_LINKS, '');
1271 $field_list = apply_filters( MGMLP_FILTER_SET_UPDATE_TABLE_FIELDS, '');
1272
1273 $table_list = str_replace(' ', '', $table_list);
1274 $field_list = str_replace(' ', '', $field_list);
1275
1276 if(!empty($table_list)) {
1277 $table_list = "$wpdb->posts," . $table_list;
1278 $tables = explode(',', $table_list);
1279 } else {
1280 $tables = array("$wpdb->posts");
1281 }
1282
1283 if(!empty($field_list)) {
1284 $field_list = "post_content," . $field_list;
1285 $fields = explode(',', $field_list);
1286 } else {
1287 $fields = array("post_content");
1288 }
1289
1290 if(is_array($table_list) || is_array($field_list)) {
1291 if(count($table_list) != count($field_list)) {
1292 error_log(__('An unequal number of items were sent to update_links function.','maxgalleria-media-library'));
1293 return;
1294 }
1295 }
1296
1297 $pairs = array_combine($tables, $fields);
1298
1299 foreach($pairs as $key => $value) {
1300 $replace_sql = "UPDATE $key SET `$value` = REPLACE (`$value`, '$rename_image_location', '$rename_destination');";
1301 $result = $wpdb->query($replace_sql);
1302 //error_log("replace_sql $replace_sql");
1303
1304 $replace_sql = str_replace ( '/', '\\/', $replace_sql);
1305 $result = $wpdb->query($replace_sql);
1306 }
1307
1308 }
1309
1310 public function remove_extension($file_name) {
1311 $position = strrpos($file_name, '.');
1312 if($position === false)
1313 return $file_name;
1314 else
1315 return substr($file_name, 0, $position);
1316 }
1317
1318 public function scan_attachments () {
1319
1320 global $wpdb;
1321
1322 $uploads_path = wp_upload_dir();
1323
1324 if(!$uploads_path['error']) {
1325
1326 //find the uploads folder
1327 $base_url = $uploads_path['baseurl'];
1328 $last_slash = strrpos($base_url, '/');
1329 $uploads_dir = substr($base_url, $last_slash+1);
1330 $this->uploads_folder_name = $uploads_dir;
1331 $this->uploads_folder_name_length = strlen($uploads_dir);
1332
1333 update_option(MAXGALLERIA_MEDIA_LIBRARY_UPLOAD_FOLDER_NAME, $uploads_dir);
1334
1335 //create uploads parent media folder
1336 $uploads_parent_id = $this->add_media_folder($uploads_dir, 0, $base_url);
1337 update_option(MAXGALLERIA_MEDIA_LIBRARY_UPLOAD_FOLDER_ID, $uploads_parent_id);
1338
1339 $baseurl = $this->upload_dir['baseurl'];
1340 // use for comparisons
1341 $uploads_base_url = rtrim($baseurl, '/');
1342 $baseurl = rtrim($baseurl, '/') . '/';
1343
1344 $sql = "SELECT ID, pm.meta_value as attached_file
1345 FROM {$wpdb->prefix}posts
1346 LEFT JOIN {$wpdb->prefix}postmeta AS pm ON pm.post_id = {$wpdb->prefix}posts.ID
1347 WHERE post_type = 'attachment'
1348 AND pm.meta_key = '_wp_attached_file'
1349 ORDER by ID";
1350
1351 $rows = $wpdb->get_results($sql);
1352
1353 $current_folder = "";
1354
1355 $parent_id = $uploads_parent_id;
1356
1357 if($rows) {
1358 foreach($rows as $row) {
1359
1360 if( strpos($row->attached_file, "http:") !== false ||
1361 strpos($row->attached_file, "https:") !== false ||
1362 strpos($row->attached_file, "'") !== false) {
1363 } else {
1364
1365 $image_location = $baseurl . ltrim($row->attached_file, '/');
1366
1367 // check for and add files in the uploads or root media library folder
1368 $uploads_location = $this->strip_base_file($image_location);
1369 if($uploads_base_url == $uploads_location) {
1370 $this->add_new_folder_parent($row->ID, $uploads_parent_id);
1371 continue;
1372 }
1373
1374 //check for protected folders
1375 if(!empty($image_location)) {
1376 if(strpos($image_location, MLFP_PROTECTED_DIRECTORY)) {
1377 $image_location = str_replace(MLFP_PROTECTED_DIRECTORY . '/', '', $image_location );
1378 }
1379 }
1380
1381 $sub_folders = $this->get_folders($image_location);
1382 $attachment_file = array_pop($sub_folders);
1383
1384 $uploads_length = strlen($uploads_dir);
1385 $new_folder_pos = strpos($image_location, $uploads_dir );
1386 $folder_path = substr($image_location, 0, $new_folder_pos+$uploads_length );
1387
1388 foreach($sub_folders as $sub_folder) {
1389
1390 // check for URL path in database
1391 $folder_path = $folder_path . '/' . $sub_folder;
1392
1393 $new_parent_id = $this->folder_exist($folder_path);
1394 if($new_parent_id === false) {
1395 if($this->is_new_top_level_folder($uploads_dir, $sub_folder, $folder_path)) {
1396 $parent_id = $this->add_media_folder($sub_folder, $uploads_parent_id, $folder_path);
1397 } else {
1398 $parent_id = $this->add_media_folder($sub_folder, $parent_id, $folder_path);
1399 }
1400 } else {
1401 $parent_id = $new_parent_id;
1402 }
1403 }
1404
1405 $this->add_new_folder_parent($row->ID, $parent_id );
1406 } // test for http
1407 } //foreach
1408
1409 } //rows
1410 //if ( ! wp_next_scheduled( 'new_folder_check' ) )
1411 // wp_schedule_event( time(), 'daily', 'new_folder_check' );
1412
1413 }
1414
1415 // echo "done";
1416 // die();
1417
1418 }
1419
1420 public function strip_base_file($url){
1421 $parts = explode("/", $url);
1422 if(count($parts) < 4) return $url . "/";
1423 if(strpos(end($parts), ".") !== false){
1424 array_pop($parts);
1425 }else if(end($parts) !== ""){
1426 $parts[] = "";
1427 }
1428
1429 return implode("/", $parts);
1430 }
1431
1432 private function is_new_top_level_folder($uploads_dir, $folder_name, $folder_path) {
1433
1434 $needle = $uploads_dir . '/' . $folder_name;
1435 if(strpos($folder_path . '/' , $needle . '/'))
1436 return true;
1437 else
1438 return false;
1439 }
1440
1441 private function get_folders($path) {
1442 $sub_folders = explode('/', $path);
1443 while( $sub_folders[0] !== $this->uploads_folder_name ) {
1444 array_shift($sub_folders);
1445 }
1446
1447 if($sub_folders[0] === $this->uploads_folder_name)
1448 array_shift($sub_folders);
1449
1450 return $sub_folders;
1451 }
1452
1453 private function get_folders2($path) {
1454 $sub_folders = explode('/', $path);
1455 foreach($sub_folders as $id => $folderName)
1456 if ( $folderName === $this->uploads_folder_name )
1457 return array_slice($sub_folders, $id+1);
1458 return array();
1459 }
1460
1461 public function folder_exist($folder_path) {
1462 global $wpdb;
1463
1464 // Normalize and sanitize the folder path
1465 $relative_path = substr($folder_path, $this->base_url_length);
1466 $relative_path = ltrim($relative_path, '/');
1467 $relative_path = sanitize_text_field($relative_path);
1468
1469 $normalized_relative_path = strtolower(rtrim(preg_replace('/\/+/', '/', $relative_path), '/'));
1470 //error_log("normalized_relative_path $normalized_relative_path");
1471
1472 // Use a prepared statement to query the database
1473 $sql = $wpdb->prepare(
1474 "SELECT p.ID
1475 FROM $wpdb->posts p
1476 INNER JOIN $wpdb->postmeta pm ON pm.post_id = p.ID
1477 WHERE pm.meta_value = %s
1478 AND pm.meta_key = '_wp_attached_file'
1479 LIMIT 1",
1480 $normalized_relative_path
1481 );
1482
1483 // Execute the query
1484 $row = $wpdb->get_row($sql);
1485
1486 // Return the ID if the folder exists, otherwise false
1487 return $row ? $row->ID : false;
1488 }
1489
1490 private function folder_exist2($folder_path) {
1491
1492 global $wpdb;
1493
1494 $relative_path = substr($folder_path, $this->base_url_length);
1495 $relative_path = ltrim($relative_path, '/');
1496
1497 $sql = "SELECT ID FROM {$wpdb->prefix}posts
1498 LEFT JOIN {$wpdb->prefix}postmeta AS pm ON pm.post_id = ID
1499 WHERE pm.meta_value = '$relative_path'
1500 and pm.meta_key = '_wp_attached_file'";
1501
1502 $row = $wpdb->get_row($sql);
1503 if($row === null)
1504 return false;
1505 else
1506 return $row->ID;
1507
1508 }
1509
1510 public function add_media_folder($folder_name, $parent_folder, $base_path ) {
1511
1512 global $wpdb;
1513 $table = $wpdb->prefix . "posts";
1514
1515 $new_folder_id = $this->mpmlp_insert_post(MAXGALLERIA_MEDIA_LIBRARY_POST_TYPE, $folder_name, $base_path, 'publish' );
1516
1517 $attachment_location = substr($base_path, $this->base_url_length);
1518 $attachment_location = ltrim($attachment_location, '/');
1519
1520 update_post_meta($new_folder_id, '_wp_attached_file', $attachment_location);
1521
1522 $this->add_new_folder_parent($new_folder_id, $parent_folder);
1523
1524 return $new_folder_id;
1525
1526 }
1527
1528 public function add_new_folder_parent($record_id, $parent_folder) {
1529
1530 global $wpdb;
1531 $record_id = intval($record_id);
1532 $table = $wpdb->prefix . MAXGALLERIA_MEDIA_LIBRARY_FOLDER_TABLE;
1533
1534 // check for existing record
1535 $sql = "select post_id from $table where post_id = $record_id";
1536
1537 if($wpdb->get_var($sql) == NULL) {
1538
1539 $new_record = array(
1540 'post_id' => $record_id,
1541 'folder_id' => $parent_folder
1542 );
1543
1544 $wpdb->insert( $table, $new_record );
1545 }
1546
1547 }
1548
1549 public function load_textdomain() {
1550 load_plugin_textdomain('maxgalleria-media-library', false, dirname(plugin_basename(__FILE__)) . '/languages/');
1551 }
1552
1553 public function ignore_notice() {
1554 if (current_user_can('install_plugins')) {
1555 global $current_user;
1556
1557 if (isset($_GET['maxgalleria-media-library-ignore-notice']) && $_GET['maxgalleria-media-library-ignore-notice'] == 1) {
1558 add_user_meta($current_user->ID, MAXGALLERIA_MEDIA_LIBRARY_IGNORE_NOTICE, true, true);
1559 }
1560 }
1561 }
1562
1563 public function show_mlp_admin_notice() {
1564 global $current_user;
1565
1566 if(isset($_REQUEST['page'])) {
1567
1568 if($_REQUEST['page'] == 'media-library-folders'
1569 || $_REQUEST['page'] === 'mlf-support8'
1570 || $_REQUEST['page'] === 'mlf-settings8'
1571 || $_REQUEST['page'] === 'mlf-image-seo'
1572 || $_REQUEST['page'] === 'mlf-thumbnails'
1573 || $_REQUEST['page'] === 'search-library' ) {
1574
1575
1576 $features = get_user_meta( $current_user->ID, MAXGALLERIA_MLP_FEATURE_NOTICE, true );
1577 $review = get_user_meta( $current_user->ID, MAXGALLERIA_MLP_REVIEW_NOTICE, true );
1578 if( $review !== 'off' || $features !== 'off') {
1579 if($features === '') {
1580 $features_date = date('Y-m-d', strtotime("+30 days"));
1581 update_user_meta( $current_user->ID, MAXGALLERIA_MLP_FEATURE_NOTICE, $features_date );
1582 }
1583 if($review === '') {
1584 //show review notice after three days
1585 $review_date = date('Y-m-d', strtotime("+3 days"));
1586 update_user_meta( $current_user->ID, MAXGALLERIA_MLP_REVIEW_NOTICE, $review_date );
1587
1588 //show notice if not found
1589 //add_action( 'admin_notices', array($this, 'mlp_review_notice' ));
1590 } else if( $review !== 'off') {
1591 $now = date("Y-m-d");
1592 $review_time = strtotime($review);
1593 $features_time = strtotime($features);
1594 $now_time = strtotime($now);
1595
1596 if($now_time > $features_time && $features !== 'off')
1597 add_action( 'admin_notices', array($this, 'mlp_features_notice' ));
1598 else if($now_time > $review_time)
1599 add_action( 'admin_notices', array($this, 'mlp_review_notice' ));
1600 } else if( $features !== 'off') {
1601 $now = date("Y-m-d");
1602 $features_time = strtotime($features);
1603 $now_time = strtotime($now);
1604 if($now_time > $features_time && $features !== 'off')
1605 add_action( 'admin_notices', array($this, 'mlp_features_notice' ));
1606 }
1607 }
1608 }
1609 }
1610 }
1611
1612 /* if no upload fold id, check the folder table */
1613 private function fetch_uploads_folder_id() {
1614 global $wpdb;
1615 $sql = "SELECT * FROM {$wpdb->prefix}mgmlp_folders order by folder_id limit 1";
1616 $row = $wpdb->get_row($sql);
1617 if($row) {
1618 return $row->post_id;
1619 } else {
1620 return false;
1621 }
1622 }
1623
1624 private function lookup_uploads_folder_name($current_folder_id) {
1625 global $wpdb;
1626 $current_folder_id = intval($current_folder_id);
1627 $sql = "SELECT post_title FROM {$wpdb->prefix}posts where ID = $current_folder_id";
1628 $folder_name = $wpdb->get_var($sql);
1629 return $folder_name;
1630 }
1631
1632 public function get_maxgalleria_galleries() {
1633
1634 global $wpdb;
1635
1636 $sql = "select ID, post_title
1637 from {$wpdb->prefix}posts
1638 LEFT JOIN {$wpdb->prefix}postmeta ON({$wpdb->prefix}posts.ID = {$wpdb->prefix}postmeta.post_id)
1639 where post_type = 'maxgallery' and post_status = 'publish'
1640 and {$wpdb->prefix}postmeta.meta_key = 'maxgallery_type'
1641 and {$wpdb->prefix}postmeta.meta_value = 'image'
1642 order by LOWER(post_name)";
1643
1644 //error_log($sql);
1645
1646 $gallery_list = "";
1647 $rows = $wpdb->get_results($sql);
1648
1649 if($rows) {
1650 foreach ($rows as $row) {
1651 $gallery_list .='<option value="' . esc_attr($row->ID) . '">' . esc_html($row->post_title) . '</option>' . PHP_EOL;
1652 }
1653 }
1654 return $gallery_list;
1655 }
1656
1657 public function display_folder_contents ($current_folder_id, $image_link = true, $folders_path = '', $echo = true) {
1658
1659 $folders_found = false;
1660 $images_found = false;
1661 $output = "";
1662
1663 if($image_link)
1664 $image_link = "1";
1665 else
1666 $image_link = "0";
1667
1668 // build the Javascript code to load the folder contents
1669 $output .= '<script type="text/javascript">' . PHP_EOL;
1670 $output .= ' jQuery(document).ready(function() {' . PHP_EOL;
1671 $output .= ' var mif_visible = (jQuery("#mgmlp-media-search-input").is(":visible")) ? false : true;' . PHP_EOL;
1672 $output .= ' jQuery.ajax({' . PHP_EOL;
1673 $output .= ' type: "POST",' . PHP_EOL;
1674 $output .= ' async: true,' . PHP_EOL;
1675 $output .= ' data: { action: "mlp_display_folder_contents_ajax", current_folder_id: "' . esc_attr($current_folder_id) . '", image_link: "' . esc_attr($image_link) . '", mif_visible: mif_visible, nonce: mgmlp_ajax.nonce },' . PHP_EOL;
1676 $output .= ' url: mgmlp_ajax.ajaxurl,' . PHP_EOL;
1677 $output .= ' dataType: "html",' . PHP_EOL;
1678 $output .= ' success: function (data) ' . PHP_EOL;
1679 $output .= ' {' . PHP_EOL;
1680 $output .= ' jQuery("#mgmlp-file-container").html(data);' . PHP_EOL;
1681 $output .= ' jQuery("li a.media-attachment").draggable({' . PHP_EOL;
1682 $output .= ' cursor: "move",' . PHP_EOL;
1683 $output .= ' cursorAt: { left: 25, top: 25 },' . PHP_EOL;
1684 $output .= ' helper: function() {' . PHP_EOL;
1685 $output .= ' var selected = jQuery(".mg-media-list input:checked").parents("li");' . PHP_EOL;
1686 $output .= ' if (selected.length === 0) {' . PHP_EOL;
1687 $output .= ' selected = jQuery(this);' . PHP_EOL;
1688 $output .= ' }' . PHP_EOL;
1689 $output .= ' var container = jQuery("<div/>").attr("id", "draggingContainer");' . PHP_EOL;
1690 $output .= ' container.append(selected.clone());' . PHP_EOL;
1691 $output .= ' return container;' . PHP_EOL;
1692 $output .= ' }' . PHP_EOL;
1693
1694 $output .= ' });' . PHP_EOL;
1695 $output .= ' display_protected_files();' . PHP_EOL;
1696
1697 $output .= ' jQuery(".media-link").droppable( {' . PHP_EOL;
1698 $output .= ' accept: "li a.media-attachment",' . PHP_EOL;
1699 $output .= ' hoverClass: "droppable-hover",' . PHP_EOL;
1700 $output .= ' drop: handleDropEvent' . PHP_EOL;
1701 $output .= ' });' . PHP_EOL;
1702
1703 $output .= ' },' . PHP_EOL;
1704 $output .= ' error: function (err)' . PHP_EOL;
1705 $output .= ' { alert(err.responseText)}' . PHP_EOL;
1706 $output .= ' });' . PHP_EOL;
1707
1708 if($folders_path !== '') {
1709 $output .= ' jQuery("#mgmlp-breadcrumbs").html("'. esc_html__('Location:','maxgalleria-media-library') . " " . addslashes($folders_path) .'");' . PHP_EOL;
1710 }
1711
1712 $output .= ' });' . PHP_EOL;
1713 $output .= '</script>' . PHP_EOL;
1714
1715 add_filter( 'wp_kses_allowed_html', array($this, 'kses_mlf_add_allowed_html'), 10, 4);
1716 if($echo) {
1717 echo wp_kses_post($output);
1718 } else {
1719 return wp_kses_post($output);
1720 }
1721 remove_filter( 'wp_kses_allowed_html', array($this, 'kses_mlf_add_allowed_html'));
1722
1723 }
1724
1725 public function kses_mlf_add_allowed_html($html, $context) {
1726 if($context == 'post') {
1727 $new_html = array(
1728 'script' => array(
1729 'type' => 1
1730 )
1731 );
1732
1733 $html = array_merge($html, $new_html);
1734 }
1735 return $html;
1736 }
1737
1738 public function in_array_r($needle, $haystack, $strict = false) {
1739 foreach ($haystack as $item) {
1740 if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && $this->in_array_r($needle, $item, $strict))) {
1741 return true;
1742 }
1743 }
1744 return false;
1745 }
1746
1747 public function mlp_display_folder_contents_ajax() {
1748
1749 global $wpdb;
1750
1751 //$folders_found = false;
1752
1753 // Check if the current user has the capability to upload files
1754 if(!current_user_can('upload_files')){
1755 exit(esc_html__('You do not have the capability to upload files.','maxgalleria-media-library'));
1756 }
1757
1758 $sort_order = get_option(MAXGALLERIA_MEDIA_LIBRARY_SORT_ORDER);
1759 $sort_type = trim(get_option( MAXGALLERIA_MLF_SORT_TYPE ));
1760
1761 switch($sort_order) {
1762 default:
1763 case '0': //order by date
1764 $order_by = "post_date $sort_type";
1765 break;
1766
1767 case '1': //order by name
1768 $order_by = "LOWER(attached_file) $sort_type";
1769 break;
1770 }
1771
1772 if ( !wp_verify_nonce( $_POST['nonce'], MAXGALLERIA_MEDIA_LIBRARY_NONCE)) {
1773 exit(esc_html__('missing nonce! Please refresh this page.','maxgalleria-media-library'));
1774 }
1775
1776 // Check if the current user has the capability to upload files
1777 if(!current_user_can('upload_files')){
1778 exit(esc_html__('You do not have the capability to upload files.','maxgalleria-media-library'));
1779 }
1780
1781 if ((isset($_POST['current_folder_id'])) && (strlen(trim($_POST['current_folder_id'])) > 0))
1782 $current_folder_id = intval(trim(sanitize_text_field($_POST['current_folder_id'])));
1783 else
1784 $current_folder_id = 0;
1785
1786 if ((isset($_POST['image_link'])) && (strlen(trim($_POST['image_link'])) > 0))
1787 $image_link = trim(sanitize_text_field($_POST['image_link']));
1788 else
1789 $image_link = "0";
1790
1791 if ((isset($_POST['display_type'])) && (strlen(trim($_POST['display_type'])) > 0))
1792 $display_type = trim(sanitize_text_field($_POST['display_type']));
1793 else
1794 $display_type = 0;
1795
1796 if ((isset($_POST['mif_visible'])) && (strlen(trim($_POST['mif_visible'])) > 0))
1797 $mif_visible = trim(sanitize_text_field($_POST['mif_visible']));
1798 else
1799 $mif_visible = false;
1800
1801 if($mif_visible === 'true')
1802 $mif_visible = true;
1803
1804 $folder_table = $wpdb->prefix . MAXGALLERIA_MEDIA_LIBRARY_FOLDER_TABLE;
1805
1806 $this->display_folder_nav($current_folder_id, $folder_table);
1807
1808 $this->display_files($image_link, $current_folder_id, $folder_table, $display_type, $order_by, $mif_visible );
1809
1810 die();
1811
1812 }
1813
1814 public function mlp_display_folder_contents_images_ajax() {
1815
1816 global $wpdb;
1817
1818 // Check if the current user has the capability to upload files
1819 if(!current_user_can('upload_files')){
1820 exit(esc_html__('You do not have the capability to upload files.','maxgalleria-media-library'));
1821 }
1822
1823 $sort_order = get_option(MAXGALLERIA_MEDIA_LIBRARY_SORT_ORDER);
1824 $sort_type = trim(get_option( MAXGALLERIA_MLF_SORT_TYPE ));
1825
1826 switch($sort_order) {
1827 default:
1828 case '0': //order by date
1829 $order_by = "post_date $sort_type";
1830 break;
1831
1832 case '1': //order by name
1833 $order_by = "LOWER(attached_file) $sort_type";
1834 break;
1835 }
1836
1837 if ( !wp_verify_nonce( $_POST['nonce'], MAXGALLERIA_MEDIA_LIBRARY_NONCE)) {
1838 exit(esc_html__('missing nonce! Please refresh this page.','maxgalleria-media-library'));
1839 }
1840
1841 // Check if the current user has the capability to upload files
1842 if(!current_user_can('upload_files')){
1843 exit(esc_html__('You do not have the capability to upload files.','maxgalleria-media-library'));
1844 }
1845
1846 if ((isset($_POST['current_folder_id'])) && (strlen(trim($_POST['current_folder_id'])) > 0))
1847 $current_folder_id = intval(trim(sanitize_text_field($_POST['current_folder_id'])));
1848 else
1849 $current_folder_id = 0;
1850
1851 if ((isset($_POST['image_link'])) && (strlen(trim($_POST['image_link'])) > 0))
1852 $image_link = trim(sanitize_text_field($_POST['image_link']));
1853 else
1854 $image_link = "0";
1855
1856 if ((isset($_POST['display_type'])) && (strlen(trim($_POST['display_type'])) > 0))
1857 $display_type = trim(sanitize_text_field($_POST['display_type']));
1858 else
1859 $display_type = 0;
1860
1861 $folder_table = $wpdb->prefix . MAXGALLERIA_MEDIA_LIBRARY_FOLDER_TABLE;
1862
1863 $this->display_files($image_link, $current_folder_id, $folder_table, $display_type, $order_by );
1864
1865 die();
1866
1867 }
1868
1869 public function display_folder_nav_ajax () {
1870
1871 if ( !wp_verify_nonce( $_POST['nonce'], MAXGALLERIA_MEDIA_LIBRARY_NONCE)) {
1872 exit(esc_html__('missing nonce! Please refresh this page.','maxgalleria-media-library'));
1873 }
1874
1875 // Check if the current user has the capability to upload files
1876 if(!current_user_can('upload_files')){
1877 exit(esc_html__('You do not have the capability to upload files.','maxgalleria-media-library'));
1878 }
1879
1880 if ((isset($_POST['current_folder_id'])) && (strlen(trim($_POST['current_folder_id'])) > 0))
1881 $current_folder_id = intval(trim(sanitize_text_field($_POST['current_folder_id'])));
1882 else
1883 $current_folder_id = 0;
1884
1885 $folder_table = $wpdb->prefix . MAXGALLERIA_MEDIA_LIBRARY_FOLDER_TABLE;
1886
1887 $this->display_folder_nav($current_folder_id, $folder_table);
1888
1889 die();
1890
1891 }
1892
1893 public function mlp_get_folder_data() {
1894
1895 if ( !wp_verify_nonce( $_POST['nonce'], MAXGALLERIA_MEDIA_LIBRARY_NONCE)) {
1896 exit(esc_html__('missing nonce! Please refresh this page.','maxgalleria-media-library'));
1897 }
1898
1899 // Check if the current user has the capability to upload files
1900 if(!current_user_can('upload_files')){
1901 exit(esc_html__('You do not have the capability to upload files.','maxgalleria-media-library'));
1902 }
1903
1904 if ((isset($_POST['current_folder_id'])) && (strlen(trim($_POST['current_folder_id'])) > 0))
1905 $current_folder_id = intval(trim(sanitize_text_field($_POST['current_folder_id'])));
1906 else
1907 $current_folder_id = get_option(MAXGALLERIA_MEDIA_LIBRARY_UPLOAD_FOLDER_ID );
1908
1909 $folders = array();
1910 $folders = $this->get_folder_data($current_folder_id);
1911
1912 echo json_encode($folders);
1913
1914 die();
1915
1916 }
1917
1918 public function get_folder_data($current_folder_id) {
1919
1920 global $wpdb;
1921 $current_folder_id = intval($current_folder_id);
1922
1923 $folder_parents = $this->get_parents($current_folder_id);
1924 $folder_table = $wpdb->prefix . MAXGALLERIA_MEDIA_LIBRARY_FOLDER_TABLE;
1925
1926 $sql = "select ID, post_title, $folder_table.folder_id
1927 from {$wpdb->prefix}posts
1928 LEFT JOIN $folder_table ON({$wpdb->prefix}posts.ID = $folder_table.post_id)
1929 where post_type = '" . MAXGALLERIA_MEDIA_LIBRARY_POST_TYPE ."'
1930 order by folder_id";
1931
1932 $add_child = array();
1933 $folders = array();
1934 $first = true;
1935 $rows = $wpdb->get_results($sql);
1936 if($rows) {
1937 foreach($rows as $row) {
1938
1939 // do not show protected content folder
1940 if($row->post_title == MLFP_PROTECTED_DIRECTORY)
1941 continue;
1942
1943 //$max_id = -1;
1944
1945 //if($row->ID > $max_id)
1946 // $max_id = $row->ID;
1947 $folder = array();
1948 $folder['id'] = esc_attr($row->ID);
1949 if($row->folder_id === '0') {
1950 $folder['parent'] = '#';
1951 } else {
1952 if(!$row->folder_id)
1953 continue;
1954 // check if parent folder even exists
1955 $sql = "select ID from {$wpdb->prefix}posts
1956 where ID = " . esc_attr($row->folder_id) . " and post_type = '".MAXGALLERIA_MEDIA_LIBRARY_POST_TYPE."'";
1957 if (count($wpdb->get_results($sql)) == 0)
1958 continue;
1959 $folder['parent'] = esc_attr($row->folder_id);
1960 }
1961
1962 $folder['text'] = esc_html($row->post_title);
1963 $state = array();
1964 if($row->folder_id === '0') {
1965 $state['opened'] = true;
1966 $state['disabled'] = false;
1967 $state['selected'] = true;
1968 } else if($this->in_array_r($row->ID, $folder_parents)) {
1969 $state['opened'] = true;
1970 } else if($this->uploads_folder_ID === $row->ID) {
1971 $state['opened'] = true;
1972 } else {
1973 $state['opened'] = false;
1974 }
1975 if($row->ID === $current_folder_id) {
1976 $state['opened'] = true;
1977 $state['selected'] = true;
1978 } else
1979 $state['selected'] = false;
1980 $state['disabled'] = false;
1981 $folder['state'] = $state;
1982
1983 $a_attr = array();
1984 $a_attr['href'] = "#" . esc_attr($row->ID);
1985 $a_attr['target'] = '_self';
1986
1987 $folder['a_attr'] = $a_attr;
1988
1989 $add_child[] = $row->ID;
1990 $child_index = array_search($row->folder_id, $add_child);
1991 if($child_index !== false)
1992 unset($add_child[$child_index]);
1993
1994 $folders[] = $folder;
1995 }
1996
1997 }
1998
1999 return $folders;
2000
2001 }
2002
2003 public function new_folder_check() {
2004
2005 $currnet_date_time = date('Y-m-d H:i:s');
2006
2007 $currnet_date_time_seconds = strtotime($currnet_date_time);
2008
2009 $folder_check = get_option('mlf-folder-check', $currnet_date_time);
2010 if($currnet_date_time == $folder_check) {
2011 update_option('mlf-folder-check', $currnet_date_time, true);
2012 return;
2013 }
2014
2015 $folder_check_seconds = strtotime($folder_check . ' +1 hour');
2016
2017 if($folder_check_seconds < $currnet_date_time_seconds) {
2018 $this->admin_check_for_new_folders(true);
2019 if($this->bda == 'on') {
2020 $this->remove_protected_folders();
2021 }
2022 update_option('mlf-folder-check', $currnet_date_time, true);
2023 }
2024
2025 }
2026
2027 public function display_folder_nav($current_folder_id, $folder_table ) {
2028
2029 global $wpdb;
2030
2031 if(!defined('SKIP_AUTO_FOLDER_CHECK'))
2032 $this->new_folder_check();
2033
2034 $folder_parents = $this->get_parents($current_folder_id);
2035 $folder_table = $wpdb->prefix . MAXGALLERIA_MEDIA_LIBRARY_FOLDER_TABLE;
2036
2037 $sql = "select ID, post_title, $folder_table.folder_id
2038 from {$wpdb->prefix}posts
2039 LEFT JOIN $folder_table ON({$wpdb->prefix}posts.ID = $folder_table.post_id)
2040 where post_type = '" . MAXGALLERIA_MEDIA_LIBRARY_POST_TYPE ."'
2041 order by folder_id";
2042
2043 $folders = array();
2044 $folders = $this->get_folder_data($current_folder_id);
2045
2046 ?>
2047
2048 <script>
2049 var mlp_busy = false;
2050 var folders = <?php echo json_encode($folders); ?>;
2051 jQuery(document).ready(function(){
2052 jQuery("#scanning-message").hide();
2053 jQuery("#ajaxloadernav").show();
2054 jQuery('#folder-tree').jstree({ 'core' : {
2055 'multiple' : false,
2056 'data' : folders,
2057 'check_callback' : true
2058 },
2059 'force_text' : true,
2060 'themes' : {
2061 'responsive' : false,
2062 'variant' : 'small',
2063 'stripes' : true
2064 },
2065 'types' : {
2066 'default' : { 'icon' : 'folder' },
2067 'file' : { 'icon' :'folder'},
2068 'valid_children' : {'icon' :'folder'}
2069 },
2070 'sort' : function(a, b) {
2071 return this.get_type(a).toLowerCase() === this.get_type(b).toLowerCase() ? (this.get_text(a).toLowerCase() > this.get_text(b).toLowerCase() ? 1 : -1) : (this.get_type(a).toLowerCase() >= this.get_type(b).toLowerCase() ? 1 : -1);
2072 },
2073 "contextmenu":{
2074 "select_node":false,
2075 "items": function($node) {
2076 var tree = jQuery("#tree").jstree(true);
2077 return {
2078 "Remove": {
2079 "separator_before": false,
2080 "separator_after": false,
2081 "label": "<?php esc_html_e('Delete this folder?','maxgalleria-media-library'); ?>",
2082 "action": function (obj) {
2083 var delete_ids = new Array();
2084 delete_ids[delete_ids.length] = jQuery($node).attr('id');
2085
2086 var folder_id = jQuery('#folder_id').val();
2087 var to_delete = jQuery($node).attr('id');
2088 var parent_id = jQuery($node).attr('parent');
2089
2090 if(confirm("<?php esc_html_e('Are you sure you want to delete the selected folder?','maxgalleria-media-library'); ?>")) {
2091 var serial_delete_ids = JSON.stringify(delete_ids.join());
2092 jQuery("#ajaxloader").show();
2093 jQuery.ajax({
2094 type: "POST",
2095 async: true,
2096 data: { action: "delete_maxgalleria_media", serial_delete_ids: serial_delete_ids, parent: parent_id, nonce: mgmlp_ajax.nonce },
2097 url : mgmlp_ajax.ajaxurl,
2098 dataType: "json",
2099 success: function (data) {
2100
2101 jQuery("#folder-message").html(data.message);
2102 if(data.refresh) {
2103 jQuery('#folder-tree').jstree(true).settings.core.data = data.folders;
2104 jQuery('#folder-tree').jstree(true).refresh();
2105 setTimeout(function() { jQuery('#folder-tree').jstree('select_node', '#' + parent_id); }, 4000);
2106 jQuery("#folder-message").html('');
2107 jQuery("#current-folder-id").val(parent_id);
2108 }
2109 jQuery("#ajaxloader").hide();
2110 },
2111 error: function (err)
2112 { alert(err.responseText);}
2113 });
2114 }
2115 }
2116 },
2117 "Hide": {
2118 "separator_before": false,
2119 "separator_after": false,
2120 "label": "<?php esc_html_e('Hide this folder? This will remove the folder contents from the media library database.','maxgalleria-media-library'); ?>",
2121 "action": function (obj) {
2122 var folder_id = jQuery('#folder_id').val();
2123 var to_hide = jQuery($node).attr('id');
2124
2125 if(confirm("<?php esc_html_e('Are you sure you want to hide the selected folder and all its sub folders and files?','maxgalleria-media-library'); ?>")) {
2126 //var serial_delete_ids = JSON.stringify(delete_ids.join());
2127 jQuery("#ajaxloader").show();
2128 jQuery.ajax({
2129 type: "POST",
2130 async: true,
2131 data: { action: "hide_maxgalleria_media", folder_id: to_hide, nonce: mgmlp_ajax.nonce },
2132 url : mgmlp_ajax.ajaxurl,
2133 dataType: "html",
2134 success: function (data) {
2135 jQuery("#folder-message").html(data);
2136 jQuery("#ajaxloader").hide();
2137 },
2138 error: function (err)
2139 { alert(err.responseText);}
2140 });
2141 }
2142 }
2143 }
2144 }; // end context menu
2145 }
2146 },
2147 'plugins' : [ 'sort', 'types', 'contextmenu' ],
2148 });
2149
2150 // for changing folders
2151 if(!jQuery("ul#folder-tree.jstree").hasClass("bound")) {
2152 jQuery("#folder-tree").addClass("bound").on("select_node.jstree", show_mlp_node);
2153 }
2154
2155 jQuery('#folder-tree').droppable( {
2156 accept: 'li a.media-attachment',
2157 hoverClass: 'jstree-anchor',
2158 drop: handleTreeDropEvent
2159 });
2160
2161 jQuery('#folder-tree').on('copy_node.jstree', function (e, data) {
2162 //console.log(data.node.data.more);
2163 });
2164
2165 jQuery("#ajaxloadernav").hide();
2166 });
2167
2168
2169 function show_mlp_node (e, data) {
2170
2171 if(!window.mlp_busy) {
2172 window.mlp_busy = true;
2173
2174 // opens the closed node
2175 jQuery("#folder-tree").jstree("toggle_node", data.node.id);
2176
2177 var folder = data.node.id;
2178
2179 jQuery("#ajaxloader").show();
2180
2181 jQuery.ajax({
2182 type: "POST",
2183 async: true,
2184 data: { action: "mlp_load_folder", folder: folder, nonce: mgmlp_ajax.nonce },
2185 url : mgmlp_ajax.ajaxurl,
2186 dataType: "html",
2187 success: function (data) {
2188 jQuery("#mgmlp-file-container").html(data);
2189 jQuery("#ajaxloader").hide();
2190 jQuery("#current-folder-id").val(folder);
2191 jQuery("#folder_id").val(folder);
2192 jQuery("#mlf-select-all").prop('checked', false); // reset select all checkbox
2193 sessionStorage.setItem('folder_id', folder);
2194
2195 jQuery("li a.media-attachment").draggable({
2196 cursor: "move",
2197 helper: function() {
2198 var selected = jQuery(".mg-media-list input:checked").parents("li");
2199 if (selected.length == 0) {
2200 selected = jQuery(this);
2201 }
2202 var container = jQuery("<div/>").attr("id", "draggingContainer");
2203 container.append(selected.clone());
2204 return container;
2205 }
2206 });
2207
2208 jQuery(".media-link").droppable( {
2209 accept: "li a.media-attachment",
2210 hoverClass: "droppable-hover",
2211 drop: handleDropEvent
2212 });
2213 },
2214 error: function (err) {
2215 alert(err.responseText);
2216 }
2217 });
2218
2219 window.mlp_busy = false;
2220 }
2221 }
2222
2223 function handleTreeDropEvent(event, ui ) {
2224
2225 var target=event.target || event.srcElement;
2226 //console.log(target);
2227
2228 var move_ids = new Array();
2229 var items = ui.helper.children();
2230 items.each(function() {
2231 move_ids[move_ids.length] = jQuery(this).find( "a.media-attachment" ).attr("id");
2232 });
2233
2234 if(move_ids.length < 2) {
2235 move_ids = new Array();
2236 move_ids[move_ids.length] = ui.draggable.attr("id");
2237 }
2238
2239 //var serial_copy_ids = JSON.stringify(move_ids.join());
2240 var folder_id = jQuery(target).attr("aria-activedescendant");
2241 var current_folder = jQuery("#current-folder-id").val();
2242
2243 var action_name = 'move_media';
2244 var operation_type = jQuery('#move-or-copy-status').val();
2245 if(operation_type == 'on')
2246 action_name = 'move_media';
2247 else
2248 action_name = 'copy_media';
2249
2250 console.log('action_name',action_name);
2251
2252 jQuery("#ajaxloader").show();
2253
2254 var serial_copy_ids = JSON.stringify(move_ids.join());
2255
2256 process_mc_data('1', folder_id, action_name, current_folder, serial_copy_ids);
2257
2258 }
2259
2260 function delete_current_folder(node) {
2261 var folder_id = jQuery(target).attr("aria-activedescendant");
2262 //console.log(folder_id);
2263 }
2264
2265 function process_mc_data(phase, folder_id, action_name, parent_folder, serial_copy_ids) {
2266
2267 jQuery.ajax({
2268 type: "POST",
2269 async: true,
2270 data: { action: "mlfp_process_mc_data", phase: phase, folder_id: folder_id, action_name: action_name, current_folder: parent_folder, serial_copy_ids: serial_copy_ids, nonce: mgmlp_ajax.nonce },
2271 url: mgmlp_ajax.ajaxurl,
2272 dataType: "json",
2273 success: function (data) {
2274 if(data != null && data.phase != null) {
2275 jQuery("#folder-message").html(data.message);
2276 process_mc_data(data.phase, folder_id, action_name, parent_folder, null);
2277 } else {
2278 jQuery("#folder-message").html(data.message);
2279 if(action_name == 'move_media')
2280 mlf_refresh_folders(parent_folder);
2281 jQuery("#ajaxloader").hide();
2282 return false;
2283 }
2284 },
2285 error: function (err){
2286 jQuery("#ajaxloader").hide();
2287 alert(err.responseText);
2288 }
2289 });
2290
2291 }
2292 </script>
2293 <?php
2294
2295 }
2296
2297 public function validateOrderBy($order_by) {
2298 $allowed_values = array(
2299 'post_date ASC',
2300 'post_date DESC',
2301 'LOWER(attached_file) ASC',
2302 'LOWER(attached_file) DESC',
2303 'LOWER(post_title) ASC',
2304 'LOWER(post_title) DESC'
2305 );
2306 if (empty($order_by) || !in_array($order_by, $allowed_values)) {
2307 return 'post_date ASC';
2308 }
2309 return $order_by;
2310 }
2311
2312 public function display_files($image_link, $current_folder_id, $folder_table, $display_type, $order_by, $mif_visible = false) {
2313
2314 global $wpdb;
2315 $current_folder_id = intvaL($current_folder_id);
2316 $images_found = false;
2317 $images_pre_page = get_option(MAXGALLERIA_MLP_ITEMS_PRE_PAGE, '500');
2318 if(empty($images_pre_page))
2319 $images_pre_page = '500';
2320 $author_class = '';
2321
2322 // validate the $order_by SQL
2323 $order_by = $this->validateOrderBy($order_by);
2324
2325 $allowed_html = array(
2326 'input' => array(
2327 'type' => array(),
2328 'class' => array(),
2329 'id' => array(),
2330 'protected' => array(),
2331 'value' => array()
2332 )
2333 );
2334
2335 $blocked_image_url = '';
2336 $block_access_table = sanitize_text_field($wpdb->prefix . MAXGALLERIA_MEDIA_LIBRARY_BLOCK_ACCESS_TABLE);
2337 $current_user = get_current_user_id();
2338 $is_admin = current_user_can('manage_options');
2339
2340 if($image_link === "1")
2341 $image_link = true;
2342 else
2343 $image_link = false;
2344
2345 ?>
2346 <ul class="mg-media-list">
2347 <?php
2348
2349 if($this->bda == 'on') {
2350
2351 global $wpdb;
2352
2353 // $order_by is validate by the validateOrderBy() function because passing it in via the perpare fucntions puts quote marks around the text which breaks the sorting.
2354
2355 $sql = $wpdb->prepare(
2356 "
2357 SELECT ID, post_title, post_author, post_date, {$folder_table}.folder_id, pm.meta_value as attached_file, IFNULL({$block_access_table}.block,0) as block
2358 FROM {$wpdb->prefix}posts
2359 LEFT JOIN {$folder_table} ON({$wpdb->prefix}posts.ID = {$folder_table}.post_id)
2360 LEFT JOIN {$wpdb->prefix}postmeta AS pm ON (pm.post_id = {$wpdb->prefix}posts.ID)
2361 LEFT JOIN {$block_access_table} ON({$wpdb->posts}.ID = {$block_access_table}.attachment_id)
2362 WHERE post_type = 'attachment'
2363 AND {$folder_table}.folder_id = %d
2364 AND pm.meta_key = '_wp_attached_file'
2365 ORDER BY $order_by
2366 LIMIT %d, %d
2367 ",
2368 $current_folder_id,
2369 0,
2370 $images_pre_page
2371 );
2372
2373
2374 } else {
2375
2376 global $wpdb;
2377
2378 $sql = $wpdb->prepare(
2379 "
2380 SELECT ID, post_title, post_author, post_date, {$folder_table}.folder_id, pm.meta_value as attached_file, 0 as block
2381 FROM {$wpdb->prefix}posts
2382 LEFT JOIN {$folder_table} ON({$wpdb->prefix}posts.ID = {$folder_table}.post_id)
2383 LEFT JOIN {$wpdb->prefix}postmeta AS pm ON (pm.post_id = {$wpdb->prefix}posts.ID)
2384 WHERE post_type = 'attachment'
2385 AND {$folder_table}.folder_id = %d
2386 AND pm.meta_key = '_wp_attached_file'
2387 ORDER BY $order_by
2388 LIMIT 0, %d
2389 ",
2390 $current_folder_id,
2391 $images_pre_page
2392 );
2393
2394
2395 }
2396
2397
2398 $rows = $wpdb->get_results($sql);
2399 if($rows) {
2400 $images_found = true;
2401 foreach($rows as $row) {
2402
2403 if ( (int) $row->block === 1 ) {
2404
2405 $is_author = ( get_current_user_id() === (int) $row->post_author );
2406 $can_view = (
2407 ( $this->bda_user_role === 'admins' && ! empty( $is_admin ) ) ||
2408 ( $this->bda_user_role === 'authors' && $is_author )
2409 );
2410
2411 if ( $can_view ) {
2412 $author_class = $is_author ? 'author' : '';
2413
2414 if ( wp_attachment_is_image( $row->ID ) ) {
2415 // Updated: use wp_get_attachment_image_url() which honors image sizes and is the modern API.
2416 $blocked_image_url = wp_get_attachment_image_url( $row->ID, 'thumbnail' );
2417 } else {
2418 // Get extension safely from the real file path.
2419 $filepath = get_attached_file( $row->ID );
2420 $ext = $filepath ? pathinfo( $filepath, PATHINFO_EXTENSION ) : '';
2421 $blocked_image_url = $this->get_file_thumbnail( $ext );
2422 $image_file_type = false;
2423 }
2424 } else {
2425 $blocked_image_url = '';
2426 }
2427
2428 } else {
2429
2430 // SAFE: normalize alt to a plain string to avoid PHP 8.3 strip_tags() fatal from arrays.
2431 $alt = $this->mgp_normalize_image_alt_meta( $row->ID );
2432
2433 // Prefer the modern API; pass an explicit size and attributes.
2434 $thumbnail_html = wp_get_attachment_image(
2435 $row->ID,
2436 'thumbnail',
2437 false,
2438 array(
2439 'alt' => $alt,
2440 'class' => 'mlp-thumb',
2441 )
2442 );
2443
2444 // Fallback if no HTML returned (e.g., missing metadata or preview not generated)
2445 if ( empty( $thumbnail_html ) ) {
2446 $thumbnail = wp_get_attachment_image_url( $row->ID, 'thumbnail' );
2447
2448 if ( empty( $thumbnail ) ) {
2449 $thumbnail = MAXGALLERIA_MEDIA_LIBRARY_PLUGIN_URL . '/images/file.jpg';
2450 }
2451
2452 $thumbnail_html = sprintf(
2453 '<img alt="%s" src="%s" class="mlp-thumb" />',
2454 esc_attr( $alt ),
2455 esc_url( $thumbnail )
2456 );
2457 }
2458 }
2459
2460
2461 // if($row->block == 1) {
2462 // if(($this->bda_user_role == 'admins' && $is_admin) || $this->bda_user_role == 'authors' && $current_user == $row->post_author) {
2463 // if($current_user == $row->post_author)
2464 // $author_class = 'author';
2465 // else
2466 // $author_class = '';
2467 // if(wp_attachment_is_image($row->ID)) {
2468 // $blocked_image_url = wp_get_attachment_thumb_url($row->ID);
2469 // } else {
2470 // $ext = pathinfo($row->attached_file, PATHINFO_EXTENSION);
2471 // $blocked_image_url = $this->get_file_thumbnail($ext);
2472 // $image_file_type = false;
2473 // }
2474 // } else {
2475 // $blocked_image_url = '';
2476 // }
2477 // } else {
2478 // // use wp_get_attachment_image to get the PDF preview
2479 // $thumbnail_html = "";
2480 // $thumbnail_html = wp_get_attachment_image( $row->ID);
2481 // if(!$thumbnail_html){
2482 // $thumbnail = wp_get_attachment_thumb_url($row->ID);
2483 // if($thumbnail === false) {
2484 // $thumbnail = esc_url(MAXGALLERIA_MEDIA_LIBRARY_PLUGIN_URL . "/images/file.jpg");
2485 // }
2486 // $thumbnail_html = "<img alt='' src='$thumbnail' />";
2487 // }
2488 // }
2489
2490 $checkbox = sprintf("<input type='checkbox' class='mgmlp-media' id='%s' value='%s' protected='%s' />", $row->ID, $row->ID, $row->block );
2491 if($image_link && $mif_visible)
2492 $class = "media-attachment no-pointer";
2493 else if($image_link)
2494 $class = "media-attachment";
2495 else
2496 $class = "tb-media-attachment";
2497
2498 // for WP 4.6 use /wp-admin/post.php?post=
2499 if( version_compare($this->wp_version, NEW_MEDIA_LIBRARY_VERSION, ">") )
2500 $media_edit_link = "/wp-admin/post.php?post=" . $row->ID . "&action=edit";
2501 else
2502 $media_edit_link = "/wp-admin/upload.php?item=" . $row->ID;
2503
2504 $image_location = $this->build_location_url($row->attached_file);
2505
2506 $filename = pathinfo($image_location, PATHINFO_BASENAME);
2507
2508 $protcted_class = ($row->block == 1) ? 'mlfp-protected' : '';
2509 //error_log($blocked_image_url);
2510
2511 ?>
2512 <li id='<?php echo esc_attr($row->ID) ?>'>
2513 <?php if($row->block == 1) { ?>
2514 <a id='<?php echo esc_attr($row->ID) ?>' target='_blank' class='<?php echo esc_attr($class) ?> <?php echo esc_attr($protcted_class) ?> <?php echo esc_attr($author_class) ?>' href='<?php echo esc_url_raw(site_url() . $media_edit_link) ?>' title='<?php echo esc_attr($filename) ?>'><img width='80' height='80' type='bda' src='<?php echo esc_url_raw($blocked_image_url) ?>' class='attachment-thumbnail size-thumbnail' alt='' loading='lazy' /></a>
2515 <?php } else { ?>
2516 <a id='<?php echo esc_attr($row->ID) ?>' target='_blank' class='<?php echo esc_attr($class) ?>' href='<?php echo esc_url_raw(site_url() . $media_edit_link) ?>'><?php echo wp_kses_post($thumbnail_html) ?></a>
2517 <?php } ?>
2518 <div class='attachment-name'><label><span class='image_select'><?php echo wp_kses($checkbox, $allowed_html) ?></span><span class="mediafile"><?php echo esc_html($filename) ?></span></label></div>
2519 </li>
2520 <?php
2521
2522 }
2523 }
2524 ?>
2525 </ul>
2526
2527 <script>
2528 jQuery(document).ready(function(){
2529 jQuery("#folder-message").html("");
2530 jQuery("li a.media-attachment").draggable({
2531 cursor: "move",
2532 helper: function() {
2533 var selected = jQuery(".mg-media-list input:checked").parents("li");
2534 if (selected.length === 0) {
2535 selected = jQuery(this);
2536 }
2537 var container = jQuery("<div/>").attr("id", "draggingContainer");
2538 container.append(selected.clone());
2539 return container;
2540 }
2541 });
2542 });
2543 </script>
2544 <?php
2545 if(!$images_found) {
2546 ?>
2547 <p style='text-align:center'><?php esc_html_e('No files were found.','maxgalleria-media-library') ?></p>
2548 <?php
2549 }
2550
2551
2552
2553 }
2554
2555 /**
2556 * Ensure _wp_attachment_image_alt is a scalar string.
2557 * Returns the string that will be used, and updates the meta if it needed fixing.
2558 */
2559 public function mgp_normalize_image_alt_meta( $attachment_id ) {
2560 $original_val = get_post_meta( $attachment_id, '_wp_attachment_image_alt', true );
2561 $val = $original_val;
2562
2563 if ( is_array( $val ) ) {
2564 $flat = array_filter(
2565 array_map( 'strval', $val ),
2566 function( $s ) { return $s !== ''; }
2567 );
2568 $val = $flat ? reset( $flat ) : '';
2569 } elseif ( ! is_string( $val ) ) {
2570 $val = (string) $val;
2571 }
2572
2573 $val = wp_strip_all_tags( $val, true );
2574 $val = trim( $val );
2575 $val = preg_replace( '/[^\P{C}\t\n\r]/u', '', $val );
2576
2577 if ( $original_val !== $val ) {
2578 update_post_meta( $attachment_id, '_wp_attachment_image_alt', $val );
2579 }
2580
2581 return $val;
2582 }
2583
2584 private function get_folder_path($folder_id) {
2585
2586 global $wpdb;
2587 $folder_id = intval($folder_id);
2588 $sql = "select meta_value as attached_file
2589 from {$wpdb->prefix}postmeta
2590 where post_id = $folder_id
2591 AND meta_key = '_wp_attached_file'";
2592
2593 $row = $wpdb->get_row($sql);
2594
2595 //$image_location = $this->upload_dir['baseurl'] . '/' . $row->attached_file;
2596 $baseurl = $this->upload_dir['baseurl'];
2597 $baseurl = rtrim($baseurl, '/') . '/';
2598 $image_location = $baseurl . ltrim($row->attached_file, '/');
2599 $absolute_path = $this->get_absolute_path($image_location);
2600
2601 return $absolute_path;
2602
2603 }
2604
2605 private function get_subfolder_path($folder_id) {
2606
2607 global $wpdb;
2608 $folder_id = intval($folder_id);
2609
2610 $sql = "select meta_value as attached_file
2611 from {$wpdb->prefix}postmeta
2612 where post_id = $folder_id
2613 AND meta_key = '_wp_attached_file'";
2614
2615 $row = $wpdb->get_row($sql);
2616
2617 $baseurl = $this->upload_dir['baseurl'];
2618 $baseurl = rtrim($baseurl, '/') . '/';
2619 $image_location = $baseurl . ltrim($row->attached_file, '/');
2620
2621 $postion = strpos($image_location, $this->uploads_folder_name);
2622 $path = substr($image_location, $postion+$this->uploads_folder_name_length );
2623 return $path;
2624
2625 }
2626
2627 private function get_folder_name($folder_id) {
2628 global $wpdb;
2629 $folder_id = intval($folder_id);
2630 $sql = "select post_title from $wpdb->prefix" . "posts where ID = $folder_id";
2631 $row = $wpdb->get_row($sql);
2632 return $row->post_title;
2633 }
2634
2635 private function get_parents($current_folder_id) {
2636
2637 global $wpdb;
2638 $folder_id = intval($current_folder_id);
2639 $parents = array();
2640 $folder_table = $wpdb->prefix . MAXGALLERIA_MEDIA_LIBRARY_FOLDER_TABLE;
2641 $not_found = false;
2642
2643 //while($folder_id !== '0' || !$not_found ) {
2644 while($folder_id !== '0' && !$not_found ) {
2645
2646 $sql = "select post_title, ID, $folder_table.folder_id
2647 from $wpdb->prefix" . "posts
2648 LEFT JOIN $folder_table ON ($wpdb->prefix" . "posts.ID = $folder_table.post_id)
2649 where ID = $folder_id";
2650
2651 $row = $wpdb->get_row($sql);
2652
2653 if($row) {
2654 $folder_id = $row->folder_id;
2655 $new_folder = array();
2656 $new_folder['name'] = $row->post_title;
2657 $new_folder['id'] = $row->ID;
2658 $parents[] = $new_folder;
2659 } else {
2660 $not_found = true;
2661 }
2662 }
2663
2664 $parents = array_reverse($parents);
2665
2666 return $parents;
2667
2668 }
2669
2670 private function get_parent($folder_id) {
2671
2672 global $wpdb;
2673 $folder_id = intval($folder_id);
2674 $folder_table = $wpdb->prefix . MAXGALLERIA_MEDIA_LIBRARY_FOLDER_TABLE;
2675
2676 $sql = "select folder_id from $folder_table where post_id = $folder_id";
2677
2678 $row = $wpdb->get_row($sql);
2679 if($row)
2680 return $row->folder_id;
2681 else
2682 return $this->uploads_folder_ID;
2683 }
2684
2685 public function create_new_folder() {
2686
2687 global $wpdb;
2688
2689 if ( !wp_verify_nonce( $_POST['nonce'], MAXGALLERIA_MEDIA_LIBRARY_NONCE)) {
2690 exit(esc_html__('missing nonce! Please refresh this page.','maxgalleria-media-library'));
2691 }
2692
2693 // Check if the current user has the capability to upload files
2694 if(!current_user_can('upload_files')){
2695 exit(esc_html__('You do not have the capability to upload files.','maxgalleria-media-library'));
2696 }
2697
2698 if ((isset($_POST['parent_folder'])) && (strlen(trim($_POST['parent_folder'])) > 0))
2699 $parent_folder_id = intval(trim(sanitize_text_field($_POST['parent_folder'])));
2700
2701
2702 if ((isset($_POST['new_folder_name'])) && (strlen(trim($_POST['new_folder_name'])) > 0))
2703 $new_folder_name = trim(sanitize_text_field($_POST['new_folder_name']));
2704
2705 $sql = $wpdb->prepare("select meta_value as attached_file
2706 from {$wpdb->prefix}postmeta
2707 where post_id = %d
2708 AND meta_key = '_wp_attached_file'", $parent_folder_id);
2709
2710 $row = $wpdb->get_row($sql);
2711
2712 $baseurl = $this->upload_dir['baseurl'];
2713 $baseurl = rtrim($baseurl, '/') . '/';
2714 $image_location = $baseurl . ltrim($row->attached_file, '/');
2715
2716 $absolute_path = $this->get_absolute_path($image_location);
2717 $absolute_path = rtrim($absolute_path, '/') . '/';
2718 $allowed_dir = rtrim($absolute_path, '/');
2719 //$this->write_log("absolute_path $absolute_path");
2720
2721 // Sanitize the new folder name
2722 $new_folder_name = basename($new_folder_name);
2723
2724 // Construct the new folder path
2725 $new_folder_path = rtrim($absolute_path, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . $new_folder_name;
2726
2727 // Validate up to the parent directory
2728 $parent_dir = dirname($new_folder_path);
2729 $real_parent_dir = realpath($parent_dir);
2730 $real_allowed_dir = realpath($allowed_dir);
2731
2732 // Check if the parent directory exists and is within the allowed directory
2733 if (
2734 false === $real_parent_dir ||
2735 false === $real_allowed_dir ||
2736 (
2737 $real_parent_dir !== $real_allowed_dir &&
2738 strpos($real_parent_dir, $real_allowed_dir . DIRECTORY_SEPARATOR) !== 0
2739 )
2740 ) {
2741 $message = esc_html__('Directory traversal attempt detected.', 'maxgalleria-media-library');
2742 $data = array('message' => esc_html($message), 'refresh' => false);
2743 echo json_encode($data);
2744 die();
2745 }
2746
2747 //check for new folder name that begins with '..' and abort
2748 if (strpos($new_folder_name, '..') !== false) {
2749 $message = esc_html__('Invalid folder name.','maxgalleria-media-library');
2750 $data = array ('message' => esc_html($message), 'refresh' => false );
2751 echo json_encode($data);
2752 die();
2753 }
2754
2755 $new_folder_url = $this->get_file_url_for_copy($new_folder_path);
2756 //$this->write_log("new_folder_url $new_folder_url");
2757
2758 //$this->write_log("Trying to create directory at $new_folder_path, $parent_folder_id, $new_folder_url");
2759
2760 if(!file_exists($new_folder_path)) {
2761 if(mkdir($new_folder_path)) {
2762 if(defined('FS_CHMOD_DIR'))
2763 @chmod($new_folder_path, FS_CHMOD_DIR);
2764 else
2765 @chmod($new_folder_path, 0755);
2766 //if($this->add_media_folder($new_folder_name, $parent_folder_id, $new_folder_url)){
2767 $new_folder_id = $this->add_media_folder($new_folder_name, $parent_folder_id, $new_folder_url);
2768 if($new_folder_id) {
2769
2770 $message = esc_html__('The folder was created.','maxgalleria-media-library');
2771 $folders = $this->get_folder_data($parent_folder_id);
2772 $data = array ('message' => esc_html($message), 'folders' => $folders, 'refresh' => true, 'new_folder' => esc_attr($new_folder_id));
2773 echo json_encode($data);
2774
2775 } else {
2776 $message = esc_html__('There was a problem creating the folder.','maxgalleria-media-library');
2777 $data = array ('message' => esc_html($message), 'refresh' => false );
2778 echo json_encode($data);
2779 }
2780 }
2781 } else {
2782 $message = esc_html__('The folder already exists.','maxgalleria-media-library');
2783 $data = array ('message' => esc_html($message), 'refresh' => false );
2784 echo json_encode($data);
2785 }
2786
2787 die();
2788 }
2789
2790
2791 public function get_absolute_path($url) {
2792
2793 global $blog_id, $is_IIS;
2794
2795 $baseurl = $this->upload_dir['baseurl'];
2796
2797 if(is_multisite()) {
2798 $url_slug = "site" . $blog_id . "/";
2799 $baseurl = str_replace($url_slug, "", $baseurl);
2800 if(strpos($url, MLF_WP_CONTENT_FOLDER_NAME) === false)
2801 $url = str_replace($url_slug, "wp-content/uploads/sites/" . $blog_id . "/" , $url);
2802 else
2803 $url = str_replace($url_slug, "", $url);
2804 }
2805
2806 $file_path = str_replace( $baseurl, $this->upload_dir['basedir'], $url );
2807 // fix the slashes
2808 if(strpos($this->upload_dir['basedir'], '\\') !== false)
2809 $file_path = str_replace('/', '\\', $file_path);
2810
2811 //first attempt failed; try again
2812 if((strpos($file_path, "http:") !== false) || (strpos($file_path, "https:") !== false)) {
2813 //$this->write_log("absolute path, second attempt $file_path");
2814 $baseurl = $this->upload_dir['baseurl'];
2815 $base_length = strlen($baseurl);
2816 //compare the two urls
2817 $url_stub = substr($url, 0, $base_length);
2818 if(strcmp($url_stub, $baseurl) === 0) {
2819 $non_base_file = substr($url, $base_length);
2820 $file_path = $this->upload_dir['basedir'] . DIRECTORY_SEPARATOR . $non_base_file;
2821 } else {
2822 //$this->write_log("url_stub $url_stub");
2823 //$this->write_log("baseurl $baseurl");
2824 $new_msg = esc_html__('The URL to the folder or image is not correct: ','maxgalleria-media-library') . esc_url_raw($url);
2825 //$this->write_log($new_msg);
2826 echo esc_html($new_msg);
2827 }
2828 }
2829
2830 // are we on windows?
2831 if ($is_IIS || strtoupper(substr(PHP_OS, 0, 3)) == 'WIN' || strtoupper(substr(PHP_OS, 0, 13)) == 'MICROSOFT-IIS' ) {
2832 $file_path = str_replace('/', '\\', $file_path);
2833 }
2834
2835 return $file_path;
2836 }
2837
2838 public function is_windows() {
2839 global $is_IIS;
2840 if ($is_IIS || strtoupper(substr(PHP_OS, 0, 3)) == 'WIN' || strtoupper(substr(PHP_OS, 0, 13)) == 'MICROSOFT-IIS' )
2841 return true;
2842 else
2843 return false;
2844 }
2845
2846 public function get_file_url($path) {
2847 global $is_IIS;
2848
2849 if ($is_IIS || strtoupper(substr(PHP_OS, 0, 3)) == 'WIN' || strtoupper(substr(PHP_OS, 0, 13)) == 'MICROSOFT-IIS' ) {
2850
2851 $base_url = $this->upload_dir['baseurl'];
2852
2853 $position = strpos($path, $this->uploads_folder_name);
2854 $relative_path = substr($path, $position+$this->uploads_folder_name_length+1);
2855
2856 $file_url = $base_url . '/' . $relative_path;
2857 $file_url = str_replace('\\', '/', $file_url);
2858
2859 }
2860 else {
2861 $file_url = str_replace( $this->upload_dir['basedir'], $this->upload_dir['baseurl'], $path );
2862 }
2863 return $file_url;
2864 }
2865
2866 public function get_file_url_for_copy($path) {
2867 global $is_IIS;
2868
2869 if ($is_IIS || strtoupper(substr(PHP_OS, 0, 3)) == 'WIN' || strtoupper(substr(PHP_OS, 0, 13)) == 'MICROSOFT-IIS' ) {
2870
2871 $base_url = $this->upload_dir['baseurl'];
2872
2873 // replace any slashes in the dir path when running windows
2874 $base_upload_dir1 = $this->upload_dir['basedir'];
2875 $base_upload_dir2 = str_replace('/','\\', $base_upload_dir1);
2876 $file_url = str_replace( $base_upload_dir2, $base_url, $path );
2877 $file_url = str_replace('\\', '/', $file_url);
2878
2879 }
2880 else {
2881 $file_url = str_replace( $this->upload_dir['basedir'], $this->upload_dir['baseurl'], $path );
2882 }
2883 return $file_url;
2884
2885 }
2886
2887 public function delete_maxgalleria_media() {
2888
2889 global $wpdb, $is_IIS;
2890
2891 $folder_deleted = true;
2892 $message = '';
2893
2894 /**
2895 * Combined auth gate:
2896 * - Must be logged in
2897 * - Must have upload_files capability
2898 */
2899 if ( ! is_user_logged_in() || ! current_user_can( 'upload_files' ) ) {
2900 // Keep original wording for capability failure, but also covers not-logged-in
2901 $data = array(
2902 'message' => esc_html__( 'You do not have the capability to upload files.', 'maxgalleria-media-library' ),
2903 'refresh' => false,
2904 );
2905 echo wp_json_encode( $data );
2906 wp_die();
2907 }
2908
2909 // Nonce check
2910 $nonce = isset( $_POST['nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['nonce'] ) ) : '';
2911 if ( ! wp_verify_nonce( $nonce, MAXGALLERIA_MEDIA_LIBRARY_NONCE ) ) {
2912 $data = array(
2913 'message' => esc_html__( 'Missing or invalid nonce! Please refresh this page.', 'maxgalleria-media-library' ),
2914 'refresh' => false,
2915 );
2916 echo wp_json_encode( $data );
2917 wp_die();
2918 }
2919
2920 // Parse IDs as absint list
2921 $delete_ids = array();
2922 if ( isset( $_POST['serial_delete_ids'] ) ) {
2923 $raw = wp_unslash( $_POST['serial_delete_ids'] );
2924 $raw = str_replace( '"', '', $raw );
2925 $parts = array_filter( array_map( 'trim', explode( ',', $raw ) ) );
2926 $delete_ids = array_values( array_filter( array_map( 'absint', $parts ) ) );
2927 }
2928
2929 // Parent folder
2930 $parent_folder = isset( $_POST['parent_id'] ) ? absint( wp_unslash( $_POST['parent_id'] ) ) : 0;
2931 if ( ! $parent_folder ) {
2932 $parent_folder = (int) $this->uploads_folder_ID;
2933 }
2934
2935 $table = $wpdb->prefix . MAXGALLERIA_MEDIA_LIBRARY_FOLDER_TABLE;
2936 $current_user_id = get_current_user_id();
2937 $is_admin_like = current_user_can( 'manage_options' ); // "admin-like" gate
2938
2939 foreach ( $delete_ids as $delete_id ) {
2940
2941 // prevent uploads folder from being deleted
2942 if ( (int) $delete_id === (int) $this->uploads_folder_ID ) {
2943 $message = esc_html__( 'The uploads folder cannot be deleted.', 'maxgalleria-media-library' );
2944 $data = array( 'message' => $message, 'refresh' => false );
2945 echo wp_json_encode( $data );
2946 wp_die();
2947 }
2948
2949 // Load the post object once (also protects against missing IDs)
2950 $post = get_post( $delete_id );
2951 if ( ! $post ) {
2952 continue;
2953 }
2954
2955 // 2) For each ID: current_user_can('delete_post', $id) must pass
2956 if ( ! current_user_can( 'delete_post', $delete_id ) ) {
2957 continue; // or return an error if you prefer strict behavior
2958 }
2959
2960 // 4) For folder post type: admin-only
2961 if ( $post->post_type === MAXGALLERIA_MEDIA_LIBRARY_POST_TYPE && ! $is_admin_like ) {
2962 continue;
2963 }
2964
2965 // 3) For attachments: enforce owner-only unless admin-like
2966 if ( $post->post_type === 'attachment' && ! $is_admin_like ) {
2967 if ( (int) $post->post_author !== (int) $current_user_id ) {
2968 continue;
2969 }
2970 }
2971
2972 $sql = $wpdb->prepare(
2973 "SELECT p.post_title, p.post_type, pm.meta_value AS attached_file
2974 FROM {$wpdb->posts} p
2975 LEFT JOIN {$wpdb->postmeta} pm
2976 ON (pm.post_id = p.ID AND pm.meta_key = %s)
2977 WHERE p.ID = %d",
2978 '_wp_attached_file',
2979 $delete_id
2980 );
2981
2982 $row = $wpdb->get_row( $sql );
2983 if ( ! $row ) {
2984 continue;
2985 }
2986
2987 $baseurl = rtrim( $this->upload_dir['baseurl'], '/' ) . '/';
2988 $image_location = $baseurl . ltrim( (string) $row->attached_file, '/' );
2989 $folder_path = $this->get_absolute_path( $image_location );
2990 $del_post = array( 'post_id' => $delete_id );
2991
2992 if ( $row->post_type === MAXGALLERIA_MEDIA_LIBRARY_POST_TYPE ) { // folder
2993
2994 $sql_count = $wpdb->prepare( "SELECT COUNT(*) FROM {$table} WHERE folder_id = %d", $delete_id );
2995 $row_count = (int) $wpdb->get_var( $sql_count );
2996
2997 if ( $row_count > 0 ) {
2998 $message = esc_html__( 'The folder, ', 'maxgalleria-media-library' ) . $row->post_title .
2999 esc_html__( ', is not empty. Please delete or move files from the folder', 'maxgalleria-media-library' ) . PHP_EOL;
3000
3001 $data = array( 'message' => esc_html( $message ), 'refresh' => false );
3002 echo wp_json_encode( $data );
3003 wp_die();
3004 }
3005
3006 if ( file_exists( $folder_path ) && is_dir( $folder_path ) ) {
3007 @chmod( $folder_path, 0777 );
3008 $this->remove_hidden_files( $folder_path );
3009
3010 if ( $this->is_dir_empty( $folder_path ) ) {
3011 if ( ! rmdir( $folder_path ) ) {
3012 $message = esc_html__( 'The folder could not be deleted.', 'maxgalleria-media-library' );
3013 }
3014 } else {
3015 $message = esc_html__( 'The folder is not empty and could not be deleted.', 'maxgalleria-media-library' );
3016 $folder_deleted = false;
3017 }
3018 }
3019
3020 if ( $folder_deleted ) {
3021 wp_delete_post( $delete_id, true );
3022 $wpdb->delete( $table, $del_post );
3023 $message = esc_html__( 'The folder was deleted.', 'maxgalleria-media-library' );
3024 }
3025
3026 $folders = $this->get_folder_data( $parent_folder );
3027 $data = array(
3028 'message' => esc_html( $message ),
3029 'folders' => $folders,
3030 'refresh' => $folder_deleted,
3031 );
3032 echo wp_json_encode( $data );
3033 wp_die();
3034
3035 } else { // attachment (or other non-folder post types)
3036
3037 // Ensure we only call wp_delete_attachment on attachments
3038 if ( $post->post_type !== 'attachment' ) {
3039 continue;
3040 }
3041
3042 $metadata = wp_get_attachment_metadata( $delete_id );
3043 $image_path = $this->get_absolute_path( $image_location );
3044 $path_to_thumbnails = pathinfo( $image_path, PATHINFO_DIRNAME );
3045
3046 if ( wp_delete_attachment( $delete_id, true ) !== false ) {
3047 $wpdb->delete( $table, $del_post );
3048 $message = esc_html__( 'The file(s) were deleted', 'maxgalleria-media-library' ) . PHP_EOL;
3049
3050 // ensure the attachment is deleted
3051 if ( file_exists( $image_path ) ) {
3052 unlink( $image_path );
3053 }
3054
3055 if ( isset( $metadata['sizes'] ) && is_array( $metadata['sizes'] ) ) {
3056 foreach ( $metadata['sizes'] as $source_path ) {
3057 if ( empty( $source_path['file'] ) ) {
3058 continue;
3059 }
3060
3061 $thumbnail_file = $path_to_thumbnails . DIRECTORY_SEPARATOR . $source_path['file'];
3062
3063 if ( $is_IIS || strtoupper( substr( PHP_OS, 0, 3 ) ) === 'WIN' || strtoupper( substr( PHP_OS, 0, 13 ) ) === 'MICROSOFT-IIS' ) {
3064 $thumbnail_file = str_replace( '/', '\\', $thumbnail_file );
3065 }
3066
3067 if ( file_exists( $thumbnail_file ) ) {
3068 unlink( $thumbnail_file );
3069 }
3070 }
3071 }
3072
3073 } else {
3074 $message = esc_html__( 'The file(s) were not deleted', 'maxgalleria-media-library' ) . PHP_EOL;
3075 }
3076 }
3077 }
3078
3079 $files = $this->display_folder_contents( $parent_folder, true, '', false );
3080 $refresh = true;
3081
3082 $data = array(
3083 'message' => esc_html( $message ),
3084 'files' => $files,
3085 'refresh' => $refresh,
3086 );
3087
3088 echo wp_json_encode( $data );
3089 wp_die();
3090 }
3091
3092 public function delete_maxgalleria_media1() {
3093
3094 global $wpdb, $is_IIS;
3095 $delete_ids = array();
3096 $folder_deleted = true;
3097 $message = "";
3098
3099 if ( !wp_verify_nonce( $_POST['nonce'], MAXGALLERIA_MEDIA_LIBRARY_NONCE)) {
3100 exit( esc_html__('missing nonce! Please refresh this page.','maxgalleria-media-library'));
3101 }
3102
3103 // Check if the current user has the capability to upload files
3104 if(!current_user_can('upload_files')){
3105 exit(esc_html__('You do not have the capability to upload files.','maxgalleria-media-library'));
3106 }
3107
3108 if ((isset($_POST['serial_delete_ids'])) && (strlen(trim($_POST['serial_delete_ids'])) > 0)) {
3109 $delete_ids = trim(stripslashes(sanitize_text_field($_POST['serial_delete_ids'])));
3110 $delete_ids = str_replace('"', '', $delete_ids);
3111 $delete_ids = explode(",",$delete_ids);
3112 }
3113 else
3114 $delete_ids = '';
3115
3116 if ((isset($_POST['parent_id'])) && (strlen(trim($_POST['parent_id'])) > 0))
3117 $parent_folder = trim(sanitize_text_field($_POST['parent_id']));
3118 else
3119 $parent_folder = $this->uploads_folder_ID;
3120
3121
3122 foreach( $delete_ids as $delete_id) {
3123
3124 // prevent uploads folder from being deleted
3125 if(intval($delete_id) == intval($this->uploads_folder_ID)) {
3126 $message = esc_html__('The uploads folder cannot be deleted.','maxgalleria-media-library');
3127 $data = array ('message' => esc_html($message), 'refresh' => false );
3128 echo json_encode($data);
3129 die();
3130 }
3131
3132 if(is_numeric($delete_id)) {
3133
3134 $sql = "select post_title, post_type, pm.meta_value as attached_file
3135 from {$wpdb->prefix}posts
3136 LEFT JOIN {$wpdb->prefix}postmeta AS pm ON (pm.post_id = {$wpdb->prefix}posts.ID)
3137 where ID = $delete_id
3138 AND pm.meta_key = '_wp_attached_file'";
3139
3140 $row = $wpdb->get_row($sql);
3141
3142 $baseurl = $this->upload_dir['baseurl'];
3143 $baseurl = rtrim($baseurl, '/') . '/';
3144 $image_location = $baseurl . ltrim($row->attached_file, '/');
3145
3146 $folder_path = $this->get_absolute_path($image_location);
3147 $table = $wpdb->prefix . MAXGALLERIA_MEDIA_LIBRARY_FOLDER_TABLE;
3148 $del_post = array('post_id' => $delete_id);
3149
3150 if($row->post_type === MAXGALLERIA_MEDIA_LIBRARY_POST_TYPE) { //folder
3151
3152 $sql = "SELECT COUNT(*) FROM $table where folder_id = $delete_id";
3153 $row_count = $wpdb->get_var($sql);
3154
3155 if($row_count > 0) {
3156 $message = esc_html__('The folder, ','maxgalleria-media-library'). $row->post_title . esc_html__(', is not empty. Please delete or move files from the folder','maxgalleria-media-library') . PHP_EOL;
3157
3158 $data = array ('message' => esc_html($message), 'refresh' => false );
3159 echo json_encode($data);
3160
3161 die();
3162 }
3163
3164 //$parent_folder = $this->get_parent($delete_id);
3165
3166 if(file_exists($folder_path)) {
3167 if(is_dir($folder_path)) { //folder
3168 @chmod($folder_path, 0777);
3169 $this->remove_hidden_files($folder_path);
3170 if($this->is_dir_empty($folder_path)) {
3171 if(!rmdir($folder_path)) {
3172 $message = esc_html__('The folder could not be deleted.','maxgalleria-media-library');
3173 }
3174 } else {
3175 $message = esc_html__('The folder is not empty and could not be deleted.','maxgalleria-media-library');
3176 $folder_deleted = false;
3177 }
3178 }
3179 }
3180
3181 if($folder_deleted) {
3182 wp_delete_post($delete_id, true);
3183 $wpdb->delete( $table, $del_post );
3184 $message = esc_html__('The folder was deleted.','maxgalleria-media-library');
3185 }
3186 $folders = $this->get_folder_data($parent_folder);
3187 $data = array ('message' => esc_html($message), 'folders' => $folders, 'refresh' => $folder_deleted );
3188 echo json_encode($data);
3189
3190 die();
3191 }
3192 else {
3193 //error_log("delete_id $delete_id");
3194 $attached_file = get_post_meta($delete_id, '_wp_attached_file', true);
3195 $metadata = wp_get_attachment_metadata($delete_id);
3196 $baseurl = $this->upload_dir['baseurl'];
3197 $baseurl = rtrim($baseurl, '/') . '/';
3198 $image_location = $baseurl . ltrim($row->attached_file, '/');
3199 $image_path = $this->get_absolute_path($image_location);
3200 $path_to_thumbnails = pathinfo($image_path, PATHINFO_DIRNAME);
3201
3202 if( wp_delete_attachment( $delete_id, true ) !== false ) {
3203 $wpdb->delete( $table, $del_post );
3204 $message = esc_html__('The file(s) were deleted','maxgalleria-media-library') . PHP_EOL;
3205
3206 //error_log("unlink image_path $image_path");
3207 if(file_exists($image_path))
3208 unlink($image_path);
3209 if(isset($metadata['sizes'])) {
3210 foreach($metadata['sizes'] as $source_path) {
3211 $thumbnail_file = $path_to_thumbnails . DIRECTORY_SEPARATOR . $source_path['file'];
3212
3213 if ($is_IIS || strtoupper(substr(PHP_OS, 0, 3)) == 'WIN' || strtoupper(substr(PHP_OS, 0, 13)) == 'MICROSOFT-IIS' )
3214 $thumbnail_file = str_replace('/', '\\', $thumbnail_file);
3215
3216 if(file_exists($thumbnail_file))
3217 unlink($thumbnail_file);
3218 }
3219 }
3220
3221 } else {
3222 $message = esc_html__('The file(s) were not deleted','maxgalleria-media-library') . PHP_EOL;
3223 }
3224 }
3225 }
3226 }
3227
3228 $files = $this->display_folder_contents ($parent_folder, true, "", false);
3229 $refresh = true;
3230 $data = array ('message' => esc_html($message), 'files' => $files, 'refresh' => $refresh );
3231 echo json_encode($data);
3232 die();
3233 }
3234
3235 public function remove_hidden_files($directory) {
3236 $files = array_diff(scandir($directory), array('.','..'));
3237 foreach ($files as $file) {
3238 unlink("$directory/$file");
3239 }
3240 }
3241
3242 public function is_dir_empty($directory) {
3243 $filehandle = opendir($directory);
3244 while (false !== ($entry = readdir($filehandle))) {
3245 if ($entry != "." && $entry != "..") {
3246 closedir($filehandle);
3247 return false;
3248 }
3249 }
3250 closedir($filehandle);
3251 return true;
3252 }
3253
3254 public function get_image_sizes() {
3255 global $_wp_additional_image_sizes;
3256 $sizes = array();
3257 $rSizes = array();
3258 foreach (get_intermediate_image_sizes() as $s) {
3259 $sizes[$s] = array(0, 0);
3260 if (in_array($s, array('thumbnail', 'medium', 'large'))) {
3261 $sizes[$s][0] = get_option($s . '_size_w');
3262 $sizes[$s][1] = get_option($s . '_size_h');
3263 } else {
3264 if (isset($_wp_additional_image_sizes) && isset($_wp_additional_image_sizes[$s]))
3265 $sizes[$s] = array($_wp_additional_image_sizes[$s]['width'], $_wp_additional_image_sizes[$s]['height'],);
3266 }
3267 }
3268
3269 foreach ($sizes as $size => $atts) {
3270 $rSizes[] = implode('x', $atts);
3271 }
3272
3273 return $rSizes;
3274 }
3275
3276 public function add_to_max_gallery () {
3277
3278 global $wpdb, $maxgalleria;
3279
3280 if (!wp_verify_nonce($_POST['nonce'], MAXGALLERIA_MEDIA_LIBRARY_NONCE)) {
3281 exit(__('missing nonce!', 'maxgalleria-media-library'));
3282 }
3283
3284 // Check if the current user has the capability to upload files
3285 if(!current_user_can('upload_files')){
3286 exit(esc_html__('You do not have the capability to upload files.','maxgalleria-media-library'));
3287 }
3288
3289 if ((isset($_POST['serial_gallery_image_ids'])) && (strlen(trim($_POST['serial_gallery_image_ids'])) > 0))
3290 $serial_gallery_image_ids = trim(stripslashes(strip_tags($_POST['serial_gallery_image_ids'])));
3291 else
3292 $serial_gallery_image_ids = "";
3293
3294 $serial_gallery_image_ids = str_replace('"', '', $serial_gallery_image_ids);
3295 $serial_gallery_image_ids = explode(',', $serial_gallery_image_ids);
3296
3297 if ((isset($_POST['gallery_id'])) && (strlen(trim($_POST['gallery_id'])) > 0))
3298 $gallery_id = intval(trim(stripslashes(strip_tags($_POST['gallery_id']))));
3299 else
3300 $gallery_id = 0;
3301
3302 $site_url_parts = wp_parse_url(get_site_url());
3303
3304 $images_added_count = 0; // Initialize counter
3305
3306 foreach($serial_gallery_image_ids as $attachment_id) {
3307
3308 $attachment_id = intval($attachment_id);
3309 $media_url = wp_get_attachment_url($attachment_id);
3310
3311 if ($media_url) {
3312 $media_url_parts = wp_parse_url($media_url);
3313
3314 // Check if the media file is external
3315 if (!isset($media_url_parts['host']) || $media_url_parts['host'] === $site_url_parts['host']) {
3316 // The media file is internal, proceed to add it to the gallery
3317 $result = $this->add_image_to_mg_gallery($attachment_id, $gallery_id);
3318 if ($result) {
3319 $images_added_count++; // Increment counter
3320 }
3321 } else {
3322 // The media file is external, skip adding it to the gallery
3323 continue;
3324 }
3325 }
3326
3327 }// foreach
3328
3329 // Display the count of images added
3330 echo sprintf(__('%d images were added.', 'maxgalleria-media-library'), $images_added_count) . PHP_EOL;
3331
3332 die();
3333 }
3334
3335 public function add_image_to_mg_gallery($attachment_id, $gallery_id) {
3336
3337 global $wpdb, $maxgalleria;
3338
3339 $result = $attachment_id;
3340
3341 // check for image already in the gallery
3342 $sql = "SELECT ID FROM $wpdb->prefix" . "posts where post_parent = $gallery_id and post_type = 'attachment' and ID = $attachment_id";
3343
3344 $row = $wpdb->get_row($sql);
3345
3346 if($row === null) {
3347
3348 $menu_order = $maxgalleria->common->get_next_menu_order($gallery_id);
3349
3350 $attachment = get_post( $attachment_id, ARRAY_A );
3351
3352 // assign a new value for menu_order
3353 //$menu_order = $maxgalleria->common->get_next_menu_order($gallery_id);
3354 $attachment[ 'menu_order' ] = $menu_order;
3355
3356 //If the attachment doesn't have a post parent, simply change it to the attachment we're working with and be done with it
3357 // assign a new value for menu_order
3358 if( empty( $attachment[ 'post_parent' ] ) ) {
3359 wp_update_post(
3360 array(
3361 'ID' => $attachment[ 'ID' ],
3362 'post_parent' => $gallery_id,
3363 'menu_order' => $menu_order
3364 )
3365 );
3366 $result = $attachment[ 'ID' ];
3367 } else {
3368 //Else, unset the attachment ID, change the post parent and insert a new attachment
3369 unset( $attachment[ 'ID' ] );
3370 $attachment[ 'post_parent' ] = $gallery_id;
3371 $new_attachment_id = wp_insert_post( $attachment );
3372 //$new_attachment_id = $this->mpmlp_insert_post( $attachment );
3373
3374 //Now, duplicate all the custom fields. (There's probably a better way to do this)
3375 $custom_fields = get_post_custom( $attachment_id );
3376
3377 foreach( $custom_fields as $key => $value ) {
3378 //The attachment metadata wasn't duplicating correctly so we do that below instead
3379 if( $key != '_wp_attachment_metadata' )
3380 update_post_meta( $new_attachment_id, $key, $value[0] );
3381 }
3382
3383 //Carry over the attachment metadata
3384 $data = wp_get_attachment_metadata( $attachment_id );
3385 wp_update_attachment_metadata( $new_attachment_id, $data );
3386
3387 $result = $new_attachment_id;
3388
3389 }
3390 }
3391
3392 return $result;
3393
3394 }
3395
3396 public function search_media () {
3397
3398 global $wpdb;
3399
3400 if ( !wp_verify_nonce( $_POST['nonce'], MAXGALLERIA_MEDIA_LIBRARY_NONCE)) {
3401 exit(esc_html__('missing nonce! Please refresh this page.','maxgalleria-media-library'));
3402 }
3403
3404 // Check if the current user has the capability to upload files
3405 if(!current_user_can('upload_files')){
3406 exit(esc_html__('You do not have the capability to upload files.','maxgalleria-media-library'));
3407 }
3408
3409 if ((isset($_POST['search_value'])) && (strlen(trim($_POST['search_value'])) > 0))
3410 $search_value = trim(sanitize_text_field($_POST['search_value']));
3411 else
3412 $search_value = "";
3413
3414 // Use esc_sql to escape the 'search_value' parameter before using it in the SQL query
3415 $search_value = esc_sql($search_value);
3416
3417 $sql = $wpdb->prepare("select ID, post_title, post_name, pm.meta_value as attached_file from {$wpdb->prefix}posts
3418 LEFT JOIN {$wpdb->prefix}mgmlp_folders ON( {$wpdb->prefix}posts.ID = {$wpdb->prefix}mgmlp_folders.post_id)
3419 LEFT JOIN {$wpdb->prefix}postmeta AS pm ON (pm.post_id = {$wpdb->prefix}posts.ID)
3420 where post_type= 'attachment' and pm.meta_key = '_wp_attached_file' and post_title like '%%%s%%'", $search_value);
3421
3422 $rows = $wpdb->get_results($sql);
3423
3424 if($rows) {
3425 foreach($rows as $row) {
3426 $thumbnail = wp_get_attachment_thumb_url($row->ID);
3427 if($thumbnail !== false)
3428 $ext = pathinfo($thumbnail, PATHINFO_EXTENSION);
3429 else {
3430 $baseurl = $this->upload_dir['baseurl'];
3431 $baseurl = rtrim($baseurl, '/') . '/';
3432 $image_location = $baseurl . ltrim($row->attached_file, '/');
3433 $ext_pos = strrpos($image_location, '.');
3434 $ext = substr($image_location, $ext_pos+1);
3435 $thumbnail = MAXGALLERIA_MEDIA_LIBRARY_PLUGIN_URL . "/images/file.jpg";
3436 }
3437 // Use esc_html to escape the 'search_value' parameter before echoing it back to the user
3438 ?>
3439 <li>
3440 <a class='media-attachment' href='<?php echo esc_url_raw(site_url() . "/wp-admin/upload.php?item=" . $row->ID ) ?>'><img alt='<?php echo esc_html($row->post_title . '.' . $ext) ?>' src='<?php echo esc_url($thumbnail) ?>' /></a>
3441 <div class='attachment-name'><?php echo esc_html($row->post_title . '.' . $ext) ?></div>
3442 </li>
3443 <?php
3444 }
3445 }
3446 else {
3447 echo esc_html__('No files were found matching that name.','maxgalleria-media-library') . PHP_EOL;
3448 }
3449
3450 die();
3451 }
3452
3453 public function search_library() {
3454
3455 global $wpdb;
3456 $block_access_table = $wpdb->prefix . MAXGALLERIA_MEDIA_LIBRARY_BLOCK_ACCESS_TABLE;
3457 $current_user = get_current_user_id();
3458 $author_class = '';
3459
3460 if ((isset($_GET['s'])) && (strlen(trim($_GET['s'])) > 0))
3461 $search_string = esc_sql(trim(sanitize_text_field($_GET['s'])));
3462 else
3463 $search_string = '';
3464
3465 echo '<div id="wp-media-grid" class="wrap">' . PHP_EOL;
3466 //empty h2 for where WP notices will appear
3467 echo ' <h2></h2>' . PHP_EOL;
3468 echo ' <div class="media-plus-toolbar wp-filter">' . PHP_EOL;
3469 echo '<div id="mgmlp-title-area">' . PHP_EOL;
3470 echo ' <h2 class="mgmlp-title">'. __('Media Library Folders Search Results','maxgalleria-media-library') . '</h2>' . PHP_EOL;
3471 echo ' <div>' . PHP_EOL;
3472 echo ' <p><a href="' . site_url() . '/wp-admin/admin.php?page=mlf-folders8">Back to Media Library Folders</a></p>' . PHP_EOL;
3473 echo ' <p><input type="search" placeholder="Search" id="mgmlp-media-search-input" class="search" value="'. esc_attr($search_string) .'"> <a id="mlfp-media-search-2" class="gray-blue-link" >' . __('Search','maxgalleria-media-library') . '</a></p>' . PHP_EOL;
3474 echo ' </div>' . PHP_EOL;
3475 echo '</div>' . PHP_EOL;
3476 echo '<div style="clear:both;"></div>' . PHP_EOL;
3477 echo "<div id='search-instructions'>". __('Click on an image to go to its folder or a on folder to view its contents.','maxgalleria-media-library')."</div>";
3478 if ((isset($_GET['s'])) && (strlen(trim($_GET['s'])) > 0)) {
3479 echo "<h4>" . __('Search results for: ','maxgalleria-media-library') . esc_attr($search_string) ."</h4>" . PHP_EOL;
3480
3481 echo '<ul class="mg-media-list search-results">' . PHP_EOL;
3482
3483 $folder_table = $wpdb->prefix . MAXGALLERIA_MEDIA_LIBRARY_FOLDER_TABLE;
3484
3485 if($this->bda == 'on') {
3486
3487 $sql = $wpdb->prepare("(select {$wpdb->prefix}posts.ID, post_author, post_title, {$wpdb->prefix}mgmlp_folders.folder_id, pm.meta_value as attached_file, 'a' as item_type, 0 as block
3488 from {$wpdb->prefix}posts
3489 LEFT JOIN {$wpdb->prefix}mgmlp_folders ON($wpdb->posts.ID = {$wpdb->prefix}mgmlp_folders.post_id)
3490 LEFT JOIN {$wpdb->prefix}postmeta AS pm ON (pm.post_id = {$wpdb->prefix}posts.ID)
3491 LEFT JOIN $wpdb->users AS us ON ({$wpdb->prefix}posts.post_author = us.ID)
3492 LEFT JOIN $block_access_table ON($block_access_table.attachment_id = {$wpdb->prefix}posts.ID)
3493 where post_type = 'mgmlp_media_folder' and pm.meta_key = '_wp_attached_file' and SUBSTRING_INDEX(pm.meta_value, '/', -1) like '%%%s%%')
3494 union all
3495 (select $wpdb->posts.ID, post_author, post_title, {$wpdb->prefix}mgmlp_folders.folder_id, pm.meta_value as attached_file, 'b' as item_type, IFNULL($block_access_table.block,0) as block
3496 from $wpdb->posts
3497 LEFT JOIN {$wpdb->prefix}mgmlp_folders ON( $wpdb->posts.ID = {$wpdb->prefix}mgmlp_folders.post_id)
3498 LEFT JOIN {$wpdb->prefix}postmeta AS pm ON (pm.post_id = {$wpdb->prefix}posts.ID)
3499 LEFT JOIN $wpdb->users AS us ON ({$wpdb->prefix}posts.post_author = us.ID)
3500 LEFT JOIN $block_access_table ON($block_access_table.attachment_id = {$wpdb->prefix}posts.ID)
3501 where post_type = 'attachment' and pm.meta_key = '_wp_attached_file' and SUBSTRING_INDEX(pm.meta_value, '/', -1) like '%%%s%%') order by attached_file", $search_string, $search_string);
3502
3503 } else {
3504
3505 $sql = $wpdb->prepare("(select {$wpdb->prefix}posts.ID, post_author, post_title, {$wpdb->prefix}mgmlp_folders.folder_id, pm.meta_value as attached_file, 'a' as item_type, 0 as block
3506 from {$wpdb->prefix}posts
3507 LEFT JOIN {$wpdb->prefix}mgmlp_folders ON($wpdb->posts.ID = {$wpdb->prefix}mgmlp_folders.post_id)
3508 LEFT JOIN {$wpdb->prefix}postmeta AS pm ON (pm.post_id = {$wpdb->prefix}posts.ID)
3509 LEFT JOIN $wpdb->users AS us ON ({$wpdb->prefix}posts.post_author = us.ID)
3510 where post_type = 'mgmlp_media_folder' and pm.meta_key = '_wp_attached_file' and SUBSTRING_INDEX(pm.meta_value, '/', -1) like '%%%s%%')
3511 union all
3512 (select $wpdb->posts.ID, post_author, post_title, {$wpdb->prefix}mgmlp_folders.folder_id, pm.meta_value as attached_file, 'b' as item_type, 0 as block
3513 from $wpdb->posts
3514 LEFT JOIN {$wpdb->prefix}mgmlp_folders ON( $wpdb->posts.ID = {$wpdb->prefix}mgmlp_folders.post_id)
3515 LEFT JOIN {$wpdb->prefix}postmeta AS pm ON (pm.post_id = {$wpdb->prefix}posts.ID)
3516 LEFT JOIN $wpdb->users AS us ON ({$wpdb->prefix}posts.post_author = us.ID)
3517 where post_type = 'attachment' and pm.meta_key = '_wp_attached_file' and SUBSTRING_INDEX(pm.meta_value, '/', -1) like '%%%s%%') order by attached_file", $search_string, $search_string);
3518
3519 }
3520
3521 //error_log("grid " . $sql);
3522
3523 $rows = $wpdb->get_results($sql);
3524
3525 if($rows) {
3526 foreach($rows as $row) {
3527
3528 if($row->item_type == 'a')
3529 $class = "media-folder";
3530 else
3531 $class = "media-attachment";
3532
3533 $thumbnail = wp_get_attachment_thumb_url($row->ID);
3534 if($this->bda == 'on' && $row->block == 1) {
3535 $thumbnail = $this->get_absolute_path($thumbnail);
3536 if($this->bda_user_role == 'authors' && $current_user == $row->post_author)
3537 $author_class = 'author';
3538 else
3539 $author_class = '';
3540 }
3541 if($thumbnail !== false)
3542 $ext = pathinfo($thumbnail, PATHINFO_EXTENSION);
3543 else {
3544
3545 //$image_location = $this->upload_dir['baseurl'] . '/' . $row->attached_file;
3546 $baseurl = $this->upload_dir['baseurl'];
3547 $baseurl = rtrim($baseurl, '/') . '/';
3548 $image_location = $baseurl . ltrim($row->attached_file, '/');
3549
3550 $ext_pos = strrpos($image_location, '.');
3551 $ext = substr($image_location, $ext_pos+1);
3552 if($row->item_type == 'b')
3553 $thumbnail = MAXGALLERIA_MEDIA_LIBRARY_PLUGIN_URL . "/images/file.jpg";
3554 else
3555 $thumbnail = MAXGALLERIA_MEDIA_LIBRARY_PLUGIN_URL . "/images/folder.jpg";
3556 }
3557
3558 echo "<li>" . PHP_EOL;
3559 if($row->item_type == 'a') {
3560 echo " <a class='$class' href='" . site_url() . "/wp-admin/admin.php?page=mlf-folders8&media-folder=" . $row->ID . "'><img alt='' src='$thumbnail' /></a>" . PHP_EOL;
3561 } else {
3562 if($row->block == 1) {
3563 echo " <a class='$class mlfp-protected $author_class' data-id='$row->ID' href='" . site_url() . "/wp-admin/admin.php?page=mlf-folders8&media-folder=" . $row->folder_id . "'><img class='attachment-thumbnail' alt='' src='$thumbnail' /></a>" . PHP_EOL;
3564 } else {
3565 echo " <a class='$class' data-id='$row->ID' href='" . site_url() . "/wp-admin/admin.php?page=mlf-folders8&media-folder=" . $row->folder_id . "'><img class='attachment-thumbnail' alt='' src='$thumbnail' /></a>" . PHP_EOL;
3566 }
3567 }
3568 echo " <div class='attachment-name'>$row->post_title</div>" . PHP_EOL;
3569 echo "</li>" . PHP_EOL;
3570
3571 }
3572 }
3573
3574 echo "</ul>" . PHP_EOL;
3575 }
3576 echo '</div>' . PHP_EOL;
3577
3578 ?>
3579
3580 <script>
3581 jQuery(document).ready(function(){
3582 console.log('document ready');
3583 jQuery('#mgmlp-media-search-input').keydown(function (e){
3584 if(e.keyCode == 13){
3585
3586 var search_value = jQuery('#mgmlp-media-search-input').val();
3587
3588 var home_url = "<?php echo site_url(); ?>";
3589
3590 window.location.href = home_url + '/wp-admin/admin.php?page=search-library&' + 's=' + search_value;
3591
3592 }
3593 });
3594
3595 jQuery(document).on("click", "#mlfp-media-search-2", function () {
3596
3597 var search_value = jQuery('#mgmlp-media-search-input').val();
3598
3599 var home_url = "<?php echo site_url(); ?>";
3600
3601 window.location.href = home_url + '/wp-admin/admin.php?page=search-library&' + 's=' + search_value;
3602 });
3603
3604 <?php if($this->bda == 'on') { ?>
3605
3606 console.log('bda_user_role', mgmlp_ajax.bda_user_role);
3607 if(mgmlp_ajax.bda_user_role == 'authors')
3608 var selector_class = '.mlfp-protected.author';
3609 else
3610 var selector_class = '.mlfp-protected';
3611
3612 jQuery(selector_class).each(function () {
3613
3614 var image_element = jQuery(this).find('img.attachment-thumbnail');
3615 var src = image_element.attr('src');
3616 // remove the source URL and avoid the 404 error
3617 jQuery(image_element).attr('src', '');
3618 console.log('src', src);
3619
3620 jQuery.ajax({
3621 type: 'POST',
3622 async: true,
3623 data: { action: 'mlfp_load_image', src: src, nonce: '<?php echo wp_create_nonce(MLFP_LOAD_IMAGE_NONCE) ?>' },
3624 url: mgmlp_ajax.ajaxurl,
3625 success: function (data) {
3626 if(data.length > 0)
3627 jQuery(image_element).attr('src', data);
3628 },
3629 error: function (err){
3630 alert(err.responseText);
3631 }
3632 });
3633
3634 });
3635 <?php } ?>
3636 });
3637 </script>
3638 <?php
3639 }
3640
3641 public function maxgalleria_rename_image() {
3642
3643 global $wpdb, $blog_id, $is_IIS;
3644
3645 /**
3646 * Combined auth gate:
3647 * - Must be logged in
3648 * - Must have upload_files capability
3649 */
3650 if ( ! is_user_logged_in() || ! current_user_can( 'upload_files' ) ) {
3651 // Keep original wording for capability failure, but also covers not-logged-in
3652 $data = array(
3653 'message' => esc_html__( 'You do not have the capability to upload files.', 'maxgalleria-media-library' ),
3654 'refresh' => false,
3655 );
3656 echo wp_json_encode( $data );
3657 wp_die();
3658 }
3659
3660 // Nonce check
3661 $nonce = isset( $_POST['nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['nonce'] ) ) : '';
3662 if ( ! wp_verify_nonce( $nonce, MAXGALLERIA_MEDIA_LIBRARY_NONCE ) ) {
3663 echo esc_html__( 'missing nonce! Please refresh this page.', 'maxgalleria-media-library' );
3664 die();
3665 }
3666
3667 // Baseline capability check (keep existing behavior)
3668 if ( ! current_user_can( 'upload_files' ) ) {
3669 echo esc_html__( 'You do not have the capability to upload files.', 'maxgalleria-media-library' );
3670 die();
3671 }
3672
3673 // Input: file id
3674 $file_id = isset( $_POST['image_id'] ) ? absint( wp_unslash( $_POST['image_id'] ) ) : 0;
3675 if ( ! $file_id ) {
3676 echo esc_html__( 'Invalid image ID.', 'maxgalleria-media-library' );
3677 die();
3678 }
3679
3680 // Input: new file name (base name, without extension; extension is kept from original)
3681 $new_file_name = isset( $_POST['new_file_name'] ) ? trim( sanitize_text_field( wp_unslash( $_POST['new_file_name'] ) ) ) : '';
3682 if ( $new_file_name === '' ) {
3683 echo esc_html__( 'Invalid file name.', 'maxgalleria-media-library' );
3684 die();
3685 }
3686
3687 // Do not allow whitespace
3688 if ( preg_match( '/\s/', $new_file_name ) ) {
3689 echo esc_html__( 'The file name cannot contain spaces or tabs.', 'maxgalleria-media-library' );
3690 die();
3691 }
3692
3693 // Block path traversal / separators explicitly
3694 if ( strpos( $new_file_name, '/' ) !== false || strpos( $new_file_name, '\\' ) !== false || strpos( $new_file_name, '..' ) !== false ) {
3695 echo esc_html__( 'Invalid file name.', 'maxgalleria-media-library' );
3696 die();
3697 }
3698
3699 // Sanitize base name (no extension expected here)
3700 $new_file_name = sanitize_file_name( $new_file_name );
3701 if ( $new_file_name === '' ) {
3702 echo esc_html__( 'Invalid file name.', 'maxgalleria-media-library' );
3703 die();
3704 }
3705
3706 /**
3707 * Object-level authorization (IDOR fix)
3708 * - Must be allowed to edit this attachment
3709 * - Owner-only unless admin-like
3710 */
3711 $post = get_post( $file_id );
3712 if ( ! $post || $post->post_type !== 'attachment' ) {
3713 echo esc_html__( 'The file does not exist on this site.', 'maxgalleria-media-library' );
3714 die();
3715 }
3716
3717 if ( ! current_user_can( 'edit_post', $file_id ) ) {
3718 echo esc_html__( 'You are not allowed to rename this file.', 'maxgalleria-media-library' );
3719 die();
3720 }
3721
3722 $is_admin_like = current_user_can( 'manage_options' );
3723 if ( ! $is_admin_like && (int) $post->post_author !== (int) get_current_user_id() ) {
3724 echo esc_html__( 'You are not allowed to rename files you do not own.', 'maxgalleria-media-library' );
3725 die();
3726 }
3727
3728 // Fetch current attached file path
3729 $sql = $wpdb->prepare(
3730 "SELECT p.ID, pm.meta_value AS attached_file, p.post_title, p.post_name
3731 FROM {$wpdb->posts} p
3732 LEFT JOIN {$wpdb->postmeta} pm
3733 ON (pm.post_id = p.ID AND pm.meta_key = %s)
3734 WHERE p.ID = %d",
3735 '_wp_attached_file',
3736 $file_id
3737 );
3738
3739 $row = $wpdb->get_row( $sql );
3740
3741 if ( empty( $row ) ) {
3742 echo esc_html__( 'The file does not exist on this site.', 'maxgalleria-media-library' );
3743 die();
3744 }
3745
3746 // Build locations/paths
3747 $image_location = $this->build_location_url( $row->attached_file );
3748
3749 // Preserve alt text
3750 $alt_text = get_post_meta( $file_id, '_wp_attachment_image_alt', true );
3751
3752 // Keep original extension, but allow changing base name
3753 $original_ext = pathinfo( $image_location, PATHINFO_EXTENSION );
3754 $full_new_file_name = $new_file_name . '.' . $original_ext;
3755
3756 $destination_path = $this->get_absolute_path( pathinfo( $image_location, PATHINFO_DIRNAME ) );
3757 $new_file_name = wp_unique_filename( $destination_path, $full_new_file_name, null );
3758
3759 $new_file_title = $this->remove_extension( $new_file_name );
3760
3761 $old_file_path = $this->get_absolute_path( $image_location );
3762
3763 $new_file_url = pathinfo( $image_location, PATHINFO_DIRNAME ) . DIRECTORY_SEPARATOR . $new_file_name;
3764
3765 if ( is_multisite() ) {
3766 $url_slug = 'site' . $blog_id . '/';
3767 $new_file_url = str_replace( $url_slug, '', $new_file_url );
3768 }
3769
3770 $new_file_path = $this->get_absolute_path( $new_file_url );
3771
3772 if ( $this->is_windows() ) {
3773 $old_file_path = str_replace( '\\', '/', $old_file_path );
3774 $new_file_path = str_replace( '\\', '/', $new_file_path );
3775 }
3776
3777 $rename_image_location = $this->get_base_file( $image_location );
3778 $rename_destination = $this->get_base_file( $new_file_url );
3779
3780 $position = strrpos( $image_location, '.' );
3781 $image_location_no_extension = ( $position !== false ) ? substr( $image_location, 0, $position ) : $image_location;
3782
3783 // Rename file on disk
3784 if ( rename( $old_file_path, $new_file_path ) ) {
3785
3786 /**
3787 * Keep explicit thumbnail deletion (as requested / real-world behavior)
3788 * Guard for missing metadata or missing sizes.
3789 */
3790 $metadata = wp_get_attachment_metadata( $file_id );
3791 $path_to_thumbnails = pathinfo( $old_file_path, PATHINFO_DIRNAME );
3792
3793 if ( is_array( $metadata ) && isset( $metadata['sizes'] ) && is_array( $metadata['sizes'] ) ) {
3794 foreach ( $metadata['sizes'] as $source_path ) {
3795 if ( empty( $source_path['file'] ) ) {
3796 continue;
3797 }
3798
3799 $thumbnail_file = $path_to_thumbnails . DIRECTORY_SEPARATOR . $source_path['file'];
3800
3801 if ( $is_IIS || strtoupper( substr( PHP_OS, 0, 3 ) ) === 'WIN' || strtoupper( substr( PHP_OS, 0, 13 ) ) === 'MICROSOFT-IIS' ) {
3802 $thumbnail_file = str_replace( '/', '\\', $thumbnail_file );
3803 }
3804
3805 if ( file_exists( $thumbnail_file ) ) {
3806 unlink( $thumbnail_file );
3807 }
3808 }
3809 }
3810
3811 // Update attachment post record
3812 $data = array(
3813 'guid' => $new_file_url,
3814 'post_title' => $new_file_title,
3815 'post_name' => $new_file_name,
3816 );
3817 $where = array( 'ID' => $file_id );
3818 $wpdb->update( $wpdb->posts, $data, $where );
3819
3820 /**
3821 * IMPORTANT FIX: do NOT wipe all postmeta for this attachment.
3822 * This preserves ACF / SEO / custom fields.
3823 */
3824
3825 // get the uploads dir name
3826 $basedir = $this->upload_dir['baseurl'];
3827 $uploads_dir_name_pos = strrpos( $basedir, '/' );
3828 $uploads_dir_name = ( $uploads_dir_name_pos !== false ) ? substr( $basedir, $uploads_dir_name_pos + 1 ) : '';
3829
3830 // find the name and cut off the part with the uploads path
3831 $string_position = ( $uploads_dir_name !== '' ) ? strpos( $new_file_url, $uploads_dir_name ) : false;
3832 $uploads_dir_length = strlen( $uploads_dir_name ) + 1;
3833
3834 if ( $string_position !== false ) {
3835 $uploads_location = substr( $new_file_url, $string_position + $uploads_dir_length );
3836 } else {
3837 // Fallback: best-effort relative path
3838 $uploads_location = ltrim( $new_file_url, '/' );
3839 }
3840
3841 if ( $this->is_windows() ) {
3842 $uploads_location = str_replace( '\\', '/', $uploads_location );
3843 }
3844
3845 $uploads_location = ltrim( $uploads_location, '/' );
3846
3847 update_post_meta( $file_id, '_wp_attached_file', $uploads_location );
3848
3849 if ( strlen( trim( $alt_text ) ) > 0 ) {
3850 update_post_meta( $file_id, '_wp_attachment_image_alt', $alt_text );
3851 }
3852
3853 // Regenerate metadata for the renamed file
3854 $attach_data = wp_generate_attachment_metadata( $file_id, $new_file_path );
3855 wp_update_attachment_metadata( $file_id, $attach_data );
3856
3857 // SiteOrigin Panels updates (unchanged)
3858 if ( class_exists( 'SiteOrigin_Panels' ) ) {
3859 $this->update_serial_postmeta_records( $rename_image_location, $rename_destination );
3860 }
3861
3862 // Beaver Builder updates (hardened query, rest unchanged)
3863 if ( class_exists( 'FLBuilderLoader' ) ) {
3864
3865 $like = '%' . $wpdb->esc_like( $rename_image_location ) . '%';
3866 $bb_sql = $wpdb->prepare(
3867 "SELECT ID FROM {$wpdb->posts} WHERE post_content LIKE %s",
3868 $like
3869 );
3870
3871 $records = $wpdb->get_results( $bb_sql );
3872
3873 foreach ( $records as $record ) {
3874 $this->update_bb_postmeta( $record->ID, $rename_image_location, $rename_destination );
3875 }
3876
3877 // clearing BB caches
3878 if ( class_exists( 'FLBuilderModel' ) && method_exists( 'FLBuilderModel', 'delete_asset_cache_for_all_posts' ) ) {
3879 FLBuilderModel::delete_asset_cache_for_all_posts();
3880 }
3881 if ( class_exists( 'FLCustomizer' ) && method_exists( 'FLCustomizer', 'clear_all_css_cache' ) ) {
3882 FLCustomizer::clear_all_css_cache();
3883 }
3884 }
3885
3886 // Update post content links across posts (hardened query)
3887 $replace_sql = $wpdb->prepare(
3888 "UPDATE {$wpdb->posts}
3889 SET post_content = REPLACE(post_content, %s, %s)",
3890 $rename_image_location,
3891 $rename_destination
3892 );
3893 $result = $wpdb->query( $replace_sql );
3894
3895 // for updating wp pagebuilder (unchanged)
3896 if ( defined( 'WPPB_LICENSE' ) ) {
3897 $this->update_wppb_data( $image_location_no_extension, $new_file_url );
3898 }
3899
3900 // for updating themify images (unchanged)
3901 if ( function_exists( 'themify_builder_activate' ) ) {
3902 $this->update_themify_data( $image_location_no_extension, $new_file_url );
3903 }
3904
3905 // for updating elementor background images (unchanged)
3906 if ( is_plugin_active( "elementor/elementor.php" ) ) {
3907 $this->update_elementor_data( $file_id, $image_location_no_extension, $new_file_url );
3908 }
3909
3910 echo esc_html__( 'Updating attachment links, please wait...The file was renamed', 'maxgalleria-media-library' );
3911 die();
3912 }
3913
3914 // If rename failed
3915 echo esc_html__( 'The file could not be renamed.', 'maxgalleria-media-library' );
3916 die();
3917 }
3918
3919 public function maxgalleria_rename_image1() {
3920
3921 global $wpdb, $blog_id, $is_IIS;
3922
3923 if ( !wp_verify_nonce( $_POST['nonce'], MAXGALLERIA_MEDIA_LIBRARY_NONCE)) {
3924 exit(esc_html__('missing nonce! Please refresh this page.','maxgalleria-media-library'));
3925 }
3926
3927 // Check if the current user has the capability to upload files
3928 if(!current_user_can('upload_files')){
3929 exit(esc_html__('You do not have the capability to upload files.','maxgalleria-media-library'));
3930 }
3931
3932 if ((isset($_POST['image_id'])) && (strlen(trim($_POST['image_id'])) > 0))
3933 $file_id = intval(trim(sanitize_text_field($_POST['image_id'])));
3934 else
3935 $file_id = "";
3936
3937 if ((isset($_POST['new_file_name'])) && (strlen(trim($_POST['new_file_name'])) > 0))
3938 $new_file_name = trim(sanitize_text_field($_POST['new_file_name']));
3939 else
3940 $new_file_name = "";
3941
3942 if($new_file_name === '') {
3943 echo esc_html__('Invalid file name.','maxgalleria-media-library');
3944 die();
3945 }
3946
3947 if(preg_match('^[\w,\s\-_]+\.[A-Za-z]{3}$^', $new_file_name)) {
3948 echo esc_html__('Invalid file name.','maxgalleria-media-library');
3949 die();
3950 }
3951
3952 if (preg_match("/\\s/", $new_file_name)) {
3953 echo esc_html__('The file name cannot contain spaces or tabs.','maxgalleria-media-library');
3954 die();
3955 }
3956
3957 $new_file_name = sanitize_file_name($new_file_name);
3958
3959 $sql = $wpdb->prepare("select ID, pm.meta_value as attached_file, post_title, post_name
3960 from {$wpdb->prefix}posts
3961 LEFT JOIN {$wpdb->prefix}postmeta AS pm ON (pm.post_id = {$wpdb->prefix}posts.ID)
3962 where ID = %s
3963 AND pm.meta_key = '_wp_attached_file'", $file_id);
3964
3965 $row = $wpdb->get_row($sql);
3966
3967 if (empty($row)) {
3968 echo esc_html__('The file does not exist on this site.', 'maxgalleria-media-library');
3969 die();
3970 }
3971
3972 if($row) {
3973
3974 $image_location = $this->build_location_url($row->attached_file);
3975
3976 $alt_text = get_post_meta($file_id, '_wp_attachment_image_alt', true);
3977
3978 $full_new_file_name = $new_file_name . '.' . pathinfo($image_location, PATHINFO_EXTENSION);
3979 $destination_path = $this->get_absolute_path(pathinfo($image_location, PATHINFO_DIRNAME));
3980
3981 $new_file_name = wp_unique_filename( $destination_path, $full_new_file_name, null );
3982
3983 $new_file_title = $this->remove_extension($new_file_name);
3984
3985 $old_file_path = $this->get_absolute_path($image_location);
3986
3987 $new_file_url = pathinfo($image_location, PATHINFO_DIRNAME) . DIRECTORY_SEPARATOR . $new_file_name;
3988
3989 if(is_multisite()) {
3990 $url_slug = "site" . $blog_id . "/";
3991 $new_file_url = str_replace($url_slug, "", $new_file_url);
3992 }
3993
3994 $new_file_path = $this->get_absolute_path($new_file_url);
3995
3996 if($this->is_windows()) {
3997 $old_file_path = str_replace('\\', '/', $old_file_path);
3998 $new_file_path = str_replace('\\', '/', $new_file_path);
3999 }
4000
4001 $rename_image_location = $this->get_base_file($image_location);
4002 $rename_destination = $this->get_base_file($new_file_url);
4003
4004 $position = strrpos($image_location, '.');
4005
4006 $image_location_no_extension = substr($image_location, 0, $position);
4007
4008 if(rename($old_file_path, $new_file_path )) {
4009
4010 //$old_file_path = str_replace('.', '*.', $old_file_path );
4011
4012 $metadata = wp_get_attachment_metadata($file_id);
4013 $path_to_thumbnails = pathinfo($old_file_path, PATHINFO_DIRNAME);
4014
4015 foreach($metadata['sizes'] as $source_path) {
4016 $thumbnail_file = $path_to_thumbnails . DIRECTORY_SEPARATOR . $source_path['file'];
4017
4018 if ($is_IIS || strtoupper(substr(PHP_OS, 0, 3)) == 'WIN' || strtoupper(substr(PHP_OS, 0, 13)) == 'MICROSOFT-IIS' )
4019 $thumbnail_file = str_replace('/', '\\', $thumbnail_file);
4020
4021 if(file_exists($thumbnail_file))
4022 unlink($thumbnail_file);
4023 }
4024
4025 $table = $wpdb->prefix . "posts";
4026 $data = array('guid' => $new_file_url,
4027 'post_title' => $new_file_title,
4028 'post_name' => $new_file_name
4029 );
4030 $where = array('ID' => $file_id);
4031 $wpdb->update( $table, $data, $where);
4032
4033 $table = $wpdb->prefix . "postmeta";
4034 $where = array('post_id' => $file_id);
4035 $wpdb->delete($table, $where);
4036
4037 // get the uploads dir name
4038 $basedir = $this->upload_dir['baseurl'];
4039 $uploads_dir_name_pos = strrpos($basedir, '/');
4040 $uploads_dir_name = substr($basedir, $uploads_dir_name_pos+1);
4041
4042 //find the name and cut off the part with the uploads path
4043 $string_position = strpos($new_file_url, $uploads_dir_name);
4044 $uploads_dir_length = strlen($uploads_dir_name) + 1;
4045 $uploads_location = substr($new_file_url, $string_position+$uploads_dir_length);
4046 if($this->is_windows())
4047 $uploads_location = str_replace('\\','/', $uploads_location);
4048
4049 $uploads_location = ltrim($uploads_location, '/');
4050 update_post_meta( $file_id, '_wp_attached_file', $uploads_location );
4051 if(strlen(trim($alt_text)) > 0)
4052 update_post_meta( $file_id, '_wp_attachment_image_alt', $alt_text );
4053 $attach_data = wp_generate_attachment_metadata( $file_id, $new_file_path );
4054 wp_update_attachment_metadata( $file_id, $attach_data );
4055
4056 if(class_exists( 'SiteOrigin_Panels')) {
4057 $this->update_serial_postmeta_records($rename_image_location, $rename_destination);
4058 }
4059
4060 // update postmeta records for beaver builder
4061 if(class_exists( 'FLBuilderLoader')) {
4062
4063 $sql = "SELECT ID FROM {$wpdb->prefix}posts WHERE post_content LIKE '%$rename_image_location%'";
4064
4065 $records = $wpdb->get_results($sql);
4066 foreach($records as $record) {
4067
4068 $this->update_bb_postmeta($record->ID, $rename_image_location, $rename_destination);
4069
4070 }
4071 // clearing BB caches
4072 if ( class_exists( 'FLBuilderModel' ) && method_exists( 'FLBuilderModel', 'delete_asset_cache_for_all_posts' ) ) {
4073 FLBuilderModel::delete_asset_cache_for_all_posts();
4074 }
4075 if ( class_exists( 'FLCustomizer' ) && method_exists( 'FLCustomizer', 'clear_all_css_cache' ) ) {
4076 FLCustomizer::clear_all_css_cache();
4077 }
4078
4079 }
4080
4081 $replace_sql = "UPDATE {$wpdb->prefix}posts SET `post_content` = REPLACE (`post_content`, '$rename_image_location', '$rename_destination');";
4082
4083 $replace_sql = str_replace ( '/', '\/', $replace_sql);
4084 $result = $wpdb->query($replace_sql);
4085
4086 // for updating wp pagebuilder
4087 if(defined('WPPB_LICENSE')) {
4088 $this->update_wppb_data($image_location_no_extension, $new_file_url);
4089 }
4090
4091 // for updating themify images
4092 if(function_exists('themify_builder_activate')) {
4093 $this->update_themify_data($image_location_no_extension, $new_file_url);
4094 }
4095
4096 // for updating elementor background images
4097 if(is_plugin_active("elementor/elementor.php")) {
4098 $this->update_elementor_data($file_id, $image_location_no_extension, $new_file_url);
4099 }
4100
4101 echo esc_html__('Updating attachment links, please wait...The file was renamed','maxgalleria-media-library');
4102 }
4103 }
4104
4105 die();
4106 }
4107
4108 public function build_location_url($attached_file) {
4109 return rtrim($this->upload_dir['baseurl'], '/') . '/' . ltrim($attached_file, '/');
4110 }
4111
4112 // saves the sort selection
4113 public function sort_contents() {
4114
4115 if ( !wp_verify_nonce( $_POST['nonce'], MAXGALLERIA_MEDIA_LIBRARY_NONCE)) {
4116 exit(esc_html__('missing nonce!','maxgalleria-media-library'));
4117 }
4118
4119 // Check if the current user has the capability to upload files
4120 if(!current_user_can('upload_files')){
4121 exit(esc_html__('You do not have the capability to upload files.','maxgalleria-media-library'));
4122 }
4123
4124 if ((isset($_POST['sort_order'])) && (strlen(trim($_POST['sort_order'])) > 0))
4125 $sort_order = trim(sanitize_text_field($_POST['sort_order']));
4126 else
4127 $sort_order = "0";
4128
4129 if ((isset($_POST['folder'])) && (strlen(trim($_POST['folder'])) > 0))
4130 $current_folder_id = intval(trim(sanitize_text_field($_POST['folder'])));
4131 else
4132 $current_folder_id = "";
4133
4134 update_option( MAXGALLERIA_MEDIA_LIBRARY_SORT_ORDER, $sort_order );
4135
4136 if($current_folder_id != "") {
4137 $this->display_folder_contents ($current_folder_id, true);
4138 }
4139
4140 die();
4141 }
4142
4143 public function mlf_change_sort_type() {
4144
4145 if ( !wp_verify_nonce( $_POST['nonce'], MAXGALLERIA_MEDIA_LIBRARY_NONCE)) {
4146 exit(esc_html__('missing nonce!','maxgalleria-media-library'));
4147 }
4148
4149 // Check if the current user has the capability to upload files
4150 if(!current_user_can('upload_files')){
4151 exit(esc_html__('You do not have the capability to upload files.','maxgalleria-media-library'));
4152 }
4153
4154 if ((isset($_POST['sort_type'])) && (strlen(trim($_POST['sort_type'])) > 0))
4155 $sort_type = $this->validate_sort_type(trim(sanitize_text_field($_POST['sort_type'])));
4156 else
4157 $sort_type = "ASC";
4158
4159 if ((isset($_POST['folder'])) && (strlen(trim($_POST['folder'])) > 0))
4160 $current_folder_id = intval(trim(sanitize_text_field($_POST['folder'])));
4161 else
4162 $current_folder_id = "";
4163
4164 update_option( MAXGALLERIA_MLF_SORT_TYPE, $sort_type );
4165
4166 if($current_folder_id != "") {
4167 $this->display_folder_contents ($current_folder_id, true);
4168 }
4169
4170 die();
4171 }
4172
4173 // Validate the sort type to ensure it is either "ASC" or "DESC".
4174 public function validate_sort_type($sort_type) {
4175 $allowed_sort_types = array('ASC', 'DESC');
4176 return in_array($sort_type, $allowed_sort_types) ? $sort_type : 'ASC';
4177 }
4178
4179 public function mgmlp_move_copy(){
4180
4181 if ( !wp_verify_nonce( $_POST['nonce'], MAXGALLERIA_MEDIA_LIBRARY_NONCE)) {
4182 exit(esc_html__('missing nonce! Please refresh this page.','maxgalleria-media-library'));
4183 }
4184
4185 // Check if the current user has the capability to upload files
4186 if(!current_user_can('upload_files')){
4187 exit(esc_html__('You do not have the capability to upload files.','maxgalleria-media-library'));
4188 }
4189
4190 if ((isset($_POST['move_copy_switch'])) && (strlen(trim($_POST['move_copy_switch'])) > 0))
4191 $move_copy_switch = trim(sanitize_text_field($_POST['move_copy_switch']));
4192 else
4193 $move_copy_switch = 'on';
4194
4195 update_option( MAXGALLERIA_MEDIA_LIBRARY_MOVE_OR_COPY, $move_copy_switch );
4196
4197 die();
4198
4199 }
4200
4201 public function run_on_deactivate() {
4202 wp_clear_scheduled_hook('new_folder_check');
4203 }
4204
4205 public function mlf_check_for_new_folders(){
4206
4207 if ( !wp_verify_nonce( $_POST['nonce'], MAXGALLERIA_MEDIA_LIBRARY_NONCE)) {
4208 exit(esc_html__('missing nonce!','maxgalleria-media-library'));
4209 }
4210
4211 // Check if the current user has the capability to upload files
4212 if(!current_user_can('upload_files')){
4213 exit(esc_html__('You do not have the capability to upload files.','maxgalleria-media-library'));
4214 }
4215
4216 if ((isset($_POST['parent_folder'])) && (strlen(trim($_POST['parent_folder'])) > 0))
4217 $parent_folder_id = intval(trim(sanitize_text_field($_POST['parent_folder'])));
4218
4219 //error_log("parent_folder_id $parent_folder_id");
4220
4221 $message = $this->admin_check_for_new_folders(true);
4222
4223 $folders = $this->get_folder_data($parent_folder_id);
4224 $data = array ('message' => esc_html($message), 'folders' => $folders, 'refresh' => true );
4225 echo json_encode($data);
4226
4227 die();
4228
4229 }
4230
4231 public function admin_check_for_new_folders($noecho = null) {
4232
4233 global $blog_id, $is_IIS;
4234 $skip_path = "";
4235 //$uploads_path = wp_upload_dir();
4236 $message = esc_html__('Added','maxgalleria-media-library');
4237 $first = true;
4238
4239 if(!$this->upload_dir['error']) {
4240
4241 $uploads_folder = get_option(MAXGALLERIA_MEDIA_LIBRARY_UPLOAD_FOLDER_NAME, "uploads");
4242 $uploads_folder_id = get_option(MAXGALLERIA_MEDIA_LIBRARY_UPLOAD_FOLDER_ID );
4243 $uploads_length = strlen($uploads_folder);
4244
4245 $folders_to_hide = explode("\n", file_get_contents( MAXGALLERIA_MEDIA_LIBRARY_PLUGIN_DIR .'/folders_to_hide.txt'));
4246
4247 //find the uploads folder
4248 $uploads_url = $this->upload_dir['baseurl'];
4249 $upload_path = $this->upload_dir['basedir'];
4250 $folder_found = false;
4251
4252 //not sure if this is still needed
4253 //$this->mlp_remove_slashes();
4254
4255 if(!$noecho)
4256 echo esc_html( __('Scanning for new folders in ','maxgalleria-media-library') . " $upload_path") . "<br>";
4257 $objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($upload_path), RecursiveIteratorIterator::SELF_FIRST, RecursiveIteratorIterator::CATCH_GET_CHILD);
4258 foreach($objects as $name => $object){
4259 if(is_dir($name)) {
4260 $dir_name = pathinfo($name, PATHINFO_BASENAME);
4261 if ($dir_name[0] !== '.' && strpos($dir_name, "'") === false ) {
4262 if( empty($skip_path) || (strpos($name, $skip_path) === false)) {
4263
4264 // no match, set it back to empty
4265 $skip_path = "";
4266
4267 if(!is_multisite()) {
4268 $upload_pos = strpos($name, $uploads_folder);
4269 $url = $uploads_url . substr($name, ($upload_pos+$uploads_length));
4270
4271 // fix slashes if running windows
4272 if ($is_IIS || strtoupper(substr(PHP_OS, 0, 3)) == 'WIN' || strtoupper(substr(PHP_OS, 0, 13)) == 'MICROSOFT-IIS' ) {
4273 $url = str_replace('\\', '/', $url);
4274 }
4275
4276 if($this->folder_exist($url) === false) {
4277 if(!in_array($dir_name, $folders_to_hide)) {
4278 if(!file_exists($name . DIRECTORY_SEPARATOR . 'mlpp-hidden' )){
4279 $folder_found = true;
4280 if(!$noecho)
4281 echo esc_html( __('Adding','maxgalleria-media-library') . " " . esc_url($url)) . "<br>";
4282 else {
4283 $seprator = ($first) ? ' ':', ';
4284 $first = false;
4285 $message .= $seprator . esc_url($url);
4286 }
4287 $parent_id = $this->find_parent_id($url);
4288 if($parent_id)
4289 $this->add_media_folder($dir_name, $parent_id, $url);
4290 } else {
4291 $skip_path = $name;
4292 }
4293 } else {
4294 $skip_path = $name;
4295 }
4296 }
4297 } else {
4298 if($blog_id === '1') {
4299 if(strpos($name,"uploads/sites") !== false)
4300 continue;
4301
4302 $upload_pos = strpos($name, $uploads_folder);
4303 $url = $uploads_url . substr($name, ($upload_pos+$uploads_length));
4304
4305 // fix slashes if running windows
4306 if ($is_IIS || strtoupper(substr(PHP_OS, 0, 3)) == 'WIN' || strtoupper(substr(PHP_OS, 0, 13)) == 'MICROSOFT-IIS' ) {
4307 $url = str_replace('\\', '/', $url);
4308 }
4309
4310 if($this->folder_exist($url) === false) {
4311 if(!in_array($dir_name, $folders_to_hide)) {
4312 if(!file_exists($name . DIRECTORY_SEPARATOR . 'mlpp-hidden' )){
4313 $folder_found = true;
4314 if(!$noecho)
4315 echo esc_html( __('Adding','maxgalleria-media-library') . " " . esc_url($url)) . "<br>";
4316 else {
4317 $seprator = ($first) ? ' ':', ';
4318 $first = false;
4319 $message .= $seprator . esc_url($url);
4320 }
4321 $parent_id = $this->find_parent_id($url);
4322 if($parent_id)
4323 $this->add_media_folder($dir_name, $parent_id, $url);
4324 } else {
4325 $skip_path = $name;
4326 }
4327 } else {
4328 $skip_path = $name;
4329 }
4330 }
4331 } else {
4332 if(strpos($name,"uploads/sites/$blog_id") !== false) {
4333 $upload_pos = strpos($name, $uploads_folder);
4334 $url = $uploads_url . substr($name, ($upload_pos+$uploads_length));
4335
4336 // fix slashes if running windows
4337 if ($is_IIS || strtoupper(substr(PHP_OS, 0, 3)) == 'WIN' || strtoupper(substr(PHP_OS, 0, 13)) == 'MICROSOFT-IIS' ) {
4338 $url = str_replace('\\', '/', $url);
4339 }
4340
4341 if($this->folder_exist($url) === false) {
4342 if(!in_array($dir_name, $folders_to_hide)) {
4343 if(!file_exists($name . DIRECTORY_SEPARATOR . 'mlpp-hidden' )){
4344 $folder_found = true;
4345 if(!$noecho)
4346 echo esc_html( __('Adding','maxgalleria-media-library') . " " . esc_url($url)) . "<br>";
4347 else {
4348 $seprator = ($first) ? ' ':', ';
4349 $first = false;
4350 $message .= $seprator . esc_url($url);
4351 }
4352 $parent_id = $this->find_parent_id($url);
4353 if($parent_id)
4354 $this->add_media_folder($dir_name, $parent_id, $url);
4355 }
4356 } else {
4357 $skip_path = $name;
4358 }
4359 }
4360 }
4361 }
4362 }
4363 }
4364 }
4365 }
4366 }
4367 if(!$folder_found) {
4368 $message = esc_html__('No new folders were found.','maxgalleria-media-library');
4369 if(!$noecho)
4370 echo $message . "<br>";
4371 }
4372 }
4373 else {
4374 $message = esc_html("error: " . $this->upload_dir['error']);
4375 if(!$noecho)
4376 echo $message . "<br>";
4377 }
4378 return $message;
4379 }
4380
4381 private function find_parent_id($base_url) {
4382
4383 global $wpdb;
4384 $last_slash = strrpos($base_url, '/');
4385 $parent_dir = substr($base_url, 0, $last_slash);
4386
4387 // get the relative path
4388 $parent_dir = substr($parent_dir, $this->base_url_length);
4389
4390 $sql = "SELECT ID FROM {$wpdb->prefix}posts
4391 LEFT JOIN {$wpdb->prefix}postmeta AS pm ON pm.post_id = ID
4392 WHERE pm.meta_value = '$parent_dir'
4393 and pm.meta_key = '_wp_attached_file'";
4394
4395 $row = $wpdb->get_row($sql);
4396 if($row) {
4397 $parent_id = $row->ID;
4398 }
4399 else
4400 $parent_id = $this->uploads_folder_ID; //-1;
4401
4402 return $parent_id;
4403 }
4404
4405 private function mpmlp_insert_post( $post_type, $post_title, $guid, $post_status ) {
4406 global $wpdb;
4407
4408 $user_id = get_current_user_id();
4409 $post_date = current_time('mysql');
4410
4411 $post = array(
4412 'post_content' => '',
4413 'post_name' => $post_title,
4414 'post_title' => $post_title,
4415 'post_status' => $post_status,
4416 'post_type' => $post_type,
4417 'post_author' => $user_id,
4418 'ping_status' => 'closed',
4419 'post_parent' => 0,
4420 'menu_order' => 0,
4421 'to_ping' => '',
4422 'pinged' => '',
4423 'post_password' => '',
4424 'guid' => $guid,
4425 'post_content_filtered' => '',
4426 'post_excerpt' => '',
4427 'post_date' => $post_date,
4428 'post_date_gmt' => $post_date,
4429 'comment_status' => 'closed'
4430 );
4431
4432
4433 $table = $wpdb->prefix . "posts";
4434 $wpdb->insert( $table, $post );
4435
4436 return $wpdb->insert_id;
4437 }
4438
4439 public function mlp_set_review_notice_true() {
4440
4441 $current_user_id = get_current_user_id();
4442
4443 update_user_meta( $current_user_id, MAXGALLERIA_MLP_REVIEW_NOTICE, "off" );
4444
4445 $request = sanitize_url($_SERVER["HTTP_REFERER"]);
4446
4447 echo "<script>window.location.href = '" . esc_url_raw($request) . "'</script>";
4448
4449
4450 }
4451
4452 public function mlp_set_feature_notice_true() {
4453
4454 $current_user_id = get_current_user_id();
4455
4456 update_user_meta( $current_user_id, MAXGALLERIA_MLP_FEATURE_NOTICE, "off" );
4457
4458 $request = sanitize_url($_SERVER["HTTP_REFERER"]);
4459
4460 echo "<script>window.location.href = '" . esc_url_raw($request) . "'</script>";
4461
4462 }
4463
4464 public function mlp_set_review_later() {
4465
4466 $current_user_id = get_current_user_id();
4467
4468 $review_date = date('Y-m-d', strtotime("+14 days"));
4469
4470 update_user_meta( $current_user_id, MAXGALLERIA_MLP_REVIEW_NOTICE, $review_date );
4471
4472 $request = sanitize_url($_SERVER["HTTP_REFERER"]);
4473
4474 echo "<script>window.location.href = '" . esc_url_raw($request) . "'</script>";
4475
4476 }
4477
4478 public function mlp_features_notice() {
4479 if( current_user_can( 'upload_files' ) ) { ?>
4480 <div class="updated notice maxgalleria-mlp-notice">
4481 <div id='mlp_logo'></div>
4482 <div id='maxgalleria-mlp-notice-3'><p id='mlp-notice-title'><?php esc_html_e('Is there a feature you would like for us to add to', 'maxgalleria-media-library' ); ?><br><?php esc_html_e('Media Library Folders Pro? Let us know.', 'maxgalleria-media-library' ); ?></p>
4483 <p><?php esc_html_e('Send your suggestions to', 'maxgalleria-media-library' ); ?> <a href="mailto:support@maxfoundry.com">support@maxfoundry.com</a>.</p>
4484
4485 </div>
4486 <a class="dashicons dashicons-dismiss close-mlp-notice" href="<?php echo esc_url_raw(admin_url() . "admin.php?page=mlp-feature-notice") ?>"></a>
4487 </div>
4488 <?php
4489 }
4490 }
4491
4492 public function mlp_review_notice() {
4493 if( current_user_can( 'upload_files' ) ) { ?>
4494 <div class="updated notice maxgalleria-mlp-notice">
4495 <div id='mlp_logo'></div>
4496 <div id='maxgalleria-mlp-notice-3'><p id='mlp-notice-title'><?php esc_html_e( 'Rate us Please!', 'maxgalleria-media-library' ); ?></p>
4497 <p><?php esc_html_e( 'Your rating is the simplest way to support Media Library Folders Pro. We really appreciate it!', 'maxgalleria-media-library' ); ?></p>
4498
4499 <ul id="mlp-review-notice-links">
4500 <li> <span class="dashicons dashicons-smiley"></span><a href="<?php echo esc_url_raw( admin_url() . "admin.php?page=mlp-review-notice") ?>"><?php esc_html_e( "I've already left a review", "maxgalleria-media-library" ); ?></a></li>
4501 <li><span class="dashicons dashicons-calendar-alt"></span><a href="<?php echo esc_url_raw( admin_url() . "admin.php?page=mlp-review-later") ?>"><?php esc_html_e( "Maybe Later", "maxgalleria-media-library" ); ?></a></li>
4502 <li><span class="dashicons dashicons-external"></span><a target="_blank" href="https://wordpress.org/support/plugin/media-library-plus/reviews/?filter=5"><?php esc_html_e( "Sure! I'd love to!", "maxgalleria-media-library" ); ?></a></li>
4503 </ul>
4504 </div>
4505 <a class="dashicons dashicons-dismiss close-mlp-notice" href="<?php echo esc_url_raw( admin_url() . "admin.php?page=mlp-review-notice") ?>"></a>
4506 </div>
4507 <?php
4508 }
4509 }
4510
4511 public function max_sync_contents($parent_folder) {
4512
4513 global $wpdb;
4514 global $blog_id;
4515 global $is_IIS;
4516 $skip_path = "";
4517 $last_new_folder_id = 0;
4518
4519 $files_added = 0;
4520 $alt_text = "";
4521 $default_title = "";
4522 $default_alt = "";
4523 $folders_found = false;
4524 $existing_folders = false;
4525
4526 if(!is_numeric($parent_folder))
4527 die();
4528
4529 $uploads_folder = get_option(MAXGALLERIA_MEDIA_LIBRARY_UPLOAD_FOLDER_NAME, "uploads");
4530 $uploads_length = strlen($uploads_folder);
4531 $uploads_url = $this->upload_dir['baseurl'];
4532 $upload_path = $this->upload_dir['basedir'];
4533
4534 $folders_to_hide = explode("\n", file_get_contents(MAXGALLERIA_MEDIA_LIBRARY_PLUGIN_DIR .'/folders_to_hide.txt'));
4535
4536 $sql = "select meta_value as attached_file
4537 from {$wpdb->prefix}postmeta
4538 where post_id = $parent_folder
4539 and meta_key = '_wp_attached_file'";
4540
4541 $current_row = $wpdb->get_row($sql);
4542
4543 $baseurl = rtrim($uploads_url, '/') . '/';
4544
4545 if(!is_multisite()) {
4546 $image_location = $baseurl . ltrim($current_row->attached_file, '/');
4547 $folder_path = $this->get_absolute_path($image_location);
4548 } else {
4549 $folder_path = $this->get_absolute_path($baseurl);
4550 }
4551
4552 //not sure if this is still needed
4553 //$this->mlp_remove_slashes();
4554
4555 $folders_array = array();
4556 $folders_array[] = $parent_folder;
4557
4558 $file_names = array_diff(scandir($folder_path), array('..', '.'));
4559
4560 // check for new folders
4561 foreach ($file_names as $file_name) {
4562 $name = $folder_path . DIRECTORY_SEPARATOR . $file_name;
4563 if(is_dir($name)) {
4564 //error_log($name);
4565 $dir_name = pathinfo($name, PATHINFO_BASENAME);
4566 if ($dir_name[0] !== '.' && strpos($dir_name, "'") === false ) {
4567 if( empty($skip_path) || (strpos($name, $skip_path) === false)) {
4568
4569 // no match, set it back to empty
4570 $skip_path = "";
4571
4572 if(!is_multisite()) {
4573
4574 $upload_pos = strpos($name, $uploads_folder);
4575 $url = $uploads_url . substr($name, ($upload_pos+$uploads_length));
4576
4577 // fix slashes if running windows
4578 if ($is_IIS || strtoupper(substr(PHP_OS, 0, 3)) == 'WIN' || strtoupper(substr(PHP_OS, 0, 13)) == 'MICROSOFT-IIS' ) {
4579 $url = str_replace('\\', '/', $url);
4580 }
4581
4582 $existing_folder_id = $this->folder_exist($url);
4583 if($existing_folder_id === false) {
4584 if(!in_array($dir_name, $folders_to_hide)) {
4585 if(!file_exists($name . DIRECTORY_SEPARATOR . 'mlpp-hidden' )){
4586 $folders_found = true;
4587 $parent_id = $this->find_parent_id($url);
4588 $last_new_folder_id = $this->add_media_folder($dir_name, $parent_id, $url);
4589 $files_added++;
4590 } else {
4591 $skip_path = $name;
4592 }
4593 } else {
4594 $skip_path = $name;
4595 }
4596 } else {
4597 $existing_folders = true;
4598 }
4599 } else {
4600 if($blog_id === '1') {
4601 if(strpos($name,"uploads/sites") !== false)
4602 continue;
4603
4604 $upload_pos = strpos($name, $uploads_folder);
4605 $url = $uploads_url . substr($name, ($upload_pos+$uploads_length));
4606
4607 // fix slashes if running windows
4608 if ($is_IIS || strtoupper(substr(PHP_OS, 0, 3)) == 'WIN' || strtoupper(substr(PHP_OS, 0, 13)) == 'MICROSOFT-IIS' ) {
4609 $url = str_replace('\\', '/', $url);
4610 }
4611
4612 $existing_folder_id = $this->folder_exist($url);
4613 if($existing_folder_id === false) {
4614 if(!in_array($dir_name, $folders_to_hide)) {
4615 if(!file_exists($name . DIRECTORY_SEPARATOR . 'mlpp-hidden' )){
4616 $folders_found = true;
4617 $parent_id = $this->find_parent_id($url);
4618 $last_new_folder_id = $this->add_media_folder($dir_name, $parent_id, $url);
4619 $files_added++;
4620 } else {
4621 $skip_path = $name;
4622 }
4623 } else {
4624 $skip_path = $name;
4625 }
4626 } else {
4627 $existing_folders = true;
4628 }
4629 } else {
4630 if(strpos($name,"uploads/sites/$blog_id") !== false) {
4631
4632 $upload_pos = strpos($name, $uploads_folder);
4633
4634 $url = $uploads_url . substr($name, ($upload_pos+$uploads_length));
4635
4636 // fix slashes if running windows
4637 if ($is_IIS || strtoupper(substr(PHP_OS, 0, 3)) == 'WIN' || strtoupper(substr(PHP_OS, 0, 13)) == 'MICROSOFT-IIS' ) {
4638 $url = str_replace('\\', '/', $url);
4639 }
4640 $existing_folder_id = $this->folder_exist($url);
4641 if($existing_folder_id === false) {
4642 $folders_found = true;
4643 $parent_id = $this->find_parent_id($url);
4644 $last_new_folder_id = $this->add_media_folder($dir_name, $parent_id, $url);
4645 $files_added++;
4646 } else {
4647 $existing_folders = true;
4648 }
4649 }
4650 }
4651 }
4652 }
4653 }
4654 }
4655 } // end foreach
4656
4657 $user_id = get_current_user_id();
4658 update_user_meta($user_id, MAXG_SYNC_FOLDERS, $folders_array);
4659
4660 if($folders_found || $existing_folders) {
4661 return true;
4662 } else {
4663 return false;
4664 }
4665
4666 }
4667
4668 public function get_base_file($file_path) {
4669
4670 $dot_position = strrpos($file_path, '.' );
4671 if($dot_position === false)
4672 return $file_path;
4673 else
4674 return substr($file_path, 0, $dot_position);
4675 }
4676
4677 private function is_base_file($file_path, $file_array) {
4678
4679 $dash_position = strrpos($file_path, '-' );
4680 $x_position = strrpos($file_path, 'x', $dash_position);
4681 $dot_position = strrpos($file_path, '.' );
4682
4683 if(($dash_position) && ($x_position)) {
4684 $base_file = substr($file_path, 0, $dash_position) . substr($file_path, $dot_position );
4685 if(in_array($base_file, $file_array))
4686 return false;
4687 else
4688 return true;
4689 } else
4690 return true;
4691
4692 }
4693
4694 private function search_folder_attachments($file_path, $attachments){
4695
4696 $found = false;
4697 if($attachments) {
4698 foreach($attachments as $row) {
4699 $current_file_path = pathinfo(get_attached_file($row->ID), PATHINFO_BASENAME);
4700 if(strpos($current_file_path, '-scaled.') !== false)
4701 $current_file_path = str_replace ('-scaled', '', $current_file_path);
4702 //error_log("$current_file_path $file_path");
4703 if($current_file_path === $file_path) {
4704 $found = true;
4705 break;
4706 } else {
4707 }
4708 }
4709 }
4710 return $found;
4711 }
4712
4713 public function write_log ( $log ) {
4714 if(!defined('HIDE_WRITELOG_MESSAGES')) {
4715 if ( true === WP_DEBUG ) {
4716 if ( is_array( $log ) || is_object( $log ) ) {
4717 error_log( print_r( $log, true ) );
4718 } else {
4719 error_log( $log );
4720 }
4721 }
4722 }
4723 }
4724
4725 public function mlp_load_folder() {
4726
4727 global $wpdb;
4728
4729 if ( !wp_verify_nonce( $_POST['nonce'], MAXGALLERIA_MEDIA_LIBRARY_NONCE)) {
4730 exit(esc_html__('missing nonce!','maxgalleria-media-library'));
4731 }
4732
4733 // Check if the current user has the capability to upload files
4734 if(!current_user_can('upload_files')){
4735 exit(esc_html__('You do not have the capability to upload files.','maxgalleria-media-library'));
4736 }
4737
4738 if ((isset($_POST['folder'])) && (strlen(trim($_POST['folder'])) > 0))
4739 $current_folder_id = intval(trim(sanitize_textarea_field($_POST['folder'])));
4740 else
4741 $current_folder_id = "";
4742
4743 if(!is_numeric($current_folder_id))
4744 die();
4745
4746 $folder_location = $this->get_folder_path($current_folder_id);
4747
4748 $folders_path = "";
4749 $parents = $this->get_parents($current_folder_id);
4750
4751 $folder_count = count($parents);
4752 $folder_counter = 0;
4753 $current_folder_string = site_url() . "/wp-content";
4754 foreach( $parents as $key => $obj) {
4755 $folder_counter++;
4756 if($folder_counter === $folder_count)
4757 $folders_path .= $obj['name'];
4758 else
4759 $folders_path .= '<a folder="' . $obj['id'] . '\' class="media-link\'>' . $obj['name'] . '</a>/';
4760 $current_folder_string .= '/' . $obj['name'];
4761 }
4762
4763 $this->display_folder_contents ($current_folder_id, true, $folders_path);
4764
4765 die();
4766
4767 }
4768
4769 public function mlp_upgrade_to_pro() {
4770 ?>
4771
4772 <div class="utp-body">
4773 <div class="top-section">
4774 <div class="container">
4775 <div class="row">
4776 <div class="width-50">
4777 <h1><?php esc_html_e('Media Library Folders: Update to PRO','maxgalleria-media-library') ?></h1>
4778 <a href="<?php echo esc_url(UPGRADE_TO_PRO_LINK); ?>" class="big-pluspro-btn"><?php esc_html_e('Buy Now','maxgalleria-media-library') ?></a>
4779 <a class="simple-btn block" href="<?php echo esc_url("https://maxgalleria.com/media-library-plus/") ?>"><?php esc_html_e('Click here to learn about the Media Library Folders','maxgalleria-media-library') ?></a>
4780 </div>
4781 <div class="width-50">
4782 <strong>
4783 <i><?php esc_html_e('Brought to you by','maxgalleria-media-library') ?> <img src="<?php echo esc_url(MAXGALLERIA_MEDIA_LIBRARY_PLUGIN_URL . "/images/logo-mf.png") ?>" alt="logo" /><br><?php esc_html_e('Upgrade to Media Library Folders Pro today!','maxgalleria-media-library') ?> <a class="simple-btn" href="<?php echo esc_url(UPGRADE_TO_PRO_LINK) ?>"><?php esc_html_e('Click Here','maxgalleria-media-library') ?></a></i>
4784 </strong>
4785 </div>
4786 <div class="mlf-clearfix"></div>
4787 </div>
4788 </div>
4789 <img id="mlpp-logo" alt="Media Library Folders Pro Logo" src="<?php echo esc_url(MAXGALLERIA_MEDIA_LIBRARY_PLUGIN_URL ."/images/mlfp.png") ?>" width="235" height="235" >
4790 </div>
4791
4792 <div class="section features-section">
4793 <div class="features">
4794 <div class="container">
4795 <h2><?php esc_html_e('Features','maxgalleria-media-library') ?></h2>
4796 <div class="row">
4797 <div class="width-50">
4798 <ul>
4799 <li><span><?php esc_html_e('Add images to your posts and pages','maxgalleria-media-library') ?></span></li>
4800 <li><span><?php esc_html_e('File Name View Mode','maxgalleria-media-library') ?></span></li>
4801 <li><span><?php esc_html_e('Thumbnail Management','maxgalleria-media-library') ?></span></li>
4802 <li><span><?php esc_html_e('Automatically convert uploaded JPG and PNG images to WebP format','maxgalleria-media-library') ?></span></li>
4803 <li><span><?php esc_html_e('Add Images to WooCommerce Product Gallery','maxgalleria-media-library') ?></span></li>
4804 <li><span><?php esc_html_e('Export the media library from one Wordpress site and import it into another','maxgalleria-media-library') ?></span></li>
4805 <li><span><?php esc_html_e('Front End Upload to a Specific Folder','maxgalleria-media-library') ?></span></li>
4806 <li><span><?php esc_html_e('Bulk Move of media files','maxgalleria-media-library') ?></span></li>
4807 <li><span><?php esc_html_e('Organize Nextgen Galleries','maxgalleria-media-library') ?></span></li>
4808 </ul>
4809 </div>
4810 <div class="width-50">
4811 <ul>
4812 <li><span><?php esc_html_e('Multisite Supported','maxgalleria-media-library') ?></span></li>
4813 <li><span><?php esc_html_e('Category Interchangability with Enhanced Media Library','maxgalleria-media-library') ?></span></li>
4814 <li><span><?php esc_html_e('Embed PDF files in a page via a shortcode and Embed PDF file shortcode generator','maxgalleria-media-library') ?></span></li>
4815 <li><span><?php esc_html_e('Media Library Maintenance and Bulk File Import','maxgalleria-media-library') ?></span></li>
4816 <li><span><?php esc_html_e('Jetpack and the Wordpress Gallery Shortcode Generator','maxgalleria-media-library') ?></span></li>
4817 <li><span><?php esc_html_e('Supports Advanced Custom Fields','maxgalleria-media-library') ?></span></li>
4818 <li><span><?php esc_html_e('Block Direct Access for Selected Files','maxgalleria-media-library') ?></span></li>
4819 <li><span><?php esc_html_e('AI-powered image generation','maxgalleria-media-library') ?></span></li>
4820 <li><span><?php esc_html_e('Shared Media Library for Multisites','maxgalleria-media-library') ?></span></li>
4821 </ul>
4822 </div>
4823 <div class="mlf-clearfix"></div>
4824 </div>
4825 </div>
4826 </div>
4827 </div>
4828
4829
4830 <div class="section price-section">
4831 <div class="container">
4832 <div class="prices">
4833 <h3>$49</h3>
4834 <div class="descr">
4835 <img src="<?php echo esc_url(MAXGALLERIA_MEDIA_LIBRARY_PLUGIN_URL . "/images/icons/benefits.png") ?>" class=" img-responsive" alt="ico">
4836 <p>
4837 <?php esc_html_e('Includes 1 Year Support','maxgalleria-media-library') ?>
4838 <br>
4839 <?php esc_html_e('and Updates','maxgalleria-media-library') ?>
4840 </p>
4841 </div>
4842 <a href="<?php echo esc_url(UPGRADE_TO_PRO_LINK) ?>" class="text-uppercase big-pluspro-btn">Buy MLFP</a>
4843 </div>
4844 </div>
4845 </div>
4846
4847 <div class="section options-section">
4848 <div class="option">
4849 <div class="container">
4850 <div class="row">
4851 <div class="width-100">
4852
4853 <p class="mflp-into">
4854 <?php esc_html_e('MLF Pro integrates with post and page editor pages to let you select <br>and add images to your posts and pages for the editor.','maxgalleria-media-library') ?>
4855 </p>
4856 <h4>
4857 <?php esc_html_e('Add Images to Your Posts and Pages','maxgalleria-media-library') ?>
4858 </h4>
4859 <p>
4860 <?php esc_html_e('Media Library Folders Pro helps you organize your WordPress Media Library including functions for using and managing your files and images, thubnails, image categorizes and media library maintenance.','maxgalleria-media-library') ?>
4861 </p>
4862 <p>
4863 <?php esc_html_e('Media Library Folders Pro lets you create MaxGalleria and NextGEN Galleries directly from your MLF folders. This is where your images are so it is a logical place to select them and build your Gallery.','maxgalleria-media-library') ?>
4864 </p>
4865 <img class="img-responsive" src="<?php echo esc_url(MAXGALLERIA_MEDIA_LIBRARY_PLUGIN_URL . "/images/assets/new-add-images.png") ?>" alt="img" />
4866 </div>
4867 </div>
4868 </div>
4869 </div>
4870
4871 <div class="option">
4872 <div class="container">
4873 <div class="row">
4874 <div class="width-100">
4875 <h4>
4876 <?php esc_html_e('File Name View Mode','maxgalleria-media-library') ?>
4877 </h4>
4878 <p>
4879 <?php esc_html_e('When you are dealing with large image libraries the wait time can be quite long in WordPress Media Library. In order to speed the process of image selection we have built a file name view mode options into Media Library Folders Pro.','maxgalleria-media-library') ?>
4880 </p>
4881 <p>
4882 <?php esc_html_e('This mode let\’s you see all of the file names in a folder quickly and then click on specific files to see their images.','maxgalleria-media-library') ?>
4883 </p>
4884 <img class="img-responsive" src="<?php echo esc_url(MAXGALLERIA_MEDIA_LIBRARY_PLUGIN_URL . "/images/assets/file-name.png") ?>" alt="img" />
4885 </div>
4886 </div>
4887 </div>
4888 </div>
4889
4890 <div class="option">
4891 <div class="container">
4892 <div class="row">
4893 <div class="width-100">
4894 <h4>
4895 <?php esc_html_e('Thumbnail Management','maxgalleria-media-library') ?>
4896 </h4>
4897 <p>
4898 <?php esc_html_e('Reduce the number of image thumbnail files generated by WordPress.','maxgalleria-media-library') ?>
4899 </p>
4900 <img class="img-responsive" src="<?php echo esc_url(MAXGALLERIA_MEDIA_LIBRARY_PLUGIN_URL . "/images/assets/thumbnail-management.png") ?>" alt="img" />
4901 </div>
4902 </div>
4903 </div>
4904 </div>
4905
4906 <div class="option">
4907 <div class="container">
4908 <div class="row">
4909 <div class="width-100">
4910 <h4>
4911 <?php esc_html_e('Automatically convert uploaded JPG and PNG images to WebP format','maxgalleria-media-library') ?>
4912 </h4>
4913 <p>
4914 <?php esc_html_e('Automatically convert images to the modern WebP format for faster loading, smaller file sizes, and better website performance without any loss in quality.','maxgalleria-media-library') ?>
4915 </p>
4916 <img class="img-responsive" src="<?php echo esc_url(MAXGALLERIA_MEDIA_LIBRARY_PLUGIN_URL . "/images/assets/webp-mlfp-option.png") ?>" alt="img" />
4917 </div>
4918 </div>
4919 </div>
4920 </div>
4921
4922 <div class="option">
4923 <div class="container">
4924 <div class="row">
4925 <div class="width-100">
4926 <h4>
4927 <?php esc_html_e('Media Library Maintenance','maxgalleria-media-library') ?>
4928 </h4>
4929 <p>
4930 <?php esc_html_e('Over time a site\'s media library often builds up a number of unneeded files, especially auto generated extra thumbnail file sizes that are no longer necessary due to theme or plugin changes or perhaps multiple thumbnail regenerations.','maxgalleria-media-library') ?>
4931 </p>
4932 <p>
4933 <?php esc_html_e('Media Library Maintenance allows site administrators to find, view and remove or import these uncatalogued files.','maxgalleria-media-library') ?>
4934 </p>
4935 <img class="img-responsive" src="<?php echo esc_url(MAXGALLERIA_MEDIA_LIBRARY_PLUGIN_URL . "/images/assets/maintenance.png") ?>" alt="img" />
4936 </div>
4937 </div>
4938 </div>
4939 </div>
4940
4941 <div class="option">
4942 <div class="container">
4943 <div class="row">
4944 <div class="width-100">
4945 <h4>
4946 <?php esc_html_e('Bulk File Import','maxgalleria-media-library') ?>
4947 </h4>
4948 <p>
4949 <?php esc_html_e('Our Media Library Maintenance feature makes it easy to bulk import images and files into the Media Library.','maxgalleria-media-library') ?>
4950 </p>
4951 </div>
4952 </div>
4953 </div>
4954 </div>
4955
4956 <div class="option">
4957 <div class="container">
4958 <div class="row">
4959 <div class="width-100">
4960 <h4>
4961 <?php esc_html_e('Assign and Group Images by Categories','maxgalleria-media-library') ?>
4962 </h4>
4963 <p>
4964 <?php esc_html_e('Media Library Folders Pro implements image categories which are compatible with categories created by the Enhanced Media Library plugin.','maxgalleria-media-library') ?>
4965 </p>
4966 <img class="img-responsive" src="<?php echo esc_url(MAXGALLERIA_MEDIA_LIBRARY_PLUGIN_URL . "/images/assets/image-categories.png") ?>" alt="img" />
4967 </div>
4968 </div>
4969 </div>
4970 </div>
4971
4972 <div class="option">
4973 <div class="container">
4974 <div class="row">
4975 <div class="width-100">
4976 <h4>
4977 Import/Export & Backup
4978 </h4>
4979 <p>
4980 The Import/Export feature allows an administrator to export a sites media library from one site to another.
4981 </p>
4982 <img class="img-responsive" src="<?php echo esc_url(MAXGALLERIA_MEDIA_LIBRARY_PLUGIN_URL . "/images/assets/import-export.png") ?>" alt="img" />
4983 </div>
4984 </div>
4985 </div>
4986 </div>
4987
4988 <div class="option">
4989 <div class="container">
4990 <div class="row">
4991 <div class="width-100">
4992 <h4>
4993 <?php esc_html_e('File Replacement','maxgalleria-media-library') ?>
4994 </h4>
4995 <p>
4996 <?php esc_html_e('Replace an existing file with another one of the same type in the Media Library','maxgalleria-media-library') ?>
4997 </p>
4998 <p>
4999 <?php esc_html_e('You can export and download the contents of your media library from one WordPress site and then upload and import it into the media library of another WordPress site.','maxgalleria-media-library') ?> 
5000 </p>
5001 <img class="img-responsive" src="<?php echo esc_url(MAXGALLERIA_MEDIA_LIBRARY_PLUGIN_URL . "/images/assets/file-replacement.png") ?>" alt="img" />
5002 </div>
5003 </div>
5004 </div>
5005 </div>
5006
5007 <div class="option">
5008 <div class="container">
5009 <div class="row">
5010 <div class="width-100">
5011 <h4>
5012 <?php esc_html_e('Block Direct Access for Selected Files','maxgalleria-media-library') ?>
5013 </h4>
5014 <p>
5015 <?php esc_html_e('Select the files to be protected','maxgalleria-media-library') ?>
5016 </p>
5017 <p>
5018 <?php esc_html_e('Generate and configure download links for protected files','maxgalleria-media-library') ?> 
5019 </p>
5020 <img class="img-responsive" src="<?php echo esc_url(MAXGALLERIA_MEDIA_LIBRARY_PLUGIN_URL . "/images/assets/block-direct-access.png") ?>" alt="img" />
5021 </div>
5022 </div>
5023 </div>
5024 </div>
5025
5026
5027 <div class="option">
5028 <div class="container">
5029 <div class="row">
5030 <div class="width-100">
5031 <h4>
5032 <?php esc_html_e('Frontend Upload','maxgalleria-media-library') ?>
5033 </h4>
5034 <p>
5035 <?php esc_html_e('Frontend uploading of files is available via a shortcode.','maxgalleria-media-library') ?>
5036 </p>
5037 <p>
5038 <?php esc_html_e('Allows your signed in users to upload files to specified folders without needing to grant them access to your dashboard or media library.','maxgalleria-media-library') ?>
5039 </p>
5040 <img class="img-responsive" src="<?php echo esc_url(MAXGALLERIA_MEDIA_LIBRARY_PLUGIN_URL . "/images/assets/frontend-upload.png") ?>" alt="img" />
5041 </div>
5042 </div>
5043 </div>
5044 </div>
5045
5046 <div class="option">
5047 <div class="container">
5048 <div class="row">
5049 <div class="width-100">
5050 <h4>
5051 <?php esc_html_e('Embed PDF, Audio or Video Files','maxgalleria-media-library') ?>
5052 </h4>
5053 <p>
5054 <?php esc_html_e('Media Library Folders Pro allows the embedding of PDF, audio or video files into posts and pages via a shortcode and a builtin embed file shortcode genreator.','maxgalleria-media-library') ?>
5055 </p>
5056 <img class="img-responsive" src="<?php echo esc_url(MAXGALLERIA_MEDIA_LIBRARY_PLUGIN_URL . "/images/assets/embed-file.png") ?>" alt="img" />
5057 </div>
5058 </div>
5059 </div>
5060 </div>
5061
5062 <div class="option">
5063 <div class="container">
5064 <div class="row">
5065 <div class="width-100">
5066 <h4>
5067 <?php esc_html_e('Create Audio and Video Playlists','maxgalleria-media-library') ?>
5068 </h4>
5069 <p>
5070 <?php esc_html_e('Use Media Library Folders Pro\'s playlist shortcode generator to create your own audio or video playlists.','maxgalleria-media-library') ?>
5071 </p>
5072 <img class="img-responsive" src="<?php echo esc_url(MAXGALLERIA_MEDIA_LIBRARY_PLUGIN_URL . "/images/assets/audio-playlist-generator.png") ?>" alt="img" />
5073 </div>
5074 </div>
5075 </div>
5076 </div>
5077
5078 <div class="option">
5079 <div class="container">
5080 <div class="row">
5081 <div class="width-100">
5082 <h4>
5083 <?php esc_html_e('Network Media Library for Multisites','maxgalleria-media-library') ?>
5084 </h4>
5085 <p>
5086 <?php esc_html_e('Media Library Folders Pro can now support a shared media library across a WordPress multisite network, allowing selected sites to browse, upload, insert, and organize files from one central media site. This makes it easier to manage common assets across multiple sites while preserving folder organization and Media Library Folders Pro workflows.','maxgalleria-media-library') ?>
5087 </p>
5088 <img class="img-responsive" src="<?php echo esc_url(MAXGALLERIA_MEDIA_LIBRARY_PLUGIN_URL . "/images/assets/network-media-library.png") ?>" alt="img" />
5089 </div>
5090 </div>
5091 </div>
5092 </div>
5093
5094 <div class="option">
5095 <div class="container">
5096 <div class="row">
5097 <div class="width-100">
5098 <h4>
5099 <?php esc_html_e('NextGEN Galleries','maxgalleria-media-library') ?>
5100 </h4>
5101 <p>
5102 <?php esc_html_e('Media Library Folders Pro lets you create a NextGEN gallery from the Media Library Pro Plus directory. We recommend using this capability when creating new NextGEN galleries.','maxgalleria-media-library') ?>
5103 </p>
5104 <img class="img-responsive" src="<?php echo esc_url(MAXGALLERIA_MEDIA_LIBRARY_PLUGIN_URL . "/images/assets/nextgen.png") ?>" alt="img" />
5105 </div>
5106 </div>
5107 </div>
5108 </div>
5109
5110
5111 </div>
5112
5113 <div class="section options-section last-section">
5114 <div class="container">
5115 <h4>
5116 <?php esc_html_e('Get Media Library Folders Pro','maxgalleria-media-library') ?>
5117 </h4>
5118 <a href="<?php echo esc_url(UPGRADE_TO_PRO_LINK) ?>" class="text-uppercase big-pluspro-btn"><?php esc_html_e('Get MLF Pro','maxgalleria-media-library') ?></a>
5119 </div>
5120 </div>
5121 </div>
5122
5123 <?php
5124
5125 }
5126
5127 public function mlpp_hide_template_ad() {
5128
5129 if ( !wp_verify_nonce( $_POST['nonce'], MAXGALLERIA_MEDIA_LIBRARY_NONCE)) {
5130 exit(esc_html__('missing nonce! Please refresh this page.','maxgalleria-media-library'));
5131 }
5132
5133 // Check if the current user has the capability to upload files
5134 if(!current_user_can('upload_files')){
5135 exit(esc_html__('You do not have the capability to upload files.','maxgalleria-media-library'));
5136 }
5137
5138 update_option('mlpp_show_template_ad', "off");
5139
5140 die();
5141 }
5142
5143 public function mlpp_settings() {
5144
5145 global $current_user;
5146 ?>
5147
5148 <div style="clear:both"></div>
5149
5150 <?php
5151 $meta_index = get_option( MAXGALLERIA_POSTMETA_INDEX, 'off');
5152 $this->disable_scaling = get_option( MAXGALLERIA_DISABLE_SCALLING, 'off');
5153 $images_pre_page = get_option(MAXGALLERIA_MLP_ITEMS_PRE_PAGE, '500');
5154 $this->sync_skip_webp = get_option(MLFP_SKIP_WEBP_FILES, 'off');
5155
5156 if($images_pre_page == '')
5157 $images_pre_page = 100;
5158 ?>
5159
5160 <p>
5161 <label><?php esc_html_e('Number of images to display:', 'maxgalleria-media-library'); ?></label>
5162 <input type="text" id="images-pre-page" name="images-pre-page" value="<?php echo esc_attr($images_pre_page) ?>" style="width: 50px" autocomplete=off>
5163 </p>
5164
5165 <p>
5166 <input type="checkbox" name="disable_scaling" id="disable_scaling" value="" <?php esc_attr(checked($this->disable_scaling, 'on')) ?>>
5167 <label><?php esc_html_e('Disable large image scaling', 'maxgalleria-media-library'); ?></label>
5168 </p>
5169 <p>
5170 <input type="checkbox" name="meta_index" id="meta_index" value="" <?php checked($meta_index, 'on') ?>>
5171 <label><?php esc_html_e('Add an index to the postmeta table.', 'maxgalleria-media-library'); ?> <em><?php esc_html_e('Recommend for sites with a high number of media files. Uncheck to remove the index.', 'maxgalleria-media-library'); ?></em></label>
5172 </p>
5173 <p>
5174 <input type="checkbox" name="skip_webp" id="skip_webp" value="" <?php checked($this->sync_skip_webp, 'on') ?>>
5175 <label><?php esc_html_e('Skip WEBP images when syncing media library files. <em>For sites where WEBP files are automatically generated.</em>', 'maxgalleria-media-library'); ?></label>
5176 </p>
5177 <p>
5178 <a class="button-primary" id="mlfp-update-settings"><?php esc_html_e('Update Settings','maxgalleria-media-library'); ?></a>
5179 </p>
5180
5181 <div id="saving-message"></div>
5182
5183
5184 <script>
5185 jQuery(document).ready(function(){
5186
5187 jQuery(document).on("click","#mlfp-update-settings",function(){
5188
5189 var images_per_page = jQuery("#images-pre-page").val();
5190 var scaling_status = jQuery("#disable_scaling").is(":checked");
5191 var meta_index = jQuery("#meta_index").is(":checked");
5192 var skip_webp = jQuery("#skip_webp").is(":checked");
5193
5194 jQuery("#saving-message").html('');
5195
5196 jQuery.ajax({
5197 type: "POST",
5198 async: true,
5199 data: { action: "mlfp_set_scaling", scaling_status: scaling_status, images_per_page: images_per_page, meta_index: meta_index, skip_webp: skip_webp, nonce: mgmlp_ajax.nonce },
5200 url: mgmlp_ajax.ajaxurl,
5201 dataType: "html",
5202 success: function (data) {
5203 jQuery("#saving-message").html(data);
5204 window.location.reload();
5205 },
5206 error: function (err){
5207 jQuery("#gi-ajax-loader").hide();
5208 alert(err.responseText)
5209 }
5210 });
5211
5212 });
5213
5214 });
5215 </script>
5216
5217 <?php
5218 }
5219
5220 public function regen_mlp_thumbnails() {
5221
5222 global $wpdb, $is_IIS;
5223
5224 if ( !wp_verify_nonce( $_POST['nonce'], MAXGALLERIA_MEDIA_LIBRARY_NONCE)) {
5225 exit( esc_html__('missing nonce! Please refresh this page.','maxgalleria-media-library'));
5226 }
5227
5228 // Check if the current user has the capability to upload files
5229 if(!current_user_can('upload_files')){
5230 exit(esc_html__('You do not have the capability to regenerate thumbnail images.','maxgalleria-media-library'));
5231 }
5232
5233 if ((isset($_POST['serial_image_ids'])) && (strlen(trim($_POST['serial_image_ids'])) > 0))
5234 $image_ids = trim(stripslashes(sanitize_text_field($_POST['serial_image_ids'])));
5235 else
5236 $image_ids = "";
5237
5238 //error_log("image_ids $image_ids");
5239
5240 $image_ids = str_replace('"', '', $image_ids);
5241
5242 $image_ids = explode(',', $image_ids);
5243
5244 //error_log(print_r($image_ids, true));
5245
5246 $counter = 0;
5247
5248 foreach( $image_ids as $image_id) {
5249
5250 // check if the file is an image
5251 if(wp_attachment_is_image(intval($image_id))) {
5252
5253 //error_log("is image");
5254
5255 // get the image path
5256 $image_path = get_attached_file( $image_id );
5257
5258 $scaled_position = strpos($image_path, '-scaled');
5259
5260 if($scaled_position != false) {
5261 $temp_path = substr($image_path, 0, $scaled_position);
5262 $temp_path .= substr($image_path, $scaled_position+7);
5263 $image_path = $temp_path;
5264 }
5265
5266 // get the name of the file
5267 $base_name = wp_basename( $image_path );
5268
5269 // set the time limit o five minutes
5270 @set_time_limit( 300 );
5271
5272 $mime_type = get_post_mime_type($image_id);
5273 if($mime_type != 'image/svg+xml') {
5274
5275 // regenerate the thumbnails
5276 if ($is_IIS || strtoupper(substr(PHP_OS, 0, 3)) == 'WIN' || strtoupper(substr(PHP_OS, 0, 13)) == 'MICROSOFT-IIS' ) {
5277 $this->remove_existing_thumbnails($image_id, addslashes($image_path));
5278 $metadata = wp_generate_attachment_metadata( $image_id, addslashes($image_path));
5279 } else {
5280 $this->remove_existing_thumbnails($image_id, $image_path);
5281 $metadata = wp_generate_attachment_metadata( $image_id, $image_path );
5282 }
5283
5284 // check for errors
5285 if (is_wp_error($metadata)) {
5286 echo esc_html__('Error: ','maxgalleria-media-library') . "$base_name ". $metadata->get_error_message();
5287 continue;
5288 }
5289 if(empty($metadata)) {
5290 printf( esc_html__('Unknown error with %s','maxgalleria-media-library'), $base_name);
5291 continue;
5292 }
5293
5294 // update the meta data
5295 wp_update_attachment_metadata( $image_id, $metadata );
5296 }
5297 $counter++;
5298
5299 } else {
5300 error_log("not an image");
5301 }
5302 }
5303
5304 printf( esc_html__('Thumbnails have been regenerated for %d image(s)','maxgalleria-media-library'), $counter);
5305 die();
5306 }
5307
5308 public function remove_existing_thumbnails($image_id, $image_path) {
5309
5310 global $is_IIS;
5311
5312 $metadata = wp_get_attachment_metadata(intval($image_id));
5313
5314 if ($is_IIS || strtoupper(substr(PHP_OS, 0, 3)) == 'WIN' || strtoupper(substr(PHP_OS, 0, 13)) == 'MICROSOFT-IIS' )
5315 $seprator_position = strrpos($image_path, '\\');
5316 else
5317 $seprator_position = strrpos($image_path, '/');
5318
5319 $image_path = substr($image_path, 0, $seprator_position);
5320
5321 if(isset($metadata['sizes'])) {
5322 foreach($metadata['sizes'] as $source_path) {
5323 $thumbnail_file = $image_path . DIRECTORY_SEPARATOR . $source_path['file'];
5324
5325 if ($is_IIS || strtoupper(substr(PHP_OS, 0, 3)) == 'WIN' || strtoupper(substr(PHP_OS, 0, 13)) == 'MICROSOFT-IIS' )
5326 $thumbnail_file = str_replace('/', '\\', $thumbnail_file);
5327
5328 if(file_exists($thumbnail_file))
5329 unlink($thumbnail_file);
5330 }
5331 }
5332 }
5333
5334 public function regenerate_interface() {
5335 global $wpdb;
5336
5337 $allowed_html = array(
5338 'a' => array(
5339 'href' => array(),
5340 'id' => array()
5341 )
5342 );
5343
5344 ?>
5345
5346 <div id="message" class="updated fade" style="display:none"></div>
5347
5348 <div id="wp-media-grid" class="wrap">
5349 <!--empty h1 for where WP notices will appear-->
5350 <h1></h1>
5351 <div class="media-plus-toolbar"><div class="media-toolbar-secondary">
5352
5353 <div id="mgmlp-header">
5354 <div id='mgmlp-title-area'>
5355 <h2 class='mgmlp-title'><?php esc_html_e('Regenerate Thumbnails', 'maxgalleria-media-library' ); ?></h2>
5356
5357 </div> <!-- mgmlp-title-area -->
5358 <div id="new-top-promo">
5359 <a id="mf-top-logo" target="_blank" href="https://maxfoundry.com"><img alt="maxfoundry logo" src="<?php echo esc_url(MAXGALLERIA_MEDIA_LIBRARY_PLUGIN_URL . "/images/mf-logo.png") ?>" width="140" height="25" ></a>
5360 <p class="center-text"><?php esc_html_e('Makers of', 'maxgalleria-media-library' ); ?> <a target="_blank" href="https://maxbuttons.com/">MaxButtons</a>, <a target="_blank" href="https://maxbuttons.com/product-category/button-packs/">WordPress Buttons</a> <?php esc_html_e('and', 'maxgalleria-media-library' ); ?> <a target="_blank" href="https://maxgalleria.com/">MaxGalleria</a></p>
5361 <p class="center-text-no-ital"><?php esc_html_e('Click here to', 'maxgalleria-media-library' ); ?> <a href="<?php echo esc_url(MLF_TS_URL) ?>" target="_blank"><?php esc_html_e('Fix Common Problems', 'maxgalleria-media-library'); ?></a></p>
5362 <p class="center-text-no-ital"><?php esc_html_e('Need help? Click here for', 'maxgalleria-media-library' ); ?> <a href="https://wordpress.org/support/plugin/media-library-plus" target="_blank"><?php esc_html_e('Awesome Support!', 'maxgalleria-media-library' ); ?></a></p>
5363 <p class="center-text-no-ital"><?php esc_html_e('Or Email Us at', 'maxgalleria-media-library' ); ?> <a href="mailto:support@maxfoundry.com">support@maxfoundry.com</a></p>
5364 </div>
5365
5366 </div><!--mgmlp-header-->
5367 <div class="mlf-clearfix"></div>
5368
5369
5370 <?php
5371
5372 // If the button was clicked
5373 if ( ! empty( $_POST['regenerate-thumbnails'] ) || ! empty( $_REQUEST['ids'] ) ) {
5374 // Capability check
5375 if ( ! current_user_can( $this->capability ) )
5376 wp_die( esc_html__( 'Cheatin&#8217; uh?' ) );
5377
5378 if($this->bda == 'on' && $this->bdp_autoprotect == 'on') {
5379 $this->bdp_autoprotect = 'off';
5380 update_option(MLFP_BDA_AUTO_PROTECT, 'off');
5381 update_option(MLFP_BDA_AUTO_PROTECT_DISABLED, 'on');
5382 }
5383
5384 // Form nonce check
5385 check_admin_referer(MAXGALLERIA_MEDIA_LIBRARY_NONCE);
5386
5387 // Create the list of image IDs
5388 if ( ! empty( $_REQUEST['ids'] ) ) {
5389 $images = array_map( 'intval', explode( ',', trim( sanitize_text_field($_REQUEST['ids']), ',' ) ) );
5390 $ids = implode( ',', $images );
5391 } else {
5392 if ( ! $images = $wpdb->get_results( "SELECT ID FROM $wpdb->posts WHERE post_type = 'attachment' AND post_mime_type LIKE 'image/%' AND post_mime_type != 'image/svg+xml' ORDER BY ID DESC" ) ) {
5393 echo ' <p>' . sprintf( esc_html__( "Unable to find any images. Are you sure", 'maxgalleria-media-library') . "<a href='%s'>" . esc_html__(" some exist? ", 'maxgalleria-media-library' ) . "</a>", esc_url_raw(admin_url( 'upload.php?post_mime_type=image'))) . "</p></div>";
5394 return;
5395 }
5396
5397 //error_log("IMAGES: " . print_r($images, true));
5398
5399 // Generate the list of IDs
5400 $ids = array();
5401 foreach ( $images as $image )
5402 $ids[] = $image->ID;
5403 $ids = implode( ',', $ids );
5404 }
5405
5406 echo ' <p id="wait-message">' . esc_html__( "Please wait while the thumbnails are regenerated. This may take a while.", 'maxgalleria-media-library' ) . '</p>';
5407
5408 $count = count( $images );
5409
5410 $text_goback = ( ! empty( $_GET['goback'] ) ) ? esc_html__('To go back to the previous page, ', 'maxgalleria-media-library') . '<a href="javascript:history.go(-1)">click here</a>.' : '';
5411 $text_failures = sprintf( __( 'All done! %1$s image(s) were successfully resized in %2$s seconds and there were %3$s failure(s). To try regenerating the failed images again, <a href="%4$s">click here</a>. %5$s', 'maxgalleria-media-library' ), "' + rt_successes + '", "' + rt_totaltime + '", "' + rt_errors + '", esc_url( wp_nonce_url( admin_url( 'tools.php?page=mlp-regenerate-thumbnails&goback=1' ), 'mlp-regenerate-thumbnails' ) . '&ids=' ) . "' + rt_failedlist + '", $text_goback );
5412 $text_nofailures = sprintf( __( 'All done! %1$s image(s) were successfully resized in %2$s seconds and there were 0 failures. %3$s', 'maxgalleria-media-library' ), "' + rt_successes + '", "' + rt_totaltime + '", $text_goback );
5413 ?>
5414
5415 <noscript><p><em><?php esc_html_e( 'You must enable Javascript in order to proceed!', 'maxgalleria-media-library' ) ?></em></p></noscript>
5416
5417 <div id="regenthumbs-bar" style="position:relative;height:25px;">
5418 <div id="regenthumbs-bar-percent" style="position:absolute;left:50%;top:50%;width:300px;margin-left:-150px;height:25px;margin-top:-9px;font-weight:bold;text-align:center;"></div>
5419 </div>
5420
5421 <p><input type="button" class="button hide-if-no-js" name="regenthumbs-stop" id="regenthumbs-stop" value="<?php esc_html_e( 'Abort Resizing Images', 'maxgalleria-media-library' ) ?>" /></p>
5422
5423 <h3 class="title"><?php esc_html_e( 'Debugging Information', 'maxgalleria-media-library' ) ?></h3>
5424
5425 <p>
5426 <?php echo esc_html( __( 'Total Images: ', 'maxgalleria-media-library' ) . (int) $count) ?><br />
5427 <?php echo esc_html__( 'Images Resized: ', 'maxgalleria-media-library' ) . '<span id="regenthumbs-debug-successcount">0</span>' ?><br />
5428 <?php echo esc_html__( 'Resize Failures: ', 'maxgalleria-media-library' ) . '<span id="regenthumbs-debug-failurecount">0</span>' ?>
5429 </p>
5430
5431 <ol id="regenthumbs-debuglist">
5432 <li style="display:none"></li>
5433 </ol>
5434
5435 <script type="text/javascript">
5436 // <![CDATA[
5437 jQuery(document).ready(function($){
5438 var i;
5439 var rt_images = [<?php echo esc_attr($ids) ?>];
5440 var rt_total = rt_images.length;
5441 var rt_count = 1;
5442 var rt_percent = 0;
5443 var rt_successes = 0;
5444 var rt_errors = 0;
5445 var rt_failedlist = '';
5446 var rt_resulttext = '';
5447 var rt_timestart = new Date().getTime();
5448 var rt_timeend = 0;
5449 var rt_totaltime = 0;
5450 var rt_continue = true;
5451
5452 // Create the progress bar
5453 $("#regenthumbs-bar").progressbar();
5454 $("#regenthumbs-bar-percent").html( "0%" );
5455
5456 // Stop button
5457 //$("#regenthumbs-stop").click(function() {
5458 $(document).on("click", "#regenthumbs-stop", function () {
5459 rt_continue = false;
5460 $('#regenthumbs-stop').val("<?php echo $this->esc_quotes( esc_html__( 'Stopping...', 'maxgalleria-media-library' ) ); ?>");
5461 });
5462
5463 // Clear out the empty list element that's there for HTML validation purposes
5464 $("#regenthumbs-debuglist li").remove();
5465
5466 // Called after each resize. Updates debug information and the progress bar.
5467 function RegenThumbsUpdateStatus( id, success, response ) {
5468 $("#regenthumbs-bar").progressbar( "value", ( rt_count / rt_total ) * 100 );
5469 $("#regenthumbs-bar-percent").html( Math.round( ( rt_count / rt_total ) * 1000 ) / 10 + "%" );
5470 rt_count = rt_count + 1;
5471
5472 if ( success ) {
5473 rt_successes = rt_successes + 1;
5474 $("#regenthumbs-debug-successcount").html(rt_successes);
5475 $("#regenthumbs-debuglist").append("<li>" + response.success + "</li>");
5476 }
5477 else {
5478 rt_errors = rt_errors + 1;
5479 rt_failedlist = rt_failedlist + ',' + id;
5480 $("#regenthumbs-debug-failurecount").html(rt_errors);
5481 $("#regenthumbs-debuglist").append("<li>" + response.error + "</li>");
5482 }
5483 }
5484
5485 // Called when all images have been processed. Shows the results and cleans up.
5486 function RegenThumbsFinishUp() {
5487 rt_timeend = new Date().getTime();
5488 rt_totaltime = Math.round( ( rt_timeend - rt_timestart ) / 1000 );
5489
5490 $('#regenthumbs-stop').hide();
5491
5492 if ( rt_errors > 0 ) {
5493 rt_resulttext = '<?php echo wp_kses($text_failures, $allowed_html) ?>';
5494 } else {
5495 rt_resulttext = '<?php echo wp_kses($text_nofailures, $allowed_html) ?>';
5496 }
5497
5498 $("#wait-message").html("");
5499 $("#message").html("<p><strong>" + rt_resulttext + "</strong></p>");
5500 $("#message").show();
5501 }
5502
5503 // Regenerate a specified image via AJAX
5504 function RegenThumbs( id ) {
5505 $.ajax({
5506 type: 'POST',
5507 url: ajaxurl,
5508 data: { action: "regeneratethumbnail", id: id },
5509 success: function( response ) {
5510 if ( response !== Object( response ) || ( typeof response.success === "undefined" && typeof response.error === "undefined" ) ) {
5511 response = new Object;
5512 response.success = false;
5513 response.error = "<?php printf( esc_js( __( 'The resize request was abnormally terminated (ID %s). This is likely due to the image exceeding available memory or some other type of fatal error.', 'maxgalleria-media-library' ) ), '" + id + "' ); ?>";
5514 }
5515
5516 if ( response.success ) {
5517 RegenThumbsUpdateStatus( id, true, response );
5518 }
5519 else {
5520 RegenThumbsUpdateStatus( id, false, response );
5521 }
5522
5523 if ( rt_images.length && rt_continue ) {
5524 RegenThumbs( rt_images.shift() );
5525 }
5526 else {
5527 RegenThumbsFinishUp();
5528 }
5529 },
5530 error: function( response ) {
5531 RegenThumbsUpdateStatus( id, false, response );
5532
5533 if ( rt_images.length && rt_continue ) {
5534 RegenThumbs( rt_images.shift() );
5535 }
5536 else {
5537 RegenThumbsFinishUp();
5538 }
5539 }
5540 });
5541 }
5542
5543 RegenThumbs( rt_images.shift() );
5544 });
5545 // ]]>
5546 </script>
5547 <?php
5548 }
5549
5550 // No button click? Display the form.
5551 else {
5552 ?>
5553 <form method="post" action="">
5554 <?php wp_nonce_field(MAXGALLERIA_MEDIA_LIBRARY_NONCE) ?>
5555
5556 <p><?php printf( esc_html__( "Click the button below to regenerate thumbnails for all images in the Media Library. This is helpful if you have added new thumbnail sizes to your site. Existing thumbnails will not be removed to prevent breaking any links.", 'maxgalleria-media-library' ), admin_url( 'options-media.php' ) ); ?></p>
5557
5558 <p><?php printf( esc_html__( "You can regenerate thumbnails for individual images from the Media Library Folders page by checking the box below one or more images and clicking the Regenerate Thumbnails button. The regenerate operation is not reversible but you can always generate the sizes you need by adding additional thumbnail sizes to your theme.", 'maxgalleria-media-library'), admin_url( 'upload.php' ) ); ?></p>
5559
5560 <p><input type="submit" class="button hide-if-no-js" name="regenerate-thumbnails" id="regenerate-thumbnails" value="<?php esc_html_e( 'Regenerate All Thumbnails', 'maxgalleria-media-library' ) ?>" /></p>
5561
5562 <noscript><p><em><?php esc_html_e( 'You must enable Javascript in order to proceed!', 'maxgalleria-media-library' ) ?></em></p></noscript>
5563
5564 </form>
5565 <?php
5566 } // End if button
5567 ?>
5568 </div>
5569 </div>
5570 </div>
5571
5572 <?php
5573 }
5574
5575 // Process a single image ID (this is an AJAX handler)
5576 public function ajax_process_image() {
5577
5578 global $is_IIS;
5579
5580 // Check if the current user has the capability to upload files
5581 if(!current_user_can('upload_files')){
5582 exit(esc_html__('You do not have the capability to upload files.','maxgalleria-media-library'));
5583 }
5584
5585 @error_reporting( 0 ); // Don't break the JSON result
5586
5587 header( 'Content-type: application/json' );
5588
5589 $id = (int) $_REQUEST['id'];
5590 $image = get_post( $id );
5591
5592 if ( ! $image || 'attachment' != $image->post_type || 'image/' != substr( $image->post_mime_type, 0, 6 ) )
5593 die( json_encode( array( 'error' => sprintf( esc_html__( 'Failed resize: %s is an invalid image ID.', 'maxgalleria-media-library' ), esc_html( $_REQUEST['id'] ) ) ) ) );
5594
5595 if ( ! current_user_can( $this->capability ) )
5596 $this->die_json_error_msg( $image->ID, esc_html__( "Your user account doesn't have permission to resize images", 'maxgalleria-media-library' ) );
5597
5598 $fullsizepath = get_attached_file( $image->ID );
5599
5600 $scaled_position = strpos($fullsizepath, '-scaled');
5601
5602 if($scaled_position != false) {
5603 $temp_path = substr($fullsizepath, 0, $scaled_position);
5604 $temp_path .= substr($fullsizepath, $scaled_position+7);
5605 //error_log("temp_path $temp_path");
5606 $fullsizepath = $temp_path;
5607 }
5608
5609 if ( false === $fullsizepath || ! file_exists( $fullsizepath ) )
5610 $this->die_json_error_msg( $image->ID, sprintf( esc_html__( 'The originally uploaded image file cannot be found at %s', 'maxgalleria-media-library' ), '<code>' . esc_html( $fullsizepath ) . '</code>' ) );
5611
5612 @set_time_limit( 900 ); // 5 minutes per image should be PLENTY
5613
5614 if($image->post_mime_type != 'image/svg+xml') {
5615 if ($is_IIS || strtoupper(substr(PHP_OS, 0, 3)) == 'WIN' || strtoupper(substr(PHP_OS, 0, 13)) == 'MICROSOFT-IIS' ) {
5616 $this->remove_existing_thumbnails($image->ID, addslashes($fullsizepath));
5617 $metadata = wp_generate_attachment_metadata( $image->ID, addslashes($fullsizepath));
5618 } else {
5619 $this->remove_existing_thumbnails($image->ID, $fullsizepath);
5620 $metadata = wp_generate_attachment_metadata( $image->ID, $fullsizepath );
5621 }
5622 }
5623
5624 if(isset($metadata)) {
5625 if ( is_wp_error( $metadata ) )
5626 $this->die_json_error_msg( $image->ID, $metadata->get_error_message() );
5627 if ( empty( $metadata ) )
5628 $this->die_json_error_msg( $image->ID, esc_html__( 'Unknown failure reason.', 'maxgalleria-media-library' ) );
5629
5630 // If this fails, then it just means that nothing was changed (old value == new value)
5631 wp_update_attachment_metadata( $image->ID, $metadata );
5632 }
5633
5634 die( json_encode( array( 'success' => sprintf( esc_html__( '&quot;%1$s&quot; (ID %2$s) was successfully resized in %3$s seconds.', 'maxgalleria-media-library' ), esc_html( get_the_title( $image->ID ) ), $image->ID, timer_stop() ) ) ) );
5635 }
5636
5637 // Helper to make a JSON error message
5638 public function die_json_error_msg( $id, $message ) {
5639 die( json_encode( array( 'error' => sprintf( esc_html__( '&quot;%1$s&quot; (ID %2$s) failed to resize. The error message was: %3$s', 'maxgalleria-media-library' ), esc_html( get_the_title( $id ) ), $id, $message ) ) ) );
5640 }
5641
5642 // Helper function to escape quotes in strings for use in Javascript
5643 public function esc_quotes( $string ) {
5644 return str_replace( '"', '\"', $string );
5645 }
5646
5647 public function mflp_enable_auto_protect() {
5648
5649 if ( !wp_verify_nonce( $_POST['nonce'], MAXGALLERIA_MEDIA_LIBRARY_NONCE)) {
5650 exit(__('missing nonce!','maxgalleria-media-library'));
5651 }
5652
5653 // Check if the current user has the capability to manage options
5654 if(!current_user_can('manage_options')){
5655 exit(esc_html__('You do not have the capability to manage options.','maxgalleria-media-library'));
5656 }
5657
5658 if(get_option(MLFP_BDA_AUTO_PROTECT_DISABLED, 'off') == 'on') {
5659 $this->bdp_autoprotect = 'on';
5660 update_option(MLFP_BDA_AUTO_PROTECT, 'on');
5661 update_option(MLFP_BDA_AUTO_PROTECT_DISABLED, 'off');
5662 }
5663
5664 die();
5665 }
5666
5667 public function mlp_image_seo_change() {
5668
5669 if ( !wp_verify_nonce( $_POST['nonce'], MAXGALLERIA_MEDIA_LIBRARY_NONCE)) {
5670 exit(esc_html__('missing nonce! Please refresh this page.','maxgalleria-media-library'));
5671 }
5672
5673 // Check if the current user has the capability to upload files
5674 if(!current_user_can('upload_files')){
5675 exit(esc_html__('You do not have the capability to upload files.','maxgalleria-media-library'));
5676 }
5677
5678 if ((isset($_POST['checked'])) && (strlen(trim($_POST['checked'])) > 0))
5679 $checked = trim(sanitize_text_field($_POST['checked']));
5680 else
5681 $checked = "off";
5682
5683 if ((isset($_POST['default_alt'])) && (strlen(trim($_POST['default_alt'])) > 0))
5684 $default_alt = trim(sanitize_text_field($_POST['default_alt']));
5685 else
5686 $default_alt = "";
5687
5688 if ((isset($_POST['default_title'])) && (strlen(trim($_POST['default_title'])) > 0))
5689 $default_title = trim(sanitize_text_field($_POST['default_title']));
5690 else
5691 $default_title = "";
5692
5693 //error_log("default_title $default_title");
5694
5695 update_option(MAXGALLERIA_MEDIA_LIBRARY_IMAGE_SEO, $checked );
5696
5697 update_option(MAXGALLERIA_MEDIA_LIBRARY_ATL_DEFAULT, $default_alt );
5698
5699 update_option(MAXGALLERIA_MEDIA_LIBRARY_TITLE_DEFAULT, $default_title );
5700
5701 echo esc_html__('The Image SEO settings have been updated ','maxgalleria-media-library');
5702
5703 die();
5704
5705
5706 }
5707
5708 public function locaton_without_basedir($image_location, $uploads_dir, $upload_length) {
5709
5710 $position = strpos($image_location, $uploads_dir);
5711 return substr($image_location, $position+$upload_length );
5712
5713 }
5714
5715 public function get_browser() {
5716 // https://www.php.net/manual/en/function.get-browser.php#101125.
5717 // Cleaned up a bit, but overall it's the same.
5718
5719 $user_agent = $_SERVER['HTTP_USER_AGENT'];
5720 $browser_name = 'Unknown';
5721 $platform = 'Unknown';
5722 $version= "";
5723
5724 // First get the platform
5725 if (preg_match('/linux/i', $user_agent)) {
5726 $platform = 'Linux';
5727 }
5728 elseif (preg_match('/macintosh|mac os x/i', $user_agent)) {
5729 $platform = 'Mac';
5730 }
5731 elseif (preg_match('/windows|win32/i', $user_agent)) {
5732 $platform = 'Windows';
5733 }
5734
5735 // Next get the name of the user agent yes seperately and for good reason
5736 if (preg_match('/MSIE/i', $user_agent) && !preg_match('/Opera/i', $user_agent)) {
5737 $browser_name = 'Internet Explorer';
5738 $browser_name_short = "MSIE";
5739 }
5740 elseif (preg_match('/Firefox/i', $user_agent)) {
5741 $browser_name = 'Mozilla Firefox';
5742 $browser_name_short = "Firefox";
5743 }
5744 elseif (preg_match('/Chrome/i', $user_agent)) {
5745 $browser_name = 'Google Chrome';
5746 $browser_name_short = "Chrome";
5747 }
5748 elseif (preg_match('/Safari/i', $user_agent)) {
5749 $browser_name = 'Apple Safari';
5750 $browser_name_short = "Safari";
5751 }
5752 elseif (preg_match('/Opera/i', $user_agent)) {
5753 $browser_name = 'Opera';
5754 $browser_name_short = "Opera";
5755 }
5756 elseif (preg_match('/Netscape/i', $user_agent)) {
5757 $browser_name = 'Netscape';
5758 $browser_name_short = "Netscape";
5759 }
5760
5761 // Finally get the correct version number
5762 $known = array('Version', $browser_name_short, 'other');
5763 $pattern = '#(?<browser>' . join('|', $known) . ')[/ ]+(?<version>[0-9.|a-zA-Z.]*)#';
5764 if (!preg_match_all($pattern, $user_agent, $matches)) {
5765 // We have no matching number just continue
5766 }
5767
5768 // See how many we have
5769 $i = count($matches['browser']);
5770 if ($i != 1) {
5771 // We will have two since we are not using 'other' argument yet
5772 // See if version is before or after the name
5773 if (strripos($user_agent, "Version") < strripos($user_agent, $browser_name_short)){
5774 $version= $matches['version'][0];
5775 }
5776 else {
5777 $version= $matches['version'][1];
5778 }
5779 }
5780 else {
5781 $version= $matches['version'][0];
5782 }
5783
5784 // Check if we have a number
5785 if ($version == null || $version == "") { $version = "?"; }
5786
5787 return array(
5788 'user_agent' => $user_agent,
5789 'name' => $browser_name,
5790 'version' => $version,
5791 'platform' => $platform,
5792 'pattern' => $pattern
5793 );
5794 }
5795
5796 public function mlp_support() {
5797 require_once MAXGALLERIA_MEDIA_LIBRARY_PLUGIN_DIR . '/includes/mlf_support.php';
5798 }
5799
5800 public function mlp_remove_slashes() {
5801
5802 global $wpdb;
5803
5804 $sql = "select ID, pm.meta_value, pm.meta_id
5805 from {$wpdb->prefix}posts
5806 LEFT JOIN {$wpdb->prefix}postmeta AS pm ON pm.post_id = {$wpdb->prefix}posts.ID
5807 where post_type = 'attachment'
5808 or post_type = '" . MAXGALLERIA_MEDIA_LIBRARY_POST_TYPE . "'
5809 and pm.meta_key = '_wp_attached_file'
5810 group by ID
5811 order by meta_id";
5812
5813
5814 //error_log($sql);
5815
5816 $rows = $wpdb->get_results($sql);
5817
5818 if($rows) {
5819 foreach($rows as $row) {
5820 if($row->meta_value !== '') {
5821 if( $row->meta_value[0] == "/") {
5822 $new_meta = $row->meta_value;
5823 $new_meta = ltrim($new_meta, '/');
5824 update_post_meta($row->ID, '_wp_attached_file', $new_meta);
5825 }
5826 }
5827 }
5828 }
5829 }
5830
5831 public function hide_maxgalleria_media() {
5832
5833 //error_log("hide_maxgalleria_media");
5834
5835 global $wpdb;
5836
5837 if ( !wp_verify_nonce( $_POST['nonce'], MAXGALLERIA_MEDIA_LIBRARY_NONCE)) {
5838 exit( esc_html__('missing nonce! Please refresh this page.','maxgalleria-media-library'));
5839 }
5840
5841 // Check if the current user has the capability to upload files
5842 if(!current_user_can('upload_files')){
5843 exit(esc_html__('You do not have the capability to upload files.','maxgalleria-media-library'));
5844 }
5845
5846 if ((isset($_POST['folder_id'])) && (strlen(trim($_POST['folder_id'])) > 0))
5847 $folder_id = intval(trim(sanitize_text_field($_POST['folder_id'])));
5848 else
5849 $folder_id = "";
5850
5851 // prevent hiding of the uploads folder and sub folders
5852 if($folder_id == intval($this->uploads_folder_ID)) {
5853 echo esc_html__('The uploads folder cannot be hidden.','maxgalleria-media-library');
5854 die();
5855 }
5856
5857 if($folder_id !== '') {
5858
5859 $folder_table = $wpdb->prefix . MAXGALLERIA_MEDIA_LIBRARY_FOLDER_TABLE;
5860 $parent_folder = $this->get_parent($folder_id);
5861
5862 $sql = "select meta_value as attached_file
5863 from {$wpdb->prefix}postmeta
5864 where post_id = $folder_id
5865 and meta_key = '_wp_attached_file';";
5866
5867 $row = $wpdb->get_row($sql);
5868 if($row) {
5869
5870 $basedir = $this->upload_dir['basedir'];
5871 $basedir = rtrim($basedir, '/') . '/';
5872 $skip_folder_file = $basedir . ltrim($row->attached_file, '/') . DIRECTORY_SEPARATOR . "mlpp-hidden";
5873 file_put_contents($skip_folder_file, '');
5874
5875 $this->remove_children($folder_id);
5876 $del_post = array('post_id' => $folder_id);
5877 $this->mlf_delete_post($folder_id, false); //delete the post record
5878 $wpdb->delete( $folder_table, $del_post ); // delete the folder table record
5879
5880 }
5881
5882 echo esc_html__('The selected folder, subfolders and thier files have been hidden.','maxgalleria-media-library');
5883 echo "<script>window.location.href = '" . esc_url_raw(site_url() . '/wp-admin/admin.php?page=mlf-folders8&media-folder=' . $parent_folder) . "'</script>";
5884
5885 }
5886
5887 die();
5888 }
5889
5890 // $folder_id aready forced to an inteter in hide_maxgalleria_media()
5891 private function remove_children($folder_id) {
5892
5893 global $wpdb;
5894
5895 if($folder_id !== 0) {
5896
5897 $folder_table = $wpdb->prefix . MAXGALLERIA_MEDIA_LIBRARY_FOLDER_TABLE;
5898
5899 $sql = "select post_id
5900 from $folder_table
5901 where folder_id = $folder_id";
5902
5903 $rows = $wpdb->get_results($sql);
5904 if($rows) {
5905 foreach($rows as $row) {
5906
5907 $this->remove_children($row->post_id);
5908 $del_post = array('post_id' => $row->post_id);
5909 $this->mlf_delete_post($row->post_id, false); //delete the post record
5910 $wpdb->delete( $folder_table, $del_post ); // delete the folder table record
5911
5912 }
5913 }
5914 }
5915 }
5916
5917 // modifed version of wp_delete_post
5918 private function mlf_delete_post( $postid = 0, $force_delete = false ) {
5919 global $wpdb;
5920
5921 $postid = intval($postid);
5922
5923 if ( !$post = $wpdb->get_row($wpdb->prepare("SELECT * FROM $wpdb->posts WHERE ID = %d", $postid)) )
5924 return $post;
5925
5926 if ( !$force_delete && ( $post->post_type == 'post' || $post->post_type == 'page') && get_post_status( $postid ) != 'trash' && EMPTY_TRASH_DAYS )
5927 return wp_trash_post( $postid );
5928
5929 delete_post_meta($postid,'_wp_trash_meta_status');
5930 delete_post_meta($postid,'_wp_trash_meta_time');
5931
5932 wp_delete_object_term_relationships($postid, get_object_taxonomies($post->post_type));
5933
5934 $parent_data = array( 'post_parent' => $post->post_parent );
5935 $parent_where = array( 'post_parent' => $postid );
5936
5937 if ( is_post_type_hierarchical( $post->post_type ) ) {
5938 // Point children of this page to its parent, also clean the cache of affected children.
5939 $children_query = $wpdb->prepare( "SELECT * FROM $wpdb->posts WHERE post_parent = %d AND post_type = %s", $postid, $post->post_type );
5940 $children = $wpdb->get_results( $children_query );
5941 if ( $children ) {
5942 $wpdb->update( $wpdb->posts, $parent_data, $parent_where + array( 'post_type' => $post->post_type ) );
5943 }
5944 }
5945
5946 // Do raw query. wp_get_post_revisions() is filtered.
5947 $revision_ids = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_parent = %d AND post_type = 'revision'", $postid ) );
5948 // Use wp_delete_post (via wp_delete_post_revision) again. Ensures any meta/misplaced data gets cleaned up.
5949 foreach ( $revision_ids as $revision_id )
5950 wp_delete_post_revision( $revision_id );
5951
5952 // Point all attachments to this post up one level.
5953 $wpdb->update( $wpdb->posts, $parent_data, $parent_where + array( 'post_type' => 'attachment' ) );
5954
5955 wp_defer_comment_counting( true );
5956
5957 $comment_ids = $wpdb->get_col( $wpdb->prepare( "SELECT comment_ID FROM $wpdb->comments WHERE comment_post_ID = %d", $postid ));
5958 foreach ( $comment_ids as $comment_id ) {
5959 wp_delete_comment( $comment_id, true );
5960 }
5961
5962 wp_defer_comment_counting( false );
5963
5964 $post_meta_ids = $wpdb->get_col( $wpdb->prepare( "SELECT meta_id FROM $wpdb->postmeta WHERE post_id = %d ", $postid ));
5965 foreach ( $post_meta_ids as $mid )
5966 delete_metadata_by_mid( 'post', $mid );
5967
5968 $result = $wpdb->delete( $wpdb->posts, array( 'ID' => $postid ) );
5969 if ( ! $result ) {
5970 return false;
5971 }
5972
5973 if ( is_post_type_hierarchical( $post->post_type ) && $children ) {
5974 foreach ( $children as $child )
5975 clean_post_cache( $child );
5976 }
5977
5978 wp_clear_scheduled_hook('publish_future_post', array( $postid ) );
5979
5980 return $post;
5981 }
5982
5983 public function mlf_hide_info() {
5984
5985 if ( !wp_verify_nonce( $_POST['nonce'], MAXGALLERIA_MEDIA_LIBRARY_NONCE)) {
5986 exit(esc_html__('missing nonce! Please refresh this page.','maxgalleria-media-library'));
5987 }
5988
5989 // Check if the current user has the capability to upload files
5990 if(!current_user_can('upload_files')){
5991 exit(esc_html__('You do not have the capability to upload files.','maxgalleria-media-library'));
5992 }
5993
5994 $current_user_id = get_current_user_id();
5995
5996 update_user_meta( $current_user_id, MAXGALLERIA_MLP_DISPLAY_INFO, 'off' );
5997
5998 }
5999
6000 public function mlfp_set_scaling() {
6001
6002 if ( !wp_verify_nonce( $_POST['nonce'], MAXGALLERIA_MEDIA_LIBRARY_NONCE)) {
6003 exit(esc_html__('missing nonce! Please refresh this page.','maxgalleria-media-library'));
6004 }
6005
6006 // Check if the current user has the capability to manage options
6007 if(!current_user_can('manage_options')){
6008 exit(esc_html__('You do not have the capability to manage_options.','maxgalleria-media-library'));
6009 }
6010
6011 if ((isset($_POST['scaling_status'])) && (strlen(trim($_POST['scaling_status'])) > 0))
6012 $scaling_status = trim(sanitize_text_field($_POST['scaling_status']));
6013 else
6014 $scaling_status = "";
6015
6016 if ((isset($_POST['images_per_page'])) && (strlen(trim($_POST['images_per_page'])) > 0))
6017 $images_per_page = intval(trim(sanitize_text_field($_POST['images_per_page'])));
6018 else
6019 $images_per_page = "";
6020
6021 if ((isset($_POST['meta_index'])) && (strlen(trim($_POST['meta_index'])) > 0))
6022 $meta_index = trim(sanitize_text_field($_POST['meta_index']));
6023 else
6024 $meta_index = "";
6025
6026 if ((isset($_POST['skip_webp'])) && (strlen(trim($_POST['skip_webp'])) > 0))
6027 $skip_webp = trim(sanitize_text_field($_POST['skip_webp']));
6028 else
6029 $skip_webp = "";
6030
6031 $this->mlf_option_true_update(MAXGALLERIA_DISABLE_SCALLING, $scaling_status);
6032
6033 update_option(MAXGALLERIA_MLP_ITEMS_PRE_PAGE, $images_per_page, true);
6034
6035 if($meta_index == 'true') {
6036 if(get_option(MAXGALLERIA_POSTMETA_INDEX) == 'off') {
6037 $this->add_postmeta_index();
6038 update_option(MAXGALLERIA_POSTMETA_INDEX, 'on', true);
6039 }
6040 } else {
6041 if(get_option(MAXGALLERIA_POSTMETA_INDEX) == 'on') {
6042 $this->remove_postmeta_index();
6043 update_option(MAXGALLERIA_POSTMETA_INDEX, 'off', true);
6044 }
6045 }
6046
6047 $this->mlf_option_true_update(MLFP_SKIP_WEBP_FILES, $skip_webp);
6048
6049 echo esc_html__('The settings were updated.','maxgalleria-media-library');
6050 die();
6051 }
6052
6053 public function mlf_option_true_update($option_id, $option_value) {
6054 if($option_value == 'true') {
6055 update_option($option_id, 'on', true);
6056 } else {
6057 update_option($option_id, 'off', true);
6058 }
6059 }
6060
6061 public function add_postmeta_index() {
6062
6063 global $wpdb;
6064
6065 $sql = "ALTER TABLE $wpdb->postmeta ADD INDEX mg_meta_value (meta_key ASC, meta_value(255) ASC);";
6066
6067 //error_log($sql);
6068
6069 $wpdb->get_results($sql);
6070
6071 }
6072
6073 public function remove_postmeta_index() {
6074
6075 global $wpdb;
6076
6077 $sql = "DROP INDEX mg_meta_value ON $wpdb->postmeta";
6078
6079 //error_log($sql);
6080
6081 $wpdb->get_results($sql);
6082
6083 }
6084
6085 public function max_discover_files($parent_folder) {
6086
6087 //error_log("max_discover_files parent_folder $parent_folder");
6088
6089 global $wpdb, $is_IIS;
6090 $user_id = get_current_user_id();
6091 $files_to_add = array();
6092 $files_count = 0;
6093 $parent_folder = intval($parent_folder);
6094
6095 $folder_table = $wpdb->prefix . MAXGALLERIA_MEDIA_LIBRARY_FOLDER_TABLE;
6096
6097 $sql = "select ID, pm.meta_value as attached_file, post_title, $folder_table.folder_id
6098 from $wpdb->prefix" . "posts
6099 LEFT JOIN $folder_table ON($wpdb->prefix" . "posts.ID = $folder_table.post_id)
6100 LEFT JOIN {$wpdb->prefix}postmeta AS pm ON (pm.post_id = {$wpdb->prefix}posts.ID)
6101 where post_type = 'attachment'
6102 and folder_id = '$parent_folder'
6103 and pm.meta_key = '_wp_attached_file'
6104 order by post_title";
6105
6106 $attachments = $wpdb->get_results($sql);
6107
6108 $sql = "select meta_value as attached_file
6109 from {$wpdb->prefix}postmeta
6110 where post_id = $parent_folder
6111 and meta_key = '_wp_attached_file'";
6112
6113 $current_row = $wpdb->get_row($sql);
6114
6115 $baseurl = $this->upload_dir['baseurl'];
6116 $baseurl = rtrim($baseurl, '/') . '/';
6117 $image_location = $baseurl . ltrim($current_row->attached_file, '/');
6118
6119 //error_log("image location 1" . $image_location);
6120
6121 //str_replace('localhost', 'www.localhost', $image_location);
6122
6123 //error_log("image location 2" . $image_location);
6124
6125 $folder_path = $this->get_absolute_path($image_location);
6126
6127 //error_log($folder_path);
6128
6129 update_user_meta($user_id, MAXG_SYNC_FOLDER_PATH_ID, $parent_folder);
6130
6131 if ($is_IIS || strtoupper(substr(PHP_OS, 0, 3)) == 'WIN' || strtoupper(substr(PHP_OS, 0, 13)) == 'MICROSOFT-IIS' )
6132 update_user_meta($user_id, MAXG_SYNC_FOLDER_PATH, str_replace('\\', '\\\\', $folder_path));
6133 else
6134 update_user_meta($user_id, MAXG_SYNC_FOLDER_PATH, $folder_path);
6135
6136 $folder_contents = array_diff(scandir($folder_path), array('..', '.'));
6137
6138 foreach ($folder_contents as $file_path) {
6139
6140 if($file_path !== '.DS_Store' && $file_path !== '.htaccess') {
6141 $new_attachment = $folder_path . DIRECTORY_SEPARATOR . $file_path;
6142 if(!$this->is_webp($new_attachment) || ($this->is_webp($new_attachment) && $this->sync_skip_webp == 'off')) {
6143 if(!strpos($new_attachment, '-uai-')) { // skip thumbnails created by the Uncode theme
6144 if(!strpos($new_attachment, '-scaled.')) { // skip scaled images
6145 if(!strpos($new_attachment, '-pdf.jpg')) { // skip pdf thumbnails
6146 if(!is_dir($new_attachment)) {
6147 if($this->is_base_file($file_path, $folder_contents)) {
6148 if(!$this->search_folder_attachments($file_path, $attachments)) {
6149
6150 $old_attachment_name = $new_attachment;
6151 $new_attachment = pathinfo($new_attachment, PATHINFO_DIRNAME) . DIRECTORY_SEPARATOR . sanitize_file_name(pathinfo($new_attachment, PATHINFO_FILENAME) . "." . strtolower(pathinfo($new_attachment, PATHINFO_EXTENSION)));
6152
6153 if(rename($old_attachment_name, $new_attachment)) {
6154 $files_to_add[] = basename($new_attachment);
6155 $files_count++;
6156 } else {
6157 $files_to_add[] = basename($old_attachment_name);
6158 $files_count++;
6159 }
6160 }
6161 }
6162 }
6163 }
6164 }
6165 }
6166 }
6167 }
6168 }
6169
6170 if(is_array($files_to_add)) {
6171 update_user_meta($user_id, MAXG_SYNC_FILES, $files_to_add);
6172 }
6173 if($files_count > 0)
6174 return '3'; // add the files
6175 else
6176 return '2'; // check next folder
6177
6178 }
6179
6180 public function is_webp($new_attachment ) {
6181 if(strpos($new_attachment, '.webp') !== false)
6182 return true;
6183 else
6184 return false;
6185 }
6186
6187 public function mlfp_run_sync_process() {
6188
6189 global $wpdb;
6190 $user_id = get_current_user_id();
6191 $message = "";
6192 $folders_array = array();
6193
6194 if ( !wp_verify_nonce( $_POST['nonce'], MAXGALLERIA_MEDIA_LIBRARY_NONCE)) {
6195 exit(esc_html__('missing nonce! Please refresh this page.','maxgalleria-media-library'));
6196 }
6197
6198 // Check if the current user has the capability to upload files
6199 if(!current_user_can('upload_files')){
6200 exit(esc_html__('You do not have the capability to sync files.','maxgalleria-media-library'));
6201 }
6202
6203 if ((isset($_POST['phase'])) && (strlen(trim($_POST['phase'])) > 0))
6204 $phase = trim(sanitize_text_field($_POST['phase']));
6205 else
6206 $phase = "";
6207
6208 if ((isset($_POST['parent_folder'])) && (strlen(trim($_POST['parent_folder'])) > 0))
6209 $parent_folder = intval(trim(sanitize_text_field($_POST['parent_folder'])));
6210 else
6211 $parent_folder = "";
6212
6213 if ((isset($_POST['mlp_title_text'])) && (strlen(trim($_POST['mlp_title_text'])) > 0))
6214 $mlp_title_text = trim(sanitize_text_field($_POST['mlp_title_text']));
6215 else
6216 $mlp_title_text = "";
6217
6218 if ((isset($_POST['mlp_alt_text'])) && (strlen(trim($_POST['mlp_alt_text'])) > 0))
6219 $mlp_alt_text = trim(sanitize_text_field($_POST['mlp_alt_text']));
6220 else
6221 $mlp_alt_text = "";
6222
6223 $next_phase = '1';
6224
6225 switch($phase) {
6226 // find folders
6227 case '1':
6228 $next_phase = '2';
6229 $this->max_sync_contents($parent_folder);
6230 break;
6231
6232 // for each folder. get the folder ids
6233 case '2':
6234
6235 $folders_array = get_user_meta($user_id, MAXG_SYNC_FOLDERS, true);
6236
6237 if(is_array($folders_array)) {
6238 $next_folder = array_pop($folders_array);
6239 } else {
6240 $next_folder = $folders_array;
6241 }
6242
6243 if($next_folder != "") {
6244 $message = esc_html__("Scanning for new files and folders...please wait.",'maxgalleria-media-library');
6245 $this->max_discover_files($next_folder);
6246 update_user_meta($user_id, MAXG_SYNC_FOLDERS, $folders_array);
6247 $next_phase = '3';
6248 } else {
6249 $message = esc_html__("Syncing finished.",'maxgalleria-media-library');
6250 delete_user_meta($user_id, MAXG_SYNC_FOLDERS);
6251 delete_user_meta($user_id, MAXG_SYNC_FILES);
6252 delete_user_meta($user_id, MAXG_SYNC_FOLDER_PATH_ID);
6253 delete_user_meta($user_id, MAXG_SYNC_FOLDER_PATH);
6254 $next_phase = null;
6255 }
6256 break;
6257
6258 // add each file
6259 case '3':
6260 $files_to_add = get_user_meta($user_id, MAXG_SYNC_FILES, true);
6261
6262 if(is_array($files_to_add)) {
6263 $next_file = array_pop($files_to_add);
6264 } else {
6265 $next_file = $files_to_add;
6266 }
6267
6268 if($next_file != "") {
6269
6270 $next_phase = '3';
6271
6272 $wp_filetype = wp_check_filetype_and_ext($next_file, $next_file );
6273
6274 if ($wp_filetype['ext'] !== false) {
6275 $message = esc_html__("Adding ",'maxgalleria-media-library') . $next_file;
6276 $this->mlfp_process_sync_file($next_file, $mlp_title_text, $mlp_alt_text);
6277 } else {
6278 $message = $next_file . esc_html__(" is not an allowed file type. It was not added.",'maxgalleria-media-library');
6279 }
6280 update_user_meta($user_id, MAXG_SYNC_FILES, $files_to_add);
6281
6282 } else {
6283 $next_phase = '2';
6284 delete_user_meta($user_id, MAXG_SYNC_FILES);
6285 }
6286 break;
6287 }
6288 $phase = $next_phase;
6289
6290 $data = array('phase' => $phase, 'message' => esc_html($message));
6291 echo json_encode($data);
6292 die();
6293 }
6294
6295 public function mlfp_process_sync_file($next_file, $mlp_title_text, $mlp_alt_text) {
6296
6297 global $wpdb;
6298 $user_id = get_current_user_id();
6299
6300 if($next_file != "") {
6301
6302 $parent_folder = get_user_meta($user_id, MAXG_SYNC_FOLDER_PATH_ID, true);
6303
6304 $folder_path = get_user_meta($user_id, MAXG_SYNC_FOLDER_PATH, true);
6305
6306 $new_attachment = $folder_path . DIRECTORY_SEPARATOR . $next_file;
6307
6308 //$new_file_title = preg_replace( '/\.[^.]+$/', '', $next_file);
6309 $new_file_title = preg_replace('/(\.[a-zA-Z0-9]+)$/', '', $next_file); // only remove the extention when several periods are in the name.
6310
6311 $attach_id = $this->add_new_attachment($new_attachment, $parent_folder, $new_file_title, $mlp_alt_text, $mlp_title_text);
6312
6313 }
6314 }
6315
6316 public function mlfp_save_mc_data($serial_copy_ids, $folder_id, $user_id) {
6317
6318 global $is_IIS;
6319
6320 update_user_meta($user_id, MAXG_MC_FILES, $serial_copy_ids);
6321
6322 $destination_folder = $this->get_folder_path($folder_id);
6323
6324 if ($is_IIS || strtoupper(substr(PHP_OS, 0, 3)) == 'WIN' || strtoupper(substr(PHP_OS, 0, 13)) == 'MICROSOFT-IIS' )
6325 update_user_meta($user_id, MAXG_MC_DESTINATION_FOLDER, str_replace('\\', '\\\\', $destination_folder));
6326 else
6327 update_user_meta($user_id, MAXG_MC_DESTINATION_FOLDER, $destination_folder);
6328
6329 }
6330
6331 public function mlfp_process_mc_data() {
6332
6333 $user_id = get_current_user_id();
6334 $message = "";
6335 $next_phase = '2';
6336
6337 if ( !wp_verify_nonce( $_POST['nonce'], MAXGALLERIA_MEDIA_LIBRARY_NONCE)) {
6338 exit(esc_html__('missing nonce! Please refresh this page.','maxgalleria-media-library'));
6339 }
6340
6341 // Check if the current user has the capability to upload files
6342 if(!current_user_can('upload_files')){
6343 exit(esc_html__('You do not have the capability to upload files.','maxgalleria-media-library'));
6344 }
6345
6346 if ((isset($_POST['phase'])) && (strlen(trim($_POST['phase'])) > 0))
6347 $phase = trim(sanitize_textarea_field($_POST['phase']));
6348 else
6349 $phase = "";
6350
6351 if ((isset($_POST['folder_id'])) && (strlen(trim($_POST['folder_id'])) > 0))
6352 $folder_id = intval(trim(sanitize_textarea_field($_POST['folder_id'])));
6353 else
6354 $folder_id = "";
6355
6356 if ((isset($_POST['current_folder'])) && (strlen(trim($_POST['current_folder'])) > 0))
6357 $current_folder = intval(trim(sanitize_textarea_field($_POST['current_folder'])));
6358 else
6359 $current_folder = "";
6360
6361 if ((isset($_POST['action_name'])) && (strlen(trim($_POST['action_name'])) > 0))
6362 $action_name = trim(sanitize_textarea_field($_POST['action_name']));
6363 else
6364 $action_name = "";
6365
6366 if ((isset($_POST['serial_copy_ids'])) && (strlen(trim($_POST['serial_copy_ids'])) > 0))
6367 $serial_copy_ids = trim(sanitize_textarea_field($_POST['serial_copy_ids']));
6368 else
6369 $serial_copy_ids = "";
6370
6371
6372 switch($phase) {
6373
6374 case '1':
6375
6376 $serial_copy_ids = str_replace('"', '', $serial_copy_ids);
6377
6378 $serial_copy_ids = explode(',', $serial_copy_ids);
6379
6380 $this->mlfp_save_mc_data($serial_copy_ids, $folder_id, $user_id);
6381
6382 $next_phase = '2';
6383
6384 break;
6385
6386 case '2':
6387
6388 $files_to_move = get_user_meta($user_id, MAXG_MC_FILES, true);
6389
6390 if(is_array($files_to_move)) {
6391 $next_id = array_pop($files_to_move);
6392 } else {
6393 $next_id = $files_to_move;
6394 $files_to_move = "";
6395 }
6396
6397 if($next_id != "") {
6398 if(is_numeric($next_id)) {
6399 if($action_name == 'copy_media') {
6400 $message = $this->move_copy_file(true, $next_id, $folder_id, $current_folder, $user_id);
6401 } else {
6402 $message = $this->move_copy_file(false, $next_id, $folder_id, $current_folder, $user_id);
6403 }
6404 }
6405 update_user_meta($user_id, MAXG_MC_FILES, $files_to_move);
6406 } else {
6407 $next_phase = null;
6408 delete_user_meta($user_id, MAXG_MC_FILES);
6409 if($action_name == 'copy_media')
6410 $message = esc_html__("Finished copying files. ",'maxgalleria-media-library');
6411 else
6412 $message = esc_html__("Finished moving files. ",'maxgalleria-media-library');
6413 }
6414 break;
6415 }
6416 $phase = $next_phase;
6417
6418 $data = array('phase' => $phase, 'message' => esc_html($message));
6419
6420 echo json_encode($data);
6421
6422 die();
6423 }
6424
6425 public function move_copy_file($copy, $copy_id, $folder_id, $current_folder, $user_id) {
6426
6427 global $wpdb, $is_IIS;
6428 $message = "";
6429 $files = "";
6430 $refresh = false;
6431 $scaled = false;
6432 $copy_id = intval($copy_id);
6433
6434 $destination = get_user_meta($user_id, MAXG_MC_DESTINATION_FOLDER, true);
6435
6436 $sql = "select meta_value as attached_file
6437 from {$wpdb->prefix}postmeta
6438 where post_id = $copy_id
6439 AND meta_key = '_wp_attached_file'";
6440
6441 $row = $wpdb->get_row($sql);
6442
6443 $baseurl = $this->upload_dir['baseurl'];
6444 $baseurl = rtrim($baseurl, '/') . '/';
6445 $image_location = $baseurl . ltrim($row->attached_file, '/');
6446
6447 if(strpos($image_location, '-scaled.' ) !== false) {
6448 $scaled = true;
6449 }
6450
6451 $image_path = $this->get_absolute_path($image_location);
6452
6453 $destination_path = $this->get_absolute_path($destination);
6454
6455 $folder_basename = basename($destination_path);
6456
6457 $basename = pathinfo($image_path, PATHINFO_BASENAME);
6458
6459 $destination_name = $destination_path . DIRECTORY_SEPARATOR . $basename;
6460
6461 $copy_status = true;
6462
6463 if(file_exists($image_path)) {
6464 if(!is_dir($image_path)) {
6465 if(file_exists($destination_path)) {
6466 if(is_dir($destination_path)) {
6467
6468 if($copy) {
6469
6470 if($scaled) {
6471 $full_scaled_image_path = str_replace('-scaled*', '', $image_path);
6472 if(file_exists($full_scaled_image_path)) {
6473 $image_path = $full_scaled_image_path;
6474 $full_scaled_image = substr($full_scaled_image_path, strrpos($full_scaled_image_path, '/')+1);
6475 $destination_name = $destination_path . DIRECTORY_SEPARATOR . $full_scaled_image;
6476 }
6477 }
6478
6479 if(copy($image_path, $destination_name )) {
6480
6481 $destination_url = $this->get_file_url($destination_name);
6482 $title_text = get_the_title($copy_id);
6483 $alt_text = get_post_meta($copy_id, '_wp_attachment_image_alt', true);
6484 $attach_id = $this->add_new_attachment($destination_name, $folder_id, $title_text, $alt_text);
6485 if($attach_id === false){
6486 $copy_status = false;
6487 }
6488 }
6489 else {
6490 echo esc_html__('Unable to copy the file; please check the folder and file permissions.','maxgalleria-media-library') . PHP_EOL;
6491 $copy_status = false;
6492 }
6493 //move
6494 } else {
6495 if(rename($image_path, $destination_name )) {
6496
6497 // check current theme customizer settings for the file
6498 // and update if found
6499 $update_theme_mods = false;
6500 $move_image_url = $this->get_file_url_for_copy($image_path);
6501 $move_destination_url = $this->get_file_url_for_copy($destination_name);
6502 $key = array_search ($move_image_url, $this->theme_mods, true);
6503 if($key !== false ) {
6504 set_theme_mod( $key, $move_destination_url);
6505 $update_theme_mods = true;
6506 }
6507 if($update_theme_mods) {
6508 $theme_mods = get_theme_mods();
6509 $this->theme_mods = json_decode(json_encode($theme_mods), true);
6510 $update_theme_mods = false;
6511 }
6512
6513 $image_path = str_replace('.', '*.', $image_path );
6514 //error_log("image_path $image_path");
6515 $metadata = wp_get_attachment_metadata($copy_id);
6516 $path_to_thumbnails = pathinfo($image_path, PATHINFO_DIRNAME);
6517 //error_log("path_to_thumbnails $path_to_thumbnails");
6518
6519 if($scaled) {
6520 $full_scaled_image_path = str_replace('-scaled*', '', $image_path);
6521 $full_scaled_image = substr($full_scaled_image_path, strrpos($full_scaled_image_path, '/')+1);
6522 $scaled_image_destination = $destination_path . DIRECTORY_SEPARATOR . $full_scaled_image;
6523 if(file_exists($full_scaled_image_path))
6524 rename($full_scaled_image_path, $scaled_image_destination);
6525 }
6526
6527 if(isset($metadata['sizes'])) {
6528
6529 foreach($metadata['sizes'] as $source_path) {
6530 $thumbnail_file = $path_to_thumbnails . DIRECTORY_SEPARATOR . $source_path['file'];
6531 $thumbnail_destination = $destination_path . DIRECTORY_SEPARATOR . $source_path['file'];
6532 if(file_exists($thumbnail_file)) {
6533 rename($thumbnail_file, $thumbnail_destination);
6534
6535 // check current theme customizer settings for the fileg
6536 // and update if found
6537 $update_theme_mods = false;
6538 $move_source_url = $this->get_file_url_for_copy($source_path);
6539 $move_thumbnail_url = $this->get_file_url_for_copy($thumbnail_destination);
6540 $key = array_search ($move_source_url, $this->theme_mods, true);
6541 if($key !== false ) {
6542 set_theme_mod( $key, $move_thumbnail_url);
6543 $update_theme_mods = true;
6544 }
6545 if($update_theme_mods) {
6546 $theme_mods = get_theme_mods();
6547 $this->theme_mods = json_decode(json_encode($theme_mods), true);
6548 $update_theme_mods = false;
6549 }
6550 } else if(defined('MLF_CHECK_THUMBNAILFILE_MOVE')) {
6551 error_log("$thumbnail_file not found");
6552 }
6553 }
6554
6555 }
6556
6557 $destination_url = $this->get_file_url($destination_name);
6558
6559 // update posts table
6560 $table = $wpdb->prefix . "posts";
6561 $data = array('guid' => $destination_url );
6562 $where = array('ID' => $copy_id);
6563 $wpdb->update( $table, $data, $where);
6564
6565 // update folder table
6566 $table = $wpdb->prefix . MAXGALLERIA_MEDIA_LIBRARY_FOLDER_TABLE;
6567 $data = array('folder_id' => $folder_id );
6568 $where = array('post_id' => $copy_id);
6569 $wpdb->update( $table, $data, $where);
6570
6571 // // get the uploads dir name
6572 // $basedir = $this->upload_dir['baseurl'];
6573 // $uploads_dir_name_pos = strrpos($basedir, '/');
6574 // $uploads_dir_name = substr($basedir, $uploads_dir_name_pos+1);
6575 //
6576 // //find the name and cut off the part with the uploads path
6577 // $string_position = strpos($destination_name, $uploads_dir_name);
6578 // $uploads_dir_length = strlen($uploads_dir_name) + 1;
6579 // $uploads_location = substr($destination_name, $string_position+$uploads_dir_length);
6580
6581 // Get the uploads dir name
6582 $basedir = $this->upload_dir['baseurl'];
6583 $uploads_dir_name_pos = strrpos($basedir, '/');
6584 $uploads_dir_name = substr($basedir, $uploads_dir_name_pos + 1);
6585
6586 // Fetch the name of the content folder dynamically using the filter
6587 $content_folder = apply_filters('mlfp_content_folder', 'wp-content');
6588
6589 // Find the name and cut off the part with the uploads path
6590 $string_position = strpos($destination_name, $uploads_dir_name, strpos($destination_name, $content_folder));
6591 $uploads_dir_length = strlen($uploads_dir_name) + 1;
6592 $uploads_location = substr($destination_name, $string_position + $uploads_dir_length);
6593
6594 if($this->is_windows())
6595 $uploads_location = str_replace('\\','/', $uploads_location);
6596
6597 // update _wp_attached_file
6598
6599 $uploads_location = ltrim($uploads_location, '/');
6600 update_post_meta( $copy_id, '_wp_attached_file', $uploads_location );
6601
6602 // update _wp_attachment_metadata
6603 if ($is_IIS || strtoupper(substr(PHP_OS, 0, 3)) == 'WIN' || strtoupper(substr(PHP_OS, 0, 13)) == 'MICROSOFT-IIS' )
6604 $attach_data = wp_generate_attachment_metadata( $copy_id, addslashes($destination_name));
6605 else
6606 $attach_data = wp_generate_attachment_metadata( $copy_id, $destination_name );
6607 wp_update_attachment_metadata( $copy_id, $attach_data );
6608
6609 // update posts and pages
6610 $replace_image_location = $this->get_base_file($image_location);
6611 $replace_destination_url = $this->get_base_file($destination_url);
6612
6613 if(class_exists( 'SiteOrigin_Panels')) {
6614 $this->update_serial_postmeta_records($replace_image_location, $replace_destination_url);
6615 }
6616
6617 // update postmeta records for beaver builder
6618 if(class_exists( 'FLBuilderLoader')) {
6619 $sql = "SELECT ID FROM {$wpdb->prefix}posts WHERE post_content LIKE '%$replace_image_location%'";
6620
6621 $records = $wpdb->get_results($sql);
6622 foreach($records as $record) {
6623
6624 $this->update_bb_postmeta($record->ID, $replace_image_location, $replace_destination_url);
6625
6626 }
6627 // clearing BB caches
6628 if ( class_exists( 'FLBuilderModel' ) && method_exists( 'FLBuilderModel', 'delete_asset_cache_for_all_posts' ) ) {
6629 FLBuilderModel::delete_asset_cache_for_all_posts();
6630 }
6631 if ( class_exists( 'FLCustomizer' ) && method_exists( 'FLCustomizer', 'clear_all_css_cache' ) ) {
6632 FLCustomizer::clear_all_css_cache();
6633 }
6634
6635 }
6636
6637 $replace_sql = "UPDATE {$wpdb->prefix}posts SET `post_content` = REPLACE (`post_content`, '$replace_image_location', '$replace_destination_url');";
6638 $result = $wpdb->query($replace_sql);
6639
6640 $replace_sql = str_replace ( '/', '\/', $replace_sql);
6641 //error_log($replace_sql);
6642 $result = $wpdb->query($replace_sql);
6643
6644 // for updating wp pagebuilder
6645 if(defined('WPPB_LICENSE')) {
6646 $this->update_wppb_data($replace_image_location, $destination_url);
6647 }
6648
6649 // for updating themify images
6650 if(function_exists('themify_builder_activate')) {
6651 $this->update_themify_data($replace_image_location, $destination_url);
6652 }
6653
6654 // for updating elementor background images
6655 if(is_plugin_active("elementor/elementor.php")) {
6656 $this->update_elementor_data($copy_id, $replace_image_location, $destination_url);
6657 }
6658
6659 $message .= esc_html__('Updating attachment links, please wait...','maxgalleria-media-library') . PHP_EOL;
6660 $files = $this->display_folder_contents ($current_folder, true, "", false);
6661 $refresh = true;
6662 }
6663 else {
6664 $message .= esc_html( __('Unable to move ','maxgalleria-media-library') . $basename . __('; please check the folder and file permissions.','maxgalleria-media-library') . PHP_EOL);
6665 $copy_status = false;
6666 }
6667 }
6668 }
6669 else {
6670 $message .= esc_html( __('The destination is not a folder: ','maxgalleria-media-library') . $destination_path . PHP_EOL);
6671 $copy_status = false;
6672 }
6673 }
6674 else {
6675 $message .= esc_html( __('Cannot find destination folder: ','maxgalleria-media-library') . $destination_path . PHP_EOL);
6676 $copy_status = false;
6677 }
6678 }
6679 else {
6680 $message .= esc_html__('Coping or moving a folder is not allowed.','maxgalleria-media-library') . PHP_EOL;
6681 $copy_status = false;
6682 }
6683 }
6684 else {
6685 $message .= esc_html( __('Cannot find the file: ','maxgalleria-media-library') . $image_path . ". " . PHP_EOL);
6686 //$this->write_log("Cannot find the file: $image_path");
6687 $copy_status = false;
6688 }
6689
6690 if($copy) {
6691 if($copy_status)
6692 $message .= esc_html($basename . __(' was copied to ','maxgalleria-media-library') . $folder_basename . PHP_EOL);
6693 else
6694 $message .= esc_html($basename . __(' was not copied.','maxgalleria-media-library') . PHP_EOL);
6695 }
6696 else {
6697 if($copy_status)
6698 $message .= esc_html($basename . __(' was moved to ','maxgalleria-media-library') . $folder_basename . PHP_EOL);
6699 else
6700 $message .= esc_html($basename . __(' was not moved.','maxgalleria-media-library') . PHP_EOL);
6701 }
6702
6703 return $message;
6704
6705 }
6706
6707 public function update_wppb_data($replace_image_location, $destination_url) {
6708
6709 global $wpdb;
6710 $save = false;
6711 $table = $wpdb->prefix . "postmeta";
6712
6713 $position = strrpos($destination_url, '.');
6714 $url_without_extension = substr($destination_url, 0, $position);
6715
6716 $base_file_name = basename($replace_image_location);
6717
6718 $sql = "select post_id, meta_id, meta_value from wp_postmeta where meta_key = '_wppb_content' and meta_value like '%{$base_file_name}%'";
6719 //error_log($sql);
6720
6721 $rows = $wpdb->get_results($sql);
6722 if($rows) {
6723 foreach($rows as $row) {
6724 $jarrays = json_decode($row->meta_value, true);
6725 $this->wppb_recursive_find_and_update($jarrays, $replace_image_location, $destination_url, $url_without_extension);
6726 //error_log(print_r($jarrays, true));
6727
6728 $jarrays = json_encode($jarrays);
6729 $data = array('meta_value' => $jarrays);
6730 $where = array('meta_id' => $row->meta_id);
6731 $wpdb->update($table, $data, $where);
6732 }
6733 }
6734 }
6735
6736 public function wppb_recursive_find_and_update(&$jarrays, $replace_image_location, $destination_url ) {
6737
6738 foreach($jarrays as $key => &$value) {
6739 if(is_array($value)) {
6740 $this->wppb_recursive_find_and_update($value, $replace_image_location, $destination_url);
6741 } else {
6742 if($key == 'url' && strpos($value, $replace_image_location) !== false) {
6743 $value = $destination_url;
6744 }
6745 }
6746 }
6747 }
6748
6749 public function update_themify_data($replace_image_location, $destination_url) {
6750
6751 global $wpdb;
6752 $save = false;
6753 $table = $wpdb->prefix . "postmeta";
6754
6755 $position = strrpos($destination_url, '.');
6756 $url_without_extension = substr($destination_url, 0, $position);
6757
6758 $base_file_name = basename($replace_image_location);
6759
6760 $sql = "select post_id, meta_id, meta_value from {$table} where meta_key = '_themify_builder_settings_json' and meta_value like '%$base_file_name%'";
6761
6762 $rows = $wpdb->get_results($sql);
6763 if($rows) {
6764 foreach($rows as $row) {
6765 $jarrays = json_decode($row->meta_value, true);
6766 $this->recursive_find_and_update($jarrays, $replace_image_location, $destination_url, $url_without_extension);
6767
6768 $jarrays = json_encode($jarrays);
6769 $data = array('meta_value' => $jarrays);
6770 $where = array('meta_id' => $row->meta_id);
6771 $wpdb->update($table, $data, $where);
6772 }
6773 }
6774 }
6775
6776 public function recursive_find_and_update(&$jarrays, $replace_image_location, $destination_url, $url_without_extension) {
6777
6778 foreach($jarrays as $key => &$value) {
6779 if(is_array($value)) {
6780 $this->recursive_find_and_update($value, $replace_image_location, $destination_url, $url_without_extension);
6781 } else {
6782 if($key == 'url_image' && strpos($value, $replace_image_location) !== false) {
6783 $value = $destination_url;
6784 } else if($key == 'img_url_slider' && strpos($value, $replace_image_location) !== false) {
6785 $value = $destination_url;
6786 } else if($key == 'content_text' && strpos($value, $replace_image_location) !== false ) {
6787 $content_text = $value;
6788 $value = str_replace($replace_image_location, $url_without_extension, $content_text);
6789 }
6790 }
6791 }
6792 }
6793
6794 public function update_elementor_data($image_id, $replace_image_location, $replace_destination_url) {
6795
6796 global $wpdb;
6797
6798 $base_file_name = basename($replace_image_location);
6799
6800 $sql = $wpdb->prepare(
6801 "select post_id, meta_id, meta_value from {$wpdb->prefix}postmeta where meta_key = '_elementor_data' and meta_value like %s",
6802 '%' . $wpdb->esc_like($base_file_name) . '%'
6803 );
6804
6805 $rows = $wpdb->get_results($sql);
6806
6807 if($rows) {
6808 foreach($rows as $row) {
6809 $save = false;
6810 $saved = false;
6811 $jarrays = null;
6812 $data_format = '';
6813
6814 // check for serialized data
6815 $data = @unserialize($row->meta_value);
6816 if($data === false) {
6817 $data_format = 'json';
6818 $jarrays = json_decode($row->meta_value, true);
6819 } else {
6820 $data_format = 'serialized';
6821 $jarrays = $data;
6822 }
6823
6824 if(is_array($jarrays)) {
6825 foreach($jarrays as &$jarray) {
6826 if($this->search_elementor_array($image_id, $jarray, $replace_image_location, $replace_destination_url, $row->post_id)) {
6827 $save = true;
6828 }
6829 }
6830 }
6831
6832 if($save) {
6833 if($data_format === 'json') {
6834 $meta_value = wp_json_encode($jarrays);
6835 $updated = $wpdb->update(
6836 $wpdb->postmeta,
6837 array('meta_value' => $meta_value),
6838 array('meta_id' => $row->meta_id),
6839 array('%s'),
6840 array('%d')
6841 );
6842 wp_cache_delete($row->post_id, 'post_meta');
6843 } else {
6844 $meta_value = $jarrays;
6845 $updated = update_post_meta($row->post_id, '_elementor_data', $meta_value);
6846 }
6847 $saved = ($updated !== false);
6848 }
6849 $this->update_elemenator_css_file($row->post_id, $replace_image_location, $replace_destination_url);
6850 if($saved) {
6851 $this->clear_elementor_post_generated_data($row->post_id);
6852 }
6853 }
6854 }
6855 }
6856
6857 public function clear_elementor_post_generated_data($post_id) {
6858
6859 delete_post_meta($post_id, '_elementor_css');
6860 delete_post_meta($post_id, '_elementor_element_cache');
6861 delete_post_meta($post_id, '_elementor_page_assets');
6862
6863 if(class_exists('\Elementor\Core\Files\CSS\Post')) {
6864 try {
6865 $post_css = new \Elementor\Core\Files\CSS\Post($post_id);
6866 $post_css->delete();
6867 } catch(\Throwable $exception) {
6868 // Elementor cache cleanup is best-effort; the meta update above is already complete.
6869 }
6870 }
6871
6872 clean_post_cache($post_id);
6873 }
6874
6875 public function search_elementor_array($image_id, &$jarray, $replace_image_location, $replace_destination_url, $post_id) {
6876
6877 $save = false;
6878 if(!is_array($jarray)) {
6879 return $save;
6880 }
6881
6882 $destination_url_without_extension = $this->get_base_file($replace_destination_url);
6883
6884 if(array_key_exists('id', $jarray) && (string) $jarray['id'] === (string) $image_id && array_key_exists('url', $jarray) && is_string($jarray['url'])) {
6885 $jarray['url'] = $replace_destination_url;
6886 $save = true;
6887 }
6888
6889 foreach($jarray as $key => &$value) {
6890 if(is_array($value)) {
6891 if($this->search_elementor_array($image_id, $value, $replace_image_location, $replace_destination_url, $post_id)) {
6892 $save = true;
6893 }
6894 } else if(is_string($value) && strpos($value, $replace_image_location) !== false) {
6895 $value = str_replace($replace_image_location, $destination_url_without_extension, $value);
6896 $save = true;
6897 }
6898 }
6899 unset($value);
6900
6901 if(array_key_exists('settings', $jarray)) {
6902 if(is_array($jarray['settings'])) {
6903 if(array_key_exists('background_background', $jarray['settings'])) {
6904 if($jarray['settings']['background_background'] == 'classic') {
6905 if(array_key_exists('background_image', $jarray['settings']) && is_array($jarray['settings']['background_image']) && array_key_exists('id', $jarray['settings']['background_image'])) {
6906 if($jarray['settings']['background_image']['id'] == $image_id) {
6907 $jarray['settings']['background_image']['url'] = $replace_destination_url;
6908 $save = true;
6909 }
6910 }
6911 }
6912 }
6913 }
6914 }
6915
6916 return $save;
6917 }
6918
6919 public function search_elementor_array1($image_id, &$jarray, $replace_image_location, $replace_destination_url, $post_id) {
6920
6921 $save = false;
6922
6923 if(!is_array($jarray)) {
6924 return $save;
6925 }
6926
6927 if(array_key_exists('settings', $jarray) && is_array($jarray['settings'])) {
6928 if(array_key_exists('background_background', $jarray['settings']) && $jarray['settings']['background_background'] == 'classic') {
6929 if(
6930 array_key_exists('background_image', $jarray['settings'])
6931 && is_array($jarray['settings']['background_image'])
6932 && array_key_exists('id', $jarray['settings']['background_image'])
6933 && $jarray['settings']['background_image']['id'] == $image_id
6934 ) {
6935 $jarray['settings']['background_image']['url'] = $replace_destination_url;
6936 $save = true;
6937 }
6938 }
6939 }
6940
6941 return $save;
6942 }
6943
6944 public function update_elemenator_css_file($post_id, $replace_image_location, $replace_destination_url) {
6945
6946 $css_file_path = trailingslashit($this->upload_dir['basedir']) . "elementor/css/post-{$post_id}.css";
6947
6948 $position = strrpos($replace_destination_url, '.');
6949
6950 $url_without_extension = substr($replace_destination_url, 0, $position);
6951
6952 if(file_exists($css_file_path)) {
6953
6954 $css = file_get_contents($css_file_path);
6955
6956 if($css === false) {
6957 return;
6958 }
6959
6960 $css = str_replace($replace_image_location, $url_without_extension, $css);
6961
6962 file_put_contents($css_file_path, $css);
6963 }
6964
6965 }
6966
6967 public function update_bb_postmeta($post_id, $replace_image_location, $replace_destination_url) {
6968
6969 $this->update_bb_postmeta_item('_fl_builder_draft', $post_id, $replace_image_location, $replace_destination_url);
6970 $this->update_bb_postmeta_item('_fl_builder_data', $post_id, $replace_image_location, $replace_destination_url);
6971
6972 }
6973
6974 public function update_bb_postmeta_item($metakey, $post_id, $replace_image_location, $replace_destination_url) {
6975
6976 $save = false;
6977 $builder_info = json_decode(json_encode(get_post_meta($post_id, $metakey, true)));
6978 $builder_info = $this->objectToArray($builder_info);
6979
6980 if(is_array($builder_info)){
6981 foreach ($builder_info as $key => &$info_head) {
6982 foreach ($info_head as $info_key => &$info_value) {
6983 if(is_array($info_value)) {
6984 foreach ($info_value as $data_key => &$data_value) {
6985 if(!is_array($data_value)) {
6986 if($data_key == 'photo_src' || $data_key == 'text') {
6987 $save = true;
6988 $data_value = str_replace($replace_image_location, $replace_destination_url, $data_value);
6989 }
6990 } else {
6991 foreach ($data_value as $next_key => &$next_value) {
6992 if(!is_array($next_value)) {
6993 if($next_key == 'url') {
6994 $save = true;
6995 $next_value = str_replace($replace_image_location, $replace_destination_url, $next_value);
6996 }
6997 } else {
6998 foreach ($next_value as $sizes_key => &$sizes_value) {
6999 if(is_array($sizes_value)) {
7000 foreach ($sizes_value as $final_key => &$final_value) {
7001 if(!is_array($final_value)) {
7002 if($final_key == 'url') {
7003 $save = true;
7004 $final_value = str_replace($replace_image_location, $replace_destination_url, $final_value);
7005 }
7006 }
7007 }
7008 }
7009 }
7010 }
7011 }
7012 }
7013 }
7014 }
7015 }
7016 }
7017 }
7018
7019 if($save) {
7020 $builder_info = $this->arrayToObject($builder_info);
7021 $builder_info = serialize($builder_info);
7022 update_post_meta($post_id, $metakey, $builder_info);
7023 }
7024
7025 }
7026
7027 function objectToArray( $object ) {
7028 if( !is_object( $object ) && !is_array( $object )){
7029 return $object;
7030 }
7031 if( is_object( $object ) ){
7032 $object = get_object_vars( $object );
7033 }
7034 return array_map( array($this, 'objectToArray'), $object );
7035 }
7036
7037 public function arrayToObject($d){
7038 if (is_array($d)){
7039 return (object) array_map(array($this, 'arrayToObject'), $d);
7040 } else {
7041 return $d;
7042 }
7043 }
7044
7045 public function get_upload_status() {
7046 $data = get_userdata(get_current_user_id());
7047 if (!is_object($data) || !isset($data->allcaps['upload_files']))
7048 $this->current_user_can_upload = false;
7049 else
7050 $this->current_user_can_upload = $data->allcaps['upload_files'];
7051 }
7052
7053 public function update_serial_postmeta_records($replace_image_location, $replace_destination_url) {
7054
7055 global $wpdb;
7056
7057 // = instead oflike?
7058 $sql = "SELECT * FROM {$wpdb->prefix}postmeta WHERE meta_key = 'panels_data' and meta_value like '%$replace_image_location%'";
7059
7060 $widgets = array('text','content','url','mp4','m4v','webm','ogv','flv');
7061
7062 $records = $wpdb->get_results($sql);
7063 foreach($records as $record) {
7064
7065 $data = unserialize($record->meta_value);
7066
7067 if (isset($data['widgets']) && is_array($data['widgets'])) {
7068
7069 for ($index = 0; $index < count($data['widgets']); $index++) {
7070
7071 foreach($widgets as $widget) {
7072
7073 if(isset($data['widgets'][$index][$widget])) {
7074
7075 if(is_string($data['widgets'][$index][$widget])) {
7076 $text = $data['widgets'][$index][$widget];
7077 //error_log("$widget: $text");
7078 $data['widgets'][$index][$widget] = str_replace($replace_image_location, $replace_destination_url, $text);
7079 //error_log($data['widgets'][$index][$widget]);
7080 }
7081 }
7082
7083 }
7084
7085 }
7086
7087 }
7088
7089 update_post_meta($record->post_id, $record->meta_key, $data);
7090 }
7091 }
7092
7093 public function get_ajax_paramater($parameter_name, $default = '') {
7094
7095 if ((isset($_POST[$parameter_name])) && (strlen(trim($_POST[$parameter_name])) > 0))
7096 $return_value = trim(sanitize_text_field($_POST[$parameter_name]));
7097 else
7098 $return_value = $default;
7099
7100 return $return_value;
7101
7102 }
7103
7104 public function mlfp_process_bdp() {
7105
7106 $message = "";
7107
7108 if ( !wp_verify_nonce( $_POST['nonce'], MAXGALLERIA_MEDIA_LIBRARY_NONCE)) {
7109 exit(esc_html__('Missing nonce! Please refresh this page.','maxgalleria-media-library'));
7110 }
7111
7112 // Check if the current user has the capability to manage options
7113 if(!current_user_can('manage_options')){
7114 exit(esc_html__('You do not have the capability to manage options.','maxgalleria-media-library'));
7115 }
7116
7117 $activate_mlfp_bdp = $this->get_ajax_paramater('activate_mlfp_bdp');
7118 $disable_listing = $this->get_ajax_paramater('disable_listing');
7119 $disable_hotlinking = $this->get_ajax_paramater('disable_hotlinking');
7120 $auto_protect = $this->get_ajax_paramater('auto_protect');
7121 $display_fe_protected_images = $this->get_ajax_paramater('display_fe_protected_images');
7122 $prevent_right_click = $this->get_ajax_paramater('prevent_right_click');
7123 $bda_role = $this->get_ajax_paramater('bda_role');
7124 $no_access_page_id = intval($this->get_ajax_paramater('no_access_page_id'));
7125 $no_access_page_name = $this->get_ajax_paramater('no_access_page_name');
7126
7127 if($this->bda == 'off' && $activate_mlfp_bdp == 'true') {
7128 //error_log("mlfp_process_bdp 2");
7129
7130 $this->protected_content_dir = $this->upload_dir['basedir'] . '/' . MLFP_PROTECTED_DIRECTORY;
7131
7132 $content_folder = apply_filters( 'mlfp_content_folder', 'wp-content');
7133
7134 $position = strpos($this->protected_content_dir, $content_folder);
7135
7136 $bda_path = substr($this->protected_content_dir, $position);
7137
7138 if(!file_exists($this->protected_content_dir)) {
7139 if(mkdir($this->protected_content_dir)) {
7140 //error_log("created " . $this->protected_content_dir);
7141 if(defined('FS_CHMOD_DIR'))
7142 @chmod($this->protected_content_dir, FS_CHMOD_DIR);
7143 else
7144 @chmod($this->protected_content_dir, 0775);
7145 //@chmod($this->protected_content_dir, 0755);
7146
7147 if(file_exists($this->protected_content_dir)) {
7148
7149 $this->bda_folder_id = $this->add_media_folder(MLFP_PROTECTED_DIRECTORY, $this->uploads_folder_ID, $this->protected_content_dir);
7150 update_option(MLFP_PROTECTED_DIR, $this->protected_content_dir);
7151
7152 $skip_folder_file = $this->protected_content_dir . DIRECTORY_SEPARATOR . "mlpp-hidden";
7153
7154 file_put_contents($skip_folder_file, '');
7155
7156 $message .= esc_html__('Procteced-content folder added.','maxgalleria-media-library') . '<br>';
7157 }
7158 }
7159 }
7160
7161 $message .= esc_html__('Block Direct Access activated.','maxgalleria-media-library');
7162
7163 $this->bda = 'on';
7164 update_option(MLFP_BDA, $this->bda);
7165 add_filter('mod_rewrite_rules', array( $this, 'mlfp_update_htaccess'));
7166 flush_rewrite_rules();
7167
7168 // check for download page
7169 if(!get_page_by_path("mlfp-download")) {
7170 $wordpress_page = array(
7171 'post_title' => esc_html__('MLFP Download','maxgalleria-media-library'),
7172 'post_content' => '',
7173 'post_status' => 'publish',
7174 'post_author' => 1,
7175 'post_type' => 'page'
7176 );
7177 $download_page_id = wp_insert_post($wordpress_page);
7178 update_option(MLFP_BDA_DOWNLOAD_PAGE, $download_page_id);
7179 }
7180
7181 } else if($this->bda == 'on' && $activate_mlfp_bdp == 'false') {
7182 $this->bda = 'off';
7183 update_option(MLFP_BDA, 'off');
7184 if($post = get_page_by_path('mlfp-download')) {
7185 wp_delete_post($post->ID, true);
7186 }
7187 $message .= esc_html__('Block Direct Access deactivated.','maxgalleria-media-library');
7188
7189 remove_filter('mod_rewrite_rules', array( $this, 'mlfp_update_htaccess'));
7190 flush_rewrite_rules();
7191 //error_log("removing bda rules");
7192 }
7193
7194 if($disable_listing == 'true') {
7195 update_option(MLFP_BDA_DIR_LISTING, 'on');
7196 } else {
7197 update_option(MLFP_BDA_DIR_LISTING, 'off');
7198 }
7199
7200 if($disable_hotlinking == 'true') {
7201 update_option(MLFP_BDA_HOTLINKING, 'on');
7202 } else {
7203 update_option(MLFP_BDA_HOTLINKING, 'off');
7204 }
7205
7206 if($auto_protect == 'true') {
7207 update_option(MLFP_BDA_AUTO_PROTECT, 'on');
7208 } else {
7209 update_option(MLFP_BDA_AUTO_PROTECT, 'off');
7210 }
7211
7212 if($display_fe_protected_images == 'true') {
7213 update_option(MLFP_BDA_DISPLAY_FE_IMAGES, 'on');
7214 } else {
7215 update_option(MLFP_BDA_DISPLAY_FE_IMAGES, 'off');
7216 }
7217
7218 if($prevent_right_click == 'true') {
7219 update_option(MLFP_BDA_PREVENT_RIGHT_CLICK, 'on');
7220 } else {
7221 update_option(MLFP_BDA_PREVENT_RIGHT_CLICK, 'off');
7222 }
7223
7224 if(!empty($bda_role)) {
7225 update_option(MLFP_BDA_USER_ROLE, $bda_role);
7226 }
7227
7228 echo $message;
7229
7230 die();
7231
7232 }
7233
7234 public function mlfp_save_noaccess_page() {
7235
7236 if ( !wp_verify_nonce( $_POST['nonce'], MAXGALLERIA_MEDIA_LIBRARY_NONCE)) {
7237 exit(esc_html__('Missing nonce! Please refresh this page.','maxgalleria-media-library'));
7238 }
7239
7240 // Check if the current user has the capability to manage options
7241 if(!current_user_can('manage_options')){
7242 exit(esc_html__('You do not have the capability to manage options.','maxgalleria-media-library'));
7243 }
7244
7245 $no_access_page_id = intval($this->get_ajax_paramater('no_access_page_id'));
7246 $no_access_page_name = $this->get_ajax_paramater('no_access_page_name');
7247
7248 if(!empty($no_access_page_id))
7249 update_option(MLFP_NO_ACCESS_PAGE_ID, $no_access_page_id);
7250
7251 if(!empty($no_access_page_name))
7252 update_option(MLFP_NO_ACCESS_PAGE_TITLE, $no_access_page_name);
7253
7254 echo '';
7255
7256 die();
7257 }
7258
7259 public function mlfp_update_htaccess($rules) {
7260
7261 //error_log("mlfp_update_htaccess");
7262
7263 global $wpdb;
7264 $endpoint = "mlfp_bdp";
7265 $display_listing = '';
7266 $bdp_rules = '';
7267
7268 $bdp_rules .= "# Block Direct Access Rewrite Rules" . PHP_EOL;
7269 $bdp_rules .= "RewriteRule private/([a-zA-Z0-9]+)$ index.php?{$endpoint}=$1 [L]" . PHP_EOL;
7270 $bdp_rules .= "RewriteCond %{REQUEST_FILENAME} -s" . PHP_EOL;
7271 $bdp_rules .= "RewriteCond %{HTTP_USER_AGENT} !facebookexternalhit/[0-9]" . PHP_EOL;
7272 $bdp_rules .= "RewriteCond %{HTTP_USER_AGENT} !Googlebot/[0-9]" . PHP_EOL;
7273 $bdp_rules .= "RewriteCond %{HTTP_USER_AGENT} !Twitterbot/[0-9]" . PHP_EOL;
7274 $directAccessPath = str_replace( trailingslashit( site_url() ), '', 'index.php' ) . "?{$endpoint}=$1&block_access=true [QSA,L]" . PHP_EOL;
7275 $upload_dir_url = str_replace( "https", "http", wp_upload_dir()['baseurl'] );
7276 $site_url = str_replace( "https", "http", site_url() );
7277 $bdp_rules .= "RewriteRule " . str_replace(trailingslashit($site_url), '', $upload_dir_url) . "/" . MLFP_PROTECTED_DIRECTORY . "(\/[A-Za-z0-9_@.\/&+-]+)+\.([A-Za-z0-9_@.\/&+-]+)$ " . $directAccessPath . PHP_EOL;
7278
7279 if(get_option(MLFP_BDA_HOTLINKING) == 'on') {
7280 $domain = home_url( '/', is_ssl() ? 'https' : 'http' );
7281 $bdp_rules .= "# Block Direct Access Prevent Hotlinking Rules" . PHP_EOL;
7282 $bdp_rules .= "RewriteCond %{HTTP_REFERER} !^$" . PHP_EOL;
7283 $bdp_rules .= "RewriteCond %{HTTP_REFERER} !^{$domain} [NC]" . PHP_EOL;
7284 $bdp_rules .= "RewriteRule \.(gif|jpg|jpeg|bmp|zip|rar|mp3|flv|swf|xml|png|avif|css|pdf)$ - [F]" . PHP_EOL;
7285 $bdp_rules .= "# Block Direct Access Prevent Hotlinking Rules End" . PHP_EOL;
7286 }
7287
7288 if(get_option(MLFP_BDA_DIR_LISTING) == 'on') {
7289 $display_listing = "Options -Indexes" . PHP_EOL;
7290 }
7291
7292 $bdp_rules .= "# Block Direct Access Rewrite Rules End" . PHP_EOL;
7293
7294 return $bdp_rules . $rules . $display_listing;
7295
7296 }
7297
7298 public function mlfp_toggle_file_access() {
7299
7300 if ( !wp_verify_nonce( $_POST['nonce'], MAXGALLERIA_MEDIA_LIBRARY_NONCE)) {
7301 exit(esc_html__('missing nonce!','maxgalleria-media-library'));
7302 }
7303
7304 // Check if the current user has the capability to upload files
7305 if(!current_user_can('upload_files')){
7306 exit(esc_html__('You do not have the capability to upload files.','maxgalleria-media-library'));
7307 }
7308
7309 $next_id = intval($this->get_ajax_paramater('file_id', ''));
7310
7311 $current_folder = intval($this->get_ajax_paramater('current_folder', ''));
7312
7313 $protected = intval($this->get_ajax_paramater('protected', '0'));
7314
7315 if($next_id != "") {
7316 $message = $this->move_to_protected_folder($next_id, $current_folder, $protected);
7317 } else {
7318 $message = esc_html__("Finished moving files to protected folder. ",'maxgalleria-media-library');
7319 }
7320
7321 echo $message;
7322
7323 die();
7324
7325 }
7326
7327 public function move_to_protected_folder($next_id, $current_folder, $protected) {
7328
7329 require_once( ABSPATH . 'wp-admin/includes/image.php' );
7330
7331 global $wpdb, $is_IIS;
7332 $message = "";
7333 $files = "";
7334 $refresh = false;
7335 $scaled = false;
7336 $next_id = intval($next_id);
7337
7338 $sql = "select meta_value as attached_file
7339 from $wpdb->postmeta
7340 where post_id = $next_id
7341 AND meta_key = '_wp_attached_file'";
7342
7343 //error_log($sql);
7344
7345 $row = $wpdb->get_row($sql);
7346
7347 if(!$row) {
7348 return esc_html__('Could not find the selected file.','maxgalleria-media-library') . PHP_EOL;
7349 }
7350
7351 remove_filter( 'wp_generate_attachment_metadata', array($this, 'add_attachment_to_folder2'));
7352
7353 $baseurl = $this->upload_dir['baseurl'];
7354 $baseurl = rtrim($baseurl, '/') . '/';
7355 $image_location = $baseurl . ltrim($row->attached_file, '/');
7356
7357 //error_log("image_location $image_location");
7358 if(strpos($image_location, '-scaled.' ) !== false) {
7359 $scaled = true;
7360 }
7361
7362 $image_path = $this->get_absolute_path($image_location);
7363 //error_log("image_path $image_path");
7364
7365 if($protected == 0 ) {
7366 $destination_path = $this->protected_content_dir;
7367
7368 //error_log('Protecting file ' . $row->attached_file);
7369
7370 $destination_name = $destination_path . DIRECTORY_SEPARATOR . $row->attached_file;
7371 //error_log("destination_name $destination_name");
7372 $position = strrpos($destination_name, '/');
7373 $destination_folder = substr($destination_name, 0, $position);
7374
7375 } else {
7376 $destination_path = $this->get_folder_path($current_folder);
7377 $destination_folder = $destination_path;
7378
7379 //error_log('Unprotecting file ' . $row->attached_file);
7380
7381 $basename = pathinfo($row->attached_file, PATHINFO_BASENAME);
7382
7383 $destination_name = $destination_path . DIRECTORY_SEPARATOR . $basename;
7384
7385 }
7386 //error_log("destination_path $destination_path");
7387
7388
7389 if(!file_exists($destination_folder)) {
7390 if($this->make_dir_path($destination_folder)) {
7391 if(defined('FS_CHMOD_DIR'))
7392 @chmod($destination_folder, FS_CHMOD_DIR);
7393 else
7394 @chmod($destination_folder, 0755);
7395 }
7396 }
7397
7398 $copy_status = true;
7399
7400 if(file_exists($image_path)) {
7401 if(!is_dir($image_path)) {
7402 if(file_exists($destination_path)) {
7403 if(is_dir($destination_path)) {
7404 //error_log("rename $image_path, $destination_name");
7405 //return false;
7406 if(rename($image_path, $destination_name )) {
7407
7408 $image_path = str_replace('.', '*.', $image_path );
7409 $metadata = wp_get_attachment_metadata($next_id);
7410 $path_to_thumbnails = pathinfo($image_path, PATHINFO_DIRNAME);
7411
7412 if($scaled) {
7413 $full_scaled_image_path = str_replace('-scaled*', '', $image_path);
7414 //error_log("full_scaled_image_path $full_scaled_image_path");
7415 $full_scaled_image = substr($full_scaled_image_path, strrpos($full_scaled_image_path, '/')+1);
7416 //error_log("full_scaled_image $full_scaled_image");
7417 $scaled_image_destination = $destination_folder . DIRECTORY_SEPARATOR . $full_scaled_image;
7418 //error_log("scaled_image_destination $scaled_image_destination");
7419 if(file_exists($full_scaled_image_path))
7420 rename($full_scaled_image_path, $scaled_image_destination);
7421 }
7422
7423 if(isset($metadata['sizes'])) {
7424
7425 foreach($metadata['sizes'] as $source_path) {
7426 $thumbnail_file = $path_to_thumbnails . DIRECTORY_SEPARATOR . $source_path['file'];
7427 $thumbnail_destination = $destination_folder . DIRECTORY_SEPARATOR . $source_path['file'];
7428 //error_log("thumbnail_file $thumbnail_file");
7429 if(file_exists($thumbnail_file)) {
7430 unlink($thumbnail_file);
7431
7432 }
7433 }
7434 }
7435
7436 $destination_url = $this->get_file_url($destination_name);
7437
7438 // update block_access table
7439 if($protected == 0) {
7440 $this->add_bda_record($next_id);
7441 $message = esc_html__('The file', 'maxgalleria-media-library') . esc_html(" $row->attached_file ") . esc_html__('is protected.', 'maxgalleria-media-library');
7442 } else {
7443 $this->remove_bda_record($next_id);
7444 $message = esc_html__('The file', 'maxgalleria-media-library') . esc_html(" $row->attached_file ") . esc_html__('is unprotected.', 'maxgalleria-media-library');
7445 }
7446 //error_log("block_access_table updated $protected");
7447
7448 //add postmete record
7449
7450 // // get the uploads dir name
7451 // $basedir = $this->upload_dir['baseurl'];
7452 // $uploads_dir_name_pos = strrpos($basedir, '/');
7453 // $uploads_dir_name = substr($basedir, $uploads_dir_name_pos+1);
7454 //
7455 // //find the name and cut off the part with the uploads path
7456 // $string_position = strpos($destination_name, $uploads_dir_name);
7457 // $uploads_dir_length = strlen($uploads_dir_name) + 1;
7458 // $uploads_location = substr($destination_name, $string_position+$uploads_dir_length);
7459
7460 // Get the uploads dir name
7461 $basedir = $this->upload_dir['baseurl'];
7462 $uploads_dir_name_pos = strrpos($basedir, '/');
7463 $uploads_dir_name = substr($basedir, $uploads_dir_name_pos + 1);
7464
7465 // Fetch the name of the content folder dynamically using the filter
7466 $content_folder = apply_filters('mlfp_content_folder', 'wp-content');
7467
7468 // Find the name and cut off the part with the uploads path
7469 $string_position = strpos($destination_name, $uploads_dir_name, strpos($destination_name, $content_folder));
7470 $uploads_dir_length = strlen($uploads_dir_name) + 1;
7471 $uploads_location = substr($destination_name, $string_position + $uploads_dir_length);
7472
7473 if($this->is_windows())
7474 $uploads_location = str_replace('\\','/', $uploads_location);
7475
7476 // update _wp_attached_file
7477
7478 $uploads_location = ltrim($uploads_location, '/');
7479 update_post_meta( $next_id, '_wp_attached_file', $uploads_location );
7480 //error_log("new file location $uploads_location");
7481
7482 // update _wp_attachment_metadata
7483 if ($is_IIS || strtoupper(substr(PHP_OS, 0, 3)) == 'WIN' || strtoupper(substr(PHP_OS, 0, 13)) == 'MICROSOFT-IIS' )
7484 $attach_data = wp_generate_attachment_metadata( $next_id, addslashes($destination_name));
7485 else
7486 $attach_data = wp_generate_attachment_metadata( $next_id, $destination_name );
7487 wp_update_attachment_metadata( $next_id, $attach_data );
7488
7489 // update posts and pages
7490 $replace_image_location = $this->get_base_file($image_location);
7491 $replace_destination_url = $this->get_base_file($destination_url);
7492
7493 if(class_exists( 'SiteOrigin_Panels')) {
7494 $this->update_serial_postmeta_records($replace_image_location, $replace_destination_url);
7495 }
7496
7497 // update postmeta records for beaver builder
7498 if(class_exists( 'FLBuilderLoader')) {
7499 $sql = "SELECT ID FROM {$wpdb->prefix}posts WHERE post_content LIKE '%$replace_image_location%'";
7500 //error_log($sql);
7501
7502 $records = $wpdb->get_results($sql);
7503 foreach($records as $record) {
7504
7505 $this->update_bb_postmeta($record->ID, $replace_image_location, $replace_destination_url);
7506
7507 //}
7508 // clearing BB caches
7509 //error_log("check for cache");
7510 if ( class_exists( 'FLBuilderModel' ) && method_exists( 'FLBuilderModel', 'delete_asset_cache_for_all_posts' ) ) {
7511 FLBuilderModel::delete_asset_cache_for_all_posts();
7512 //error_log("delete_asset_cache_for_all_posts");
7513 }
7514
7515 if ( class_exists( 'FLBuilderModel' ) && method_exists( 'FLBuilderModel', 'delete_all_asset_cache' ) ) {
7516 FLBuilderModel::delete_all_asset_cache( $record->ID );
7517 //error_log("delete_all_asset_cache");
7518 }
7519
7520 if ( class_exists( 'FLCustomizer' ) && method_exists( 'FLCustomizer', 'clear_all_css_cache' ) ) {
7521 FLCustomizer::clear_all_css_cache();
7522 //error_log("clear_all_css_cache");
7523 }
7524 }
7525 wp_cache_flush();
7526
7527 }
7528
7529 $this->update_links($replace_image_location, $replace_destination_url);
7530
7531 // for updating wp pagebuilder
7532 if(defined('WPPB_LICENSE')) {
7533 $this->update_wppb_data($replace_image_location, $destination_url);
7534 }
7535
7536 // for updating themify images
7537 if(function_exists('themify_builder_activate')) {
7538 $this->update_themify_data($replace_image_location, $destination_url);
7539 }
7540
7541 // for updating elementor background images
7542 if(is_plugin_active("elementor/elementor.php")) {
7543 $this->update_elementor_data($next_id, $replace_image_location, $destination_url);
7544 }
7545
7546 //$message .= __('Updating attachment links, please wait...','maxgalleria-media-library') . PHP_EOL;
7547 $files = $this->display_folder_contents ($current_folder, true, "", false);
7548 $refresh = true;
7549 } else {
7550 //$message .= sprintf(__("Could not move %s to the protected folder",'maxgalleria-media-library'), $row->attached_file) . PHP_EOL;
7551 }
7552 }
7553 }
7554 }
7555 }
7556
7557 add_filter( 'wp_generate_attachment_metadata', array($this, 'add_attachment_to_folder2'), 10, 4);
7558
7559 return $message;
7560
7561 }
7562
7563 public function is_file_protected($file_id) {
7564
7565 global $wpdb;
7566 $file_id = intval($file_id);
7567
7568 $sql = "select block from wp_mgmlp_block_access where attachment_id = $file_id";
7569
7570 $row = $wpdb->get_row($sql);
7571
7572 if($row) {
7573 if($row->block == 1)
7574 return true;
7575 else
7576 return false;
7577 } else {
7578 return false;
7579 }
7580
7581 }
7582
7583 public function file_exists($file_id) {
7584
7585 global $wpdb;
7586 $file_id = intval($file_id);
7587
7588 $sql = "select post_title from $wpdb->posts where ID = $file_id and post_type = 'attachment'";
7589
7590 $row = $wpdb->get_row($sql);
7591
7592 if($row) {
7593 return true;
7594 } else {
7595 return false;
7596 }
7597 }
7598
7599 public function make_dir_path($path) {
7600 return (file_exists($path) || mkdir($path, 0775, true));
7601 }
7602
7603 public function add_bda_record($attachment_id) {
7604 global $wpdb;
7605 $attachment_id = intval($attachment_id);
7606 $block_access_table = $wpdb->prefix . MAXGALLERIA_MEDIA_LIBRARY_BLOCK_ACCESS_TABLE;
7607 $time = date('D n/j/Y g:i a');
7608
7609 $data = array(
7610 'attachment_id'=> $attachment_id,
7611 'hash_id' => md5(rand()),
7612 'time' => $time,
7613 'block' => 1
7614 );
7615
7616 $wpdb->replace($block_access_table, $data);
7617 update_post_meta($attachment_id, MLFP_BDA_MEDIA, TRUE);
7618 }
7619
7620 public function remove_bda_record($attachment_id) {
7621 global $wpdb;
7622 $attachment_id = intval($attachment_id);
7623 $block_access_table = $wpdb->prefix . MAXGALLERIA_MEDIA_LIBRARY_BLOCK_ACCESS_TABLE;
7624 $where = array('attachment_id' => $attachment_id);
7625 $wpdb->delete($block_access_table,$where);
7626 delete_post_meta($attachment_id, MLFP_BDA_MEDIA);
7627 }
7628
7629 public function bda_help() {
7630 ?>
7631 <p><strong><?php esc_html_e("Block Direct Access","maxgalleria-media-library")?></strong></p>
7632 <p><?php esc_html_e("The Block Direct Access feature allows an administrator to block viewing and download of selected media files. Files to be blocked are moved to a protected folder in the media library and their embedded links in any posts or pages are automatically updated.","maxgalleria-media-library")?></p>
7633 <p><?php esc_html_e("Blocked file links can be generated and configured to limit the number of downloads or to expire with an expiration date on the Library page.","maxgalleria-media-library")?></p>
7634 <p><?php esc_html_e("To activate this feature, check the 'Activate Block Direct Access' checkbox and click the Update Settings button.","maxgalleria-media-library")?></p>
7635 <p><?php esc_html_e("You can also check the 'Prevent Directory Listing' and the 'Prevent Hotlinking'. Hotlinking is the practice and linking to files hosted on a different website.","maxgalleria-media-library")?></p>
7636 <p><?php esc_html_e("The viewing of protected files on the front end of the site can be enabled by check the 'Display Protected Images on the Front End of the Site' option, but this may not work in some browsers. Also the ability to copy and save images displayed in a browser can be disable using the 'Disable Image Copy and Right Click' option.","maxgalleria-media-library")?></p>
7637 <p><?php esc_html_e("Also either Administrators or the Author, the user who upload the protected file, can be set to view the protected files from Media Library Folders Pro.","maxgalleria-media-library")?></p>
7638 <p><strong><?php esc_html_e("Block Access to Private Download Links","maxgalleria-media-library")?></strong>, <?php esc_html_e("IP addresses to private links to protected files can be blocked by adding them to the Block Access to Private Download Links.","maxgalleria-media-library")?></p>
7639 <p><strong><?php esc_html_e("Custom No Access Page,","maxgalleria-media-library")?></strong>, <?php esc_html_e("A page can be created to display a no access message in place of the site's 404 page. Under Custom No Access Page, an administrator can select and set the page to be used for this purpose.","maxgalleria-media-library")?></p>
7640 <p>&nbsp;</p>
7641 <p>&nbsp;</p>
7642 <p>&nbsp;</p>
7643 <?php
7644 }
7645
7646 public function mlp_generate_file_link() {
7647
7648 $message = "";
7649
7650 if ( !wp_verify_nonce( $_POST['nonce'], MAXGALLERIA_MEDIA_LIBRARY_NONCE)) {
7651 exit(esc_html__('Missing nonce! Please refresh this page.','maxgalleria-media-library'));
7652 }
7653
7654 // Check if the current user has the capability to upload files
7655 if(!current_user_can('upload_files')){
7656 exit(esc_html__('You do not have the capability to upload files.','maxgalleria-media-library'));
7657 }
7658
7659 if ((isset($_POST['image_id'])) && (strlen(trim($_POST['image_id'])) > 0))
7660 $image_id = intval(trim(sanitize_text_field($_POST['image_id'])));
7661 else
7662 $image_id = 0;
7663
7664 if ((isset($_POST['title'])) && (strlen(trim($_POST['title'])) > 0))
7665 $title = trim(sanitize_text_field($_POST['title']));
7666 else
7667 $title = "";
7668
7669
7670 if ((isset($_POST['current_user'])) && (strlen(trim($_POST['current_user'])) > 0))
7671 $current_user = intval(trim(sanitize_text_field($_POST['current_user'])));
7672 else
7673 $current_user = 0;
7674
7675 if($image_id != 0) {
7676
7677 if(!$this->is_protected_file($image_id)) {
7678 $message = $title . esc_html__(' is not a protected file','maxgalleria-media-library');
7679 } else {
7680 $download_link = $this->get_private_link($image_id, $current_user);
7681 $message = esc_html($title) . " - " . esc_url($download_link);
7682 }
7683 }
7684
7685 echo $message;
7686 die();
7687
7688 }
7689
7690 public function is_protected_file($image_id) {
7691
7692 global $wpdb;
7693 $image_id = intval($image_id);
7694
7695 $table = $wpdb->prefix . MAXGALLERIA_MEDIA_LIBRARY_BLOCK_ACCESS_TABLE;
7696
7697 $sql = "select time from $table where attachment_id = $image_id";
7698
7699 //error_log($sql);
7700
7701 if($wpdb->get_var($sql) != NULL)
7702 return true;
7703 else
7704 return false;
7705 }
7706
7707 public function get_hash_id($image_id) {
7708
7709 global $wpdb;
7710 $image_id = intval($image_id);
7711
7712 $table = $wpdb->prefix . MAXGALLERIA_MEDIA_LIBRARY_BLOCK_ACCESS_TABLE;
7713
7714 $sql = "select hash_id from $table where attachment_id = $image_id";
7715
7716 //error_log($sql);
7717
7718 $hash_id = $wpdb->get_var($sql);
7719
7720 return $hash_id;
7721 }
7722
7723 public function get_private_link($image_id, $current_user) {
7724
7725 $hash = $this->get_hash_id($image_id);
7726
7727 $download_page = get_permalink(get_option(MLFP_BDA_DOWNLOAD_PAGE));
7728
7729 return esc_url(add_query_arg('download', $hash, $download_page));
7730 }
7731
7732 public function mlfp_display_bda_info() {
7733
7734 if ( !wp_verify_nonce( $_POST['nonce'], MAXGALLERIA_MEDIA_LIBRARY_NONCE)) {
7735 exit(esc_html__('Missing nonce! Please refresh this page.','maxgalleria-media-library'));
7736 }
7737
7738 // Check if the current user has the capability to upload files
7739 if(!current_user_can('upload_files')){
7740 exit(esc_html__('You do not have the capability to upload files.','maxgalleria-media-library'));
7741 }
7742
7743 $image_id = intval($this->get_ajax_paramater('image_id', 0));
7744
7745 $title = $this->get_ajax_paramater('title', '');
7746
7747 $count = $this->get_ajax_paramater('count', '');
7748
7749 //error_log("$image_id, $title, $count");
7750
7751 $row = $this->get_bda_file_info($image_id, $title, $count);
7752
7753 if($row)
7754 echo $row;
7755 else
7756 echo "none";
7757
7758 die();
7759
7760 }
7761
7762 public function get_bda_file_info($image_id, $title, $count) {
7763
7764 global $wpdb;
7765 $image_id = intval($image_id);
7766
7767 $table = $wpdb->prefix . MAXGALLERIA_MEDIA_LIBRARY_BLOCK_ACCESS_TABLE;
7768
7769 $sql = "select * from $table where attachment_id = $image_id";
7770 //error_log($sql);
7771 $row = $wpdb->get_row($sql);
7772
7773 if($count % 2)
7774 $row_color = "";
7775 else
7776 $row_color = "gray-row";
7777
7778 if($row) {
7779 $download_count = ($row->count) ? $row->count : '0';
7780 $download_limit = ($row->download_limit) ? $row->download_limit : '0';
7781 $line = "<tr class='bda-row $row_color' data-id='$image_id'><td class='bda-name-col'>$title</td><td class='bda-count-col mflp-align-center'>$download_count</td><td class='bda-limit-col mflp-align-center'><input type='text' id='limit-{$image_id}' class='bda-limit-input mflp-align-right' value='$download_limit' ></td><td class='bda-exp-date-col'><input type='date' class='bda-exp-date-input' id='ex-date-{$image_id}' value='$row->expiration_date'></td><td class='bda-copy-link-col'><a class='bda-copy-link gray-blue-link' data-hash='$row->hash_id'>" . __('Copy Link','maxgalleria-media-library') . "</a></td>\r\n";
7782 return $line;
7783 } else {
7784 return false;
7785 }
7786 }
7787
7788 public function mlfp_update_bda_record() {
7789
7790 global $wpdb;
7791
7792 if ( !wp_verify_nonce( $_POST['nonce'], MAXGALLERIA_MEDIA_LIBRARY_NONCE)) {
7793 exit(__('Missing nonce! Please refresh this page.','maxgalleria-media-library'));
7794 }
7795
7796 // Check if the current user has the capability to upload files
7797 if(!current_user_can('upload_files')){
7798 exit(esc_html__('You do not have the capability to upload files.','maxgalleria-media-library'));
7799 }
7800
7801 $image_id = intval($this->get_ajax_paramater('image_id', 0));
7802
7803 $download_limit = intval($this->get_ajax_paramater('download_limit', 0));
7804
7805 $expiration_date = $this->get_ajax_paramater('expiration_date', 0);
7806
7807 $this->update_bda_record($image_id, $download_limit, $expiration_date);
7808
7809 die();
7810
7811 }
7812
7813 public function update_bda_record($image_id, $download_limit, $expiration_date) {
7814
7815 global $wpdb;
7816 $image_id = intval($image_id);
7817
7818 $table = $wpdb->prefix . MAXGALLERIA_MEDIA_LIBRARY_BLOCK_ACCESS_TABLE;
7819
7820 $data = array(
7821 'download_limit' => $download_limit,
7822 'expiration_date' => $expiration_date
7823 );
7824
7825 $where = array('attachment_id' => $image_id);
7826
7827 $wpdb->update($table, $data, $where);
7828
7829 }
7830
7831 public function copy_template_to_theme() {
7832
7833 // Copy gallery post type template file to theme directory
7834 $source = MAXGALLERIA_MEDIA_LIBRARY_PLUGIN_DIR . '/page-mlfp-download.php';
7835 $destination = $this->get_theme_dir() . '/page-mlfp-download.php';
7836 if(!defined('PRESERVE_MLFP_TEMPLATE')) {
7837 copy($source, $destination);
7838 }
7839 else if(!file_exists($destination)) {
7840 copy($source, $destination);
7841 }
7842 flush_rewrite_rules();
7843 }
7844
7845 public function get_theme_dir() {
7846 if(is_child_theme())
7847 return WP_CONTENT_DIR . '/themes/' . get_stylesheet();
7848 else
7849 return WP_CONTENT_DIR . '/themes/' . get_template();
7850 }
7851
7852
7853 public function mlfp_bdp_report() {
7854
7855 global $wpdb;
7856 $images_found = false;
7857 $items_per_page = 10;
7858
7859 if ( !wp_verify_nonce( $_POST['nonce'], MAXGALLERIA_MEDIA_LIBRARY_NONCE)) {
7860 exit(esc_html__('Missing nonce! Please refresh this page.','maxgalleria-media-library'));
7861 }
7862
7863 // Check if the current user has the capability to upload files
7864 if(!current_user_can('manage_options')){
7865 exit(esc_html__('You do not have the capability to upload files.','maxgalleria-media-library'));
7866 }
7867
7868 $page_id = intval($this->get_ajax_paramater('page_id', 0));
7869
7870 $table = $wpdb->prefix . MAXGALLERIA_MEDIA_LIBRARY_BLOCK_ACCESS_TABLE;
7871
7872 $offset = $page_id * $items_per_page;
7873
7874 $sql = $wpdb->prepare("SELECT SQL_CALC_FOUND_ROWS pm.meta_value AS attached_file, ba.count, ba.download_limit, ba.expiration_date
7875 FROM $table AS ba
7876 LEFT JOIN $wpdb->postmeta AS pm ON pm.post_id = ba.attachment_id
7877 WHERE pm.meta_key = '_wp_attached_file' limit %d, %d", $offset, $items_per_page);
7878
7879 //error_log($sql);
7880
7881 $rows = $wpdb->get_results($sql);
7882
7883 $count = $wpdb->get_row("select FOUND_ROWS()", ARRAY_A);
7884 $total_images = $count['FOUND_ROWS()'];
7885 $total_number_pages = ceil($total_images / $items_per_page);
7886
7887 if($rows) {
7888 $images_found = true;
7889 echo "<table id='protected-files'>" . PHP_EOL;
7890 echo " <thead>" . PHP_EOL;
7891 echo " <tr>" . PHP_EOL;
7892 echo " <td class='pf-name'>". esc_html__('File','maxgalleria-media-library')."</td>" . PHP_EOL;
7893 echo " <td class='pf-count'>". esc_html__('Download count','maxgalleria-media-library')."</td>" . PHP_EOL;
7894 echo " <td class='pf-limit'>". esc_html__('Download limit','maxgalleria-media-library')."</td>" . PHP_EOL;
7895 echo " <td class='pf-expiration'>". esc_html__('Expirtation Date','maxgalleria-media-library')."</td>" . PHP_EOL;
7896 echo " </tr>" . PHP_EOL;
7897 echo " </thead>" . PHP_EOL;
7898 echo " <tbody>" . PHP_EOL;
7899 foreach($rows as $row) {
7900 echo " <tr>" . PHP_EOL;
7901 echo " <td class='pf-name'>" . esc_html($row->attached_file) ."</td>" . PHP_EOL;
7902 $count = ($row->count) ? $row->count : '0';
7903 echo " <td class='pf-count'>". esc_html($count) ."</td>" . PHP_EOL;
7904 $download_limit = ($row->download_limit) ? $row->download_limit : 'none';
7905 echo " <td class='pf-limit'>" . esc_html($download_limit) ."</td>" . PHP_EOL;
7906 //error_log($row->attached_file . " expiration_date " . $row->expiration_date);
7907 //$expiration_date = ($row->expiration_date == '0000-00-00') ? 'none' : date("m/d/Y", strtotime($row->expiration_date));
7908 if($row->expiration_date == null || $row->expiration_date == '0000-00-00')
7909 $expiration_date = 'none';
7910 else
7911 $expiration_date = date("m/d/Y", strtotime($row->expiration_date));
7912 echo " <td class='pf-expiration'>" . esc_html($expiration_date) ." </td>" . PHP_EOL;
7913 echo " </tr>" . PHP_EOL;
7914 }
7915 echo " <tbody>" . PHP_EOL;
7916 echo "<table>" . PHP_EOL;
7917 } else {
7918 echo "<p style='text-align:center'>" . esc_html__('No files were found.','maxgalleria-media-library') . "</p>";
7919 }
7920
7921 if($images_found) {
7922 $last_page = $total_number_pages-1;
7923 $previous_page = $page_id - 1;
7924 $next_page = $page_id + 1;
7925 echo "<div class='mlfp-page-nav'>" . PHP_EOL;
7926 if($page_id > 0)
7927 echo "<a id='mlfp-previous' page-id='" . esc_attr($previous_page) . "' style='float:left;cursor:pointer'>< " . esc_html__( 'Previous', 'maxgalleria-media-library' ) ."</a>" . PHP_EOL;
7928 if($page_id < $total_number_pages-1 && $total_images > $items_per_page)
7929 echo "<a id='mlfp-next' page-id='" . esc_attr($next_page) ."' style='float:right;cursor:pointer'>" . esc_html__( 'Next', 'maxgalleria-media-library' ) ." ></a>" . PHP_EOL;
7930 echo "</div>" . PHP_EOL;
7931 }
7932
7933 die();
7934
7935 }
7936
7937 public function mlfp_block_new_ip() {
7938
7939 global $wpdb;
7940 $message = '';
7941 $result = '';
7942 $new_id = 0;
7943
7944 if ( !wp_verify_nonce( $_POST['nonce'], MAXGALLERIA_MEDIA_LIBRARY_NONCE)) {
7945 exit(esc_html__('Missing nonce! Please refresh this page.','maxgalleria-media-library'));
7946 }
7947
7948 // Check if the current user has the capability to manage options
7949 if(!current_user_can('manage_options')){
7950 exit(esc_html__('You do not have the capability to manage options.','maxgalleria-media-library'));
7951 }
7952
7953 $new_block_ip = $this->get_ajax_paramater('new_block_ip');
7954
7955 if(filter_var($new_block_ip, FILTER_VALIDATE_IP)) {
7956
7957 $table = $wpdb->prefix . BLOCKED_IPS_TABLE;
7958
7959 $sql = $wpdb->prepare("select * from $table where address = '%s'", $new_block_ip);
7960
7961 $row = $wpdb->get_row($sql);
7962 if($row) {
7963 $message = esc_html__('The address is already in the blocked IPs list.','maxgalleria-media-library');
7964 $result = false;
7965 } else {
7966 $data = array('address' => $new_block_ip);
7967 $retval = $wpdb->insert($table, $data);
7968 $new_id = $wpdb->insert_id;
7969 //error_log("$new_block_ip retval $retval");
7970 $message = esc_html__('The address has been added to the blocked IPs list.','maxgalleria-media-library');
7971 $result = true;
7972 }
7973
7974 } else {
7975 $message = esc_html__('The IP address is not valid.','maxgalleria-media-library');
7976 $result = false;
7977 }
7978
7979 $return = array('message' => $message, 'result' => $result, 'id' => $new_id);
7980
7981 echo json_encode($return);
7982
7983 die();
7984 }
7985
7986 public function get_blocked_ips() {
7987 global $wpdb;
7988 $buffer = '';
7989 $table = $wpdb->prefix . BLOCKED_IPS_TABLE;
7990 $sql = "select * from $table order by address";
7991 //error_log($sql);
7992 $rows = $wpdb->get_results($sql);
7993 if($rows) {
7994 foreach($rows as $row) {
7995 $buffer .= '<option value="' . esc_attr($row->ip_id) . '">' . esc_html($row->address) . '</option>' . PHP_EOL ;
7996 }
7997 }
7998
7999 return $buffer;
8000 }
8001
8002 public function mlfp_get_block_ips() {
8003
8004 if ( !wp_verify_nonce( $_POST['nonce'], MAXGALLERIA_MEDIA_LIBRARY_NONCE)) {
8005 exit(esc_html__('Missing nonce! Please refresh this page.','maxgalleria-media-library'));
8006 }
8007
8008 // Check if the current user has the capability to manage options
8009 if(!current_user_can('manage_options')){
8010 exit(esc_html__('You do not have the capability to manage options.','maxgalleria-media-library'));
8011 }
8012
8013 $data = $this->get_blocked_ips();
8014
8015 echo $data;
8016
8017 die();
8018 }
8019
8020 public function mlfp_unblock_ips() {
8021
8022 global $wpdb;
8023 $updated = false;
8024 $message = esc_html__('No IP addresses were removed from the blocked IPs lists','maxgalleria-media-library');
8025
8026 if ( !wp_verify_nonce( $_POST['nonce'], MAXGALLERIA_MEDIA_LIBRARY_NONCE)) {
8027 exit(esc_html__('Missing nonce! Please refresh this page.','maxgalleria-media-library'));
8028 }
8029
8030 // Check if the current user has the capability to manage options
8031 if(!current_user_can('manage_options')){
8032 exit(esc_html__('You do not have the capability to manage options.','maxgalleria-media-library'));
8033 }
8034
8035 if ((isset($_POST['serial_ips'])) && (strlen(trim($_POST['serial_ips'])) > 0)) {
8036 $unblock_ips = trim(stripslashes(sanitize_text_field($_POST['serial_ips'])));
8037 //error_log("unblock_ips 1: $unblock_ips");
8038 $unblock_ips = str_replace('"', '', $unblock_ips);
8039 //error_log("unblock_ips 2: $unblock_ips");
8040 $unblock_ips = explode(",",$unblock_ips);
8041 }
8042 else
8043 $unblock_ips = '';
8044
8045 $table = $wpdb->prefix . BLOCKED_IPS_TABLE;
8046
8047 foreach($unblock_ips as $unblock_ip) {
8048 $updated = true;
8049 $where = array('ip_id' => (int) $unblock_ip);
8050 if($wpdb->delete($table, $where))
8051 $message = esc_html__('The IP addresses were unblocked.','maxgalleria-media-library');
8052 }
8053
8054 $return = array('message' => $message, 'result' => $updated);
8055
8056 echo json_encode($return);
8057
8058 die();
8059 }
8060
8061 public function get_all_pages() {
8062 global $wpdb;
8063 $sql = "select ID, post_title FROM $wpdb->posts where post_status = 'publish' and post_type = 'page' order by post_title";
8064 $pages = $wpdb->get_results($sql);
8065 return $pages;
8066 }
8067
8068 public function bda_prepare_attachment_for_js( $response, $attachment, $meta ) {
8069
8070 $current_user = get_current_user_id();
8071 $attach_arr = $this->objectToArray($attachment);
8072 $blocked = get_post_meta($attach_arr['ID'], MLFP_BDA_MEDIA, true );
8073
8074 if($blocked == '1' && $current_user == $attach_arr['post_author'])
8075 $response['customClass'] = "mlfp-protected author";
8076 else if($blocked == '1')
8077 $response['customClass'] = "mlfp-protected";
8078 else
8079 $response['customClass'] = "";
8080
8081 return $response;
8082
8083 }
8084
8085 public function bda_add_class_to_media_library_grid_elements() {
8086
8087 $currentScreen = get_current_screen();
8088
8089 if('upload' === $currentScreen->id) :
8090
8091 global $mode;
8092
8093 wp_enqueue_script('jquery');
8094 wp_enqueue_script('bda-media', MAXGALLERIA_MEDIA_LIBRARY_PLUGIN_URL . '/js/bda-media.js', array('jquery'));
8095
8096 endif;
8097
8098 }
8099
8100 public function get_file_thumbnail($ext) {
8101 switch ($ext) {
8102
8103 case 'psd':
8104 $thumbnail = MAXGALLERIA_MEDIA_LIBRARY_PLUGIN_URL . "/images/file-types/psd.png";
8105 break;
8106
8107 // spread sheet
8108 case 'xlsx':
8109 case 'xlsm':
8110 case 'xlsb':
8111 case 'xltx':
8112 case 'xltm':
8113 case 'xlam':
8114 case 'ods':
8115 case 'numbers':
8116 $thumbnail = MAXGALLERIA_MEDIA_LIBRARY_PLUGIN_URL . "/images/file-types/xls.png";
8117 break;
8118
8119 // video formats
8120 case 'asf':
8121 case 'asx':
8122 case 'wmv':
8123 case 'wmx':
8124 case 'wm':
8125 case 'avi':
8126 case 'divx':
8127 case 'flv':
8128 case 'mov':
8129 case 'qt':
8130 case 'mpeg':
8131 case 'mpg':
8132 case 'mpe':
8133 case 'mp4':
8134 case 'm4v':
8135 case 'ogv':
8136 case 'webm':
8137 case 'mkv':
8138 $thumbnail = MAXGALLERIA_MEDIA_LIBRARY_PLUGIN_URL . "/images/file-types/video.png";
8139 break;
8140
8141 // text formats
8142 case 'txt':
8143 case 'asc':
8144 case 'c':
8145 case 'cc':
8146 case 'h':
8147 case 'js':
8148 case 'cpp':
8149 case 'csv':
8150 case 'tsv':
8151 case 'ics':
8152 case 'rtx':
8153 case 'css':
8154 case 'htm':
8155 case 'html':
8156 $thumbnail = MAXGALLERIA_MEDIA_LIBRARY_PLUGIN_URL . "/images/file-types/txt.png";
8157 break;
8158
8159 case 'mp3':
8160 case 'm4a':
8161 case 'm4b':
8162 case 'ra':
8163 case 'ram':
8164 case 'wav':
8165 case 'ogg':
8166 case 'oga':
8167 case 'mid':
8168 case 'midi':
8169 case 'wma':
8170 case 'wax':
8171 case 'mka':
8172 $thumbnail = MAXGALLERIA_MEDIA_LIBRARY_PLUGIN_URL . "/images/file-types/audio.png";
8173 break;
8174
8175 // archive formats
8176 case '7z':
8177 case 'rar':
8178 case 'gz':
8179 case 'gzip':
8180 case 'zip':
8181 case 'tar':
8182 case 'swf':
8183 case 'class':
8184 $thumbnail = MAXGALLERIA_MEDIA_LIBRARY_PLUGIN_URL . "/images/file-types/arch.png";
8185 break;
8186
8187 // doc files
8188 case 'doc':
8189 case 'odt':
8190 case 'rtf':
8191 case 'wri':
8192 case 'mdb':
8193 case 'mpp':
8194 case 'docx':
8195 case 'docm':
8196 case 'dotx':
8197 case 'dotm':
8198 case 'wp':
8199 case 'wpd':
8200 case 'pages':
8201 $thumbnail = MAXGALLERIA_MEDIA_LIBRARY_PLUGIN_URL . "/images/file-types/doc.png";
8202 break;
8203
8204 case 'pdf':
8205 $thumbnail = MAXGALLERIA_MEDIA_LIBRARY_PLUGIN_URL . "/images/file-types/pdf.png";
8206 break;
8207
8208 // power point
8209 case 'pptx':
8210 case 'pptm':
8211 case 'ppsx':
8212 case 'ppsm':
8213 case 'potx':
8214 case 'potm':
8215 case 'ppam':
8216 case 'sldx':
8217 case 'sldm':
8218 case 'odp':
8219 case 'key':
8220 $thumbnail = MAXGALLERIA_MEDIA_LIBRARY_PLUGIN_URL . "/images/file-types/ppt.png";
8221 break;
8222
8223 default:
8224 $thumbnail = MAXGALLERIA_MEDIA_LIBRARY_PLUGIN_URL . "/images/file-types/default.png";
8225 break;
8226
8227 }
8228 return $thumbnail;
8229 }
8230
8231 }
8232
8233 $mg_media_library_folders = new MGMediaLibraryFolders();
8234