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

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