PluginProbe
Media Library Folders / 8.3.8
Media Library Folders v8.3.8
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 8.3.8, at media-library-plus.php

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