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

7,560 lines 288.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.3
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.3');
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_PRO_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 search_media () {
3117
3118 global $wpdb;
3119
3120 if ( !wp_verify_nonce( $_POST['nonce'], MAXGALLERIA_MEDIA_LIBRARY_NONCE)) {
3121 exit(esc_html__('missing nonce! Please refresh this page.','maxgalleria-media-library'));
3122 }
3123
3124 // Check if the current user has the capability to upload files
3125 if(!current_user_can('upload_files')){
3126 exit(esc_html__('You do not have the capability to upload files.','maxgalleria-media-library'));
3127 }
3128
3129 if ((isset($_POST['search_value'])) && (strlen(trim($_POST['search_value'])) > 0))
3130 $search_value = trim(sanitize_text_field($_POST['search_value']));
3131 else
3132 $search_value = "";
3133
3134 // Use esc_sql to escape the 'search_value' parameter before using it in the SQL query
3135 $search_value = esc_sql($search_value);
3136
3137 $sql = $wpdb->prepare("select ID, post_title, post_name, pm.meta_value as attached_file from {$wpdb->prefix}posts
3138 LEFT JOIN {$wpdb->prefix}mgmlp_folders ON( {$wpdb->prefix}posts.ID = {$wpdb->prefix}mgmlp_folders.post_id)
3139 LEFT JOIN {$wpdb->prefix}postmeta AS pm ON (pm.post_id = {$wpdb->prefix}posts.ID)
3140 where post_type= 'attachment' and pm.meta_key = '_wp_attached_file' and post_title like '%%%s%%'", $search_value);
3141
3142 $rows = $wpdb->get_results($sql);
3143
3144 if($rows) {
3145 foreach($rows as $row) {
3146 $thumbnail = wp_get_attachment_thumb_url($row->ID);
3147 if($thumbnail !== false)
3148 $ext = pathinfo($thumbnail, PATHINFO_EXTENSION);
3149 else {
3150 $baseurl = $this->upload_dir['baseurl'];
3151 $baseurl = rtrim($baseurl, '/') . '/';
3152 $image_location = $baseurl . ltrim($row->attached_file, '/');
3153 $ext_pos = strrpos($image_location, '.');
3154 $ext = substr($image_location, $ext_pos+1);
3155 $thumbnail = MAXGALLERIA_MEDIA_LIBRARY_PLUGIN_URL . "/images/file.jpg";
3156 }
3157 // Use esc_html to escape the 'search_value' parameter before echoing it back to the user
3158 ?>
3159 <li>
3160 <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>
3161 <div class='attachment-name'><?php echo esc_html($row->post_title . '.' . $ext) ?></div>
3162 </li>
3163 <?php
3164 }
3165 }
3166 else {
3167 echo esc_html__('No files were found matching that name.','maxgalleria-media-library') . PHP_EOL;
3168 }
3169
3170 die();
3171 }
3172
3173 public function search_library() {
3174
3175 global $wpdb;
3176 $block_access_table = $wpdb->prefix . MAXGALLERIA_MEDIA_LIBRARY_BLOCK_ACCESS_TABLE;
3177 $current_user = get_current_user_id();
3178 $author_class = '';
3179
3180 if ((isset($_GET['s'])) && (strlen(trim($_GET['s'])) > 0))
3181 $search_string = esc_sql(trim(sanitize_text_field($_GET['s'])));
3182 else
3183 $search_string = '';
3184
3185 echo '<div id="wp-media-grid" class="wrap">' . PHP_EOL;
3186 //empty h2 for where WP notices will appear
3187 echo ' <h2></h2>' . PHP_EOL;
3188 echo ' <div class="media-plus-toolbar wp-filter">' . PHP_EOL;
3189 echo '<div id="mgmlp-title-area">' . PHP_EOL;
3190 echo ' <h2 class="mgmlp-title">'. __('Media Library Folders Search Results','maxgalleria-media-library') . '</h2>' . PHP_EOL;
3191 echo ' <div>' . PHP_EOL;
3192 echo ' <p><a href="' . site_url() . '/wp-admin/admin.php?page=mlf-folders8">Back to Media Library Folders</a></p>' . PHP_EOL;
3193 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;
3194 echo ' </div>' . PHP_EOL;
3195 echo '</div>' . PHP_EOL;
3196 echo '<div style="clear:both;"></div>' . PHP_EOL;
3197 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>";
3198 if ((isset($_GET['s'])) && (strlen(trim($_GET['s'])) > 0)) {
3199 echo "<h4>" . __('Search results for: ','maxgalleria-media-library') . esc_attr($search_string) ."</h4>" . PHP_EOL;
3200
3201 echo '<ul class="mg-media-list search-results">' . PHP_EOL;
3202
3203 $folder_table = $wpdb->prefix . MAXGALLERIA_MEDIA_LIBRARY_FOLDER_TABLE;
3204
3205 if($this->bda == 'on') {
3206
3207 $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
3208 from {$wpdb->prefix}posts
3209 LEFT JOIN {$wpdb->prefix}mgmlp_folders ON($wpdb->posts.ID = {$wpdb->prefix}mgmlp_folders.post_id)
3210 LEFT JOIN {$wpdb->prefix}postmeta AS pm ON (pm.post_id = {$wpdb->prefix}posts.ID)
3211 LEFT JOIN $wpdb->users AS us ON ({$wpdb->prefix}posts.post_author = us.ID)
3212 LEFT JOIN $block_access_table ON($block_access_table.attachment_id = {$wpdb->prefix}posts.ID)
3213 where post_type = 'mgmlp_media_folder' and pm.meta_key = '_wp_attached_file' and SUBSTRING_INDEX(pm.meta_value, '/', -1) like '%%%s%%')
3214 union all
3215 (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
3216 from $wpdb->posts
3217 LEFT JOIN {$wpdb->prefix}mgmlp_folders ON( $wpdb->posts.ID = {$wpdb->prefix}mgmlp_folders.post_id)
3218 LEFT JOIN {$wpdb->prefix}postmeta AS pm ON (pm.post_id = {$wpdb->prefix}posts.ID)
3219 LEFT JOIN $wpdb->users AS us ON ({$wpdb->prefix}posts.post_author = us.ID)
3220 LEFT JOIN $block_access_table ON($block_access_table.attachment_id = {$wpdb->prefix}posts.ID)
3221 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);
3222
3223 } else {
3224
3225 $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
3226 from {$wpdb->prefix}posts
3227 LEFT JOIN {$wpdb->prefix}mgmlp_folders ON($wpdb->posts.ID = {$wpdb->prefix}mgmlp_folders.post_id)
3228 LEFT JOIN {$wpdb->prefix}postmeta AS pm ON (pm.post_id = {$wpdb->prefix}posts.ID)
3229 LEFT JOIN $wpdb->users AS us ON ({$wpdb->prefix}posts.post_author = us.ID)
3230 where post_type = 'mgmlp_media_folder' and pm.meta_key = '_wp_attached_file' and SUBSTRING_INDEX(pm.meta_value, '/', -1) like '%%%s%%')
3231 union all
3232 (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
3233 from $wpdb->posts
3234 LEFT JOIN {$wpdb->prefix}mgmlp_folders ON( $wpdb->posts.ID = {$wpdb->prefix}mgmlp_folders.post_id)
3235 LEFT JOIN {$wpdb->prefix}postmeta AS pm ON (pm.post_id = {$wpdb->prefix}posts.ID)
3236 LEFT JOIN $wpdb->users AS us ON ({$wpdb->prefix}posts.post_author = us.ID)
3237 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);
3238
3239 }
3240
3241 //error_log("grid " . $sql);
3242
3243 $rows = $wpdb->get_results($sql);
3244
3245 if($rows) {
3246 foreach($rows as $row) {
3247
3248 if($row->item_type == 'a')
3249 $class = "media-folder";
3250 else
3251 $class = "media-attachment";
3252
3253 $thumbnail = wp_get_attachment_thumb_url($row->ID);
3254 if($this->bda == 'on' && $row->block == 1) {
3255 $thumbnail = $this->get_absolute_path($thumbnail);
3256 if($this->bda_user_role == 'authors' && $current_user == $row->post_author)
3257 $author_class = 'author';
3258 else
3259 $author_class = '';
3260 }
3261 if($thumbnail !== false)
3262 $ext = pathinfo($thumbnail, PATHINFO_EXTENSION);
3263 else {
3264
3265 //$image_location = $this->upload_dir['baseurl'] . '/' . $row->attached_file;
3266 $baseurl = $this->upload_dir['baseurl'];
3267 $baseurl = rtrim($baseurl, '/') . '/';
3268 $image_location = $baseurl . ltrim($row->attached_file, '/');
3269
3270 $ext_pos = strrpos($image_location, '.');
3271 $ext = substr($image_location, $ext_pos+1);
3272 if($row->item_type == 'b')
3273 $thumbnail = MAXGALLERIA_MEDIA_LIBRARY_PLUGIN_URL . "/images/file.jpg";
3274 else
3275 $thumbnail = MAXGALLERIA_MEDIA_LIBRARY_PLUGIN_URL . "/images/folder.jpg";
3276 }
3277
3278 echo "<li>" . PHP_EOL;
3279 if($row->item_type == 'a') {
3280 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;
3281 } else {
3282 if($row->block == 1) {
3283 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;
3284 } else {
3285 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;
3286 }
3287 }
3288 echo " <div class='attachment-name'>$row->post_title</div>" . PHP_EOL;
3289 echo "</li>" . PHP_EOL;
3290
3291 }
3292 }
3293
3294 echo "</ul>" . PHP_EOL;
3295 }
3296 echo '</div>' . PHP_EOL;
3297
3298 ?>
3299
3300 <script>
3301 jQuery(document).ready(function(){
3302 console.log('document ready');
3303 jQuery('#mgmlp-media-search-input').keydown(function (e){
3304 if(e.keyCode == 13){
3305
3306 var search_value = jQuery('#mgmlp-media-search-input').val();
3307
3308 var home_url = "<?php echo site_url(); ?>";
3309
3310 window.location.href = home_url + '/wp-admin/admin.php?page=search-library&' + 's=' + search_value;
3311
3312 }
3313 });
3314
3315 jQuery(document).on("click", "#mlfp-media-search-2", function () {
3316
3317 var search_value = jQuery('#mgmlp-media-search-input').val();
3318
3319 var home_url = "<?php echo site_url(); ?>";
3320
3321 window.location.href = home_url + '/wp-admin/admin.php?page=search-library&' + 's=' + search_value;
3322 });
3323
3324 <?php if($this->bda == 'on') { ?>
3325
3326 console.log('bda_user_role', mgmlp_ajax.bda_user_role);
3327 if(mgmlp_ajax.bda_user_role == 'authors')
3328 var selector_class = '.mlfp-protected.author';
3329 else
3330 var selector_class = '.mlfp-protected';
3331
3332 jQuery(selector_class).each(function () {
3333
3334 var image_element = jQuery(this).find('img.attachment-thumbnail');
3335 var src = image_element.attr('src');
3336 // remove the source URL and avoid the 404 error
3337 jQuery(image_element).attr('src', '');
3338 console.log('src', src);
3339
3340 jQuery.ajax({
3341 type: 'POST',
3342 async: true,
3343 data: { action: 'mlfp_load_image', src: src, nonce: mgmlp_ajax.nonce },
3344 url: mgmlp_ajax.ajaxurl,
3345 success: function (data) {
3346 if(data.length > 0)
3347 jQuery(image_element).attr('src', data);
3348 },
3349 error: function (err){
3350 alert(err.responseText);
3351 }
3352 });
3353
3354 });
3355 <?php } ?>
3356 });
3357 </script>
3358 <?php
3359 }
3360
3361 public function maxgalleria_rename_image() {
3362
3363 global $wpdb, $blog_id, $is_IIS;
3364
3365 if ( !wp_verify_nonce( $_POST['nonce'], MAXGALLERIA_MEDIA_LIBRARY_NONCE)) {
3366 exit(esc_html__('missing nonce! Please refresh this page.','maxgalleria-media-library'));
3367 }
3368
3369 // Check if the current user has the capability to upload files
3370 if(!current_user_can('upload_files')){
3371 exit(esc_html__('You do not have the capability to upload files.','maxgalleria-media-library'));
3372 }
3373
3374 if ((isset($_POST['image_id'])) && (strlen(trim($_POST['image_id'])) > 0))
3375 $file_id = intval(trim(sanitize_text_field($_POST['image_id'])));
3376 else
3377 $file_id = "";
3378
3379 if ((isset($_POST['new_file_name'])) && (strlen(trim($_POST['new_file_name'])) > 0))
3380 $new_file_name = trim(sanitize_text_field($_POST['new_file_name']));
3381 else
3382 $new_file_name = "";
3383
3384 if($new_file_name === '') {
3385 echo esc_html__('Invalid file name.','maxgalleria-media-library');
3386 die();
3387 }
3388
3389 if(preg_match('^[\w,\s\-_]+\.[A-Za-z]{3}$^', $new_file_name)) {
3390 echo esc_html__('Invalid file name.','maxgalleria-media-library');
3391 die();
3392 }
3393
3394 if (preg_match("/\\s/", $new_file_name)) {
3395 echo esc_html__('The file name cannot contain spaces or tabs.','maxgalleria-media-library');
3396 die();
3397 }
3398
3399 $new_file_name = sanitize_file_name($new_file_name);
3400
3401 $sql = $wpdb->prepare("select ID, pm.meta_value as attached_file, post_title, post_name
3402 from {$wpdb->prefix}posts
3403 LEFT JOIN {$wpdb->prefix}postmeta AS pm ON (pm.post_id = {$wpdb->prefix}posts.ID)
3404 where ID = %s
3405 AND pm.meta_key = '_wp_attached_file'", $file_id);
3406
3407 $row = $wpdb->get_row($sql);
3408
3409 if (empty($row)) {
3410 echo esc_html__('The file does not exist on this site.', 'maxgalleria-media-library');
3411 die();
3412 }
3413
3414 if($row) {
3415
3416 $image_location = $this->build_location_url($row->attached_file);
3417
3418 $alt_text = get_post_meta($file_id, '_wp_attachment_image_alt', true);
3419
3420 $full_new_file_name = $new_file_name . '.' . pathinfo($image_location, PATHINFO_EXTENSION);
3421 $destination_path = $this->get_absolute_path(pathinfo($image_location, PATHINFO_DIRNAME));
3422
3423 $new_file_name = wp_unique_filename( $destination_path, $full_new_file_name, null );
3424
3425 $new_file_title = $this->remove_extension($new_file_name);
3426
3427 $old_file_path = $this->get_absolute_path($image_location);
3428
3429 $new_file_url = pathinfo($image_location, PATHINFO_DIRNAME) . DIRECTORY_SEPARATOR . $new_file_name;
3430
3431 if(is_multisite()) {
3432 $url_slug = "site" . $blog_id . "/";
3433 $new_file_url = str_replace($url_slug, "", $new_file_url);
3434 }
3435
3436 $new_file_path = $this->get_absolute_path($new_file_url);
3437
3438 if($this->is_windows()) {
3439 $old_file_path = str_replace('\\', '/', $old_file_path);
3440 $new_file_path = str_replace('\\', '/', $new_file_path);
3441 }
3442
3443 $rename_image_location = $this->get_base_file($image_location);
3444 $rename_destination = $this->get_base_file($new_file_url);
3445
3446 $position = strrpos($image_location, '.');
3447
3448 $image_location_no_extension = substr($image_location, 0, $position);
3449
3450 if(rename($old_file_path, $new_file_path )) {
3451
3452 //$old_file_path = str_replace('.', '*.', $old_file_path );
3453
3454 $metadata = wp_get_attachment_metadata($file_id);
3455 $path_to_thumbnails = pathinfo($old_file_path, PATHINFO_DIRNAME);
3456
3457 foreach($metadata['sizes'] as $source_path) {
3458 $thumbnail_file = $path_to_thumbnails . DIRECTORY_SEPARATOR . $source_path['file'];
3459
3460 if ($is_IIS || strtoupper(substr(PHP_OS, 0, 3)) == 'WIN' || strtoupper(substr(PHP_OS, 0, 13)) == 'MICROSOFT-IIS' )
3461 $thumbnail_file = str_replace('/', '\\', $thumbnail_file);
3462
3463 if(file_exists($thumbnail_file))
3464 unlink($thumbnail_file);
3465 }
3466
3467 $table = $wpdb->prefix . "posts";
3468 $data = array('guid' => $new_file_url,
3469 'post_title' => $new_file_title,
3470 'post_name' => $new_file_name
3471 );
3472 $where = array('ID' => $file_id);
3473 $wpdb->update( $table, $data, $where);
3474
3475 $table = $wpdb->prefix . "postmeta";
3476 $where = array('post_id' => $file_id);
3477 $wpdb->delete($table, $where);
3478
3479 // get the uploads dir name
3480 $basedir = $this->upload_dir['baseurl'];
3481 $uploads_dir_name_pos = strrpos($basedir, '/');
3482 $uploads_dir_name = substr($basedir, $uploads_dir_name_pos+1);
3483
3484 //find the name and cut off the part with the uploads path
3485 $string_position = strpos($new_file_url, $uploads_dir_name);
3486 $uploads_dir_length = strlen($uploads_dir_name) + 1;
3487 $uploads_location = substr($new_file_url, $string_position+$uploads_dir_length);
3488 if($this->is_windows())
3489 $uploads_location = str_replace('\\','/', $uploads_location);
3490
3491 $uploads_location = ltrim($uploads_location, '/');
3492 update_post_meta( $file_id, '_wp_attached_file', $uploads_location );
3493 if(strlen(trim($alt_text)) > 0)
3494 update_post_meta( $file_id, '_wp_attachment_image_alt', $alt_text );
3495 $attach_data = wp_generate_attachment_metadata( $file_id, $new_file_path );
3496 wp_update_attachment_metadata( $file_id, $attach_data );
3497
3498 if(class_exists( 'SiteOrigin_Panels')) {
3499 $this->update_serial_postmeta_records($rename_image_location, $rename_destination);
3500 }
3501
3502 // update postmeta records for beaver builder
3503 if(class_exists( 'FLBuilderLoader')) {
3504
3505 $sql = "SELECT ID FROM {$wpdb->prefix}posts WHERE post_content LIKE '%$rename_image_location%'";
3506
3507 $records = $wpdb->get_results($sql);
3508 foreach($records as $record) {
3509
3510 $this->update_bb_postmeta($record->ID, $rename_image_location, $rename_destination);
3511
3512 }
3513 // clearing BB caches
3514 if ( class_exists( 'FLBuilderModel' ) && method_exists( 'FLBuilderModel', 'delete_asset_cache_for_all_posts' ) ) {
3515 FLBuilderModel::delete_asset_cache_for_all_posts();
3516 }
3517 if ( class_exists( 'FLCustomizer' ) && method_exists( 'FLCustomizer', 'clear_all_css_cache' ) ) {
3518 FLCustomizer::clear_all_css_cache();
3519 }
3520
3521 }
3522
3523 $replace_sql = "UPDATE {$wpdb->prefix}posts SET `post_content` = REPLACE (`post_content`, '$rename_image_location', '$rename_destination');";
3524
3525 $replace_sql = str_replace ( '/', '\/', $replace_sql);
3526 $result = $wpdb->query($replace_sql);
3527
3528 // for updating wp pagebuilder
3529 if(defined('WPPB_LICENSE')) {
3530 $this->update_wppb_data($image_location_no_extension, $new_file_url);
3531 }
3532
3533 // for updating themify images
3534 if(function_exists('themify_builder_activate')) {
3535 $this->update_themify_data($image_location_no_extension, $new_file_url);
3536 }
3537
3538 // for updating elementor background images
3539 if(is_plugin_active("elementor/elementor.php")) {
3540 $this->update_elementor_data($file_id, $image_location_no_extension, $new_file_url);
3541 }
3542
3543 echo esc_html__('Updating attachment links, please wait...The file was renamed','maxgalleria-media-library');
3544 }
3545 }
3546
3547 die();
3548 }
3549
3550 public function build_location_url($attached_file) {
3551 return rtrim($this->upload_dir['baseurl'], '/') . '/' . ltrim($attached_file, '/');
3552 }
3553
3554 // saves the sort selection
3555 public function sort_contents() {
3556
3557 if ( !wp_verify_nonce( $_POST['nonce'], MAXGALLERIA_MEDIA_LIBRARY_NONCE)) {
3558 exit(esc_html__('missing nonce!','maxgalleria-media-library'));
3559 }
3560
3561 // Check if the current user has the capability to upload files
3562 if(!current_user_can('upload_files')){
3563 exit(esc_html__('You do not have the capability to upload files.','maxgalleria-media-library'));
3564 }
3565
3566 if ((isset($_POST['sort_order'])) && (strlen(trim($_POST['sort_order'])) > 0))
3567 $sort_order = trim(sanitize_text_field($_POST['sort_order']));
3568 else
3569 $sort_order = "0";
3570
3571 if ((isset($_POST['folder'])) && (strlen(trim($_POST['folder'])) > 0))
3572 $current_folder_id = intval(trim(sanitize_text_field($_POST['folder'])));
3573 else
3574 $current_folder_id = "";
3575
3576 update_option( MAXGALLERIA_MEDIA_LIBRARY_SORT_ORDER, $sort_order );
3577
3578 if($current_folder_id != "") {
3579 $this->display_folder_contents ($current_folder_id, true);
3580 }
3581
3582 die();
3583 }
3584
3585 public function mlf_change_sort_type() {
3586
3587 if ( !wp_verify_nonce( $_POST['nonce'], MAXGALLERIA_MEDIA_LIBRARY_NONCE)) {
3588 exit(esc_html__('missing nonce!','maxgalleria-media-library'));
3589 }
3590
3591 // Check if the current user has the capability to upload files
3592 if(!current_user_can('upload_files')){
3593 exit(esc_html__('You do not have the capability to upload files.','maxgalleria-media-library'));
3594 }
3595
3596 if ((isset($_POST['sort_type'])) && (strlen(trim($_POST['sort_type'])) > 0))
3597 $sort_type = $this->validate_sort_type(trim(sanitize_text_field($_POST['sort_type'])));
3598 else
3599 $sort_type = "ASC";
3600
3601 if ((isset($_POST['folder'])) && (strlen(trim($_POST['folder'])) > 0))
3602 $current_folder_id = intval(trim(sanitize_text_field($_POST['folder'])));
3603 else
3604 $current_folder_id = "";
3605
3606 update_option( MAXGALLERIA_MLF_SORT_TYPE, $sort_type );
3607
3608 if($current_folder_id != "") {
3609 $this->display_folder_contents ($current_folder_id, true);
3610 }
3611
3612 die();
3613 }
3614
3615 // Validate the sort type to ensure it is either "ASC" or "DESC".
3616 public function validate_sort_type($sort_type) {
3617 $allowed_sort_types = array('ASC', 'DESC');
3618 return in_array($sort_type, $allowed_sort_types) ? $sort_type : 'ASC';
3619 }
3620
3621 public function mgmlp_move_copy(){
3622
3623 if ( !wp_verify_nonce( $_POST['nonce'], MAXGALLERIA_MEDIA_LIBRARY_NONCE)) {
3624 exit(esc_html__('missing nonce! Please refresh this page.','maxgalleria-media-library'));
3625 }
3626
3627 // Check if the current user has the capability to upload files
3628 if(!current_user_can('upload_files')){
3629 exit(esc_html__('You do not have the capability to upload files.','maxgalleria-media-library'));
3630 }
3631
3632 if ((isset($_POST['move_copy_switch'])) && (strlen(trim($_POST['move_copy_switch'])) > 0))
3633 $move_copy_switch = trim(sanitize_text_field($_POST['move_copy_switch']));
3634 else
3635 $move_copy_switch = 'on';
3636
3637 update_option( MAXGALLERIA_MEDIA_LIBRARY_MOVE_OR_COPY, $move_copy_switch );
3638
3639 die();
3640
3641 }
3642
3643 public function run_on_deactivate() {
3644 wp_clear_scheduled_hook('new_folder_check');
3645 }
3646
3647 public function mlf_check_for_new_folders(){
3648
3649 if ( !wp_verify_nonce( $_POST['nonce'], MAXGALLERIA_MEDIA_LIBRARY_NONCE)) {
3650 exit(esc_html__('missing nonce!','maxgalleria-media-library'));
3651 }
3652
3653 // Check if the current user has the capability to upload files
3654 if(!current_user_can('upload_files')){
3655 exit(esc_html__('You do not have the capability to upload files.','maxgalleria-media-library'));
3656 }
3657
3658 if ((isset($_POST['parent_folder'])) && (strlen(trim($_POST['parent_folder'])) > 0))
3659 $parent_folder_id = intval(trim(sanitize_text_field($_POST['parent_folder'])));
3660
3661 //error_log("parent_folder_id $parent_folder_id");
3662
3663 $message = $this->admin_check_for_new_folders(true);
3664
3665 $folders = $this->get_folder_data($parent_folder_id);
3666 $data = array ('message' => esc_html($message), 'folders' => $folders, 'refresh' => true );
3667 echo json_encode($data);
3668
3669 die();
3670
3671 }
3672
3673 public function admin_check_for_new_folders($noecho = null) {
3674
3675 global $blog_id, $is_IIS;
3676 $skip_path = "";
3677 //$uploads_path = wp_upload_dir();
3678 $message = esc_html__('Added','maxgalleria-media-library');
3679 $first = true;
3680
3681 if(!$this->upload_dir['error']) {
3682
3683 $uploads_folder = get_option(MAXGALLERIA_MEDIA_LIBRARY_UPLOAD_FOLDER_NAME, "uploads");
3684 $uploads_folder_id = get_option(MAXGALLERIA_MEDIA_LIBRARY_UPLOAD_FOLDER_ID );
3685 $uploads_length = strlen($uploads_folder);
3686
3687 $folders_to_hide = explode("\n", file_get_contents( MAXGALLERIA_MEDIA_LIBRARY_PLUGIN_DIR .'/folders_to_hide.txt'));
3688
3689 //find the uploads folder
3690 $uploads_url = $this->upload_dir['baseurl'];
3691 $upload_path = $this->upload_dir['basedir'];
3692 $folder_found = false;
3693
3694 //not sure if this is still needed
3695 //$this->mlp_remove_slashes();
3696
3697 if(!$noecho)
3698 echo esc_html( __('Scanning for new folders in ','maxgalleria-media-library') . " $upload_path") . "<br>";
3699 $objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($upload_path), RecursiveIteratorIterator::SELF_FIRST, RecursiveIteratorIterator::CATCH_GET_CHILD);
3700 foreach($objects as $name => $object){
3701 if(is_dir($name)) {
3702 $dir_name = pathinfo($name, PATHINFO_BASENAME);
3703 if ($dir_name[0] !== '.' && strpos($dir_name, "'") === false ) {
3704 if( empty($skip_path) || (strpos($name, $skip_path) === false)) {
3705
3706 // no match, set it back to empty
3707 $skip_path = "";
3708
3709 if(!is_multisite()) {
3710 $upload_pos = strpos($name, $uploads_folder);
3711 $url = $uploads_url . substr($name, ($upload_pos+$uploads_length));
3712
3713 // fix slashes if running windows
3714 if ($is_IIS || strtoupper(substr(PHP_OS, 0, 3)) == 'WIN' || strtoupper(substr(PHP_OS, 0, 13)) == 'MICROSOFT-IIS' ) {
3715 $url = str_replace('\\', '/', $url);
3716 }
3717
3718 if($this->folder_exist($url) === false) {
3719 if(!in_array($dir_name, $folders_to_hide)) {
3720 if(!file_exists($name . DIRECTORY_SEPARATOR . 'mlpp-hidden' )){
3721 $folder_found = true;
3722 if(!$noecho)
3723 echo esc_html( __('Adding','maxgalleria-media-library') . " " . esc_url($url)) . "<br>";
3724 else {
3725 $seprator = ($first) ? ' ':', ';
3726 $first = false;
3727 $message .= $seprator . esc_url($url);
3728 }
3729 $parent_id = $this->find_parent_id($url);
3730 if($parent_id)
3731 $this->add_media_folder($dir_name, $parent_id, $url);
3732 } else {
3733 $skip_path = $name;
3734 }
3735 } else {
3736 $skip_path = $name;
3737 }
3738 }
3739 } else {
3740 if($blog_id === '1') {
3741 if(strpos($name,"uploads/sites") !== false)
3742 continue;
3743
3744 $upload_pos = strpos($name, $uploads_folder);
3745 $url = $uploads_url . substr($name, ($upload_pos+$uploads_length));
3746
3747 // fix slashes if running windows
3748 if ($is_IIS || strtoupper(substr(PHP_OS, 0, 3)) == 'WIN' || strtoupper(substr(PHP_OS, 0, 13)) == 'MICROSOFT-IIS' ) {
3749 $url = str_replace('\\', '/', $url);
3750 }
3751
3752 if($this->folder_exist($url) === false) {
3753 if(!in_array($dir_name, $folders_to_hide)) {
3754 if(!file_exists($name . DIRECTORY_SEPARATOR . 'mlpp-hidden' )){
3755 $folder_found = true;
3756 if(!$noecho)
3757 echo esc_html( __('Adding','maxgalleria-media-library') . " " . esc_url($url)) . "<br>";
3758 else {
3759 $seprator = ($first) ? ' ':', ';
3760 $first = false;
3761 $message .= $seprator . esc_url($url);
3762 }
3763 $parent_id = $this->find_parent_id($url);
3764 if($parent_id)
3765 $this->add_media_folder($dir_name, $parent_id, $url);
3766 } else {
3767 $skip_path = $name;
3768 }
3769 } else {
3770 $skip_path = $name;
3771 }
3772 }
3773 } else {
3774 if(strpos($name,"uploads/sites/$blog_id") !== false) {
3775 $upload_pos = strpos($name, $uploads_folder);
3776 $url = $uploads_url . substr($name, ($upload_pos+$uploads_length));
3777
3778 // fix slashes if running windows
3779 if ($is_IIS || strtoupper(substr(PHP_OS, 0, 3)) == 'WIN' || strtoupper(substr(PHP_OS, 0, 13)) == 'MICROSOFT-IIS' ) {
3780 $url = str_replace('\\', '/', $url);
3781 }
3782
3783 if($this->folder_exist($url) === false) {
3784 if(!in_array($dir_name, $folders_to_hide)) {
3785 if(!file_exists($name . DIRECTORY_SEPARATOR . 'mlpp-hidden' )){
3786 $folder_found = true;
3787 if(!$noecho)
3788 echo esc_html( __('Adding','maxgalleria-media-library') . " " . esc_url($url)) . "<br>";
3789 else {
3790 $seprator = ($first) ? ' ':', ';
3791 $first = false;
3792 $message .= $seprator . esc_url($url);
3793 }
3794 $parent_id = $this->find_parent_id($url);
3795 if($parent_id)
3796 $this->add_media_folder($dir_name, $parent_id, $url);
3797 }
3798 } else {
3799 $skip_path = $name;
3800 }
3801 }
3802 }
3803 }
3804 }
3805 }
3806 }
3807 }
3808 }
3809 if(!$folder_found) {
3810 $message = esc_html__('No new folders were found.','maxgalleria-media-library');
3811 if(!$noecho)
3812 echo $message . "<br>";
3813 }
3814 }
3815 else {
3816 $message = esc_html("error: " . $this->upload_dir['error']);
3817 if(!$noecho)
3818 echo $message . "<br>";
3819 }
3820 return $message;
3821 }
3822
3823 private function find_parent_id($base_url) {
3824
3825 global $wpdb;
3826 $last_slash = strrpos($base_url, '/');
3827 $parent_dir = substr($base_url, 0, $last_slash);
3828
3829 // get the relative path
3830 $parent_dir = substr($parent_dir, $this->base_url_length);
3831
3832 $sql = "SELECT ID FROM {$wpdb->prefix}posts
3833 LEFT JOIN {$wpdb->prefix}postmeta AS pm ON pm.post_id = ID
3834 WHERE pm.meta_value = '$parent_dir'
3835 and pm.meta_key = '_wp_attached_file'";
3836
3837 $row = $wpdb->get_row($sql);
3838 if($row) {
3839 $parent_id = $row->ID;
3840 }
3841 else
3842 $parent_id = $this->uploads_folder_ID; //-1;
3843
3844 return $parent_id;
3845 }
3846
3847 private function mpmlp_insert_post( $post_type, $post_title, $guid, $post_status ) {
3848 global $wpdb;
3849
3850 $user_id = get_current_user_id();
3851 $post_date = current_time('mysql');
3852
3853 $post = array(
3854 'post_content' => '',
3855 'post_name' => $post_title,
3856 'post_title' => $post_title,
3857 'post_status' => $post_status,
3858 'post_type' => $post_type,
3859 'post_author' => $user_id,
3860 'ping_status' => 'closed',
3861 'post_parent' => 0,
3862 'menu_order' => 0,
3863 'to_ping' => '',
3864 'pinged' => '',
3865 'post_password' => '',
3866 'guid' => $guid,
3867 'post_content_filtered' => '',
3868 'post_excerpt' => '',
3869 'post_date' => $post_date,
3870 'post_date_gmt' => $post_date,
3871 'comment_status' => 'closed'
3872 );
3873
3874
3875 $table = $wpdb->prefix . "posts";
3876 $wpdb->insert( $table, $post );
3877
3878 return $wpdb->insert_id;
3879 }
3880
3881 public function mlp_set_review_notice_true() {
3882
3883 $current_user_id = get_current_user_id();
3884
3885 update_user_meta( $current_user_id, MAXGALLERIA_MLP_REVIEW_NOTICE, "off" );
3886
3887 $request = sanitize_url($_SERVER["HTTP_REFERER"]);
3888
3889 echo "<script>window.location.href = '" . esc_url_raw($request) . "'</script>";
3890
3891
3892 }
3893
3894 public function mlp_set_feature_notice_true() {
3895
3896 $current_user_id = get_current_user_id();
3897
3898 update_user_meta( $current_user_id, MAXGALLERIA_MLP_FEATURE_NOTICE, "off" );
3899
3900 $request = sanitize_url($_SERVER["HTTP_REFERER"]);
3901
3902 echo "<script>window.location.href = '" . esc_url_raw($request) . "'</script>";
3903
3904 }
3905
3906 public function mlp_set_review_later() {
3907
3908 $current_user_id = get_current_user_id();
3909
3910 $review_date = date('Y-m-d', strtotime("+14 days"));
3911
3912 update_user_meta( $current_user_id, MAXGALLERIA_MLP_REVIEW_NOTICE, $review_date );
3913
3914 $request = sanitize_url($_SERVER["HTTP_REFERER"]);
3915
3916 echo "<script>window.location.href = '" . esc_url_raw($request) . "'</script>";
3917
3918 }
3919
3920 public function mlp_features_notice() {
3921 if( current_user_can( 'upload_files' ) ) { ?>
3922 <div class="updated notice maxgalleria-mlp-notice">
3923 <div id='mlp_logo'></div>
3924 <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>
3925 <p><?php esc_html_e('Send your suggestions to', 'maxgalleria-media-library' ); ?> <a href="mailto:support@maxfoundry.com">support@maxfoundry.com</a>.</p>
3926
3927 </div>
3928 <a class="dashicons dashicons-dismiss close-mlp-notice" href="<?php echo esc_url_raw(admin_url() . "admin.php?page=mlp-feature-notice") ?>"></a>
3929 </div>
3930 <?php
3931 }
3932 }
3933
3934 public function mlp_review_notice() {
3935 if( current_user_can( 'upload_files' ) ) { ?>
3936 <div class="updated notice maxgalleria-mlp-notice">
3937 <div id='mlp_logo'></div>
3938 <div id='maxgalleria-mlp-notice-3'><p id='mlp-notice-title'><?php esc_html_e( 'Rate us Please!', 'maxgalleria-media-library' ); ?></p>
3939 <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>
3940
3941 <ul id="mlp-review-notice-links">
3942 <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>
3943 <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>
3944 <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>
3945 </ul>
3946 </div>
3947 <a class="dashicons dashicons-dismiss close-mlp-notice" href="<?php echo esc_url_raw( admin_url() . "admin.php?page=mlp-review-notice") ?>"></a>
3948 </div>
3949 <?php
3950 }
3951 }
3952
3953 public function max_sync_contents($parent_folder) {
3954
3955 global $wpdb;
3956 global $blog_id;
3957 global $is_IIS;
3958 $skip_path = "";
3959 $last_new_folder_id = 0;
3960
3961 $files_added = 0;
3962 $alt_text = "";
3963 $default_title = "";
3964 $default_alt = "";
3965 $folders_found = false;
3966 $existing_folders = false;
3967
3968 if(!is_numeric($parent_folder))
3969 die();
3970
3971 $uploads_folder = get_option(MAXGALLERIA_MEDIA_LIBRARY_UPLOAD_FOLDER_NAME, "uploads");
3972 $uploads_length = strlen($uploads_folder);
3973 $uploads_url = $this->upload_dir['baseurl'];
3974 $upload_path = $this->upload_dir['basedir'];
3975
3976 $folders_to_hide = explode("\n", file_get_contents(MAXGALLERIA_MEDIA_LIBRARY_PLUGIN_DIR .'/folders_to_hide.txt'));
3977
3978 $sql = "select meta_value as attached_file
3979 from {$wpdb->prefix}postmeta
3980 where post_id = $parent_folder
3981 and meta_key = '_wp_attached_file'";
3982
3983 $current_row = $wpdb->get_row($sql);
3984
3985 $baseurl = rtrim($uploads_url, '/') . '/';
3986
3987 if(!is_multisite()) {
3988 $image_location = $baseurl . ltrim($current_row->attached_file, '/');
3989 $folder_path = $this->get_absolute_path($image_location);
3990 } else {
3991 $folder_path = $this->get_absolute_path($baseurl);
3992 }
3993
3994 //not sure if this is still needed
3995 //$this->mlp_remove_slashes();
3996
3997 $folders_array = array();
3998 $folders_array[] = $parent_folder;
3999
4000 $file_names = array_diff(scandir($folder_path), array('..', '.'));
4001
4002 // check for new folders
4003 foreach ($file_names as $file_name) {
4004 $name = $folder_path . DIRECTORY_SEPARATOR . $file_name;
4005 if(is_dir($name)) {
4006 //error_log($name);
4007 $dir_name = pathinfo($name, PATHINFO_BASENAME);
4008 if ($dir_name[0] !== '.' && strpos($dir_name, "'") === false ) {
4009 if( empty($skip_path) || (strpos($name, $skip_path) === false)) {
4010
4011 // no match, set it back to empty
4012 $skip_path = "";
4013
4014 if(!is_multisite()) {
4015
4016 $upload_pos = strpos($name, $uploads_folder);
4017 $url = $uploads_url . substr($name, ($upload_pos+$uploads_length));
4018
4019 // fix slashes if running windows
4020 if ($is_IIS || strtoupper(substr(PHP_OS, 0, 3)) == 'WIN' || strtoupper(substr(PHP_OS, 0, 13)) == 'MICROSOFT-IIS' ) {
4021 $url = str_replace('\\', '/', $url);
4022 }
4023
4024 $existing_folder_id = $this->folder_exist($url);
4025 if($existing_folder_id === false) {
4026 if(!in_array($dir_name, $folders_to_hide)) {
4027 if(!file_exists($name . DIRECTORY_SEPARATOR . 'mlpp-hidden' )){
4028 $folders_found = true;
4029 $parent_id = $this->find_parent_id($url);
4030 $last_new_folder_id = $this->add_media_folder($dir_name, $parent_id, $url);
4031 $files_added++;
4032 } else {
4033 $skip_path = $name;
4034 }
4035 } else {
4036 $skip_path = $name;
4037 }
4038 } else {
4039 $existing_folders = true;
4040 }
4041 } else {
4042 if($blog_id === '1') {
4043 if(strpos($name,"uploads/sites") !== false)
4044 continue;
4045
4046 $upload_pos = strpos($name, $uploads_folder);
4047 $url = $uploads_url . substr($name, ($upload_pos+$uploads_length));
4048
4049 // fix slashes if running windows
4050 if ($is_IIS || strtoupper(substr(PHP_OS, 0, 3)) == 'WIN' || strtoupper(substr(PHP_OS, 0, 13)) == 'MICROSOFT-IIS' ) {
4051 $url = str_replace('\\', '/', $url);
4052 }
4053
4054 $existing_folder_id = $this->folder_exist($url);
4055 if($existing_folder_id === false) {
4056 if(!in_array($dir_name, $folders_to_hide)) {
4057 if(!file_exists($name . DIRECTORY_SEPARATOR . 'mlpp-hidden' )){
4058 $folders_found = true;
4059 $parent_id = $this->find_parent_id($url);
4060 $last_new_folder_id = $this->add_media_folder($dir_name, $parent_id, $url);
4061 $files_added++;
4062 } else {
4063 $skip_path = $name;
4064 }
4065 } else {
4066 $skip_path = $name;
4067 }
4068 } else {
4069 $existing_folders = true;
4070 }
4071 } else {
4072 if(strpos($name,"uploads/sites/$blog_id") !== false) {
4073
4074 $upload_pos = strpos($name, $uploads_folder);
4075
4076 $url = $uploads_url . substr($name, ($upload_pos+$uploads_length));
4077
4078 // fix slashes if running windows
4079 if ($is_IIS || strtoupper(substr(PHP_OS, 0, 3)) == 'WIN' || strtoupper(substr(PHP_OS, 0, 13)) == 'MICROSOFT-IIS' ) {
4080 $url = str_replace('\\', '/', $url);
4081 }
4082 $existing_folder_id = $this->folder_exist($url);
4083 if($existing_folder_id === false) {
4084 $folders_found = true;
4085 $parent_id = $this->find_parent_id($url);
4086 $last_new_folder_id = $this->add_media_folder($dir_name, $parent_id, $url);
4087 $files_added++;
4088 } else {
4089 $existing_folders = true;
4090 }
4091 }
4092 }
4093 }
4094 }
4095 }
4096 }
4097 } // end foreach
4098
4099 $user_id = get_current_user_id();
4100 update_user_meta($user_id, MAXG_SYNC_FOLDERS, $folders_array);
4101
4102 if($folders_found || $existing_folders) {
4103 return true;
4104 } else {
4105 return false;
4106 }
4107
4108 }
4109
4110 public function get_base_file($file_path) {
4111
4112 $dot_position = strrpos($file_path, '.' );
4113 if($dot_position === false)
4114 return $file_path;
4115 else
4116 return substr($file_path, 0, $dot_position);
4117 }
4118
4119 private function is_base_file($file_path, $file_array) {
4120
4121 $dash_position = strrpos($file_path, '-' );
4122 $x_position = strrpos($file_path, 'x', $dash_position);
4123 $dot_position = strrpos($file_path, '.' );
4124
4125 if(($dash_position) && ($x_position)) {
4126 $base_file = substr($file_path, 0, $dash_position) . substr($file_path, $dot_position );
4127 if(in_array($base_file, $file_array))
4128 return false;
4129 else
4130 return true;
4131 } else
4132 return true;
4133
4134 }
4135
4136 private function search_folder_attachments($file_path, $attachments){
4137
4138 $found = false;
4139 if($attachments) {
4140 foreach($attachments as $row) {
4141 $current_file_path = pathinfo(get_attached_file($row->ID), PATHINFO_BASENAME);
4142 if(strpos($current_file_path, '-scaled.') !== false)
4143 $current_file_path = str_replace ('-scaled', '', $current_file_path);
4144 //error_log("$current_file_path $file_path");
4145 if($current_file_path === $file_path) {
4146 $found = true;
4147 break;
4148 } else {
4149 }
4150 }
4151 }
4152 return $found;
4153 }
4154
4155 public function write_log ( $log ) {
4156 if(!defined('HIDE_WRITELOG_MESSAGES')) {
4157 if ( true === WP_DEBUG ) {
4158 if ( is_array( $log ) || is_object( $log ) ) {
4159 error_log( print_r( $log, true ) );
4160 } else {
4161 error_log( $log );
4162 }
4163 }
4164 }
4165 }
4166
4167 public function mlp_load_folder() {
4168
4169 global $wpdb;
4170
4171 if ( !wp_verify_nonce( $_POST['nonce'], MAXGALLERIA_MEDIA_LIBRARY_NONCE)) {
4172 exit(esc_html__('missing nonce!','maxgalleria-media-library'));
4173 }
4174
4175 // Check if the current user has the capability to upload files
4176 if(!current_user_can('upload_files')){
4177 exit(esc_html__('You do not have the capability to upload files.','maxgalleria-media-library'));
4178 }
4179
4180 if ((isset($_POST['folder'])) && (strlen(trim($_POST['folder'])) > 0))
4181 $current_folder_id = intval(trim(sanitize_textarea_field($_POST['folder'])));
4182 else
4183 $current_folder_id = "";
4184
4185 if(!is_numeric($current_folder_id))
4186 die();
4187
4188 $folder_location = $this->get_folder_path($current_folder_id);
4189
4190 $folders_path = "";
4191 $parents = $this->get_parents($current_folder_id);
4192
4193 $folder_count = count($parents);
4194 $folder_counter = 0;
4195 $current_folder_string = site_url() . "/wp-content";
4196 foreach( $parents as $key => $obj) {
4197 $folder_counter++;
4198 if($folder_counter === $folder_count)
4199 $folders_path .= $obj['name'];
4200 else
4201 $folders_path .= '<a folder="' . $obj['id'] . '\' class="media-link\'>' . $obj['name'] . '</a>/';
4202 $current_folder_string .= '/' . $obj['name'];
4203 }
4204
4205 $this->display_folder_contents ($current_folder_id, true, $folders_path);
4206
4207 die();
4208
4209 }
4210
4211 public function mlp_upgrade_to_pro() {
4212 ?>
4213
4214 <div class="utp-body">
4215 <div class="top-section">
4216 <div class="container">
4217 <div class="row">
4218 <div class="width-50">
4219 <h1><?php esc_html_e('Media Library Folders: Update to PRO','maxgalleria-media-library') ?></h1>
4220 <a href="<?php echo esc_url(UPGRADE_TO_PRO_LINK); ?>" class="big-pluspro-btn"><?php esc_html_e('Buy Now','maxgalleria-media-library') ?></a>
4221 <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>
4222 </div>
4223 <div class="width-50">
4224 <strong>
4225 <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>
4226 </strong>
4227 </div>
4228 <div class="mlf-clearfix"></div>
4229 </div>
4230 </div>
4231 <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" >
4232 </div>
4233
4234 <div class="section features-section">
4235 <div class="features">
4236 <div class="container">
4237 <h2><?php esc_html_e('Features','maxgalleria-media-library') ?></h2>
4238 <div class="row">
4239 <div class="width-50">
4240 <ul>
4241 <li><span><?php esc_html_e('Add images to your posts and pages','maxgalleria-media-library') ?></span></li>
4242 <li><span><?php esc_html_e('File Name View Mode','maxgalleria-media-library') ?></span></li>
4243 <li><span><?php esc_html_e('Thumbnail Management','maxgalleria-media-library') ?></span></li>
4244 <li><span><?php esc_html_e('Add Images to WooCommerce Product Gallery','maxgalleria-media-library') ?></span></li>
4245 <li><span><?php esc_html_e('Export the media library from one Wordpress site and import it into another','maxgalleria-media-library') ?></span></li>
4246 <li><span><?php esc_html_e('Front End Upload to a Specific Folder','maxgalleria-media-library') ?></span></li>
4247 <li><span><?php esc_html_e('Bulk Move of media files','maxgalleria-media-library') ?></span></li>
4248 <li><span><?php esc_html_e('Supports Advanced Custom Fields','maxgalleria-media-library') ?></span></li>
4249 <li><span><?php esc_html_e('Organize Nextgen Galleries','maxgalleria-media-library') ?></span></li>
4250 </ul>
4251 </div>
4252 <div class="width-50">
4253 <ul>
4254 <li><span><?php esc_html_e('Multisite Supported','maxgalleria-media-library') ?></span></li>
4255 <li><span><?php esc_html_e('Category Interchangability with Enhanced Media Library','maxgalleria-media-library') ?></span></li>
4256 <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>
4257 <li><span><?php esc_html_e('Media Library Maintenance and Bulk File Import','maxgalleria-media-library') ?></span></li>
4258 <li><span><?php esc_html_e('Jetpack and the Wordpress Gallery Shortcode Generator','maxgalleria-media-library') ?></span></li>
4259 <li><span><?php esc_html_e('Block Direct Access for Selected Files','maxgalleria-media-library') ?></span></li>
4260 <li><span><?php esc_html_e('AI-powered image generation','maxgalleria-media-library') ?></span></li>
4261 </ul>
4262 </div>
4263 <div class="mlf-clearfix"></div>
4264 </div>
4265 </div>
4266 </div>
4267 </div>
4268
4269
4270 <div class="section price-section">
4271 <div class="container">
4272 <div class="prices">
4273 <h3>$49</h3>
4274 <div class="descr">
4275 <img src="<?php echo esc_url(MAXGALLERIA_MEDIA_LIBRARY_PLUGIN_URL . "/images/icons/benefits.png") ?>" class=" img-responsive" alt="ico">
4276 <p>
4277 <?php esc_html_e('Includes 1 Year Support','maxgalleria-media-library') ?>
4278 <br>
4279 <?php esc_html_e('and Updates','maxgalleria-media-library') ?>
4280 </p>
4281 </div>
4282 <a href="<?php echo esc_url(UPGRADE_TO_PRO_LINK) ?>" class="text-uppercase big-pluspro-btn">Buy MLFP</a>
4283 </div>
4284 </div>
4285 </div>
4286
4287 <div class="section options-section">
4288 <div class="option">
4289 <div class="container">
4290 <div class="row">
4291 <div class="width-100">
4292
4293 <p class="mflp-into">
4294 <?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') ?>
4295 </p>
4296 <h4>
4297 <?php esc_html_e('Add Images to Your Posts and Pages','maxgalleria-media-library') ?>
4298 </h4>
4299 <p>
4300 <?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') ?>
4301 </p>
4302 <p>
4303 <?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') ?>
4304 </p>
4305 <img class="img-responsive" src="<?php echo esc_url(MAXGALLERIA_MEDIA_LIBRARY_PLUGIN_URL . "/images/assets/new-add-images.png") ?>" alt="img" />
4306 </div>
4307 </div>
4308 </div>
4309 </div>
4310
4311 <div class="option">
4312 <div class="container">
4313 <div class="row">
4314 <div class="width-100">
4315 <h4>
4316 <?php esc_html_e('File Name View Mode','maxgalleria-media-library') ?>
4317 </h4>
4318 <p>
4319 <?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') ?>
4320 </p>
4321 <p>
4322 <?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') ?>
4323 </p>
4324 <img class="img-responsive" src="<?php echo esc_url(MAXGALLERIA_MEDIA_LIBRARY_PLUGIN_URL . "/images/assets/file-name.png") ?>" alt="img" />
4325 </div>
4326 </div>
4327 </div>
4328 </div>
4329
4330 <div class="option">
4331 <div class="container">
4332 <div class="row">
4333 <div class="width-100">
4334 <h4>
4335 <?php esc_html_e('Thumbnail Management','maxgalleria-media-library') ?>
4336 </h4>
4337 <p>
4338 <?php esc_html_e('Reduce the number of image thumbnail files generated by WordPress.','maxgalleria-media-library') ?>
4339 </p>
4340 <img class="img-responsive" src="<?php echo esc_url(MAXGALLERIA_MEDIA_LIBRARY_PLUGIN_URL . "/images/assets/thumbnail-management.png") ?>" alt="img" />
4341 </div>
4342 </div>
4343 </div>
4344 </div>
4345
4346 <div class="option">
4347 <div class="container">
4348 <div class="row">
4349 <div class="width-100">
4350 <h4>
4351 <?php esc_html_e('Media Library Maintenance','maxgalleria-media-library') ?>
4352 </h4>
4353 <p>
4354 <?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') ?>
4355 </p>
4356 <p>
4357 <?php esc_html_e('Media Library Maintenance allows site administrators to find, view and remove or import these uncatalogued files.','maxgalleria-media-library') ?>
4358 </p>
4359 <img class="img-responsive" src="<?php echo esc_url(MAXGALLERIA_MEDIA_LIBRARY_PLUGIN_URL . "/images/assets/maintenance.png") ?>" alt="img" />
4360 </div>
4361 </div>
4362 </div>
4363 </div>
4364
4365 <div class="option">
4366 <div class="container">
4367 <div class="row">
4368 <div class="width-100">
4369 <h4>
4370 <?php esc_html_e('Bulk File Import','maxgalleria-media-library') ?>
4371 </h4>
4372 <p>
4373 <?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') ?>
4374 </p>
4375 </div>
4376 </div>
4377 </div>
4378 </div>
4379
4380 <div class="option">
4381 <div class="container">
4382 <div class="row">
4383 <div class="width-100">
4384 <h4>
4385 <?php esc_html_e('Assign and Group Images by Categories','maxgalleria-media-library') ?>
4386 </h4>
4387 <p>
4388 <?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') ?>
4389 </p>
4390 <img class="img-responsive" src="<?php echo esc_url(MAXGALLERIA_MEDIA_LIBRARY_PLUGIN_URL . "/images/assets/image-categories.png") ?>" alt="img" />
4391 </div>
4392 </div>
4393 </div>
4394 </div>
4395
4396 <div class="option">
4397 <div class="container">
4398 <div class="row">
4399 <div class="width-100">
4400 <h4>
4401 Import/Export & Backup
4402 </h4>
4403 <p>
4404 The Import/Export feature allows an administrator to export a sites media library from one site to another.
4405 </p>
4406 <img class="img-responsive" src="<?php echo esc_url(MAXGALLERIA_MEDIA_LIBRARY_PLUGIN_URL . "/images/assets/import-export.png") ?>" alt="img" />
4407 </div>
4408 </div>
4409 </div>
4410 </div>
4411
4412 <div class="option">
4413 <div class="container">
4414 <div class="row">
4415 <div class="width-100">
4416 <h4>
4417 <?php esc_html_e('File Replacement','maxgalleria-media-library') ?>
4418 </h4>
4419 <p>
4420 <?php esc_html_e('Replace an existing file with another one of the same type in the Media Library','maxgalleria-media-library') ?>
4421 </p>
4422 <p>
4423 <?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') ?> 
4424 </p>
4425 <img class="img-responsive" src="<?php echo esc_url(MAXGALLERIA_MEDIA_LIBRARY_PLUGIN_URL . "/images/assets/file-replacement.png") ?>" alt="img" />
4426 </div>
4427 </div>
4428 </div>
4429 </div>
4430
4431 <div class="option">
4432 <div class="container">
4433 <div class="row">
4434 <div class="width-100">
4435 <h4>
4436 <?php esc_html_e('Block Direct Access for Selected Files','maxgalleria-media-library') ?>
4437 </h4>
4438 <p>
4439 <?php esc_html_e('Select the files to be protected','maxgalleria-media-library') ?>
4440 </p>
4441 <p>
4442 <?php esc_html_e('Generate and configure download links for protected files','maxgalleria-media-library') ?> 
4443 </p>
4444 <img class="img-responsive" src="<?php echo esc_url(MAXGALLERIA_MEDIA_LIBRARY_PLUGIN_URL . "/images/assets/block-direct-access.png") ?>" alt="img" />
4445 </div>
4446 </div>
4447 </div>
4448 </div>
4449
4450
4451 <div class="option">
4452 <div class="container">
4453 <div class="row">
4454 <div class="width-100">
4455 <h4>
4456 <?php esc_html_e('Frontend Upload','maxgalleria-media-library') ?>
4457 </h4>
4458 <p>
4459 <?php esc_html_e('Frontend uploading of files is available via a shortcode.','maxgalleria-media-library') ?>
4460 </p>
4461 <p>
4462 <?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') ?>
4463 </p>
4464 <img class="img-responsive" src="<?php echo esc_url(MAXGALLERIA_MEDIA_LIBRARY_PLUGIN_URL . "/images/assets/frontend-upload.png") ?>" alt="img" />
4465 </div>
4466 </div>
4467 </div>
4468 </div>
4469
4470 <div class="option">
4471 <div class="container">
4472 <div class="row">
4473 <div class="width-100">
4474 <h4>
4475 <?php esc_html_e('Embed PDF, Audio or Video Files','maxgalleria-media-library') ?>
4476 </h4>
4477 <p>
4478 <?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') ?>
4479 </p>
4480 <img class="img-responsive" src="<?php echo esc_url(MAXGALLERIA_MEDIA_LIBRARY_PLUGIN_URL . "/images/assets/embed-file.png") ?>" alt="img" />
4481 </div>
4482 </div>
4483 </div>
4484 </div>
4485
4486 <div class="option">
4487 <div class="container">
4488 <div class="row">
4489 <div class="width-100">
4490 <h4>
4491 <?php esc_html_e('Create Audio and Video Playlists','maxgalleria-media-library') ?>
4492 </h4>
4493 <p>
4494 <?php esc_html_e('Use Media Library Folders Pro\'s playlist shortcode generator to create your own audio or video playlists.','maxgalleria-media-library') ?>
4495 </p>
4496 <img class="img-responsive" src="<?php echo esc_url(MAXGALLERIA_MEDIA_LIBRARY_PLUGIN_URL . "/images/assets/audio-playlist-generator.png") ?>" alt="img" />
4497 </div>
4498 </div>
4499 </div>
4500 </div>
4501
4502 <div class="option">
4503 <div class="container">
4504 <div class="row">
4505 <div class="width-100">
4506 <h4>
4507 <?php esc_html_e('NextGEN Galleries','maxgalleria-media-library') ?>
4508 </h4>
4509 <p>
4510 <?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') ?>
4511 </p>
4512 <img class="img-responsive" src="<?php echo esc_url(MAXGALLERIA_MEDIA_LIBRARY_PLUGIN_URL . "/images/assets/nextgen.png") ?>" alt="img" />
4513 </div>
4514 </div>
4515 </div>
4516 </div>
4517
4518
4519 </div>
4520
4521 <div class="section options-section last-section">
4522 <div class="container">
4523 <h4>
4524 <?php esc_html_e('Get Media Library Folders Pro','maxgalleria-media-library') ?>
4525 </h4>
4526 <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>
4527 </div>
4528 </div>
4529 </div>
4530
4531 <?php
4532
4533 }
4534
4535 public function mlpp_hide_template_ad() {
4536
4537 if ( !wp_verify_nonce( $_POST['nonce'], MAXGALLERIA_MEDIA_LIBRARY_NONCE)) {
4538 exit(esc_html__('missing nonce! Please refresh this page.','maxgalleria-media-library'));
4539 }
4540
4541 // Check if the current user has the capability to upload files
4542 if(!current_user_can('upload_files')){
4543 exit(esc_html__('You do not have the capability to upload files.','maxgalleria-media-library'));
4544 }
4545
4546 update_option('mlpp_show_template_ad', "off");
4547
4548 die();
4549 }
4550
4551 public function mlpp_settings() {
4552
4553 global $current_user;
4554 ?>
4555
4556 <div style="clear:both"></div>
4557
4558 <?php
4559 $meta_index = get_option( MAXGALLERIA_POSTMETA_INDEX, 'off');
4560 $this->disable_scaling = get_option( MAXGALLERIA_DISABLE_SCALLING, 'off');
4561 $images_pre_page = get_option(MAXGALLERIA_MLP_ITEMS_PRE_PAGE, '500');
4562 $this->sync_skip_webp = get_option(MLFP_SKIP_WEBP_FILES, 'off');
4563
4564 if($images_pre_page == '')
4565 $images_pre_page = 100;
4566 ?>
4567
4568 <p>
4569 <label><?php esc_html_e('Number of images to display:', 'maxgalleria-media-library'); ?></label>
4570 <input type="text" id="images-pre-page" name="images-pre-page" value="<?php echo esc_attr($images_pre_page) ?>" style="width: 50px" autocomplete=off>
4571 </p>
4572
4573 <p>
4574 <input type="checkbox" name="disable_scaling" id="disable_scaling" value="" <?php esc_attr(checked($this->disable_scaling, 'on')) ?>>
4575 <label><?php esc_html_e('Disable large image scaling', 'maxgalleria-media-library'); ?></label>
4576 </p>
4577 <p>
4578 <input type="checkbox" name="meta_index" id="meta_index" value="" <?php checked($meta_index, 'on') ?>>
4579 <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>
4580 </p>
4581 <p>
4582 <input type="checkbox" name="skip_webp" id="skip_webp" value="" <?php checked($this->sync_skip_webp, 'on') ?>>
4583 <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>
4584 </p>
4585 <p>
4586 <a class="button-primary" id="mlfp-update-settings"><?php esc_html_e('Update Settings','maxgalleria-media-library'); ?></a>
4587 </p>
4588
4589 <div id="saving-message"></div>
4590
4591
4592 <script>
4593 jQuery(document).ready(function(){
4594
4595 jQuery(document).on("click","#mlfp-update-settings",function(){
4596
4597 var images_per_page = jQuery("#images-pre-page").val();
4598 var scaling_status = jQuery("#disable_scaling").is(":checked");
4599 var meta_index = jQuery("#meta_index").is(":checked");
4600 var skip_webp = jQuery("#skip_webp").is(":checked");
4601
4602 jQuery("#saving-message").html('');
4603
4604 jQuery.ajax({
4605 type: "POST",
4606 async: true,
4607 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 },
4608 url: mgmlp_ajax.ajaxurl,
4609 dataType: "html",
4610 success: function (data) {
4611 jQuery("#saving-message").html(data);
4612 window.location.reload();
4613 },
4614 error: function (err){
4615 jQuery("#gi-ajax-loader").hide();
4616 alert(err.responseText)
4617 }
4618 });
4619
4620 });
4621
4622 });
4623 </script>
4624
4625 <?php
4626 }
4627
4628 public function regen_mlp_thumbnails() {
4629
4630 global $wpdb, $is_IIS;
4631
4632 if ( !wp_verify_nonce( $_POST['nonce'], MAXGALLERIA_MEDIA_LIBRARY_NONCE)) {
4633 exit( esc_html__('missing nonce! Please refresh this page.','maxgalleria-media-library'));
4634 }
4635
4636 // Check if the current user has the capability to upload files
4637 if(!current_user_can('upload_files')){
4638 exit(esc_html__('You do not have the capability to regenerate thumbnail images.','maxgalleria-media-library'));
4639 }
4640
4641 if ((isset($_POST['serial_image_ids'])) && (strlen(trim($_POST['serial_image_ids'])) > 0))
4642 $image_ids = trim(stripslashes(sanitize_text_field($_POST['serial_image_ids'])));
4643 else
4644 $image_ids = "";
4645
4646 //error_log("image_ids $image_ids");
4647
4648 $image_ids = str_replace('"', '', $image_ids);
4649
4650 $image_ids = explode(',', $image_ids);
4651
4652 //error_log(print_r($image_ids, true));
4653
4654 $counter = 0;
4655
4656 foreach( $image_ids as $image_id) {
4657
4658 // check if the file is an image
4659 if(wp_attachment_is_image(intval($image_id))) {
4660
4661 //error_log("is image");
4662
4663 // get the image path
4664 $image_path = get_attached_file( $image_id );
4665
4666 $scaled_position = strpos($image_path, '-scaled');
4667
4668 if($scaled_position != false) {
4669 $temp_path = substr($image_path, 0, $scaled_position);
4670 $temp_path .= substr($image_path, $scaled_position+7);
4671 $image_path = $temp_path;
4672 }
4673
4674 // get the name of the file
4675 $base_name = wp_basename( $image_path );
4676
4677 // set the time limit o five minutes
4678 @set_time_limit( 300 );
4679
4680 $mime_type = get_post_mime_type($image_id);
4681 if($mime_type != 'image/svg+xml') {
4682
4683 // regenerate the thumbnails
4684 if ($is_IIS || strtoupper(substr(PHP_OS, 0, 3)) == 'WIN' || strtoupper(substr(PHP_OS, 0, 13)) == 'MICROSOFT-IIS' ) {
4685 $this->remove_existing_thumbnails($image_id, addslashes($image_path));
4686 $metadata = wp_generate_attachment_metadata( $image_id, addslashes($image_path));
4687 } else {
4688 $this->remove_existing_thumbnails($image_id, $image_path);
4689 $metadata = wp_generate_attachment_metadata( $image_id, $image_path );
4690 }
4691
4692 // check for errors
4693 if (is_wp_error($metadata)) {
4694 echo esc_html__('Error: ','maxgalleria-media-library') . "$base_name ". $metadata->get_error_message();
4695 continue;
4696 }
4697 if(empty($metadata)) {
4698 printf( esc_html__('Unknown error with %s','maxgalleria-media-library'), $base_name);
4699 continue;
4700 }
4701
4702 // update the meta data
4703 wp_update_attachment_metadata( $image_id, $metadata );
4704 }
4705 $counter++;
4706
4707 } else {
4708 error_log("not an image");
4709 }
4710 }
4711
4712 printf( esc_html__('Thumbnails have been regenerated for %d image(s)','maxgalleria-media-library'), $counter);
4713 die();
4714 }
4715
4716 public function remove_existing_thumbnails($image_id, $image_path) {
4717
4718 global $is_IIS;
4719
4720 $metadata = wp_get_attachment_metadata(intval($image_id));
4721
4722 if ($is_IIS || strtoupper(substr(PHP_OS, 0, 3)) == 'WIN' || strtoupper(substr(PHP_OS, 0, 13)) == 'MICROSOFT-IIS' )
4723 $seprator_position = strrpos($image_path, '\\');
4724 else
4725 $seprator_position = strrpos($image_path, '/');
4726
4727 $image_path = substr($image_path, 0, $seprator_position);
4728
4729 if(isset($metadata['sizes'])) {
4730 foreach($metadata['sizes'] as $source_path) {
4731 $thumbnail_file = $image_path . DIRECTORY_SEPARATOR . $source_path['file'];
4732
4733 if ($is_IIS || strtoupper(substr(PHP_OS, 0, 3)) == 'WIN' || strtoupper(substr(PHP_OS, 0, 13)) == 'MICROSOFT-IIS' )
4734 $thumbnail_file = str_replace('/', '\\', $thumbnail_file);
4735
4736 if(file_exists($thumbnail_file))
4737 unlink($thumbnail_file);
4738 }
4739 }
4740 }
4741
4742 public function regenerate_interface() {
4743 global $wpdb;
4744
4745 $allowed_html = array(
4746 'a' => array(
4747 'href' => array(),
4748 'id' => array()
4749 )
4750 );
4751
4752 ?>
4753
4754 <div id="message" class="updated fade" style="display:none"></div>
4755
4756 <div id="wp-media-grid" class="wrap">
4757 <!--empty h1 for where WP notices will appear-->
4758 <h1></h1>
4759 <div class="media-plus-toolbar"><div class="media-toolbar-secondary">
4760
4761 <div id="mgmlp-header">
4762 <div id='mgmlp-title-area'>
4763 <h2 class='mgmlp-title'><?php esc_html_e('Regenerate Thumbnails', 'maxgalleria-media-library' ); ?></h2>
4764
4765 </div> <!-- mgmlp-title-area -->
4766 <div id="new-top-promo">
4767 <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>
4768 <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>
4769 <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>
4770 <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>
4771 <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>
4772 </div>
4773
4774 </div><!--mgmlp-header-->
4775 <div class="mlf-clearfix"></div>
4776
4777
4778 <?php
4779
4780 // If the button was clicked
4781 if ( ! empty( $_POST['regenerate-thumbnails'] ) || ! empty( $_REQUEST['ids'] ) ) {
4782 // Capability check
4783 if ( ! current_user_can( $this->capability ) )
4784 wp_die( esc_html__( 'Cheatin&#8217; uh?' ) );
4785
4786 if($this->bda == 'on' && $this->bdp_autoprotect == 'on') {
4787 $this->bdp_autoprotect = 'off';
4788 update_option(MLFP_BDA_AUTO_PROTECT, 'off');
4789 update_option(MLFP_BDA_AUTO_PROTECT_DISABLED, 'on');
4790 }
4791
4792 // Form nonce check
4793 check_admin_referer(MAXGALLERIA_MEDIA_LIBRARY_NONCE);
4794
4795 // Create the list of image IDs
4796 if ( ! empty( $_REQUEST['ids'] ) ) {
4797 $images = array_map( 'intval', explode( ',', trim( sanitize_text_field($_REQUEST['ids']), ',' ) ) );
4798 $ids = implode( ',', $images );
4799 } else {
4800 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" ) ) {
4801 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>";
4802 return;
4803 }
4804
4805 //error_log("IMAGES: " . print_r($images, true));
4806
4807 // Generate the list of IDs
4808 $ids = array();
4809 foreach ( $images as $image )
4810 $ids[] = $image->ID;
4811 $ids = implode( ',', $ids );
4812 }
4813
4814 echo ' <p id="wait-message">' . esc_html__( "Please wait while the thumbnails are regenerated. This may take a while.", 'maxgalleria-media-library' ) . '</p>';
4815
4816 $count = count( $images );
4817
4818 $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>.' : '';
4819 $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 );
4820 $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 );
4821 ?>
4822
4823 <noscript><p><em><?php esc_html_e( 'You must enable Javascript in order to proceed!', 'maxgalleria-media-library' ) ?></em></p></noscript>
4824
4825 <div id="regenthumbs-bar" style="position:relative;height:25px;">
4826 <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>
4827 </div>
4828
4829 <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>
4830
4831 <h3 class="title"><?php esc_html_e( 'Debugging Information', 'maxgalleria-media-library' ) ?></h3>
4832
4833 <p>
4834 <?php echo esc_html( __( 'Total Images: ', 'maxgalleria-media-library' ) . (int) $count) ?><br />
4835 <?php echo esc_html__( 'Images Resized: ', 'maxgalleria-media-library' ) . '<span id="regenthumbs-debug-successcount">0</span>' ?><br />
4836 <?php echo esc_html__( 'Resize Failures: ', 'maxgalleria-media-library' ) . '<span id="regenthumbs-debug-failurecount">0</span>' ?>
4837 </p>
4838
4839 <ol id="regenthumbs-debuglist">
4840 <li style="display:none"></li>
4841 </ol>
4842
4843 <script type="text/javascript">
4844 // <![CDATA[
4845 jQuery(document).ready(function($){
4846 var i;
4847 var rt_images = [<?php echo esc_attr($ids) ?>];
4848 var rt_total = rt_images.length;
4849 var rt_count = 1;
4850 var rt_percent = 0;
4851 var rt_successes = 0;
4852 var rt_errors = 0;
4853 var rt_failedlist = '';
4854 var rt_resulttext = '';
4855 var rt_timestart = new Date().getTime();
4856 var rt_timeend = 0;
4857 var rt_totaltime = 0;
4858 var rt_continue = true;
4859
4860 // Create the progress bar
4861 $("#regenthumbs-bar").progressbar();
4862 $("#regenthumbs-bar-percent").html( "0%" );
4863
4864 // Stop button
4865 //$("#regenthumbs-stop").click(function() {
4866 $(document).on("click", "#regenthumbs-stop", function () {
4867 rt_continue = false;
4868 $('#regenthumbs-stop').val("<?php echo $this->esc_quotes( esc_html__( 'Stopping...', 'maxgalleria-media-library' ) ); ?>");
4869 });
4870
4871 // Clear out the empty list element that's there for HTML validation purposes
4872 $("#regenthumbs-debuglist li").remove();
4873
4874 // Called after each resize. Updates debug information and the progress bar.
4875 function RegenThumbsUpdateStatus( id, success, response ) {
4876 $("#regenthumbs-bar").progressbar( "value", ( rt_count / rt_total ) * 100 );
4877 $("#regenthumbs-bar-percent").html( Math.round( ( rt_count / rt_total ) * 1000 ) / 10 + "%" );
4878 rt_count = rt_count + 1;
4879
4880 if ( success ) {
4881 rt_successes = rt_successes + 1;
4882 $("#regenthumbs-debug-successcount").html(rt_successes);
4883 $("#regenthumbs-debuglist").append("<li>" + response.success + "</li>");
4884 }
4885 else {
4886 rt_errors = rt_errors + 1;
4887 rt_failedlist = rt_failedlist + ',' + id;
4888 $("#regenthumbs-debug-failurecount").html(rt_errors);
4889 $("#regenthumbs-debuglist").append("<li>" + response.error + "</li>");
4890 }
4891 }
4892
4893 // Called when all images have been processed. Shows the results and cleans up.
4894 function RegenThumbsFinishUp() {
4895 rt_timeend = new Date().getTime();
4896 rt_totaltime = Math.round( ( rt_timeend - rt_timestart ) / 1000 );
4897
4898 $('#regenthumbs-stop').hide();
4899
4900 if ( rt_errors > 0 ) {
4901 rt_resulttext = '<?php echo wp_kses($text_failures, $allowed_html) ?>';
4902 } else {
4903 rt_resulttext = '<?php echo wp_kses($text_nofailures, $allowed_html) ?>';
4904 }
4905
4906 $("#wait-message").html("");
4907 $("#message").html("<p><strong>" + rt_resulttext + "</strong></p>");
4908 $("#message").show();
4909 }
4910
4911 // Regenerate a specified image via AJAX
4912 function RegenThumbs( id ) {
4913 $.ajax({
4914 type: 'POST',
4915 url: ajaxurl,
4916 data: { action: "regeneratethumbnail", id: id },
4917 success: function( response ) {
4918 if ( response !== Object( response ) || ( typeof response.success === "undefined" && typeof response.error === "undefined" ) ) {
4919 response = new Object;
4920 response.success = false;
4921 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 + "' ); ?>";
4922 }
4923
4924 if ( response.success ) {
4925 RegenThumbsUpdateStatus( id, true, response );
4926 }
4927 else {
4928 RegenThumbsUpdateStatus( id, false, response );
4929 }
4930
4931 if ( rt_images.length && rt_continue ) {
4932 RegenThumbs( rt_images.shift() );
4933 }
4934 else {
4935 RegenThumbsFinishUp();
4936 }
4937 },
4938 error: function( response ) {
4939 RegenThumbsUpdateStatus( id, false, response );
4940
4941 if ( rt_images.length && rt_continue ) {
4942 RegenThumbs( rt_images.shift() );
4943 }
4944 else {
4945 RegenThumbsFinishUp();
4946 }
4947 }
4948 });
4949 }
4950
4951 RegenThumbs( rt_images.shift() );
4952 });
4953 // ]]>
4954 </script>
4955 <?php
4956 }
4957
4958 // No button click? Display the form.
4959 else {
4960 ?>
4961 <form method="post" action="">
4962 <?php wp_nonce_field(MAXGALLERIA_MEDIA_LIBRARY_NONCE) ?>
4963
4964 <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>
4965
4966 <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>
4967
4968 <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>
4969
4970 <noscript><p><em><?php esc_html_e( 'You must enable Javascript in order to proceed!', 'maxgalleria-media-library' ) ?></em></p></noscript>
4971
4972 </form>
4973 <?php
4974 } // End if button
4975 ?>
4976 </div>
4977 </div>
4978 </div>
4979
4980 <?php
4981 }
4982
4983 // Process a single image ID (this is an AJAX handler)
4984 public function ajax_process_image() {
4985
4986 global $is_IIS;
4987
4988 // Check if the current user has the capability to upload files
4989 if(!current_user_can('upload_files')){
4990 exit(esc_html__('You do not have the capability to upload files.','maxgalleria-media-library'));
4991 }
4992
4993 @error_reporting( 0 ); // Don't break the JSON result
4994
4995 header( 'Content-type: application/json' );
4996
4997 $id = (int) $_REQUEST['id'];
4998 $image = get_post( $id );
4999
5000 if ( ! $image || 'attachment' != $image->post_type || 'image/' != substr( $image->post_mime_type, 0, 6 ) )
5001 die( json_encode( array( 'error' => sprintf( esc_html__( 'Failed resize: %s is an invalid image ID.', 'maxgalleria-media-library' ), esc_html( $_REQUEST['id'] ) ) ) ) );
5002
5003 if ( ! current_user_can( $this->capability ) )
5004 $this->die_json_error_msg( $image->ID, esc_html__( "Your user account doesn't have permission to resize images", 'maxgalleria-media-library' ) );
5005
5006 $fullsizepath = get_attached_file( $image->ID );
5007
5008 $scaled_position = strpos($fullsizepath, '-scaled');
5009
5010 if($scaled_position != false) {
5011 $temp_path = substr($fullsizepath, 0, $scaled_position);
5012 $temp_path .= substr($fullsizepath, $scaled_position+7);
5013 //error_log("temp_path $temp_path");
5014 $fullsizepath = $temp_path;
5015 }
5016
5017 if ( false === $fullsizepath || ! file_exists( $fullsizepath ) )
5018 $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>' ) );
5019
5020 @set_time_limit( 900 ); // 5 minutes per image should be PLENTY
5021
5022 if($image->post_mime_type != 'image/svg+xml') {
5023 if ($is_IIS || strtoupper(substr(PHP_OS, 0, 3)) == 'WIN' || strtoupper(substr(PHP_OS, 0, 13)) == 'MICROSOFT-IIS' ) {
5024 $this->remove_existing_thumbnails($image->ID, addslashes($fullsizepath));
5025 $metadata = wp_generate_attachment_metadata( $image->ID, addslashes($fullsizepath));
5026 } else {
5027 $this->remove_existing_thumbnails($image->ID, $fullsizepath);
5028 $metadata = wp_generate_attachment_metadata( $image->ID, $fullsizepath );
5029 }
5030 }
5031
5032 if(isset($metadata)) {
5033 if ( is_wp_error( $metadata ) )
5034 $this->die_json_error_msg( $image->ID, $metadata->get_error_message() );
5035 if ( empty( $metadata ) )
5036 $this->die_json_error_msg( $image->ID, esc_html__( 'Unknown failure reason.', 'maxgalleria-media-library' ) );
5037
5038 // If this fails, then it just means that nothing was changed (old value == new value)
5039 wp_update_attachment_metadata( $image->ID, $metadata );
5040 }
5041
5042 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() ) ) ) );
5043 }
5044
5045 // Helper to make a JSON error message
5046 public function die_json_error_msg( $id, $message ) {
5047 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 ) ) ) );
5048 }
5049
5050 // Helper function to escape quotes in strings for use in Javascript
5051 public function esc_quotes( $string ) {
5052 return str_replace( '"', '\"', $string );
5053 }
5054
5055 public function mflp_enable_auto_protect() {
5056
5057 if ( !wp_verify_nonce( $_POST['nonce'], MAXGALLERIA_MEDIA_LIBRARY_PRO_NONCE)) {
5058 exit(__('missing nonce!','maxgalleria-media-library'));
5059 }
5060
5061 // Check if the current user has the capability to manage options
5062 if(!current_user_can('manage_options')){
5063 exit(esc_html__('You do not have the capability to manage options.','maxgalleria-media-library'));
5064 }
5065
5066 if(get_option(MLFP_BDA_AUTO_PROTECT_DISABLED, 'off') == 'on') {
5067 $this->bdp_autoprotect = 'on';
5068 update_option(MLFP_BDA_AUTO_PROTECT, 'on');
5069 update_option(MLFP_BDA_AUTO_PROTECT_DISABLED, 'off');
5070 }
5071
5072 die();
5073 }
5074
5075 public function mlp_image_seo_change() {
5076
5077 if ( !wp_verify_nonce( $_POST['nonce'], MAXGALLERIA_MEDIA_LIBRARY_NONCE)) {
5078 exit(esc_html__('missing nonce! Please refresh this page.','maxgalleria-media-library'));
5079 }
5080
5081 // Check if the current user has the capability to upload files
5082 if(!current_user_can('upload_files')){
5083 exit(esc_html__('You do not have the capability to upload files.','maxgalleria-media-library'));
5084 }
5085
5086 if ((isset($_POST['checked'])) && (strlen(trim($_POST['checked'])) > 0))
5087 $checked = trim(sanitize_text_field($_POST['checked']));
5088 else
5089 $checked = "off";
5090
5091 if ((isset($_POST['default_alt'])) && (strlen(trim($_POST['default_alt'])) > 0))
5092 $default_alt = trim(sanitize_text_field($_POST['default_alt']));
5093 else
5094 $default_alt = "";
5095
5096 if ((isset($_POST['default_title'])) && (strlen(trim($_POST['default_title'])) > 0))
5097 $default_title = trim(sanitize_text_field($_POST['default_title']));
5098 else
5099 $default_title = "";
5100
5101 //error_log("default_title $default_title");
5102
5103 update_option(MAXGALLERIA_MEDIA_LIBRARY_IMAGE_SEO, $checked );
5104
5105 update_option(MAXGALLERIA_MEDIA_LIBRARY_ATL_DEFAULT, $default_alt );
5106
5107 update_option(MAXGALLERIA_MEDIA_LIBRARY_TITLE_DEFAULT, $default_title );
5108
5109 echo esc_html__('The Image SEO settings have been updated ','maxgalleria-media-library');
5110
5111 die();
5112
5113
5114 }
5115
5116 public function locaton_without_basedir($image_location, $uploads_dir, $upload_length) {
5117
5118 $position = strpos($image_location, $uploads_dir);
5119 return substr($image_location, $position+$upload_length );
5120
5121 }
5122
5123 public function get_browser() {
5124 // https://www.php.net/manual/en/function.get-browser.php#101125.
5125 // Cleaned up a bit, but overall it's the same.
5126
5127 $user_agent = $_SERVER['HTTP_USER_AGENT'];
5128 $browser_name = 'Unknown';
5129 $platform = 'Unknown';
5130 $version= "";
5131
5132 // First get the platform
5133 if (preg_match('/linux/i', $user_agent)) {
5134 $platform = 'Linux';
5135 }
5136 elseif (preg_match('/macintosh|mac os x/i', $user_agent)) {
5137 $platform = 'Mac';
5138 }
5139 elseif (preg_match('/windows|win32/i', $user_agent)) {
5140 $platform = 'Windows';
5141 }
5142
5143 // Next get the name of the user agent yes seperately and for good reason
5144 if (preg_match('/MSIE/i', $user_agent) && !preg_match('/Opera/i', $user_agent)) {
5145 $browser_name = 'Internet Explorer';
5146 $browser_name_short = "MSIE";
5147 }
5148 elseif (preg_match('/Firefox/i', $user_agent)) {
5149 $browser_name = 'Mozilla Firefox';
5150 $browser_name_short = "Firefox";
5151 }
5152 elseif (preg_match('/Chrome/i', $user_agent)) {
5153 $browser_name = 'Google Chrome';
5154 $browser_name_short = "Chrome";
5155 }
5156 elseif (preg_match('/Safari/i', $user_agent)) {
5157 $browser_name = 'Apple Safari';
5158 $browser_name_short = "Safari";
5159 }
5160 elseif (preg_match('/Opera/i', $user_agent)) {
5161 $browser_name = 'Opera';
5162 $browser_name_short = "Opera";
5163 }
5164 elseif (preg_match('/Netscape/i', $user_agent)) {
5165 $browser_name = 'Netscape';
5166 $browser_name_short = "Netscape";
5167 }
5168
5169 // Finally get the correct version number
5170 $known = array('Version', $browser_name_short, 'other');
5171 $pattern = '#(?<browser>' . join('|', $known) . ')[/ ]+(?<version>[0-9.|a-zA-Z.]*)#';
5172 if (!preg_match_all($pattern, $user_agent, $matches)) {
5173 // We have no matching number just continue
5174 }
5175
5176 // See how many we have
5177 $i = count($matches['browser']);
5178 if ($i != 1) {
5179 // We will have two since we are not using 'other' argument yet
5180 // See if version is before or after the name
5181 if (strripos($user_agent, "Version") < strripos($user_agent, $browser_name_short)){
5182 $version= $matches['version'][0];
5183 }
5184 else {
5185 $version= $matches['version'][1];
5186 }
5187 }
5188 else {
5189 $version= $matches['version'][0];
5190 }
5191
5192 // Check if we have a number
5193 if ($version == null || $version == "") { $version = "?"; }
5194
5195 return array(
5196 'user_agent' => $user_agent,
5197 'name' => $browser_name,
5198 'version' => $version,
5199 'platform' => $platform,
5200 'pattern' => $pattern
5201 );
5202 }
5203
5204 public function mlp_support() {
5205 require_once MAXGALLERIA_MEDIA_LIBRARY_PLUGIN_DIR . '/includes/mlf_support.php';
5206 }
5207
5208 public function mlp_remove_slashes() {
5209
5210 global $wpdb;
5211
5212 $sql = "select ID, pm.meta_value, pm.meta_id
5213 from {$wpdb->prefix}posts
5214 LEFT JOIN {$wpdb->prefix}postmeta AS pm ON pm.post_id = {$wpdb->prefix}posts.ID
5215 where post_type = 'attachment'
5216 or post_type = '" . MAXGALLERIA_MEDIA_LIBRARY_POST_TYPE . "'
5217 and pm.meta_key = '_wp_attached_file'
5218 group by ID
5219 order by meta_id";
5220
5221
5222 //error_log($sql);
5223
5224 $rows = $wpdb->get_results($sql);
5225
5226 if($rows) {
5227 foreach($rows as $row) {
5228 if($row->meta_value !== '') {
5229 if( $row->meta_value[0] == "/") {
5230 $new_meta = $row->meta_value;
5231 $new_meta = ltrim($new_meta, '/');
5232 update_post_meta($row->ID, '_wp_attached_file', $new_meta);
5233 }
5234 }
5235 }
5236 }
5237 }
5238
5239 public function hide_maxgalleria_media() {
5240
5241 //error_log("hide_maxgalleria_media");
5242
5243 global $wpdb;
5244
5245 if ( !wp_verify_nonce( $_POST['nonce'], MAXGALLERIA_MEDIA_LIBRARY_NONCE)) {
5246 exit( esc_html__('missing nonce! Please refresh this page.','maxgalleria-media-library'));
5247 }
5248
5249 // Check if the current user has the capability to upload files
5250 if(!current_user_can('upload_files')){
5251 exit(esc_html__('You do not have the capability to upload files.','maxgalleria-media-library'));
5252 }
5253
5254 if ((isset($_POST['folder_id'])) && (strlen(trim($_POST['folder_id'])) > 0))
5255 $folder_id = intval(trim(sanitize_text_field($_POST['folder_id'])));
5256 else
5257 $folder_id = "";
5258
5259 // prevent hiding of the uploads folder and sub folders
5260 if($folder_id == intval($this->uploads_folder_ID)) {
5261 echo esc_html__('The uploads folder cannot be hidden.','maxgalleria-media-library');
5262 die();
5263 }
5264
5265 if($folder_id !== '') {
5266
5267 $folder_table = $wpdb->prefix . MAXGALLERIA_MEDIA_LIBRARY_FOLDER_TABLE;
5268 $parent_folder = $this->get_parent($folder_id);
5269
5270 $sql = "select meta_value as attached_file
5271 from {$wpdb->prefix}postmeta
5272 where post_id = $folder_id
5273 and meta_key = '_wp_attached_file';";
5274
5275 $row = $wpdb->get_row($sql);
5276 if($row) {
5277
5278 $basedir = $this->upload_dir['basedir'];
5279 $basedir = rtrim($basedir, '/') . '/';
5280 $skip_folder_file = $basedir . ltrim($row->attached_file, '/') . DIRECTORY_SEPARATOR . "mlpp-hidden";
5281 file_put_contents($skip_folder_file, '');
5282
5283 $this->remove_children($folder_id);
5284 $del_post = array('post_id' => $folder_id);
5285 $this->mlf_delete_post($folder_id, false); //delete the post record
5286 $wpdb->delete( $folder_table, $del_post ); // delete the folder table record
5287
5288 }
5289
5290 echo esc_html__('The selected folder, subfolders and thier files have been hidden.','maxgalleria-media-library');
5291 echo "<script>window.location.href = '" . esc_url_raw(site_url() . '/wp-admin/admin.php?page=mlf-folders8&media-folder=' . $parent_folder) . "'</script>";
5292
5293 }
5294
5295 die();
5296 }
5297
5298 // $folder_id aready forced to an inteter in hide_maxgalleria_media()
5299 private function remove_children($folder_id) {
5300
5301 global $wpdb;
5302
5303 if($folder_id !== 0) {
5304
5305 $folder_table = $wpdb->prefix . MAXGALLERIA_MEDIA_LIBRARY_FOLDER_TABLE;
5306
5307 $sql = "select post_id
5308 from $folder_table
5309 where folder_id = $folder_id";
5310
5311 $rows = $wpdb->get_results($sql);
5312 if($rows) {
5313 foreach($rows as $row) {
5314
5315 $this->remove_children($row->post_id);
5316 $del_post = array('post_id' => $row->post_id);
5317 $this->mlf_delete_post($row->post_id, false); //delete the post record
5318 $wpdb->delete( $folder_table, $del_post ); // delete the folder table record
5319
5320 }
5321 }
5322 }
5323 }
5324
5325 // modifed version of wp_delete_post
5326 private function mlf_delete_post( $postid = 0, $force_delete = false ) {
5327 global $wpdb;
5328
5329 $postid = intval($postid);
5330
5331 if ( !$post = $wpdb->get_row($wpdb->prepare("SELECT * FROM $wpdb->posts WHERE ID = %d", $postid)) )
5332 return $post;
5333
5334 if ( !$force_delete && ( $post->post_type == 'post' || $post->post_type == 'page') && get_post_status( $postid ) != 'trash' && EMPTY_TRASH_DAYS )
5335 return wp_trash_post( $postid );
5336
5337 delete_post_meta($postid,'_wp_trash_meta_status');
5338 delete_post_meta($postid,'_wp_trash_meta_time');
5339
5340 wp_delete_object_term_relationships($postid, get_object_taxonomies($post->post_type));
5341
5342 $parent_data = array( 'post_parent' => $post->post_parent );
5343 $parent_where = array( 'post_parent' => $postid );
5344
5345 if ( is_post_type_hierarchical( $post->post_type ) ) {
5346 // Point children of this page to its parent, also clean the cache of affected children.
5347 $children_query = $wpdb->prepare( "SELECT * FROM $wpdb->posts WHERE post_parent = %d AND post_type = %s", $postid, $post->post_type );
5348 $children = $wpdb->get_results( $children_query );
5349 if ( $children ) {
5350 $wpdb->update( $wpdb->posts, $parent_data, $parent_where + array( 'post_type' => $post->post_type ) );
5351 }
5352 }
5353
5354 // Do raw query. wp_get_post_revisions() is filtered.
5355 $revision_ids = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_parent = %d AND post_type = 'revision'", $postid ) );
5356 // Use wp_delete_post (via wp_delete_post_revision) again. Ensures any meta/misplaced data gets cleaned up.
5357 foreach ( $revision_ids as $revision_id )
5358 wp_delete_post_revision( $revision_id );
5359
5360 // Point all attachments to this post up one level.
5361 $wpdb->update( $wpdb->posts, $parent_data, $parent_where + array( 'post_type' => 'attachment' ) );
5362
5363 wp_defer_comment_counting( true );
5364
5365 $comment_ids = $wpdb->get_col( $wpdb->prepare( "SELECT comment_ID FROM $wpdb->comments WHERE comment_post_ID = %d", $postid ));
5366 foreach ( $comment_ids as $comment_id ) {
5367 wp_delete_comment( $comment_id, true );
5368 }
5369
5370 wp_defer_comment_counting( false );
5371
5372 $post_meta_ids = $wpdb->get_col( $wpdb->prepare( "SELECT meta_id FROM $wpdb->postmeta WHERE post_id = %d ", $postid ));
5373 foreach ( $post_meta_ids as $mid )
5374 delete_metadata_by_mid( 'post', $mid );
5375
5376 $result = $wpdb->delete( $wpdb->posts, array( 'ID' => $postid ) );
5377 if ( ! $result ) {
5378 return false;
5379 }
5380
5381 if ( is_post_type_hierarchical( $post->post_type ) && $children ) {
5382 foreach ( $children as $child )
5383 clean_post_cache( $child );
5384 }
5385
5386 wp_clear_scheduled_hook('publish_future_post', array( $postid ) );
5387
5388 return $post;
5389 }
5390
5391 public function mlf_hide_info() {
5392
5393 if ( !wp_verify_nonce( $_POST['nonce'], MAXGALLERIA_MEDIA_LIBRARY_NONCE)) {
5394 exit(esc_html__('missing nonce! Please refresh this page.','maxgalleria-media-library'));
5395 }
5396
5397 // Check if the current user has the capability to upload files
5398 if(!current_user_can('upload_files')){
5399 exit(esc_html__('You do not have the capability to upload files.','maxgalleria-media-library'));
5400 }
5401
5402 $current_user_id = get_current_user_id();
5403
5404 update_user_meta( $current_user_id, MAXGALLERIA_MLP_DISPLAY_INFO, 'off' );
5405
5406 }
5407
5408 public function mlfp_set_scaling() {
5409
5410 if ( !wp_verify_nonce( $_POST['nonce'], MAXGALLERIA_MEDIA_LIBRARY_NONCE)) {
5411 exit(esc_html__('missing nonce! Please refresh this page.','maxgalleria-media-library'));
5412 }
5413
5414 // Check if the current user has the capability to manage options
5415 if(!current_user_can('manage_options')){
5416 exit(esc_html__('You do not have the capability to manage_options.','maxgalleria-media-library'));
5417 }
5418
5419 if ((isset($_POST['scaling_status'])) && (strlen(trim($_POST['scaling_status'])) > 0))
5420 $scaling_status = trim(sanitize_text_field($_POST['scaling_status']));
5421 else
5422 $scaling_status = "";
5423
5424 if ((isset($_POST['images_per_page'])) && (strlen(trim($_POST['images_per_page'])) > 0))
5425 $images_per_page = intval(trim(sanitize_text_field($_POST['images_per_page'])));
5426 else
5427 $images_per_page = "";
5428
5429 if ((isset($_POST['meta_index'])) && (strlen(trim($_POST['meta_index'])) > 0))
5430 $meta_index = trim(sanitize_text_field($_POST['meta_index']));
5431 else
5432 $meta_index = "";
5433
5434 if ((isset($_POST['skip_webp'])) && (strlen(trim($_POST['skip_webp'])) > 0))
5435 $skip_webp = trim(sanitize_text_field($_POST['skip_webp']));
5436 else
5437 $skip_webp = "";
5438
5439 $this->mlf_option_true_update(MAXGALLERIA_DISABLE_SCALLING, $scaling_status);
5440
5441 update_option(MAXGALLERIA_MLP_ITEMS_PRE_PAGE, $images_per_page, true);
5442
5443 if($meta_index == 'true') {
5444 if(get_option(MAXGALLERIA_POSTMETA_INDEX) == 'off') {
5445 $this->add_postmeta_index();
5446 update_option(MAXGALLERIA_POSTMETA_INDEX, 'on', true);
5447 }
5448 } else {
5449 if(get_option(MAXGALLERIA_POSTMETA_INDEX) == 'on') {
5450 $this->remove_postmeta_index();
5451 update_option(MAXGALLERIA_POSTMETA_INDEX, 'off', true);
5452 }
5453 }
5454
5455 $this->mlf_option_true_update(MLFP_SKIP_WEBP_FILES, $skip_webp);
5456
5457 echo esc_html__('The settings were updated.','maxgalleria-media-library');
5458 die();
5459 }
5460
5461 public function mlf_option_true_update($option_id, $option_value) {
5462 if($option_value == 'true') {
5463 update_option($option_id, 'on', true);
5464 } else {
5465 update_option($option_id, 'off', true);
5466 }
5467 }
5468
5469 public function add_postmeta_index() {
5470
5471 global $wpdb;
5472
5473 $sql = "ALTER TABLE $wpdb->postmeta ADD INDEX mg_meta_value (meta_key ASC, meta_value(255) ASC);";
5474
5475 //error_log($sql);
5476
5477 $wpdb->get_results($sql);
5478
5479 }
5480
5481 public function remove_postmeta_index() {
5482
5483 global $wpdb;
5484
5485 $sql = "DROP INDEX mg_meta_value ON $wpdb->postmeta";
5486
5487 //error_log($sql);
5488
5489 $wpdb->get_results($sql);
5490
5491 }
5492
5493 public function max_discover_files($parent_folder) {
5494
5495 //error_log("max_discover_files parent_folder $parent_folder");
5496
5497 global $wpdb, $is_IIS;
5498 $user_id = get_current_user_id();
5499 $files_to_add = array();
5500 $files_count = 0;
5501 $parent_folder = intval($parent_folder);
5502
5503 $folder_table = $wpdb->prefix . MAXGALLERIA_MEDIA_LIBRARY_FOLDER_TABLE;
5504
5505 $sql = "select ID, pm.meta_value as attached_file, post_title, $folder_table.folder_id
5506 from $wpdb->prefix" . "posts
5507 LEFT JOIN $folder_table ON($wpdb->prefix" . "posts.ID = $folder_table.post_id)
5508 LEFT JOIN {$wpdb->prefix}postmeta AS pm ON (pm.post_id = {$wpdb->prefix}posts.ID)
5509 where post_type = 'attachment'
5510 and folder_id = '$parent_folder'
5511 and pm.meta_key = '_wp_attached_file'
5512 order by post_title";
5513
5514 $attachments = $wpdb->get_results($sql);
5515
5516 $sql = "select meta_value as attached_file
5517 from {$wpdb->prefix}postmeta
5518 where post_id = $parent_folder
5519 and meta_key = '_wp_attached_file'";
5520
5521 $current_row = $wpdb->get_row($sql);
5522
5523 $baseurl = $this->upload_dir['baseurl'];
5524 $baseurl = rtrim($baseurl, '/') . '/';
5525 $image_location = $baseurl . ltrim($current_row->attached_file, '/');
5526
5527 //error_log("image location 1" . $image_location);
5528
5529 //str_replace('localhost', 'www.localhost', $image_location);
5530
5531 //error_log("image location 2" . $image_location);
5532
5533 $folder_path = $this->get_absolute_path($image_location);
5534
5535 //error_log($folder_path);
5536
5537 update_user_meta($user_id, MAXG_SYNC_FOLDER_PATH_ID, $parent_folder);
5538
5539 if ($is_IIS || strtoupper(substr(PHP_OS, 0, 3)) == 'WIN' || strtoupper(substr(PHP_OS, 0, 13)) == 'MICROSOFT-IIS' )
5540 update_user_meta($user_id, MAXG_SYNC_FOLDER_PATH, str_replace('\\', '\\\\', $folder_path));
5541 else
5542 update_user_meta($user_id, MAXG_SYNC_FOLDER_PATH, $folder_path);
5543
5544 $folder_contents = array_diff(scandir($folder_path), array('..', '.'));
5545
5546 foreach ($folder_contents as $file_path) {
5547
5548 if($file_path !== '.DS_Store' && $file_path !== '.htaccess') {
5549 $new_attachment = $folder_path . DIRECTORY_SEPARATOR . $file_path;
5550 if(!$this->is_webp($new_attachment) || ($this->is_webp($new_attachment) && $this->sync_skip_webp == 'off')) {
5551 if(!strpos($new_attachment, '-uai-')) { // skip thumbnails created by the Uncode theme
5552 if(!strpos($new_attachment, '-scaled.')) { // skip scaled images
5553 if(!strpos($new_attachment, '-pdf.jpg')) { // skip pdf thumbnails
5554 if(!is_dir($new_attachment)) {
5555 if($this->is_base_file($file_path, $folder_contents)) {
5556 if(!$this->search_folder_attachments($file_path, $attachments)) {
5557
5558 $old_attachment_name = $new_attachment;
5559 $new_attachment = pathinfo($new_attachment, PATHINFO_DIRNAME) . DIRECTORY_SEPARATOR . sanitize_file_name(pathinfo($new_attachment, PATHINFO_FILENAME) . "." . strtolower(pathinfo($new_attachment, PATHINFO_EXTENSION)));
5560
5561 if(rename($old_attachment_name, $new_attachment)) {
5562 $files_to_add[] = basename($new_attachment);
5563 $files_count++;
5564 } else {
5565 $files_to_add[] = basename($old_attachment_name);
5566 $files_count++;
5567 }
5568 }
5569 }
5570 }
5571 }
5572 }
5573 }
5574 }
5575 }
5576 }
5577
5578 if(is_array($files_to_add)) {
5579 update_user_meta($user_id, MAXG_SYNC_FILES, $files_to_add);
5580 }
5581 if($files_count > 0)
5582 return '3'; // add the files
5583 else
5584 return '2'; // check next folder
5585
5586 }
5587
5588 public function is_webp($new_attachment ) {
5589 if(strpos($new_attachment, '.webp') !== false)
5590 return true;
5591 else
5592 return false;
5593 }
5594
5595 public function mlfp_run_sync_process() {
5596
5597 global $wpdb;
5598 $user_id = get_current_user_id();
5599 $message = "";
5600 $folders_array = array();
5601
5602 if ( !wp_verify_nonce( $_POST['nonce'], MAXGALLERIA_MEDIA_LIBRARY_NONCE)) {
5603 exit(esc_html__('missing nonce! Please refresh this page.','maxgalleria-media-library'));
5604 }
5605
5606 // Check if the current user has the capability to upload files
5607 if(!current_user_can('upload_files')){
5608 exit(esc_html__('You do not have the capability to sync files.','maxgalleria-media-library'));
5609 }
5610
5611 if ((isset($_POST['phase'])) && (strlen(trim($_POST['phase'])) > 0))
5612 $phase = trim(sanitize_text_field($_POST['phase']));
5613 else
5614 $phase = "";
5615
5616 if ((isset($_POST['parent_folder'])) && (strlen(trim($_POST['parent_folder'])) > 0))
5617 $parent_folder = intval(trim(sanitize_text_field($_POST['parent_folder'])));
5618 else
5619 $parent_folder = "";
5620
5621 if ((isset($_POST['mlp_title_text'])) && (strlen(trim($_POST['mlp_title_text'])) > 0))
5622 $mlp_title_text = trim(sanitize_text_field($_POST['mlp_title_text']));
5623 else
5624 $mlp_title_text = "";
5625
5626 if ((isset($_POST['mlp_alt_text'])) && (strlen(trim($_POST['mlp_alt_text'])) > 0))
5627 $mlp_alt_text = trim(sanitize_text_field($_POST['mlp_alt_text']));
5628 else
5629 $mlp_alt_text = "";
5630
5631 $next_phase = '1';
5632
5633 switch($phase) {
5634 // find folders
5635 case '1':
5636 $next_phase = '2';
5637 $this->max_sync_contents($parent_folder);
5638 break;
5639
5640 // for each folder. get the folder ids
5641 case '2':
5642
5643 $folders_array = get_user_meta($user_id, MAXG_SYNC_FOLDERS, true);
5644
5645 if(is_array($folders_array)) {
5646 $next_folder = array_pop($folders_array);
5647 } else {
5648 $next_folder = $folders_array;
5649 }
5650
5651 if($next_folder != "") {
5652 $message = esc_html__("Scanning for new files and folders...please wait.",'maxgalleria-media-library');
5653 $this->max_discover_files($next_folder);
5654 update_user_meta($user_id, MAXG_SYNC_FOLDERS, $folders_array);
5655 $next_phase = '3';
5656 } else {
5657 $message = esc_html__("Syncing finished.",'maxgalleria-media-library');
5658 delete_user_meta($user_id, MAXG_SYNC_FOLDERS);
5659 delete_user_meta($user_id, MAXG_SYNC_FILES);
5660 delete_user_meta($user_id, MAXG_SYNC_FOLDER_PATH_ID);
5661 delete_user_meta($user_id, MAXG_SYNC_FOLDER_PATH);
5662 $next_phase = null;
5663 }
5664 break;
5665
5666 // add each file
5667 case '3':
5668 $files_to_add = get_user_meta($user_id, MAXG_SYNC_FILES, true);
5669
5670 if(is_array($files_to_add)) {
5671 $next_file = array_pop($files_to_add);
5672 } else {
5673 $next_file = $files_to_add;
5674 }
5675
5676 if($next_file != "") {
5677
5678 $next_phase = '3';
5679
5680 $wp_filetype = wp_check_filetype_and_ext($next_file, $next_file );
5681
5682 if ($wp_filetype['ext'] !== false) {
5683 $message = esc_html__("Adding ",'maxgalleria-media-library') . $next_file;
5684 $this->mlfp_process_sync_file($next_file, $mlp_title_text, $mlp_alt_text);
5685 } else {
5686 $message = $next_file . esc_html__(" is not an allowed file type. It was not added.",'maxgalleria-media-library');
5687 }
5688 update_user_meta($user_id, MAXG_SYNC_FILES, $files_to_add);
5689
5690 } else {
5691 $next_phase = '2';
5692 delete_user_meta($user_id, MAXG_SYNC_FILES);
5693 }
5694 break;
5695 }
5696 $phase = $next_phase;
5697
5698 $data = array('phase' => $phase, 'message' => esc_html($message));
5699 echo json_encode($data);
5700 die();
5701 }
5702
5703 public function mlfp_process_sync_file($next_file, $mlp_title_text, $mlp_alt_text) {
5704
5705 global $wpdb;
5706 $user_id = get_current_user_id();
5707
5708 if($next_file != "") {
5709
5710 $parent_folder = get_user_meta($user_id, MAXG_SYNC_FOLDER_PATH_ID, true);
5711
5712 $folder_path = get_user_meta($user_id, MAXG_SYNC_FOLDER_PATH, true);
5713
5714 $new_attachment = $folder_path . DIRECTORY_SEPARATOR . $next_file;
5715
5716 //$new_file_title = preg_replace( '/\.[^.]+$/', '', $next_file);
5717 $new_file_title = preg_replace('/(\.[a-zA-Z0-9]+)$/', '', $next_file); // only remove the extention when several periods are in the name.
5718
5719 $attach_id = $this->add_new_attachment($new_attachment, $parent_folder, $new_file_title, $mlp_alt_text, $mlp_title_text);
5720
5721 }
5722 }
5723
5724 public function mlfp_save_mc_data($serial_copy_ids, $folder_id, $user_id) {
5725
5726 global $is_IIS;
5727
5728 update_user_meta($user_id, MAXG_MC_FILES, $serial_copy_ids);
5729
5730 $destination_folder = $this->get_folder_path($folder_id);
5731
5732 if ($is_IIS || strtoupper(substr(PHP_OS, 0, 3)) == 'WIN' || strtoupper(substr(PHP_OS, 0, 13)) == 'MICROSOFT-IIS' )
5733 update_user_meta($user_id, MAXG_MC_DESTINATION_FOLDER, str_replace('\\', '\\\\', $destination_folder));
5734 else
5735 update_user_meta($user_id, MAXG_MC_DESTINATION_FOLDER, $destination_folder);
5736
5737 }
5738
5739 public function mlfp_process_mc_data() {
5740
5741 $user_id = get_current_user_id();
5742 $message = "";
5743 $next_phase = '2';
5744
5745 if ( !wp_verify_nonce( $_POST['nonce'], MAXGALLERIA_MEDIA_LIBRARY_NONCE)) {
5746 exit(esc_html__('missing nonce! Please refresh this page.','maxgalleria-media-library'));
5747 }
5748
5749 // Check if the current user has the capability to upload files
5750 if(!current_user_can('upload_files')){
5751 exit(esc_html__('You do not have the capability to upload files.','maxgalleria-media-library'));
5752 }
5753
5754 if ((isset($_POST['phase'])) && (strlen(trim($_POST['phase'])) > 0))
5755 $phase = trim(sanitize_textarea_field($_POST['phase']));
5756 else
5757 $phase = "";
5758
5759 if ((isset($_POST['folder_id'])) && (strlen(trim($_POST['folder_id'])) > 0))
5760 $folder_id = intval(trim(sanitize_textarea_field($_POST['folder_id'])));
5761 else
5762 $folder_id = "";
5763
5764 if ((isset($_POST['current_folder'])) && (strlen(trim($_POST['current_folder'])) > 0))
5765 $current_folder = intval(trim(sanitize_textarea_field($_POST['current_folder'])));
5766 else
5767 $current_folder = "";
5768
5769 if ((isset($_POST['action_name'])) && (strlen(trim($_POST['action_name'])) > 0))
5770 $action_name = trim(sanitize_textarea_field($_POST['action_name']));
5771 else
5772 $action_name = "";
5773
5774 if ((isset($_POST['serial_copy_ids'])) && (strlen(trim($_POST['serial_copy_ids'])) > 0))
5775 $serial_copy_ids = trim(sanitize_textarea_field($_POST['serial_copy_ids']));
5776 else
5777 $serial_copy_ids = "";
5778
5779
5780 switch($phase) {
5781
5782 case '1':
5783
5784 $serial_copy_ids = str_replace('"', '', $serial_copy_ids);
5785
5786 $serial_copy_ids = explode(',', $serial_copy_ids);
5787
5788 $this->mlfp_save_mc_data($serial_copy_ids, $folder_id, $user_id);
5789
5790 $next_phase = '2';
5791
5792 break;
5793
5794 case '2':
5795
5796 $files_to_move = get_user_meta($user_id, MAXG_MC_FILES, true);
5797
5798 if(is_array($files_to_move)) {
5799 $next_id = array_pop($files_to_move);
5800 } else {
5801 $next_id = $files_to_move;
5802 $files_to_move = "";
5803 }
5804
5805 if($next_id != "") {
5806 if(is_numeric($next_id)) {
5807 if($action_name == 'copy_media') {
5808 $message = $this->move_copy_file(true, $next_id, $folder_id, $current_folder, $user_id);
5809 } else {
5810 $message = $this->move_copy_file(false, $next_id, $folder_id, $current_folder, $user_id);
5811 }
5812 }
5813 update_user_meta($user_id, MAXG_MC_FILES, $files_to_move);
5814 } else {
5815 $next_phase = null;
5816 delete_user_meta($user_id, MAXG_MC_FILES);
5817 if($action_name == 'copy_media')
5818 $message = esc_html__("Finished copying files. ",'maxgalleria-media-library');
5819 else
5820 $message = esc_html__("Finished moving files. ",'maxgalleria-media-library');
5821 }
5822 break;
5823 }
5824 $phase = $next_phase;
5825
5826 $data = array('phase' => $phase, 'message' => esc_html($message));
5827
5828 echo json_encode($data);
5829
5830 die();
5831 }
5832
5833 public function move_copy_file($copy, $copy_id, $folder_id, $current_folder, $user_id) {
5834
5835 global $wpdb, $is_IIS;
5836 $message = "";
5837 $files = "";
5838 $refresh = false;
5839 $scaled = false;
5840 $copy_id = intval($copy_id);
5841
5842 $destination = get_user_meta($user_id, MAXG_MC_DESTINATION_FOLDER, true);
5843
5844 $sql = "select meta_value as attached_file
5845 from {$wpdb->prefix}postmeta
5846 where post_id = $copy_id
5847 AND meta_key = '_wp_attached_file'";
5848
5849 $row = $wpdb->get_row($sql);
5850
5851 $baseurl = $this->upload_dir['baseurl'];
5852 $baseurl = rtrim($baseurl, '/') . '/';
5853 $image_location = $baseurl . ltrim($row->attached_file, '/');
5854
5855 if(strpos($image_location, '-scaled.' ) !== false) {
5856 $scaled = true;
5857 }
5858
5859 $image_path = $this->get_absolute_path($image_location);
5860
5861 $destination_path = $this->get_absolute_path($destination);
5862
5863 $folder_basename = basename($destination_path);
5864
5865 $basename = pathinfo($image_path, PATHINFO_BASENAME);
5866
5867 $destination_name = $destination_path . DIRECTORY_SEPARATOR . $basename;
5868
5869 $copy_status = true;
5870
5871 if(file_exists($image_path)) {
5872 if(!is_dir($image_path)) {
5873 if(file_exists($destination_path)) {
5874 if(is_dir($destination_path)) {
5875
5876 if($copy) {
5877
5878 if($scaled) {
5879 $full_scaled_image_path = str_replace('-scaled*', '', $image_path);
5880 if(file_exists($full_scaled_image_path)) {
5881 $image_path = $full_scaled_image_path;
5882 $full_scaled_image = substr($full_scaled_image_path, strrpos($full_scaled_image_path, '/')+1);
5883 $destination_name = $destination_path . DIRECTORY_SEPARATOR . $full_scaled_image;
5884 }
5885 }
5886
5887 if(copy($image_path, $destination_name )) {
5888
5889 $destination_url = $this->get_file_url($destination_name);
5890 $title_text = get_the_title($copy_id);
5891 $alt_text = get_post_meta($copy_id, '_wp_attachment_image_alt', true);
5892 $attach_id = $this->add_new_attachment($destination_name, $folder_id, $title_text, $alt_text);
5893 if($attach_id === false){
5894 $copy_status = false;
5895 }
5896 }
5897 else {
5898 echo esc_html__('Unable to copy the file; please check the folder and file permissions.','maxgalleria-media-library') . PHP_EOL;
5899 $copy_status = false;
5900 }
5901 //move
5902 } else {
5903 if(rename($image_path, $destination_name )) {
5904
5905 // check current theme customizer settings for the file
5906 // and update if found
5907 $update_theme_mods = false;
5908 $move_image_url = $this->get_file_url_for_copy($image_path);
5909 $move_destination_url = $this->get_file_url_for_copy($destination_name);
5910 $key = array_search ($move_image_url, $this->theme_mods, true);
5911 if($key !== false ) {
5912 set_theme_mod( $key, $move_destination_url);
5913 $update_theme_mods = true;
5914 }
5915 if($update_theme_mods) {
5916 $theme_mods = get_theme_mods();
5917 $this->theme_mods = json_decode(json_encode($theme_mods), true);
5918 $update_theme_mods = false;
5919 }
5920
5921 $image_path = str_replace('.', '*.', $image_path );
5922 //error_log("image_path $image_path");
5923 $metadata = wp_get_attachment_metadata($copy_id);
5924 $path_to_thumbnails = pathinfo($image_path, PATHINFO_DIRNAME);
5925 //error_log("path_to_thumbnails $path_to_thumbnails");
5926
5927 if($scaled) {
5928 $full_scaled_image_path = str_replace('-scaled*', '', $image_path);
5929 $full_scaled_image = substr($full_scaled_image_path, strrpos($full_scaled_image_path, '/')+1);
5930 $scaled_image_destination = $destination_path . DIRECTORY_SEPARATOR . $full_scaled_image;
5931 if(file_exists($full_scaled_image_path))
5932 rename($full_scaled_image_path, $scaled_image_destination);
5933 }
5934
5935 if(isset($metadata['sizes'])) {
5936
5937 foreach($metadata['sizes'] as $source_path) {
5938 $thumbnail_file = $path_to_thumbnails . DIRECTORY_SEPARATOR . $source_path['file'];
5939 $thumbnail_destination = $destination_path . DIRECTORY_SEPARATOR . $source_path['file'];
5940 if(file_exists($thumbnail_file)) {
5941 rename($thumbnail_file, $thumbnail_destination);
5942
5943 // check current theme customizer settings for the fileg
5944 // and update if found
5945 $update_theme_mods = false;
5946 $move_source_url = $this->get_file_url_for_copy($source_path);
5947 $move_thumbnail_url = $this->get_file_url_for_copy($thumbnail_destination);
5948 $key = array_search ($move_source_url, $this->theme_mods, true);
5949 if($key !== false ) {
5950 set_theme_mod( $key, $move_thumbnail_url);
5951 $update_theme_mods = true;
5952 }
5953 if($update_theme_mods) {
5954 $theme_mods = get_theme_mods();
5955 $this->theme_mods = json_decode(json_encode($theme_mods), true);
5956 $update_theme_mods = false;
5957 }
5958 } else if(defined('MLF_CHECK_THUMBNAILFILE_MOVE')) {
5959 error_log("$thumbnail_file not found");
5960 }
5961 }
5962
5963 }
5964
5965 $destination_url = $this->get_file_url($destination_name);
5966
5967 // update posts table
5968 $table = $wpdb->prefix . "posts";
5969 $data = array('guid' => $destination_url );
5970 $where = array('ID' => $copy_id);
5971 $wpdb->update( $table, $data, $where);
5972
5973 // update folder table
5974 $table = $wpdb->prefix . MAXGALLERIA_MEDIA_LIBRARY_FOLDER_TABLE;
5975 $data = array('folder_id' => $folder_id );
5976 $where = array('post_id' => $copy_id);
5977 $wpdb->update( $table, $data, $where);
5978
5979 // // get the uploads dir name
5980 // $basedir = $this->upload_dir['baseurl'];
5981 // $uploads_dir_name_pos = strrpos($basedir, '/');
5982 // $uploads_dir_name = substr($basedir, $uploads_dir_name_pos+1);
5983 //
5984 // //find the name and cut off the part with the uploads path
5985 // $string_position = strpos($destination_name, $uploads_dir_name);
5986 // $uploads_dir_length = strlen($uploads_dir_name) + 1;
5987 // $uploads_location = substr($destination_name, $string_position+$uploads_dir_length);
5988
5989 // Get the uploads dir name
5990 $basedir = $this->upload_dir['baseurl'];
5991 $uploads_dir_name_pos = strrpos($basedir, '/');
5992 $uploads_dir_name = substr($basedir, $uploads_dir_name_pos + 1);
5993
5994 // Fetch the name of the content folder dynamically using the filter
5995 $content_folder = apply_filters('mlfp_content_folder', 'wp-content');
5996
5997 // Find the name and cut off the part with the uploads path
5998 $string_position = strpos($destination_name, $uploads_dir_name, strpos($destination_name, $content_folder));
5999 $uploads_dir_length = strlen($uploads_dir_name) + 1;
6000 $uploads_location = substr($destination_name, $string_position + $uploads_dir_length);
6001
6002 if($this->is_windows())
6003 $uploads_location = str_replace('\\','/', $uploads_location);
6004
6005 // update _wp_attached_file
6006
6007 $uploads_location = ltrim($uploads_location, '/');
6008 update_post_meta( $copy_id, '_wp_attached_file', $uploads_location );
6009
6010 // update _wp_attachment_metadata
6011 if ($is_IIS || strtoupper(substr(PHP_OS, 0, 3)) == 'WIN' || strtoupper(substr(PHP_OS, 0, 13)) == 'MICROSOFT-IIS' )
6012 $attach_data = wp_generate_attachment_metadata( $copy_id, addslashes($destination_name));
6013 else
6014 $attach_data = wp_generate_attachment_metadata( $copy_id, $destination_name );
6015 wp_update_attachment_metadata( $copy_id, $attach_data );
6016
6017 // update posts and pages
6018 $replace_image_location = $this->get_base_file($image_location);
6019 $replace_destination_url = $this->get_base_file($destination_url);
6020
6021 if(class_exists( 'SiteOrigin_Panels')) {
6022 $this->update_serial_postmeta_records($replace_image_location, $replace_destination_url);
6023 }
6024
6025 // update postmeta records for beaver builder
6026 if(class_exists( 'FLBuilderLoader')) {
6027 $sql = "SELECT ID FROM {$wpdb->prefix}posts WHERE post_content LIKE '%$replace_image_location%'";
6028
6029 $records = $wpdb->get_results($sql);
6030 foreach($records as $record) {
6031
6032 $this->update_bb_postmeta($record->ID, $replace_image_location, $replace_destination_url);
6033
6034 }
6035 // clearing BB caches
6036 if ( class_exists( 'FLBuilderModel' ) && method_exists( 'FLBuilderModel', 'delete_asset_cache_for_all_posts' ) ) {
6037 FLBuilderModel::delete_asset_cache_for_all_posts();
6038 }
6039 if ( class_exists( 'FLCustomizer' ) && method_exists( 'FLCustomizer', 'clear_all_css_cache' ) ) {
6040 FLCustomizer::clear_all_css_cache();
6041 }
6042
6043 }
6044
6045 $replace_sql = "UPDATE {$wpdb->prefix}posts SET `post_content` = REPLACE (`post_content`, '$replace_image_location', '$replace_destination_url');";
6046 $result = $wpdb->query($replace_sql);
6047
6048 $replace_sql = str_replace ( '/', '\/', $replace_sql);
6049 //error_log($replace_sql);
6050 $result = $wpdb->query($replace_sql);
6051
6052 // for updating wp pagebuilder
6053 if(defined('WPPB_LICENSE')) {
6054 $this->update_wppb_data($replace_image_location, $destination_url);
6055 }
6056
6057 // for updating themify images
6058 if(function_exists('themify_builder_activate')) {
6059 $this->update_themify_data($replace_image_location, $destination_url);
6060 }
6061
6062 // for updating elementor background images
6063 if(is_plugin_active("elementor/elementor.php")) {
6064 $this->update_elementor_data($copy_id, $replace_image_location, $destination_url);
6065 }
6066
6067 $message .= esc_html__('Updating attachment links, please wait...','maxgalleria-media-library') . PHP_EOL;
6068 $files = $this->display_folder_contents ($current_folder, true, "", false);
6069 $refresh = true;
6070 }
6071 else {
6072 $message .= esc_html( __('Unable to move ','maxgalleria-media-library') . $basename . __('; please check the folder and file permissions.','maxgalleria-media-library') . PHP_EOL);
6073 $copy_status = false;
6074 }
6075 }
6076 }
6077 else {
6078 $message .= esc_html( __('The destination is not a folder: ','maxgalleria-media-library') . $destination_path . PHP_EOL);
6079 $copy_status = false;
6080 }
6081 }
6082 else {
6083 $message .= esc_html( __('Cannot find destination folder: ','maxgalleria-media-library') . $destination_path . PHP_EOL);
6084 $copy_status = false;
6085 }
6086 }
6087 else {
6088 $message .= esc_html__('Coping or moving a folder is not allowed.','maxgalleria-media-library') . PHP_EOL;
6089 $copy_status = false;
6090 }
6091 }
6092 else {
6093 $message .= esc_html( __('Cannot find the file: ','maxgalleria-media-library') . $image_path . ". " . PHP_EOL);
6094 //$this->write_log("Cannot find the file: $image_path");
6095 $copy_status = false;
6096 }
6097
6098 if($copy) {
6099 if($copy_status)
6100 $message .= esc_html($basename . __(' was copied to ','maxgalleria-media-library') . $folder_basename . PHP_EOL);
6101 else
6102 $message .= esc_html($basename . __(' was not copied.','maxgalleria-media-library') . PHP_EOL);
6103 }
6104 else {
6105 if($copy_status)
6106 $message .= esc_html($basename . __(' was moved to ','maxgalleria-media-library') . $folder_basename . PHP_EOL);
6107 else
6108 $message .= esc_html($basename . __(' was not moved.','maxgalleria-media-library') . PHP_EOL);
6109 }
6110
6111 return $message;
6112
6113 }
6114
6115 public function update_wppb_data($replace_image_location, $destination_url) {
6116
6117 global $wpdb;
6118 $save = false;
6119 $table = $wpdb->prefix . "postmeta";
6120
6121 $position = strrpos($destination_url, '.');
6122 $url_without_extension = substr($destination_url, 0, $position);
6123
6124 $base_file_name = basename($replace_image_location);
6125
6126 $sql = "select post_id, meta_id, meta_value from wp_postmeta where meta_key = '_wppb_content' and meta_value like '%{$base_file_name}%'";
6127 //error_log($sql);
6128
6129 $rows = $wpdb->get_results($sql);
6130 if($rows) {
6131 foreach($rows as $row) {
6132 $jarrays = json_decode($row->meta_value, true);
6133 $this->wppb_recursive_find_and_update($jarrays, $replace_image_location, $destination_url, $url_without_extension);
6134 //error_log(print_r($jarrays, true));
6135
6136 $jarrays = json_encode($jarrays);
6137 $data = array('meta_value' => $jarrays);
6138 $where = array('meta_id' => $row->meta_id);
6139 $wpdb->update($table, $data, $where);
6140 }
6141 }
6142 }
6143
6144 public function wppb_recursive_find_and_update(&$jarrays, $replace_image_location, $destination_url ) {
6145
6146 foreach($jarrays as $key => &$value) {
6147 if(is_array($value)) {
6148 $this->wppb_recursive_find_and_update($value, $replace_image_location, $destination_url);
6149 } else {
6150 if($key == 'url' && strpos($value, $replace_image_location) !== false) {
6151 $value = $destination_url;
6152 }
6153 }
6154 }
6155 }
6156
6157 public function update_themify_data($replace_image_location, $destination_url) {
6158
6159 global $wpdb;
6160 $save = false;
6161 $table = $wpdb->prefix . "postmeta";
6162
6163 $position = strrpos($destination_url, '.');
6164 $url_without_extension = substr($destination_url, 0, $position);
6165
6166 $base_file_name = basename($replace_image_location);
6167
6168 $sql = "select post_id, meta_id, meta_value from {$table} where meta_key = '_themify_builder_settings_json' and meta_value like '%$base_file_name%'";
6169
6170 $rows = $wpdb->get_results($sql);
6171 if($rows) {
6172 foreach($rows as $row) {
6173 $jarrays = json_decode($row->meta_value, true);
6174 $this->recursive_find_and_update($jarrays, $replace_image_location, $destination_url, $url_without_extension);
6175
6176 $jarrays = json_encode($jarrays);
6177 $data = array('meta_value' => $jarrays);
6178 $where = array('meta_id' => $row->meta_id);
6179 $wpdb->update($table, $data, $where);
6180 }
6181 }
6182 }
6183
6184 public function recursive_find_and_update(&$jarrays, $replace_image_location, $destination_url, $url_without_extension) {
6185
6186 foreach($jarrays as $key => &$value) {
6187 if(is_array($value)) {
6188 $this->recursive_find_and_update($value, $replace_image_location, $destination_url, $url_without_extension);
6189 } else {
6190 if($key == 'url_image' && strpos($value, $replace_image_location) !== false) {
6191 $value = $destination_url;
6192 } else if($key == 'img_url_slider' && strpos($value, $replace_image_location) !== false) {
6193 $value = $destination_url;
6194 } else if($key == 'content_text' && strpos($value, $replace_image_location) !== false ) {
6195 $content_text = $value;
6196 $value = str_replace($replace_image_location, $url_without_extension, $content_text);
6197 }
6198 }
6199 }
6200 }
6201
6202 public function update_elementor_data($image_id, $replace_image_location, $replace_destination_url) {
6203
6204 global $wpdb;
6205 $save = false;
6206
6207 $base_file_name = basename($replace_image_location);
6208
6209 $sql = "select post_id, meta_id, meta_value from {$wpdb->prefix}postmeta where meta_key = '_elementor_data' and meta_value like '%$base_file_name%'";
6210
6211 $rows = $wpdb->get_results($sql);
6212 if($rows) {
6213 foreach($rows as $row) {
6214
6215 // check for serialized data
6216 $data = @unserialize($row->meta_value);
6217 if($data === false)
6218 $jarrays = json_decode($row->meta_value, true);
6219 else {
6220 $jarrays = $data;
6221 }
6222
6223 if(is_array($jarrays)) {
6224 foreach($jarrays as &$jarray) {
6225 if($this->search_elementor_array($image_id, $jarray, $replace_image_location, $replace_destination_url, $row->post_id))
6226 $save = true;
6227 }
6228 } else {
6229 //error_log("is not an array");
6230 }
6231 if($save) {
6232 update_post_meta($row->post_id, '_elementor_data', $jarrays);
6233 }
6234 $this->update_elemenator_css_file($row->post_id, $replace_image_location, $replace_destination_url);
6235 }
6236 }
6237 }
6238
6239 public function search_elementor_array($image_id, &$jarray, $replace_image_location, $replace_destination_url, $post_id) {
6240
6241 $save = false;
6242 if(array_key_exists('settings', $jarray)) {
6243 if($jarray['settings'] !== null) { // Add null check here
6244 if(array_key_exists('background_background', $jarray['settings'])) {
6245 if($jarray['settings']['background_background'] == 'classic') {
6246 if(array_key_exists('id', $jarray['settings']['background_image'])) {
6247 if($jarray['settings']['background_image']['id'] == $image_id) {
6248 $jarray['settings']['background_image']['url'] = $replace_destination_url;
6249 $save = true;
6250 }
6251 }
6252 }
6253 }
6254 }
6255 }
6256 }
6257
6258 public function search_elementor_array1($image_id, &$jarray, $replace_image_location, $replace_destination_url, $post_id) {
6259
6260 $save = false;
6261 if(array_key_exists('settings', $jarray)) {
6262 if(array_key_exists('background_background', $jarray['settings'])) {
6263 if($jarray['settings']['background_background'] == 'classic') {
6264 if(array_key_exists('id', $jarray['settings']['background_image'])) {
6265 if($jarray['settings']['background_image']['id'] == $image_id) {
6266 $jarray['settings']['background_image']['url'] = $replace_destination_url;
6267 $save = true;
6268 }
6269 }
6270 }
6271 }
6272 }
6273 }
6274
6275 public function update_elemenator_css_file($post_id, $replace_image_location, $replace_destination_url) {
6276
6277 $css_file_path = trailingslashit($this->upload_dir['basedir']) . "elementor/css/post-{$post_id}.css";
6278
6279 $position = strrpos($replace_destination_url, '.');
6280
6281 $url_without_extension = substr($replace_destination_url, 0, $position);
6282
6283 if(file_exists($css_file_path)) {
6284
6285 $css = file_get_contents($css_file_path);
6286
6287 $css = str_replace($replace_image_location, $url_without_extension, $css);
6288
6289 file_put_contents($css_file_path, $css);
6290 }
6291
6292 }
6293
6294 public function update_bb_postmeta($post_id, $replace_image_location, $replace_destination_url) {
6295
6296 $this->update_bb_postmeta_item('_fl_builder_draft', $post_id, $replace_image_location, $replace_destination_url);
6297 $this->update_bb_postmeta_item('_fl_builder_data', $post_id, $replace_image_location, $replace_destination_url);
6298
6299 }
6300
6301 public function update_bb_postmeta_item($metakey, $post_id, $replace_image_location, $replace_destination_url) {
6302
6303 $save = false;
6304 $builder_info = json_decode(json_encode(get_post_meta($post_id, $metakey, true)));
6305 $builder_info = $this->objectToArray($builder_info);
6306
6307 if(is_array($builder_info)){
6308 foreach ($builder_info as $key => &$info_head) {
6309 foreach ($info_head as $info_key => &$info_value) {
6310 if(is_array($info_value)) {
6311 foreach ($info_value as $data_key => &$data_value) {
6312 if(!is_array($data_value)) {
6313 if($data_key == 'photo_src' || $data_key == 'text') {
6314 $save = true;
6315 $data_value = str_replace($replace_image_location, $replace_destination_url, $data_value);
6316 }
6317 } else {
6318 foreach ($data_value as $next_key => &$next_value) {
6319 if(!is_array($next_value)) {
6320 if($next_key == 'url') {
6321 $save = true;
6322 $next_value = str_replace($replace_image_location, $replace_destination_url, $next_value);
6323 }
6324 } else {
6325 foreach ($next_value as $sizes_key => &$sizes_value) {
6326 if(is_array($sizes_value)) {
6327 foreach ($sizes_value as $final_key => &$final_value) {
6328 if(!is_array($final_value)) {
6329 if($final_key == 'url') {
6330 $save = true;
6331 $final_value = str_replace($replace_image_location, $replace_destination_url, $final_value);
6332 }
6333 }
6334 }
6335 }
6336 }
6337 }
6338 }
6339 }
6340 }
6341 }
6342 }
6343 }
6344 }
6345
6346 if($save) {
6347 $builder_info = $this->arrayToObject($builder_info);
6348 $builder_info = serialize($builder_info);
6349 update_post_meta($post_id, $metakey, $builder_info);
6350 }
6351
6352 }
6353
6354 function objectToArray( $object ) {
6355 if( !is_object( $object ) && !is_array( $object )){
6356 return $object;
6357 }
6358 if( is_object( $object ) ){
6359 $object = get_object_vars( $object );
6360 }
6361 return array_map( array($this, 'objectToArray'), $object );
6362 }
6363
6364 public function arrayToObject($d){
6365 if (is_array($d)){
6366 return (object) array_map(array($this, 'arrayToObject'), $d);
6367 } else {
6368 return $d;
6369 }
6370 }
6371
6372 public function get_upload_status() {
6373 $data = get_userdata(get_current_user_id());
6374 if (!is_object($data) || !isset($data->allcaps['upload_files']))
6375 $this->current_user_can_upload = false;
6376 else
6377 $this->current_user_can_upload = $data->allcaps['upload_files'];
6378 }
6379
6380 public function update_serial_postmeta_records($replace_image_location, $replace_destination_url) {
6381
6382 global $wpdb;
6383
6384 // = instead oflike?
6385 $sql = "SELECT * FROM {$wpdb->prefix}postmeta WHERE meta_key = 'panels_data' and meta_value like '%$replace_image_location%'";
6386
6387 $widgets = array('text','content','url','mp4','m4v','webm','ogv','flv');
6388
6389 $records = $wpdb->get_results($sql);
6390 foreach($records as $record) {
6391
6392 $data = unserialize($record->meta_value);
6393
6394 if (isset($data['widgets']) && is_array($data['widgets'])) {
6395
6396 for ($index = 0; $index < count($data['widgets']); $index++) {
6397
6398 foreach($widgets as $widget) {
6399
6400 if(isset($data['widgets'][$index][$widget])) {
6401
6402 if(is_string($data['widgets'][$index][$widget])) {
6403 $text = $data['widgets'][$index][$widget];
6404 //error_log("$widget: $text");
6405 $data['widgets'][$index][$widget] = str_replace($replace_image_location, $replace_destination_url, $text);
6406 //error_log($data['widgets'][$index][$widget]);
6407 }
6408 }
6409
6410 }
6411
6412 }
6413
6414 }
6415
6416 update_post_meta($record->post_id, $record->meta_key, $data);
6417 }
6418 }
6419
6420 public function get_ajax_paramater($parameter_name, $default = '') {
6421
6422 if ((isset($_POST[$parameter_name])) && (strlen(trim($_POST[$parameter_name])) > 0))
6423 $return_value = trim(sanitize_text_field($_POST[$parameter_name]));
6424 else
6425 $return_value = $default;
6426
6427 return $return_value;
6428
6429 }
6430
6431 public function mlfp_process_bdp() {
6432
6433 $message = "";
6434
6435 if ( !wp_verify_nonce( $_POST['nonce'], MAXGALLERIA_MEDIA_LIBRARY_NONCE)) {
6436 exit(esc_html__('Missing nonce! Please refresh this page.','maxgalleria-media-library'));
6437 }
6438
6439 // Check if the current user has the capability to manage options
6440 if(!current_user_can('manage_options')){
6441 exit(esc_html__('You do not have the capability to manage options.','maxgalleria-media-library'));
6442 }
6443
6444 $activate_mlfp_bdp = $this->get_ajax_paramater('activate_mlfp_bdp');
6445 $disable_listing = $this->get_ajax_paramater('disable_listing');
6446 $disable_hotlinking = $this->get_ajax_paramater('disable_hotlinking');
6447 $auto_protect = $this->get_ajax_paramater('auto_protect');
6448 $display_fe_protected_images = $this->get_ajax_paramater('display_fe_protected_images');
6449 $prevent_right_click = $this->get_ajax_paramater('prevent_right_click');
6450 $bda_role = $this->get_ajax_paramater('bda_role');
6451 $no_access_page_id = intval($this->get_ajax_paramater('no_access_page_id'));
6452 $no_access_page_name = $this->get_ajax_paramater('no_access_page_name');
6453
6454 if($this->bda == 'off' && $activate_mlfp_bdp == 'true') {
6455 //error_log("mlfp_process_bdp 2");
6456
6457 $this->protected_content_dir = $this->upload_dir['basedir'] . '/' . MLFP_PROTECTED_DIRECTORY;
6458
6459 $content_folder = apply_filters( 'mlfp_content_folder', 'wp-content');
6460
6461 $position = strpos($this->protected_content_dir, $content_folder);
6462
6463 $bda_path = substr($this->protected_content_dir, $position);
6464
6465 if(!file_exists($this->protected_content_dir)) {
6466 if(mkdir($this->protected_content_dir)) {
6467 //error_log("created " . $this->protected_content_dir);
6468 if(defined('FS_CHMOD_DIR'))
6469 @chmod($this->protected_content_dir, FS_CHMOD_DIR);
6470 else
6471 @chmod($this->protected_content_dir, 0775);
6472 //@chmod($this->protected_content_dir, 0755);
6473
6474 if(file_exists($this->protected_content_dir)) {
6475
6476 $this->bda_folder_id = $this->add_media_folder(MLFP_PROTECTED_DIRECTORY, $this->uploads_folder_ID, $this->protected_content_dir);
6477 update_option(MLFP_PROTECTED_DIR, $this->protected_content_dir);
6478
6479 $skip_folder_file = $this->protected_content_dir . DIRECTORY_SEPARATOR . "mlpp-hidden";
6480
6481 file_put_contents($skip_folder_file, '');
6482
6483 $message .= esc_html__('Procteced-content folder added.','maxgalleria-media-library') . '<br>';
6484 }
6485 }
6486 }
6487
6488 $message .= esc_html__('Block Direct Access activated.','maxgalleria-media-library');
6489
6490 $this->bda = 'on';
6491 update_option(MLFP_BDA, $this->bda);
6492 add_filter('mod_rewrite_rules', array( $this, 'mlfp_update_htaccess'));
6493 flush_rewrite_rules();
6494
6495 // check for download page
6496 if(!get_page_by_path("mlfp-download")) {
6497 $wordpress_page = array(
6498 'post_title' => esc_html__('MLFP Download','maxgalleria-media-library'),
6499 'post_content' => '',
6500 'post_status' => 'publish',
6501 'post_author' => 1,
6502 'post_type' => 'page'
6503 );
6504 $download_page_id = wp_insert_post($wordpress_page);
6505 update_option(MLFP_BDA_DOWNLOAD_PAGE, $download_page_id);
6506 }
6507
6508 } else if($this->bda == 'on' && $activate_mlfp_bdp == 'false') {
6509 $this->bda = 'off';
6510 update_option(MLFP_BDA, 'off');
6511 if($post = get_page_by_path('mlfp-download')) {
6512 wp_delete_post($post->ID, true);
6513 }
6514 $message .= esc_html__('Block Direct Access deactivated.','maxgalleria-media-library');
6515
6516 remove_filter('mod_rewrite_rules', array( $this, 'mlfp_update_htaccess'));
6517 flush_rewrite_rules();
6518 //error_log("removing bda rules");
6519 }
6520
6521 if($disable_listing == 'true') {
6522 update_option(MLFP_BDA_DIR_LISTING, 'on');
6523 } else {
6524 update_option(MLFP_BDA_DIR_LISTING, 'off');
6525 }
6526
6527 if($disable_hotlinking == 'true') {
6528 update_option(MLFP_BDA_HOTLINKING, 'on');
6529 } else {
6530 update_option(MLFP_BDA_HOTLINKING, 'off');
6531 }
6532
6533 if($auto_protect == 'true') {
6534 update_option(MLFP_BDA_AUTO_PROTECT, 'on');
6535 } else {
6536 update_option(MLFP_BDA_AUTO_PROTECT, 'off');
6537 }
6538
6539 if($display_fe_protected_images == 'true') {
6540 update_option(MLFP_BDA_DISPLAY_FE_IMAGES, 'on');
6541 } else {
6542 update_option(MLFP_BDA_DISPLAY_FE_IMAGES, 'off');
6543 }
6544
6545 if($prevent_right_click == 'true') {
6546 update_option(MLFP_BDA_PREVENT_RIGHT_CLICK, 'on');
6547 } else {
6548 update_option(MLFP_BDA_PREVENT_RIGHT_CLICK, 'off');
6549 }
6550
6551 if(!empty($bda_role)) {
6552 update_option(MLFP_BDA_USER_ROLE, $bda_role);
6553 }
6554
6555 echo $message;
6556
6557 die();
6558
6559 }
6560
6561 public function mlfp_save_noaccess_page() {
6562
6563 if ( !wp_verify_nonce( $_POST['nonce'], MAXGALLERIA_MEDIA_LIBRARY_NONCE)) {
6564 exit(esc_html__('Missing nonce! Please refresh this page.','maxgalleria-media-library'));
6565 }
6566
6567 // Check if the current user has the capability to manage options
6568 if(!current_user_can('manage_options')){
6569 exit(esc_html__('You do not have the capability to manage options.','maxgalleria-media-library'));
6570 }
6571
6572 $no_access_page_id = intval($this->get_ajax_paramater('no_access_page_id'));
6573 $no_access_page_name = $this->get_ajax_paramater('no_access_page_name');
6574
6575 if(!empty($no_access_page_id))
6576 update_option(MLFP_NO_ACCESS_PAGE_ID, $no_access_page_id);
6577
6578 if(!empty($no_access_page_name))
6579 update_option(MLFP_NO_ACCESS_PAGE_TITLE, $no_access_page_name);
6580
6581 echo '';
6582
6583 die();
6584 }
6585
6586 public function mlfp_update_htaccess($rules) {
6587
6588 //error_log("mlfp_update_htaccess");
6589
6590 global $wpdb;
6591 $endpoint = "mlfp_bdp";
6592 $display_listing = '';
6593 $bdp_rules = '';
6594
6595 $bdp_rules .= "# Block Direct Access Rewrite Rules" . PHP_EOL;
6596 $bdp_rules .= "RewriteRule private/([a-zA-Z0-9]+)$ index.php?{$endpoint}=$1 [L]" . PHP_EOL;
6597 $bdp_rules .= "RewriteCond %{REQUEST_FILENAME} -s" . PHP_EOL;
6598 $bdp_rules .= "RewriteCond %{HTTP_USER_AGENT} !facebookexternalhit/[0-9]" . PHP_EOL;
6599 $bdp_rules .= "RewriteCond %{HTTP_USER_AGENT} !Googlebot/[0-9]" . PHP_EOL;
6600 $bdp_rules .= "RewriteCond %{HTTP_USER_AGENT} !Twitterbot/[0-9]" . PHP_EOL;
6601 $directAccessPath = str_replace( trailingslashit( site_url() ), '', 'index.php' ) . "?{$endpoint}=$1&block_access=true [QSA,L]" . PHP_EOL;
6602 $upload_dir_url = str_replace( "https", "http", wp_upload_dir()['baseurl'] );
6603 $site_url = str_replace( "https", "http", site_url() );
6604 $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;
6605
6606 if(get_option(MLFP_BDA_HOTLINKING) == 'on') {
6607 $domain = home_url( '/', is_ssl() ? 'https' : 'http' );
6608 $bdp_rules .= "# Block Direct Access Prevent Hotlinking Rules" . PHP_EOL;
6609 $bdp_rules .= "RewriteCond %{HTTP_REFERER} !^$" . PHP_EOL;
6610 $bdp_rules .= "RewriteCond %{HTTP_REFERER} !^{$domain} [NC]" . PHP_EOL;
6611 $bdp_rules .= "RewriteRule \.(gif|jpg|jpeg|bmp|zip|rar|mp3|flv|swf|xml|png|avif|css|pdf)$ - [F]" . PHP_EOL;
6612 $bdp_rules .= "# Block Direct Access Prevent Hotlinking Rules End" . PHP_EOL;
6613 }
6614
6615 if(get_option(MLFP_BDA_DIR_LISTING) == 'on') {
6616 $display_listing = "Options -Indexes" . PHP_EOL;
6617 }
6618
6619 $bdp_rules .= "# Block Direct Access Rewrite Rules End" . PHP_EOL;
6620
6621 return $bdp_rules . $rules . $display_listing;
6622
6623 }
6624
6625 public function mlfp_toggle_file_access() {
6626
6627 if ( !wp_verify_nonce( $_POST['nonce'], MAXGALLERIA_MEDIA_LIBRARY_NONCE)) {
6628 exit(esc_html__('missing nonce!','maxgalleria-media-library'));
6629 }
6630
6631 // Check if the current user has the capability to upload files
6632 if(!current_user_can('upload_files')){
6633 exit(esc_html__('You do not have the capability to upload files.','maxgalleria-media-library'));
6634 }
6635
6636 $next_id = intval($this->get_ajax_paramater('file_id', ''));
6637
6638 $current_folder = intval($this->get_ajax_paramater('current_folder', ''));
6639
6640 $protected = intval($this->get_ajax_paramater('protected', '0'));
6641
6642 if($next_id != "") {
6643 $message = $this->move_to_protected_folder($next_id, $current_folder, $protected);
6644 } else {
6645 $message = esc_html__("Finished moving files to protected folder. ",'maxgalleria-media-library');
6646 }
6647
6648 echo $message;
6649
6650 die();
6651
6652 }
6653
6654 public function move_to_protected_folder($next_id, $current_folder, $protected) {
6655
6656 require_once( ABSPATH . 'wp-admin/includes/image.php' );
6657
6658 global $wpdb, $is_IIS;
6659 $message = "";
6660 $files = "";
6661 $refresh = false;
6662 $scaled = false;
6663 $next_id = intval($next_id);
6664
6665 $sql = "select meta_value as attached_file
6666 from $wpdb->postmeta
6667 where post_id = $next_id
6668 AND meta_key = '_wp_attached_file'";
6669
6670 //error_log($sql);
6671
6672 $row = $wpdb->get_row($sql);
6673
6674 if(!$row) {
6675 return esc_html__('Could not find the selected file.','maxgalleria-media-library') . PHP_EOL;
6676 }
6677
6678 remove_filter( 'wp_generate_attachment_metadata', array($this, 'add_attachment_to_folder2'));
6679
6680 $baseurl = $this->upload_dir['baseurl'];
6681 $baseurl = rtrim($baseurl, '/') . '/';
6682 $image_location = $baseurl . ltrim($row->attached_file, '/');
6683
6684 //error_log("image_location $image_location");
6685 if(strpos($image_location, '-scaled.' ) !== false) {
6686 $scaled = true;
6687 }
6688
6689 $image_path = $this->get_absolute_path($image_location);
6690 //error_log("image_path $image_path");
6691
6692 if($protected == 0 ) {
6693 $destination_path = $this->protected_content_dir;
6694
6695 //error_log('Protecting file ' . $row->attached_file);
6696
6697 $destination_name = $destination_path . DIRECTORY_SEPARATOR . $row->attached_file;
6698 //error_log("destination_name $destination_name");
6699 $position = strrpos($destination_name, '/');
6700 $destination_folder = substr($destination_name, 0, $position);
6701
6702 } else {
6703 $destination_path = $this->get_folder_path($current_folder);
6704 $destination_folder = $destination_path;
6705
6706 //error_log('Unprotecting file ' . $row->attached_file);
6707
6708 $basename = pathinfo($row->attached_file, PATHINFO_BASENAME);
6709
6710 $destination_name = $destination_path . DIRECTORY_SEPARATOR . $basename;
6711
6712 }
6713 //error_log("destination_path $destination_path");
6714
6715
6716 if(!file_exists($destination_folder)) {
6717 if($this->make_dir_path($destination_folder)) {
6718 if(defined('FS_CHMOD_DIR'))
6719 @chmod($destination_folder, FS_CHMOD_DIR);
6720 else
6721 @chmod($destination_folder, 0755);
6722 }
6723 }
6724
6725 $copy_status = true;
6726
6727 if(file_exists($image_path)) {
6728 if(!is_dir($image_path)) {
6729 if(file_exists($destination_path)) {
6730 if(is_dir($destination_path)) {
6731 //error_log("rename $image_path, $destination_name");
6732 //return false;
6733 if(rename($image_path, $destination_name )) {
6734
6735 $image_path = str_replace('.', '*.', $image_path );
6736 $metadata = wp_get_attachment_metadata($next_id);
6737 $path_to_thumbnails = pathinfo($image_path, PATHINFO_DIRNAME);
6738
6739 if($scaled) {
6740 $full_scaled_image_path = str_replace('-scaled*', '', $image_path);
6741 //error_log("full_scaled_image_path $full_scaled_image_path");
6742 $full_scaled_image = substr($full_scaled_image_path, strrpos($full_scaled_image_path, '/')+1);
6743 //error_log("full_scaled_image $full_scaled_image");
6744 $scaled_image_destination = $destination_folder . DIRECTORY_SEPARATOR . $full_scaled_image;
6745 //error_log("scaled_image_destination $scaled_image_destination");
6746 if(file_exists($full_scaled_image_path))
6747 rename($full_scaled_image_path, $scaled_image_destination);
6748 }
6749
6750 if(isset($metadata['sizes'])) {
6751
6752 foreach($metadata['sizes'] as $source_path) {
6753 $thumbnail_file = $path_to_thumbnails . DIRECTORY_SEPARATOR . $source_path['file'];
6754 $thumbnail_destination = $destination_folder . DIRECTORY_SEPARATOR . $source_path['file'];
6755 //error_log("thumbnail_file $thumbnail_file");
6756 if(file_exists($thumbnail_file)) {
6757 unlink($thumbnail_file);
6758
6759 }
6760 }
6761 }
6762
6763 $destination_url = $this->get_file_url($destination_name);
6764
6765 // update block_access table
6766 if($protected == 0) {
6767 $this->add_bda_record($next_id);
6768 $message = esc_html__('The file', 'maxgalleria-media-library') . esc_html(" $row->attached_file ") . esc_html__('is protected.', 'maxgalleria-media-library');
6769 } else {
6770 $this->remove_bda_record($next_id);
6771 $message = esc_html__('The file', 'maxgalleria-media-library') . esc_html(" $row->attached_file ") . esc_html__('is unprotected.', 'maxgalleria-media-library');
6772 }
6773 //error_log("block_access_table updated $protected");
6774
6775 //add postmete record
6776
6777 // // get the uploads dir name
6778 // $basedir = $this->upload_dir['baseurl'];
6779 // $uploads_dir_name_pos = strrpos($basedir, '/');
6780 // $uploads_dir_name = substr($basedir, $uploads_dir_name_pos+1);
6781 //
6782 // //find the name and cut off the part with the uploads path
6783 // $string_position = strpos($destination_name, $uploads_dir_name);
6784 // $uploads_dir_length = strlen($uploads_dir_name) + 1;
6785 // $uploads_location = substr($destination_name, $string_position+$uploads_dir_length);
6786
6787 // Get the uploads dir name
6788 $basedir = $this->upload_dir['baseurl'];
6789 $uploads_dir_name_pos = strrpos($basedir, '/');
6790 $uploads_dir_name = substr($basedir, $uploads_dir_name_pos + 1);
6791
6792 // Fetch the name of the content folder dynamically using the filter
6793 $content_folder = apply_filters('mlfp_content_folder', 'wp-content');
6794
6795 // Find the name and cut off the part with the uploads path
6796 $string_position = strpos($destination_name, $uploads_dir_name, strpos($destination_name, $content_folder));
6797 $uploads_dir_length = strlen($uploads_dir_name) + 1;
6798 $uploads_location = substr($destination_name, $string_position + $uploads_dir_length);
6799
6800 if($this->is_windows())
6801 $uploads_location = str_replace('\\','/', $uploads_location);
6802
6803 // update _wp_attached_file
6804
6805 $uploads_location = ltrim($uploads_location, '/');
6806 update_post_meta( $next_id, '_wp_attached_file', $uploads_location );
6807 //error_log("new file location $uploads_location");
6808
6809 // update _wp_attachment_metadata
6810 if ($is_IIS || strtoupper(substr(PHP_OS, 0, 3)) == 'WIN' || strtoupper(substr(PHP_OS, 0, 13)) == 'MICROSOFT-IIS' )
6811 $attach_data = wp_generate_attachment_metadata( $next_id, addslashes($destination_name));
6812 else
6813 $attach_data = wp_generate_attachment_metadata( $next_id, $destination_name );
6814 wp_update_attachment_metadata( $next_id, $attach_data );
6815
6816 // update posts and pages
6817 $replace_image_location = $this->get_base_file($image_location);
6818 $replace_destination_url = $this->get_base_file($destination_url);
6819
6820 if(class_exists( 'SiteOrigin_Panels')) {
6821 $this->update_serial_postmeta_records($replace_image_location, $replace_destination_url);
6822 }
6823
6824 // update postmeta records for beaver builder
6825 if(class_exists( 'FLBuilderLoader')) {
6826 $sql = "SELECT ID FROM {$wpdb->prefix}posts WHERE post_content LIKE '%$replace_image_location%'";
6827 //error_log($sql);
6828
6829 $records = $wpdb->get_results($sql);
6830 foreach($records as $record) {
6831
6832 $this->update_bb_postmeta($record->ID, $replace_image_location, $replace_destination_url);
6833
6834 //}
6835 // clearing BB caches
6836 //error_log("check for cache");
6837 if ( class_exists( 'FLBuilderModel' ) && method_exists( 'FLBuilderModel', 'delete_asset_cache_for_all_posts' ) ) {
6838 FLBuilderModel::delete_asset_cache_for_all_posts();
6839 //error_log("delete_asset_cache_for_all_posts");
6840 }
6841
6842 if ( class_exists( 'FLBuilderModel' ) && method_exists( 'FLBuilderModel', 'delete_all_asset_cache' ) ) {
6843 FLBuilderModel::delete_all_asset_cache( $record->ID );
6844 //error_log("delete_all_asset_cache");
6845 }
6846
6847 if ( class_exists( 'FLCustomizer' ) && method_exists( 'FLCustomizer', 'clear_all_css_cache' ) ) {
6848 FLCustomizer::clear_all_css_cache();
6849 //error_log("clear_all_css_cache");
6850 }
6851 }
6852 wp_cache_flush();
6853
6854 }
6855
6856 $this->update_links($replace_image_location, $replace_destination_url);
6857
6858 // for updating wp pagebuilder
6859 if(defined('WPPB_LICENSE')) {
6860 $this->update_wppb_data($replace_image_location, $destination_url);
6861 }
6862
6863 // for updating themify images
6864 if(function_exists('themify_builder_activate')) {
6865 $this->update_themify_data($replace_image_location, $destination_url);
6866 }
6867
6868 // for updating elementor background images
6869 if(is_plugin_active("elementor/elementor.php")) {
6870 $this->update_elementor_data($next_id, $replace_image_location, $destination_url);
6871 }
6872
6873 //$message .= __('Updating attachment links, please wait...','maxgalleria-media-library') . PHP_EOL;
6874 $files = $this->display_folder_contents ($current_folder, true, "", false);
6875 $refresh = true;
6876 } else {
6877 //$message .= sprintf(__("Could not move %s to the protected folder",'maxgalleria-media-library'), $row->attached_file) . PHP_EOL;
6878 }
6879 }
6880 }
6881 }
6882 }
6883
6884 add_filter( 'wp_generate_attachment_metadata', array($this, 'add_attachment_to_folder2'), 10, 4);
6885
6886 return $message;
6887
6888 }
6889
6890 public function is_file_protected($file_id) {
6891
6892 global $wpdb;
6893 $file_id = intval($file_id);
6894
6895 $sql = "select block from wp_mgmlp_block_access where attachment_id = $file_id";
6896
6897 $row = $wpdb->get_row($sql);
6898
6899 if($row) {
6900 if($row->block == 1)
6901 return true;
6902 else
6903 return false;
6904 } else {
6905 return false;
6906 }
6907
6908 }
6909
6910 public function file_exists($file_id) {
6911
6912 global $wpdb;
6913 $file_id = intval($file_id);
6914
6915 $sql = "select post_title from $wpdb->posts where ID = $file_id and post_type = 'attachment'";
6916
6917 $row = $wpdb->get_row($sql);
6918
6919 if($row) {
6920 return true;
6921 } else {
6922 return false;
6923 }
6924 }
6925
6926 public function make_dir_path($path) {
6927 return (file_exists($path) || mkdir($path, 0775, true));
6928 }
6929
6930 public function add_bda_record($attachment_id) {
6931 global $wpdb;
6932 $attachment_id = intval($attachment_id);
6933 $block_access_table = $wpdb->prefix . MAXGALLERIA_MEDIA_LIBRARY_BLOCK_ACCESS_TABLE;
6934 $time = date('D n/j/Y g:i a');
6935
6936 $data = array(
6937 'attachment_id'=> $attachment_id,
6938 'hash_id' => md5(rand()),
6939 'time' => $time,
6940 'block' => 1
6941 );
6942
6943 $wpdb->replace($block_access_table, $data);
6944 update_post_meta($attachment_id, MLFP_BDA_MEDIA, TRUE);
6945 }
6946
6947 public function remove_bda_record($attachment_id) {
6948 global $wpdb;
6949 $attachment_id = intval($attachment_id);
6950 $block_access_table = $wpdb->prefix . MAXGALLERIA_MEDIA_LIBRARY_BLOCK_ACCESS_TABLE;
6951 $where = array('attachment_id' => $attachment_id);
6952 $wpdb->delete($block_access_table,$where);
6953 delete_post_meta($attachment_id, MLFP_BDA_MEDIA);
6954 }
6955
6956 public function bda_help() {
6957 ?>
6958 <p><strong><?php esc_html_e("Block Direct Access","maxgalleria-media-library")?></strong></p>
6959 <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>
6960 <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>
6961 <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>
6962 <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>
6963 <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>
6964 <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>
6965 <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>
6966 <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>
6967 <p>&nbsp;</p>
6968 <p>&nbsp;</p>
6969 <p>&nbsp;</p>
6970 <?php
6971 }
6972
6973 public function mlp_generate_file_link() {
6974
6975 $message = "";
6976
6977 if ( !wp_verify_nonce( $_POST['nonce'], MAXGALLERIA_MEDIA_LIBRARY_NONCE)) {
6978 exit(esc_html__('Missing nonce! Please refresh this page.','maxgalleria-media-library'));
6979 }
6980
6981 // Check if the current user has the capability to upload files
6982 if(!current_user_can('upload_files')){
6983 exit(esc_html__('You do not have the capability to upload files.','maxgalleria-media-library'));
6984 }
6985
6986 if ((isset($_POST['image_id'])) && (strlen(trim($_POST['image_id'])) > 0))
6987 $image_id = intval(trim(sanitize_text_field($_POST['image_id'])));
6988 else
6989 $image_id = 0;
6990
6991 if ((isset($_POST['title'])) && (strlen(trim($_POST['title'])) > 0))
6992 $title = trim(sanitize_text_field($_POST['title']));
6993 else
6994 $title = "";
6995
6996
6997 if ((isset($_POST['current_user'])) && (strlen(trim($_POST['current_user'])) > 0))
6998 $current_user = intval(trim(sanitize_text_field($_POST['current_user'])));
6999 else
7000 $current_user = 0;
7001
7002 if($image_id != 0) {
7003
7004 if(!$this->is_protected_file($image_id)) {
7005 $message = $title . esc_html__(' is not a protected file','maxgalleria-media-library');
7006 } else {
7007 $download_link = $this->get_private_link($image_id, $current_user);
7008 $message = esc_html($title) . " - " . esc_url($download_link);
7009 }
7010 }
7011
7012 echo $message;
7013 die();
7014
7015 }
7016
7017 public function is_protected_file($image_id) {
7018
7019 global $wpdb;
7020 $image_id = intval($image_id);
7021
7022 $table = $wpdb->prefix . MAXGALLERIA_MEDIA_LIBRARY_BLOCK_ACCESS_TABLE;
7023
7024 $sql = "select time from $table where attachment_id = $image_id";
7025
7026 //error_log($sql);
7027
7028 if($wpdb->get_var($sql) != NULL)
7029 return true;
7030 else
7031 return false;
7032 }
7033
7034 public function get_hash_id($image_id) {
7035
7036 global $wpdb;
7037 $image_id = intval($image_id);
7038
7039 $table = $wpdb->prefix . MAXGALLERIA_MEDIA_LIBRARY_BLOCK_ACCESS_TABLE;
7040
7041 $sql = "select hash_id from $table where attachment_id = $image_id";
7042
7043 //error_log($sql);
7044
7045 $hash_id = $wpdb->get_var($sql);
7046
7047 return $hash_id;
7048 }
7049
7050 public function get_private_link($image_id, $current_user) {
7051
7052 $hash = $this->get_hash_id($image_id);
7053
7054 $download_page = get_permalink(get_option(MLFP_BDA_DOWNLOAD_PAGE));
7055
7056 return esc_url(add_query_arg('download', $hash, $download_page));
7057 }
7058
7059 public function mlfp_display_bda_info() {
7060
7061 if ( !wp_verify_nonce( $_POST['nonce'], MAXGALLERIA_MEDIA_LIBRARY_NONCE)) {
7062 exit(esc_html__('Missing nonce! Please refresh this page.','maxgalleria-media-library'));
7063 }
7064
7065 // Check if the current user has the capability to upload files
7066 if(!current_user_can('upload_files')){
7067 exit(esc_html__('You do not have the capability to upload files.','maxgalleria-media-library'));
7068 }
7069
7070 $image_id = intval($this->get_ajax_paramater('image_id', 0));
7071
7072 $title = $this->get_ajax_paramater('title', '');
7073
7074 $count = $this->get_ajax_paramater('count', '');
7075
7076 //error_log("$image_id, $title, $count");
7077
7078 $row = $this->get_bda_file_info($image_id, $title, $count);
7079
7080 if($row)
7081 echo $row;
7082 else
7083 echo "none";
7084
7085 die();
7086
7087 }
7088
7089 public function get_bda_file_info($image_id, $title, $count) {
7090
7091 global $wpdb;
7092 $image_id = intval($image_id);
7093
7094 $table = $wpdb->prefix . MAXGALLERIA_MEDIA_LIBRARY_BLOCK_ACCESS_TABLE;
7095
7096 $sql = "select * from $table where attachment_id = $image_id";
7097 //error_log($sql);
7098 $row = $wpdb->get_row($sql);
7099
7100 if($count % 2)
7101 $row_color = "";
7102 else
7103 $row_color = "gray-row";
7104
7105 if($row) {
7106 $download_count = ($row->count) ? $row->count : '0';
7107 $download_limit = ($row->download_limit) ? $row->download_limit : '0';
7108 $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";
7109 return $line;
7110 } else {
7111 return false;
7112 }
7113 }
7114
7115 public function mlfp_update_bda_record() {
7116
7117 global $wpdb;
7118
7119 if ( !wp_verify_nonce( $_POST['nonce'], MAXGALLERIA_MEDIA_LIBRARY_NONCE)) {
7120 exit(__('Missing nonce! Please refresh this page.','maxgalleria-media-library'));
7121 }
7122
7123 // Check if the current user has the capability to upload files
7124 if(!current_user_can('upload_files')){
7125 exit(esc_html__('You do not have the capability to upload files.','maxgalleria-media-library'));
7126 }
7127
7128 $image_id = intval($this->get_ajax_paramater('image_id', 0));
7129
7130 $download_limit = intval($this->get_ajax_paramater('download_limit', 0));
7131
7132 $expiration_date = $this->get_ajax_paramater('expiration_date', 0);
7133
7134 $this->update_bda_record($image_id, $download_limit, $expiration_date);
7135
7136 die();
7137
7138 }
7139
7140 public function update_bda_record($image_id, $download_limit, $expiration_date) {
7141
7142 global $wpdb;
7143 $image_id = intval($image_id);
7144
7145 $table = $wpdb->prefix . MAXGALLERIA_MEDIA_LIBRARY_BLOCK_ACCESS_TABLE;
7146
7147 $data = array(
7148 'download_limit' => $download_limit,
7149 'expiration_date' => $expiration_date
7150 );
7151
7152 $where = array('attachment_id' => $image_id);
7153
7154 $wpdb->update($table, $data, $where);
7155
7156 }
7157
7158 public function copy_template_to_theme() {
7159
7160 // Copy gallery post type template file to theme directory
7161 $source = MAXGALLERIA_MEDIA_LIBRARY_PLUGIN_DIR . '/page-mlfp-download.php';
7162 $destination = $this->get_theme_dir() . '/page-mlfp-download.php';
7163 if(!defined('PRESERVE_MLFP_TEMPLATE')) {
7164 copy($source, $destination);
7165 }
7166 else if(!file_exists($destination)) {
7167 copy($source, $destination);
7168 }
7169 flush_rewrite_rules();
7170 }
7171
7172 public function get_theme_dir() {
7173 if(is_child_theme())
7174 return WP_CONTENT_DIR . '/themes/' . get_stylesheet();
7175 else
7176 return WP_CONTENT_DIR . '/themes/' . get_template();
7177 }
7178
7179
7180 public function mlfp_bdp_report() {
7181
7182 global $wpdb;
7183 $images_found = false;
7184 $items_per_page = 10;
7185
7186 if ( !wp_verify_nonce( $_POST['nonce'], MAXGALLERIA_MEDIA_LIBRARY_NONCE)) {
7187 exit(esc_html__('Missing nonce! Please refresh this page.','maxgalleria-media-library'));
7188 }
7189
7190 // Check if the current user has the capability to upload files
7191 if(!current_user_can('manage_options')){
7192 exit(esc_html__('You do not have the capability to upload files.','maxgalleria-media-library'));
7193 }
7194
7195 $page_id = intval($this->get_ajax_paramater('page_id', 0));
7196
7197 $table = $wpdb->prefix . MAXGALLERIA_MEDIA_LIBRARY_BLOCK_ACCESS_TABLE;
7198
7199 $offset = $page_id * $items_per_page;
7200
7201 $sql = $wpdb->prepare("SELECT SQL_CALC_FOUND_ROWS pm.meta_value AS attached_file, ba.count, ba.download_limit, ba.expiration_date
7202 FROM $table AS ba
7203 LEFT JOIN $wpdb->postmeta AS pm ON pm.post_id = ba.attachment_id
7204 WHERE pm.meta_key = '_wp_attached_file' limit %d, %d", $offset, $items_per_page);
7205
7206 //error_log($sql);
7207
7208 $rows = $wpdb->get_results($sql);
7209
7210 $count = $wpdb->get_row("select FOUND_ROWS()", ARRAY_A);
7211 $total_images = $count['FOUND_ROWS()'];
7212 $total_number_pages = ceil($total_images / $items_per_page);
7213
7214 if($rows) {
7215 $images_found = true;
7216 echo "<table id='protected-files'>" . PHP_EOL;
7217 echo " <thead>" . PHP_EOL;
7218 echo " <tr>" . PHP_EOL;
7219 echo " <td class='pf-name'>". esc_html__('File','maxgalleria-media-library')."</td>" . PHP_EOL;
7220 echo " <td class='pf-count'>". esc_html__('Download count','maxgalleria-media-library')."</td>" . PHP_EOL;
7221 echo " <td class='pf-limit'>". esc_html__('Download limit','maxgalleria-media-library')."</td>" . PHP_EOL;
7222 echo " <td class='pf-expiration'>". esc_html__('Expirtation Date','maxgalleria-media-library')."</td>" . PHP_EOL;
7223 echo " </tr>" . PHP_EOL;
7224 echo " </thead>" . PHP_EOL;
7225 echo " <tbody>" . PHP_EOL;
7226 foreach($rows as $row) {
7227 echo " <tr>" . PHP_EOL;
7228 echo " <td class='pf-name'>" . esc_html($row->attached_file) ."</td>" . PHP_EOL;
7229 $count = ($row->count) ? $row->count : '0';
7230 echo " <td class='pf-count'>". esc_html($count) ."</td>" . PHP_EOL;
7231 $download_limit = ($row->download_limit) ? $row->download_limit : 'none';
7232 echo " <td class='pf-limit'>" . esc_html($download_limit) ."</td>" . PHP_EOL;
7233 //error_log($row->attached_file . " expiration_date " . $row->expiration_date);
7234 //$expiration_date = ($row->expiration_date == '0000-00-00') ? 'none' : date("m/d/Y", strtotime($row->expiration_date));
7235 if($row->expiration_date == null || $row->expiration_date == '0000-00-00')
7236 $expiration_date = 'none';
7237 else
7238 $expiration_date = date("m/d/Y", strtotime($row->expiration_date));
7239 echo " <td class='pf-expiration'>" . esc_html($expiration_date) ." </td>" . PHP_EOL;
7240 echo " </tr>" . PHP_EOL;
7241 }
7242 echo " <tbody>" . PHP_EOL;
7243 echo "<table>" . PHP_EOL;
7244 } else {
7245 echo "<p style='text-align:center'>" . esc_html__('No files were found.','maxgalleria-media-library') . "</p>";
7246 }
7247
7248 if($images_found) {
7249 $last_page = $total_number_pages-1;
7250 $previous_page = $page_id - 1;
7251 $next_page = $page_id + 1;
7252 echo "<div class='mlfp-page-nav'>" . PHP_EOL;
7253 if($page_id > 0)
7254 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;
7255 if($page_id < $total_number_pages-1 && $total_images > $items_per_page)
7256 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;
7257 echo "</div>" . PHP_EOL;
7258 }
7259
7260 die();
7261
7262 }
7263
7264 public function mlfp_block_new_ip() {
7265
7266 global $wpdb;
7267 $message = '';
7268 $result = '';
7269 $new_id = 0;
7270
7271 if ( !wp_verify_nonce( $_POST['nonce'], MAXGALLERIA_MEDIA_LIBRARY_NONCE)) {
7272 exit(esc_html__('Missing nonce! Please refresh this page.','maxgalleria-media-library'));
7273 }
7274
7275 // Check if the current user has the capability to manage options
7276 if(!current_user_can('manage_options')){
7277 exit(esc_html__('You do not have the capability to manage options.','maxgalleria-media-library'));
7278 }
7279
7280 $new_block_ip = $this->get_ajax_paramater('new_block_ip');
7281
7282 if(filter_var($new_block_ip, FILTER_VALIDATE_IP)) {
7283
7284 $table = $wpdb->prefix . BLOCKED_IPS_TABLE;
7285
7286 $sql = $wpdb->prepare("select * from $table where address = '%s'", $new_block_ip);
7287
7288 $row = $wpdb->get_row($sql);
7289 if($row) {
7290 $message = esc_html__('The address is already in the blocked IPs list.','maxgalleria-media-library');
7291 $result = false;
7292 } else {
7293 $data = array('address' => $new_block_ip);
7294 $retval = $wpdb->insert($table, $data);
7295 $new_id = $wpdb->insert_id;
7296 //error_log("$new_block_ip retval $retval");
7297 $message = esc_html__('The address has been added to the blocked IPs list.','maxgalleria-media-library');
7298 $result = true;
7299 }
7300
7301 } else {
7302 $message = esc_html__('The IP address is not valid.','maxgalleria-media-library');
7303 $result = false;
7304 }
7305
7306 $return = array('message' => $message, 'result' => $result, 'id' => $new_id);
7307
7308 echo json_encode($return);
7309
7310 die();
7311 }
7312
7313 public function get_blocked_ips() {
7314 global $wpdb;
7315 $buffer = '';
7316 $table = $wpdb->prefix . BLOCKED_IPS_TABLE;
7317 $sql = "select * from $table order by address";
7318 //error_log($sql);
7319 $rows = $wpdb->get_results($sql);
7320 if($rows) {
7321 foreach($rows as $row) {
7322 $buffer .= '<option value="' . esc_attr($row->ip_id) . '">' . esc_html($row->address) . '</option>' . PHP_EOL ;
7323 }
7324 }
7325
7326 return $buffer;
7327 }
7328
7329 public function mlfp_get_block_ips() {
7330
7331 if ( !wp_verify_nonce( $_POST['nonce'], MAXGALLERIA_MEDIA_LIBRARY_NONCE)) {
7332 exit(esc_html__('Missing nonce! Please refresh this page.','maxgalleria-media-library'));
7333 }
7334
7335 // Check if the current user has the capability to manage options
7336 if(!current_user_can('manage_options')){
7337 exit(esc_html__('You do not have the capability to manage options.','maxgalleria-media-library'));
7338 }
7339
7340 $data = $this->get_blocked_ips();
7341
7342 echo $data;
7343
7344 die();
7345 }
7346
7347 public function mlfp_unblock_ips() {
7348
7349 global $wpdb;
7350 $updated = false;
7351 $message = esc_html__('No IP addresses were removed from the blocked IPs lists','maxgalleria-media-library');
7352
7353 if ( !wp_verify_nonce( $_POST['nonce'], MAXGALLERIA_MEDIA_LIBRARY_NONCE)) {
7354 exit(esc_html__('Missing nonce! Please refresh this page.','maxgalleria-media-library'));
7355 }
7356
7357 // Check if the current user has the capability to manage options
7358 if(!current_user_can('manage_options')){
7359 exit(esc_html__('You do not have the capability to manage options.','maxgalleria-media-library'));
7360 }
7361
7362 if ((isset($_POST['serial_ips'])) && (strlen(trim($_POST['serial_ips'])) > 0)) {
7363 $unblock_ips = trim(stripslashes(sanitize_text_field($_POST['serial_ips'])));
7364 //error_log("unblock_ips 1: $unblock_ips");
7365 $unblock_ips = str_replace('"', '', $unblock_ips);
7366 //error_log("unblock_ips 2: $unblock_ips");
7367 $unblock_ips = explode(",",$unblock_ips);
7368 }
7369 else
7370 $unblock_ips = '';
7371
7372 $table = $wpdb->prefix . BLOCKED_IPS_TABLE;
7373
7374 foreach($unblock_ips as $unblock_ip) {
7375 $updated = true;
7376 $where = array('ip_id' => (int) $unblock_ip);
7377 if($wpdb->delete($table, $where))
7378 $message = esc_html__('The IP addresses were unblocked.','maxgalleria-media-library');
7379 }
7380
7381 $return = array('message' => $message, 'result' => $updated);
7382
7383 echo json_encode($return);
7384
7385 die();
7386 }
7387
7388 public function get_all_pages() {
7389 global $wpdb;
7390 $sql = "select ID, post_title FROM $wpdb->posts where post_status = 'publish' and post_type = 'page' order by post_title";
7391 $pages = $wpdb->get_results($sql);
7392 return $pages;
7393 }
7394
7395 public function bda_prepare_attachment_for_js( $response, $attachment, $meta ) {
7396
7397 $current_user = get_current_user_id();
7398 $attach_arr = $this->objectToArray($attachment);
7399 $blocked = get_post_meta($attach_arr['ID'], MLFP_BDA_MEDIA, true );
7400
7401 if($blocked == '1' && $current_user == $attach_arr['post_author'])
7402 $response['customClass'] = "mlfp-protected author";
7403 else if($blocked == '1')
7404 $response['customClass'] = "mlfp-protected";
7405 else
7406 $response['customClass'] = "";
7407
7408 return $response;
7409
7410 }
7411
7412 public function bda_add_class_to_media_library_grid_elements() {
7413
7414 $currentScreen = get_current_screen();
7415
7416 if('upload' === $currentScreen->id) :
7417
7418 global $mode;
7419
7420 wp_enqueue_script('jquery');
7421 wp_enqueue_script('bda-media', MAXGALLERIA_MEDIA_LIBRARY_PLUGIN_URL . '/js/bda-media.js', array('jquery'));
7422
7423 endif;
7424
7425 }
7426
7427 public function get_file_thumbnail($ext) {
7428 switch ($ext) {
7429
7430 case 'psd':
7431 $thumbnail = MAXGALLERIA_MEDIA_LIBRARY_PLUGIN_URL . "/images/file-types/psd.png";
7432 break;
7433
7434 // spread sheet
7435 case 'xlsx':
7436 case 'xlsm':
7437 case 'xlsb':
7438 case 'xltx':
7439 case 'xltm':
7440 case 'xlam':
7441 case 'ods':
7442 case 'numbers':
7443 $thumbnail = MAXGALLERIA_MEDIA_LIBRARY_PLUGIN_URL . "/images/file-types/xls.png";
7444 break;
7445
7446 // video formats
7447 case 'asf':
7448 case 'asx':
7449 case 'wmv':
7450 case 'wmx':
7451 case 'wm':
7452 case 'avi':
7453 case 'divx':
7454 case 'flv':
7455 case 'mov':
7456 case 'qt':
7457 case 'mpeg':
7458 case 'mpg':
7459 case 'mpe':
7460 case 'mp4':
7461 case 'm4v':
7462 case 'ogv':
7463 case 'webm':
7464 case 'mkv':
7465 $thumbnail = MAXGALLERIA_MEDIA_LIBRARY_PLUGIN_URL . "/images/file-types/video.png";
7466 break;
7467
7468 // text formats
7469 case 'txt':
7470 case 'asc':
7471 case 'c':
7472 case 'cc':
7473 case 'h':
7474 case 'js':
7475 case 'cpp':
7476 case 'csv':
7477 case 'tsv':
7478 case 'ics':
7479 case 'rtx':
7480 case 'css':
7481 case 'htm':
7482 case 'html':
7483 $thumbnail = MAXGALLERIA_MEDIA_LIBRARY_PLUGIN_URL . "/images/file-types/txt.png";
7484 break;
7485
7486 case 'mp3':
7487 case 'm4a':
7488 case 'm4b':
7489 case 'ra':
7490 case 'ram':
7491 case 'wav':
7492 case 'ogg':
7493 case 'oga':
7494 case 'mid':
7495 case 'midi':
7496 case 'wma':
7497 case 'wax':
7498 case 'mka':
7499 $thumbnail = MAXGALLERIA_MEDIA_LIBRARY_PLUGIN_URL . "/images/file-types/audio.png";
7500 break;
7501
7502 // archive formats
7503 case '7z':
7504 case 'rar':
7505 case 'gz':
7506 case 'gzip':
7507 case 'zip':
7508 case 'tar':
7509 case 'swf':
7510 case 'class':
7511 $thumbnail = MAXGALLERIA_MEDIA_LIBRARY_PLUGIN_URL . "/images/file-types/arch.png";
7512 break;
7513
7514 // doc files
7515 case 'doc':
7516 case 'odt':
7517 case 'rtf':
7518 case 'wri':
7519 case 'mdb':
7520 case 'mpp':
7521 case 'docx':
7522 case 'docm':
7523 case 'dotx':
7524 case 'dotm':
7525 case 'wp':
7526 case 'wpd':
7527 case 'pages':
7528 $thumbnail = MAXGALLERIA_MEDIA_LIBRARY_PLUGIN_URL . "/images/file-types/doc.png";
7529 break;
7530
7531 case 'pdf':
7532 $thumbnail = MAXGALLERIA_MEDIA_LIBRARY_PLUGIN_URL . "/images/file-types/pdf.png";
7533 break;
7534
7535 // power point
7536 case 'pptx':
7537 case 'pptm':
7538 case 'ppsx':
7539 case 'ppsm':
7540 case 'potx':
7541 case 'potm':
7542 case 'ppam':
7543 case 'sldx':
7544 case 'sldm':
7545 case 'odp':
7546 case 'key':
7547 $thumbnail = MAXGALLERIA_MEDIA_LIBRARY_PLUGIN_URL . "/images/file-types/ppt.png";
7548 break;
7549
7550 default:
7551 $thumbnail = MAXGALLERIA_MEDIA_LIBRARY_PLUGIN_URL . "/images/file-types/default.png";
7552 break;
7553
7554 }
7555 return $thumbnail;
7556 }
7557
7558 }
7559
7560 $mg_media_library_folders = new MGMediaLibraryFolders();