PluginProbe
MainWP Dashboard: Self-hosted WordPress Management for Agencies / 6.2.1
MainWP Dashboard: Self-hosted WordPress Management for Agencies v6.2.1
6.2.2 6.2.1 6.2 6.1.8 6.1.7 6.1.6 6.1.5 6.1.4 6.1.3 6.1.2 6.1.1 6.1 6.0.12 6.0.11 4.6.0.1 5.0 5.0.1 5.0.2 5.0.3 5.0.3.1 5.0.3.2 5.1 5.1.1 5.2 5.2.1 All 155 releases
← All changes | assets/js/mainwp.js +4677 -3419 5.2 → 6.2.1 View file →
@@ -1,126 +1,223 @@
1 -/* eslint complexity: ["error", 100] */
1 +/* eslint-disable complexity */
2 2 // current complexity is the only way to achieve desired results, pull request solutions appreciated.
3 3
4 -window.mainwpVars = window.mainwpVars || {};
4 +globalThis.mainwpVars = globalThis.mainwpVars || {};
5 5
6 6 jQuery(function ($) {
7 7
8 - if (jQuery('.mainwp-ui-page').length) {
9 - jQuery('.mainwp-popup-tooltip').popup()
10 - }
8 + if (jQuery('.mainwp-ui-page').length) {
9 + jQuery('.mainwp-popup-tooltip').popup()
10 + }
11 11
12 - // review for new UI update
13 - jQuery(document).on('click', '#mainwp-category-add-submit', function () {
14 - let newCat = jQuery('#newcategory').val();
15 - if (jQuery('#categorychecklist .menu').find('.item[data-value="' + encodeURIComponent(newCat) + '"]').length > 0) {
16 - console.log('Existed: ' + encodeURIComponent(newCat));
17 - jQuery('#newcategory').val('');
18 - return;
19 - }
20 - let selected_categories = jQuery('#categorychecklist').dropdown('get value');
21 - jQuery('#categorychecklist .menu').append('<div class="item" data-value="' + encodeURIComponent(newCat) + '">' + newCat + '</div>');
22 - jQuery('#categorychecklist .menu').dropdown('set selected', selected_categories); // to refresh.
23 - jQuery('#newcategory').val('');
24 - });
12 + jQuery(document).on('click', '#mainwp-help-menu-item, #mainwp-help-menu-item-mobile', function () {
13 + jQuery('#mainwp-help-modal').modal({
14 + inverted: true,
15 + blurring: false,
16 + closable: false,
17 + onShow: function () {
18 + jQuery('#mainwp-help-modal').parent('.ui.dimmer').removeClass('dimmer');
19 + jQuery('#mainwp-help-modal').css({
20 + 'top': (jQuery(globalThis).height() - jQuery('#mainwp-help-modal').outerHeight()) / 2 + 'px',
21 + 'left': (jQuery(globalThis).width() - jQuery('#mainwp-help-modal').outerWidth()) / 2 + 'px'
22 + });
23 + },
25 24
26 - // Show/Hide new category field and button
27 - jQuery(document).on('click', '#category-add-toggle', function () {
28 - jQuery('#newcategory-field').toggle();
29 - jQuery('#mainwp-category-add-submit-field').toggle();
30 - return false;
31 - });
25 + }).modal('show').draggable().resizable({
26 + handles: "n, e, s, w, ne, nw, se, sw", // Allows resizing from all edges
27 + minWidth: 300, // Set minimum width
28 + minHeight: 640, // Set minimum height
29 + });
30 + return false;
31 + });
32 32
33 - // Manage Child options
34 - $('.mainwp-parent-toggle input[type="checkbox"]').on('change', function () {
35 - if (this.checked) {
36 - $(this).closest('.mainwp-parent-toggle').next('.mainwp-child-field').fadeIn();
37 - } else {
38 - $(this).closest('.mainwp-parent-toggle').next('.mainwp-child-field').fadeOut();
39 - }
40 - });
33 + // review for new UI update
34 + jQuery(document).on('click', '#mainwp-category-add-submit', function () {
35 + let newCat = jQuery('#newcategory').val();
36 + newCat = encodeURIComponent(newCat).replaceAll('%20', ' ');
41 37
42 - //Toggle Add Site form
43 - jQuery('#mainwp_managesites_verify_installed_child').on('change', function () {
44 - if (jQuery(this).is(':checked')) {
45 - jQuery('#mainwp-add-site-hidden-form').fadeIn(500);
46 - } else {
47 - jQuery('#mainwp-add-site-hidden-form').fadeOut(500);
48 - }
49 - });
38 + if (jQuery('#categorychecklist .menu').find('.item[data-value="' + newCat + '"]').length > 0) {
39 + jQuery('#newcategory').val('');
40 + return;
41 + }
42 + let selected_categories = jQuery('#categorychecklist').dropdown('get value');
43 + jQuery('#categorychecklist .menu').append('<div class="item" data-value="' + newCat + '">' + newCat + '</div>');
44 + jQuery('#categorychecklist .menu').dropdown('set selected', selected_categories); // to refresh.
45 + jQuery('#newcategory').val('');
46 + });
50 47
51 - // Toggle Add Site / Optional Settings section
52 - jQuery('#mainwp-add-site-advanced-options-toggle').on('click', function () {
53 - jQuery('#mainwp-add-site-advanced-options').toggle(500);
54 - return false;
55 - });
48 + // Show/Hide new category field and button
49 + jQuery(document).on('click', '#category-add-toggle', function () {
50 + jQuery('#newcategory-field').toggle();
51 + jQuery('#mainwp-category-add-submit-field').toggle();
52 + return false;
53 + });
56 54
57 - jQuery('.mainwp-remove-site-button').on('click', function () {
58 - let side_id = jQuery(this).attr('site-id');
59 - let confirmation = "Are you sure you want to remove this site from your MainWP Dashboard?";
55 + // Manage Child options
56 + $('.mainwp-parent-toggle input[type="checkbox"]').on('change', function () {
57 + if (this.checked) {
58 + $(this).closest('.mainwp-parent-toggle').next('.mainwp-child-field').fadeIn();
59 + } else {
60 + $(this).closest('.mainwp-parent-toggle').next('.mainwp-child-field').fadeOut();
61 + }
62 + });
60 63
61 - let _confirm_callback = mainwp_get_remove_calback(side_id);
64 + //Toggle Add Site form
65 + jQuery('#mainwp_managesites_verify_installed_child').on('change', function () {
66 + if (jQuery(this).is(':checked')) {
67 + jQuery('#mainwp-add-site-hidden-form').fadeIn(500);
68 + } else {
69 + jQuery('#mainwp-add-site-hidden-form').fadeOut(500);
70 + }
71 + });
62 72
63 - mainwp_confirm(confirmation, _confirm_callback, false, false, false, 'REMOVE');
73 + // Toggle Add Site / Optional Settings section
74 + jQuery('#mainwp-add-site-advanced-options-toggle').on('click', function () {
75 + jQuery('#mainwp-add-site-advanced-options').toggle(500);
76 + return false;
77 + });
64 78
65 - return false;
66 - });
79 + jQuery('.mainwp-remove-site-button').on('click', function () {
80 + let side_id = jQuery(this).attr('site-id');
81 + let confirmation = "Are you sure you want to remove this site from your MainWP Dashboard?";
67 82
83 + let _confirm_callback = mainwp_get_remove_calback(side_id);
84 +
85 + mainwp_confirm(confirmation, _confirm_callback, false, false, false, 'REMOVE');
86 +
87 + return false;
88 + });
89 +
68 90 });
69 91
70 92 let mainwp_get_remove_calback = function (side_id) {
71 - return function () {
72 - feedback('mainwp-message-zone', '<i class="notched circle loading icon"></i> ' + __('Removing the site. Please wait...', 'mainwp'), '');
73 - let data = mainwp_secure_data({
74 - action: 'mainwp_removesite',
75 - id: side_id
76 - });
93 + return function () {
94 + feedback('mainwp-message-zone', '<i class="notched circle loading icon"></i> ' + MainWP.I18n.t('Removing the site. Please wait...'), '');
95 + let data = mainwp_secure_data({
96 + action: 'mainwp_removesite',
97 + id: side_id
98 + });
77 99
78 - jQuery.post(ajaxurl, data, function (response) {
100 + jQuery.ajax({
101 + url: ajaxurl,
102 + data: data,
103 + timeout: 180000, // 3 minutes. Slightly longer than the PHP server timeout (2 minutes).
104 + method: 'POST',
105 + success: function (response) {
79 106
80 - let error = false;
107 + const removed_site = response?.removed_site ?? false;
108 + let msg_not_removed = MainWP.I18n.t('Site could not be removed. Please reload the page and try again.');
81 109
82 - if (response.error != undefined) {
83 - error = response.error;
84 - } else if (response.result == 'SUCCESS') {
85 - feedback('mainwp-message-zone', __('The site has been removed and the MainWP Child plugin has been disabled. You will be redirected to the Sites page right away.', 'mainwp'), 'green');
86 - } else if (response.result == 'NOSITE') {
87 - feedback('mainwp-message-zone', __('Site could not be removed. Please reload the page and try again.', 'mainwp'), 'red');
88 - error = true;
89 - } else {
90 - feedback('mainwp-message-zone', __('The site has been removed. Please make sure that the MainWP Child plugin has been deactivated properly. You will be redirected to the Sites page right away.', 'mainwp'), 'green');
91 - }
110 + let error_msg = '';
92 111
93 - if (!error) {
94 - setTimeout(function () {
95 - window.location = 'admin.php?page=managesites';
96 - }, 3000);
97 - }
112 + if (typeof response?.error === 'string' && response.error.trim() !== '') {
113 + error_msg = MainWP.I18n.t('Details:') + ' ' + response.error;
114 + msg_not_removed += ' ' + error_msg;
115 + }
98 116
99 - }, 'json');
100 - }
117 + if (response?.undefined_error) {
118 + if (!removed_site) {
119 + feedback(
120 + 'mainwp-message-zone',
121 + msg_not_removed,
122 + 'red'
123 + );
124 + return;
125 + }
126 + feedback(
127 + 'mainwp-message-zone',
128 + MainWP.I18n.t('The site has been removed. Please make sure that the MainWP Child plugin has been deactivated properly. You will be redirected to the Sites page right away.'),
129 + 'red'
130 + );
131 + } else if (!removed_site) {
132 + feedback(
133 + 'mainwp-message-zone',
134 + msg_not_removed,
135 + 'red'
136 + );
137 + return;
138 + } else if (response?.error) {
139 + let message = MainWP.I18n.t('The site has been removed. Please make sure that the MainWP Child plugin has been deactivated properly. You will be redirected to the Sites page right away.');
140 + if (error_msg) {
141 + message += ' ' + error_msg;
142 + }
143 + feedback('mainwp-message-zone', message, 'red');
144 + } else {
145 + switch (response?.result) {
146 + case 'SUCCESS':
147 + feedback(
148 + 'mainwp-message-zone',
149 + MainWP.I18n.t('The site has been removed and the MainWP Child plugin has been disabled. You will be redirected to the Sites page right away.'),
150 + 'green'
151 + );
152 + break;
153 + case 'REMOVED': // for demo sites.
154 + feedback(
155 + 'mainwp-message-zone',
156 + MainWP.I18n.t('The site has been removed. You will be redirected to the Sites page right away.'),
157 + 'green'
158 + );
159 + break;
160 + case 'NOSITE':
161 + feedback(
162 + 'mainwp-message-zone',
163 + msg_not_removed,
164 + 'red'
165 + );
166 + return;
167 + default:
168 + feedback(
169 + 'mainwp-message-zone',
170 + MainWP.I18n.t('The site has been removed. Please make sure that the MainWP Child plugin has been deactivated properly. You will be redirected to the Sites page right away.'),
171 + 'green'
172 + );
173 + }
174 + }
175 + setTimeout(function () {
176 + mainwp_forceReload('admin.php?page=managesites');
177 + }, 3000);
178 + },
179 + error: function (xhr, textStatus) {
180 + if (textStatus === 'timeout') {
181 + feedback(
182 + 'mainwp-message-zone',
183 + MainWP.I18n.t('The request timed out. Please make sure that the MainWP Child plugin has been deactivated properly.'),
184 + 'red'
185 + );
186 + return;
187 + }
101 188
189 + feedback(
190 + 'mainwp-message-zone',
191 + MainWP.I18n.t('An unexpected error occurred. Please reload the page and try again.'),
192 + 'red'
193 + );
194 + },
195 + dataType: 'json'
196 + });
197 + }
198 +
102 199 }
103 200
104 -window.mainwp_set_message_zone = window.mainwp_set_message_zone || function (zone_selector, msg_html, colors, show) {
105 - if (msg_html) {
106 - jQuery(zone_selector).html(msg_html);
107 - } else if (msg_html === '' || msg_html === undefined) {
108 - jQuery(zone_selector).html('');
109 - }
201 +globalThis.mainwp_set_message_zone = globalThis.mainwp_set_message_zone || function (zone_selector, msg_html, colors, show) {
202 + if (msg_html) {
203 + jQuery(zone_selector).html(msg_html);
204 + } else if (msg_html === '' || msg_html === undefined) {
205 + jQuery(zone_selector).html('');
206 + }
110 207
111 - if (colors) {
112 - jQuery(zone_selector).removeClass('green yellow green');
113 - jQuery(zone_selector).addClass(colors);
114 - } else if (colors === '' || colors === undefined) {
115 - jQuery(zone_selector).removeClass('green yellow green');
116 - }
208 + if (colors !== undefined && colors != '') {
209 + jQuery(zone_selector).removeClass('green yellow red');
210 + jQuery(zone_selector).addClass(colors);
211 + } else if (colors === '' || colors === undefined) {
212 + jQuery(zone_selector).removeClass('green yellow red');
213 + }
117 214
118 - if (true === show || (false !== show && msg_html)) {
119 - jQuery(zone_selector).show();
120 - } else {
121 - jQuery(zone_selector).hide();
122 - }
215 + if (true === show || (false !== show && msg_html)) {
216 + jQuery(zone_selector).show();
217 + } else {
218 + jQuery(zone_selector).hide();
219 + }
123 220 };
124 221
125 222 let bulkInstallMaxThreads = mainwpParams['maximumInstallUpdateRequests'] == undefined ? 3 : mainwpParams['maximumInstallUpdateRequests'];
126 223 let bulkInstallCurrentThreads = 0;
@@ -129,24 +226,24 @@
129 226 /**
130 227 * Global
131 228 */
132 229 jQuery(function () {
133 - jQuery('.mainwp-row').on({
134 - mouseenter: function () {
135 - rowMouseEnter(this);
136 - },
137 - mouseleave: function () {
138 - rowMouseLeave(this);
139 - }
140 - });
230 + jQuery('.mainwp-row').on({
231 + mouseenter: function () {
232 + rowMouseEnter(this);
233 + },
234 + mouseleave: function () {
235 + rowMouseLeave(this);
236 + }
237 + });
141 238 });
142 239 let rowMouseEnter = function (elem) {
143 - if (!jQuery(elem).children('.mainwp-row-actions-working').is(":visible"))
144 - jQuery(elem).children('.mainwp-row-actions').show();
240 + if (!jQuery(elem).children('.mainwp-row-actions-working').is(":visible"))
241 + jQuery(elem).children('.mainwp-row-actions').show();
145 242 };
146 243 let rowMouseLeave = function (elem) {
147 - if (jQuery(elem).children('.mainwp-row-actions').is(":visible"))
148 - jQuery(elem).children('.mainwp-row-actions').hide();
244 + if (jQuery(elem).children('.mainwp-row-actions').is(":visible"))
245 + jQuery(elem).children('.mainwp-row-actions').hide();
149 246 };
150 247
151 248 /**
152 249 * Recent posts
@@ -151,96 +248,96 @@
151 248 /**
152 249 * Recent posts
153 250 */
154 251 jQuery(function () {
155 - jQuery(document).on('click', '.mainwp-post-unpublish', function () {
156 - postAction(jQuery(this), 'unpublish');
157 - return false;
158 - });
159 - jQuery(document).on('click', '.mainwp-post-publish', function () {
160 - postAction(jQuery(this), 'publish');
161 - return false;
162 - });
163 - jQuery(document).on('click', '.mainwp-post-trash', function () {
164 - postAction(jQuery(this), 'trash');
165 - return false;
166 - });
167 - jQuery(document).on('click', '.mainwp-post-restore', function () {
168 - postAction(jQuery(this), 'restore');
169 - return false;
170 - });
171 - jQuery(document).on('click', '.mainwp-post-delete', function () {
172 - postAction(jQuery(this), 'delete');
173 - return false;
174 - });
252 + jQuery(document).on('click', '.mainwp-post-unpublish', function () {
253 + postAction(jQuery(this), 'unpublish');
254 + return false;
255 + });
256 + jQuery(document).on('click', '.mainwp-post-publish', function () {
257 + postAction(jQuery(this), 'publish');
258 + return false;
259 + });
260 + jQuery(document).on('click', '.mainwp-post-trash', function () {
261 + postAction(jQuery(this), 'trash');
262 + return false;
263 + });
264 + jQuery(document).on('click', '.mainwp-post-restore', function () {
265 + postAction(jQuery(this), 'restore');
266 + return false;
267 + });
268 + jQuery(document).on('click', '.mainwp-post-delete', function () {
269 + postAction(jQuery(this), 'delete');
270 + return false;
271 + });
175 272
176 273 });
177 274
178 275 // Publish, Unpublish, Trash, ... posts and pages
179 276 let postAction = function (elem, what) {
180 - let rowElement = jQuery(elem).closest('.grid');
181 - let postId = rowElement.children('.postId').val();
182 - let websiteId = rowElement.children('.websiteId').val();
277 + let rowElement = jQuery(elem).closest('.grid');
278 + let postId = rowElement.children('.postId').val();
279 + let websiteId = rowElement.children('.websiteId').val();
183 280
184 - let data = mainwp_secure_data({
185 - action: 'mainwp_post_' + what,
186 - postId: postId,
187 - websiteId: websiteId
188 - });
189 - rowElement.hide();
190 - rowElement.next('.mainwp-row-actions-working').show();
191 - jQuery.post(ajaxurl, data, function (response) {
192 - if (response.error) {
193 - rowElement.show();
194 - rowElement.next('.mainwp-row-actions-working').hide();
195 - rowElement.html('<div class="sixteen wide column"><i class="times red icon"></i> ' + response.error + '</div>');
196 - } else if (response.result) {
197 - rowElement.show();
198 - rowElement.next('.mainwp-row-actions-working').hide();
199 - rowElement.html('<div class="sixteen wide column"><i class="check green icon"></i>' + response.result + '</div>');
200 - } else {
201 - rowElement.show();
202 - rowElement.next('.mainwp-row-actions-working').hide();
203 - }
204 - }, 'json');
205 - return false;
281 + let data = mainwp_secure_data({
282 + action: 'mainwp_post_' + what,
283 + postId: postId,
284 + websiteId: websiteId
285 + });
286 + rowElement.hide();
287 + rowElement.next('.mainwp-row-actions-working').show();
288 + jQuery.post(ajaxurl, data, function (response) {
289 + if (response.error) {
290 + rowElement.show();
291 + rowElement.next('.mainwp-row-actions-working').hide();
292 + rowElement.html('<div class="sixteen wide column"><i class="times red icon"></i> ' + response.error + '</div>');
293 + } else if (response.result) {
294 + rowElement.show();
295 + rowElement.next('.mainwp-row-actions-working').hide();
296 + rowElement.html('<div class="sixteen wide column"><i class="check green icon"></i>' + response.result + '</div>');
297 + } else {
298 + rowElement.show();
299 + rowElement.next('.mainwp-row-actions-working').hide();
300 + }
301 + }, 'json');
302 + return false;
206 303 };
207 304
208 305
209 306 let mainwp_post_posting_start_next = function (start) {
210 - if (typeof start !== "undefined" && start) {
211 - bulkInstallDone = 0;
212 - bulkInstallCurrentThreads = 0;
213 - mainwpVars.bulkInstallTotal = jQuery('.site-bulk-posting[status="queue"]').length;
214 - }
215 - while ((siteToPosting = jQuery('.site-bulk-posting[status="queue"]:first')) && (siteToPosting.length > 0) && (bulkInstallCurrentThreads < bulkInstallMaxThreads)) { // NOSONAR -- modified out side the function.
216 - mainwp_post_posting_start_specific(siteToPosting);
217 - }
307 + if (start !== undefined && start) {
308 + bulkInstallDone = 0;
309 + bulkInstallCurrentThreads = 0;
310 + mainwpVars.bulkInstallTotal = jQuery('.site-bulk-posting[status="queue"]').length;
311 + }
312 + while ((siteToPosting = jQuery('.site-bulk-posting[status="queue"]:first')) && (siteToPosting.length > 0) && (bulkInstallCurrentThreads < bulkInstallMaxThreads)) { // NOSONAR -- modified out side the function.
313 + mainwp_post_posting_start_specific(siteToPosting);
314 + }
218 315 };
219 316
220 317 let mainwp_post_posting_start_specific = function (siteToPosting) {
221 - siteToPosting.attr('status', 'progress');
222 - bulkInstallDone++;
223 - bulkInstallCurrentThreads++;
224 - let data = mainwp_secure_data({
225 - action: 'mainwp_post_postingbulk',
226 - post_id: jQuery('#bulk_posting_id').val(),
227 - site_id: jQuery(siteToPosting).attr('site-id'),
228 - count: bulkInstallDone,
229 - total: mainwpVars.bulkInstallTotal,
230 - delete_bulkpost: (bulkInstallDone == mainwpVars.bulkInstallTotal)
231 - });
232 - siteToPosting.find('.progress').html('<i class="notched circle loading icon"></i>');
233 - jQuery.post(ajaxurl, data, function (response) {
234 - bulkInstallCurrentThreads--;
235 - if (response?.result) {
236 - siteToPosting.find('.progress').html(response.result);
237 - if (response.edit_link !== '') {
238 - siteToPosting.after(response.edit_link);
239 - }
240 - }
241 - mainwp_post_posting_start_next();
242 - }, 'json');
318 + siteToPosting.attr('status', 'progress');
319 + bulkInstallDone++;
320 + bulkInstallCurrentThreads++;
321 + let data = mainwp_secure_data({
322 + action: 'mainwp_post_postingbulk',
323 + post_id: jQuery('#bulk_posting_id').val(),
324 + site_id: jQuery(siteToPosting).attr('site-id'),
325 + count: bulkInstallDone,
326 + total: mainwpVars.bulkInstallTotal,
327 + delete_bulkpost: (bulkInstallDone == mainwpVars.bulkInstallTotal)
328 + });
329 + siteToPosting.find('.progress').html('<i class="notched circle loading icon"></i>');
330 + jQuery.post(ajaxurl, data, function (response) {
331 + bulkInstallCurrentThreads--;
332 + if (response?.result) {
333 + siteToPosting.find('.progress').html(response.result);
334 + if (response.edit_link !== '') {
335 + siteToPosting.after(response.edit_link);
336 + }
337 + }
338 + mainwp_post_posting_start_next();
339 + }, 'json');
243 340 }
244 341
245 342
246 343 /**
@@ -246,35 +343,39 @@
246 343 /**
247 344 * Plugins Widget
248 345 */
249 346 jQuery(function () {
250 - jQuery(document).on('click', '.mainwp-plugin-deactivate', function () {
251 - pluginAction(jQuery(this), 'deactivate');
252 - return false;
253 - });
254 - jQuery(document).on('click', '.mainwp-plugin-activate', function () {
255 - pluginAction(jQuery(this), 'activate');
256 - return false;
257 - });
258 - jQuery(document).on('click', '.mainwp-plugin-delete', function () {
259 - pluginAction(jQuery(this), 'delete');
260 - return false;
261 - });
347 + jQuery(document).on('click', '.mainwp-plugin-deactivate', function () {
348 + pluginAction(jQuery(this), 'deactivate');
349 + return false;
350 + });
351 + jQuery(document).on('click', '.mainwp-plugin-activate', function () {
352 + pluginAction(jQuery(this), 'activate');
353 + return false;
354 + });
355 + jQuery(document).on('click', '.mainwp-plugin-delete', function () {
356 + let name = jQuery(this).closest('.row-manage-item').attr('plugin-title');
357 + let confirmMsg = MainWP.I18n.t('You are about to delete the %1?', name);
358 + mainwp_confirm(confirmMsg, () => {
359 + pluginAction(jQuery(this), 'delete');
360 + });
361 + return false;
362 + });
262 363 });
263 364
264 365
265 366 let pluginAction = function (elem, what) {
266 - let rowElement = jQuery(elem).closest('.row-manage-item');
267 - let plugin = rowElement.children('.pluginSlug').val();
268 - let websiteId = rowElement.children('.websiteId').val();
367 + let rowElement = jQuery(elem).closest('.row-manage-item');
368 + let plugin = rowElement.children('.pluginSlug').val();
369 + let websiteId = rowElement.children('.websiteId').val();
269 370
270 - let data = mainwp_secure_data({
271 - action: 'mainwp_widget_plugin_' + what,
272 - plugin: plugin,
273 - websiteId: websiteId
274 - });
275 - plugin_theme_doAction(data, rowElement);
276 - return false;
371 + let data = mainwp_secure_data({
372 + action: 'mainwp_widget_plugin_' + what,
373 + plugin: plugin,
374 + websiteId: websiteId
375 + });
376 + plugin_theme_doAction(data, rowElement);
377 + return false;
277 378 };
278 379
279 380 /**
280 381 * Themes Widget
@@ -279,160 +380,173 @@
279 380 /**
280 381 * Themes Widget
281 382 */
282 383 jQuery(function () {
283 - jQuery(document).on('click', '.mainwp-theme-activate', function () {
284 - themeAction(jQuery(this), 'activate');
285 - return false;
286 - });
287 - jQuery(document).on('click', '.mainwp-theme-delete', function () {
288 - themeAction(jQuery(this), 'delete');
289 - return false;
290 - });
384 + jQuery(document).on('click', '.mainwp-theme-activate', function () {
385 + themeAction(jQuery(this), 'activate');
386 + return false;
387 + });
388 + jQuery(document).on('click', '.mainwp-theme-delete', function () {
389 + let name = jQuery(this).closest('.row-manage-item').children('.themeName').val();
390 + let confirmMsg = MainWP.I18n.t('You are about to delete the %1?', name);
391 + mainwp_confirm(confirmMsg, () => {
392 + themeAction(jQuery(this), 'delete');
393 + });
394 + return false;
395 + });
291 396 });
292 397
293 398 let themeAction = function (elem, what) {
294 - let rowElement = jQuery(elem).closest('.row-manage-item');
295 - let theme = rowElement.children('.themeSlug').val();
296 - let websiteId = rowElement.children('.websiteId').val();
297 - let data = mainwp_secure_data({
298 - action: 'mainwp_widget_theme_' + what,
299 - theme: theme,
300 - websiteId: websiteId
301 - });
302 - plugin_theme_doAction(data, rowElement);
303 - return false;
399 + let rowElement = jQuery(elem).closest('.row-manage-item');
400 + let theme = rowElement.children('.themeSlug').val();
401 + let websiteId = rowElement.children('.websiteId').val();
402 + let data = mainwp_secure_data({
403 + action: 'mainwp_widget_theme_' + what,
404 + theme: theme,
405 + websiteId: websiteId
406 + });
407 + plugin_theme_doAction(data, rowElement);
408 + return false;
304 409 };
305 410
306 411 let plugin_theme_doAction = function (data, rowElement) {
307 - rowElement.children().hide();
308 - rowElement.children('.mainwp-row-actions-working').show();
309 - jQuery.post(ajaxurl, data, function (response) {
310 - if (response?.error) {
311 - rowElement.children().show();
312 - rowElement.html(response.error);
313 - } else if (response?.result) {
314 - rowElement.children().show();
315 - rowElement.html(response.result);
316 - } else {
317 - rowElement.children('.mainwp-row-actions-working').hide();
318 - }
319 - }, 'json');
412 + rowElement.children().hide();
413 + rowElement.children('.mainwp-row-actions-working').show();
414 + jQuery.post(ajaxurl, data, function (response) {
415 + if (response?.error) {
416 + rowElement.children().show();
417 + rowElement.html(response.error);
418 + } else if (response?.result) {
419 + rowElement.children().show();
420 + rowElement.html(response.result);
421 + } else {
422 + rowElement.children('.mainwp-row-actions-working').hide();
423 + }
424 + }, 'json');
320 425 };
321 426
322 427
323 428 // offsetRelative (or, if you prefer, positionRelative)
324 429 (function ($) {
325 - $.fn.offsetRelative = function (top) {
326 - let $this = $(this);
327 - let $parent = $this.offsetParent();
328 - let offset = $this.position();
329 - if (!top)
330 - return offset; // Didn't pass a 'top' element
331 - else if ($parent.get(0).tagName == "BODY")
332 - return offset; // Reached top of document
333 - else if ($(top, $parent).length)
334 - return offset; // Parent element contains the 'top' element we want the offset to be relative to
335 - else if ($parent[0] == $(top)[0])
336 - return offset; // Reached the 'top' element we want the offset to be relative to
337 - else { // Get parent's relative offset
338 - let parent_offset = $parent.offsetRelative(top);
339 - offset.top += parent_offset.top;
340 - offset.left += parent_offset.left;
341 - return offset;
342 - }
343 - };
344 - $.fn.positionRelative = function (top) {
345 - return $(this).offsetRelative(top);
346 - };
430 + $.fn.offsetRelative = function (top) {
431 + let $this = $(this);
432 + let $parent = $this.offsetParent();
433 + let offset = $this.position();
434 + if (!top)
435 + return offset; // Didn't pass a 'top' element
436 + else if ($parent.get(0).tagName == "BODY")
437 + return offset; // Reached top of document
438 + else if ($(top, $parent).length)
439 + return offset; // Parent element contains the 'top' element we want the offset to be relative to
440 + else if ($parent[0] == $(top)[0])
441 + return offset; // Reached the 'top' element we want the offset to be relative to
442 + else { // Get parent's relative offset
443 + let parent_offset = $parent.offsetRelative(top);
444 + offset.top += parent_offset.top;
445 + offset.left += parent_offset.left;
446 + return offset;
447 + }
448 + };
449 + $.fn.positionRelative = function (top) {
450 + return $(this).offsetRelative(top);
451 + };
347 452 })(jQuery);
348 453
349 454 let hidingSubMenuTimers = {};
350 455 jQuery(function () {
351 - jQuery('.mainwp-submenu-wrapper').on({
352 - mouseenter: function () {
353 - let spanId = /^menu-mainwp-(.*)$/.exec(jQuery(this).attr('id'));
354 - if (spanId) {
355 - if (hidingSubMenuTimers[spanId[1]]) {
356 - clearTimeout(hidingSubMenuTimers[spanId[1]]);
456 + jQuery('.mainwp-submenu-wrapper').on({
457 + mouseenter: function () {
458 + let spanId = /^menu-mainwp-(.*)$/.exec(jQuery(this).attr('id'));
459 + if (spanId) {
460 + if (hidingSubMenuTimers[spanId[1]]) {
461 + clearTimeout(hidingSubMenuTimers[spanId[1]]);
462 + }
463 + }
464 + },
465 + mouseleave: function () {
466 + let spanId = /^menu-mainwp-(.*)$/.exec(jQuery(this).attr('id'));
467 + if (spanId) {
468 + hidingSubMenuTimers[spanId[1]] = setTimeout(function (span) {
469 + return function () {
470 + subMenuOut(span);
471 + };
472 + }(spanId[1]), 30);
473 + }
357 474 }
358 - }
359 - },
360 - mouseleave: function () {
361 - let spanId = /^menu-mainwp-(.*)$/.exec(jQuery(this).attr('id'));
362 - if (spanId) {
363 - hidingSubMenuTimers[spanId[1]] = setTimeout(function (span) {
364 - return function () {
365 - subMenuOut(span);
366 - };
367 - }(spanId[1]), 30);
368 - }
369 - }
370 - });
475 + });
371 476 });
372 477 let subMenuOut = function (subName) {
373 - jQuery('#menu-mainwp-' + subName).hide();
374 - jQuery('#mainwp-' + subName).parent().parent().css('background-color', '');
375 - jQuery('#mainwp-' + subName).parent().parent().removeClass('hoverli');
376 - jQuery('#mainwp-' + subName).css('color', '');
478 + jQuery('#menu-mainwp-' + subName).hide();
479 + jQuery('#mainwp-' + subName).parent().parent().css('background-color', '');
480 + jQuery('#mainwp-' + subName).parent().parent().removeClass('hoverli');
481 + jQuery('#mainwp-' + subName).css('color', '');
377 482 };
483 +// eslint-disable-next-line complexity
484 +globalThis.mainwp_js_get_error_not_detected_connect = function (jsonStr, what, elemId, retErrText) { // NOSONAR - complexity.
485 + if (undefined !== jsonStr && '' != jsonStr && undefined !== what && 'html_msg' === what) {
486 + try {
487 + let obj_err = JSON.parse(jsonStr);
488 + if (typeof obj_err === 'object') {
489 + if (obj_err?.el_before && obj_err?.el_link && obj_err?.el_text) {
490 + let elafter = obj_err.el_after === undefined ? '' : obj_err.el_after;
491 + if (true === retErrText) {
492 + return obj_err.el_before + obj_err.el_text + elafter;
493 + }
494 + if (undefined !== elemId && '' != elemId) {
495 + let el = document.createElement('a');
496 + el.text = obj_err.el_text;
497 + el.href = obj_err.el_link;
498 + el.target = "_blank";
499 + console.log(el);
500 + jQuery('#' + elemId).html('').append(document.createTextNode(obj_err.el_before), el, document.createTextNode(elafter));
501 + feedback_scroll(elemId, 'red');
502 + }
503 + return true;
504 + }
505 + } else {
506 + return false; // it is not or invalid json.
507 + }
508 + } catch (e) {
509 + console.log(e);
510 + return false; // it is not or invalid json.
511 + }
512 + }
513 + return MainWP.I18n.t('MainWP Child plugin not detected or could not be reached! Ensure the MainWP Child plugin is installed and activated on the child site, and there are no security rules blocking requests. If you continue experiencing this issue, check the MainWP Community for help.');
514 +}
378 515
379 -window.mainwp_js_get_error_not_detected_connect = function (jsonStr, what, elemId, retErrText) { // NOSONAR - complexity.
380 - if (undefined !== jsonStr && '' != jsonStr && undefined !== what && 'html_msg' === what) {
381 - try {
382 - let obj_err = JSON.parse(jsonStr);
383 - if (typeof obj_err === 'object') {
384 - if (obj_err?.el_before && obj_err?.el_link && obj_err?.el_text) {
385 - let elafter = obj_err.el_after !== undefined ? obj_err.el_after : '';
386 - if (true === retErrText) {
387 - return obj_err.el_before + obj_err.el_text + elafter;
388 - }
389 - if (undefined !== elemId && '' != elemId) {
390 - let el = document.createElement('a');
391 - el.text = obj_err.el_text;
392 - el.href = obj_err.el_link;
393 - el.target = "_blank";
394 - console.log(el);
395 - jQuery('#' + elemId).html('').append(document.createTextNode(obj_err.el_before), el, document.createTextNode(elafter));
396 - feedback_scroll(elemId, 'red');
397 - }
398 - return true;
399 - }
400 - } else {
401 - return false; // it is not or invalid json.
402 - }
403 - } catch (e) {
404 - return false; // it is not or invalid json.
516 +globalThis.mainwp_get_reconnect_error = function (response, siteId) { // NOSONAR - complexity.
517 + if ('reconnect_failed' === response) {
518 + return MainWP.I18n.t('Reconnect failed. Please try again from the %1Site Settings page%2.', '<a href="admin.php?page=managesites&id=' + siteId + '">', '</a>');
519 + } else {
520 + return response;
405 521 }
406 - }
407 - return __('MainWP Child plugin not detected or could not be reached! Ensure the MainWP Child plugin is installed and activated on the child site, and there are no security rules blocking requests. If you continue experiencing this issue, check the MainWP Community for help.');
408 522 }
409 523
410 524 function shake_element(select) {
411 - let pos = jQuery(select).position();
412 - let type = jQuery(select).css('position');
525 + let pos = jQuery(select).position();
526 + let type = jQuery(select).css('position');
413 527
414 - if (type == 'static') {
415 - jQuery(select).css({
416 - position: 'relative'
417 - });
418 - }
528 + if (type == 'static') {
529 + jQuery(select).css({
530 + position: 'relative'
531 + });
532 + }
419 533
420 - if (type == 'static' || type == 'relative') {
421 - pos.top = 0;
422 - pos.left = 0;
423 - }
534 + if (type == 'static' || type == 'relative') {
535 + pos.top = 0;
536 + pos.left = 0;
537 + }
424 538
425 - jQuery(select).data('init-type', type);
539 + jQuery(select).data('init-type', type);
426 540
427 - let shake = [[0, 5, 60], [0, 0, 60], [0, -5, 60], [0, 0, 60], [0, 2, 30], [0, 0, 30], [0, -2, 30], [0, 0, 30]];
541 + let shake = [[0, 5, 60], [0, 0, 60], [0, -5, 60], [0, 0, 60], [0, 2, 30], [0, 0, 30], [0, -2, 30], [0, 0, 30]];
428 542
429 - for (let s of shake) {
430 - jQuery(select).animate({
431 - top: pos.top + s[0],
432 - left: pos.left + s[1]
433 - }, s[2], 'linear');
434 - }
543 + for (let s of shake) {
544 + jQuery(select).animate({
545 + top: pos.top + s[0],
546 + left: pos.left + s[1]
547 + }, s[2], 'linear');
548 + }
435 549 }
436 550
437 551
438 552 /**
@@ -437,62 +551,93 @@
437 551
438 552 /**
439 553 * Required
440 554 */
441 -window.feedback = function (id, text, type, append) {
442 - if (append) {
443 - let currentHtml = jQuery('#' + id).html();
444 - if (currentHtml == null)
445 - currentHtml = "";
446 - if (currentHtml != '') {
447 - currentHtml += '<br />' + text;
555 +globalThis.feedback = function (id, text, type, append) {
556 + if (append) {
557 + let currentHtml = jQuery('#' + id).html();
558 + if (currentHtml == null)
559 + currentHtml = "";
560 + if (currentHtml == '') {
561 + currentHtml = text;
562 + } else {
563 + currentHtml += '<br />' + text;
564 + }
565 + jQuery('#' + id).html(currentHtml);
566 + jQuery('#' + id).removeClass('yellow');
567 + jQuery('#' + id).removeClass('green');
568 + jQuery('#' + id).removeClass('red');
569 + jQuery('#' + id).addClass(type);
448 570 } else {
449 - currentHtml = text;
571 + jQuery('#' + id).html(text);
572 + jQuery('#' + id).removeClass('yellow');
573 + jQuery('#' + id).removeClass('green');
574 + jQuery('#' + id).removeClass('red');
575 + jQuery('#' + id).addClass(type);
450 576 }
451 - jQuery('#' + id).html(currentHtml);
452 - jQuery('#' + id).removeClass('yellow');
453 - jQuery('#' + id).removeClass('green');
454 - jQuery('#' + id).removeClass('red');
455 - jQuery('#' + id).addClass(type);
456 - } else {
457 - jQuery('#' + id).html(text);
458 - jQuery('#' + id).removeClass('yellow');
459 - jQuery('#' + id).removeClass('green');
460 - jQuery('#' + id).removeClass('red');
461 - jQuery('#' + id).addClass(type);
462 - }
463 - jQuery('#' + id).show();
577 + jQuery('#' + id).show();
464 578
465 - // automatically scroll to error message if it's not visible
466 - scrollElementTop(id);
579 + // automatically scroll to error message if it's not visible
580 + scrollElementTop(id);
467 581 };
468 582
469 -window.feedback_scroll = function (id, color) {
470 - jQuery('#' + id).removeClass('green red yellow');
471 - jQuery('#' + id).addClass(color);
472 - jQuery('#' + id).show();
473 - // automatically scroll to error message if it's not visible
474 - scrollElementTop(id);
583 +globalThis.feedback_scroll = function (id, color) {
584 + jQuery('#' + id).removeClass('green red yellow');
585 + jQuery('#' + id).addClass(color);
586 + jQuery('#' + id).show();
587 + // automatically scroll to error message if it's not visible
588 + scrollElementTop(id);
475 589 }
476 590
477 -window.scrollElementTop = function (id) {
478 - let scrolltop = jQuery(window).scrollTop();
479 - if (jQuery('#' + id).length == 0) {
480 - return;
481 - }
482 - let off = jQuery('#' + id).offset();
483 - if (scrolltop > off.top - 40)
484 - jQuery('html, body').animate({
485 - scrollTop: off.top - 40
486 - }, 1000, function () {
487 - shake_element('#' + id)
488 - });
489 - else
490 - shake_element('#' + id); // shake the error message to get attention :)
591 +globalThis.scrollElementTop = function (id) {
592 + let scrolltop = jQuery(globalThis).scrollTop();
593 + if (jQuery('#' + id).length == 0) {
594 + return;
595 + }
596 + let off = jQuery('#' + id).offset();
597 + if (scrolltop > off.top - 40)
598 + jQuery('html, body').animate({
599 + scrollTop: off.top - 40
600 + }, 1000, function () {
601 + shake_element('#' + id)
602 + });
603 + else
604 + shake_element('#' + id); // shake the error message to get attention :)
491 605 }
492 606
607 +globalThis.mainwp_showhide_message = function (id, content, cls, append, scroll) {
608 +
609 + if ('' === content) {
610 + jQuery('#' + id).html('').fadeOut(500);
611 + return;
612 + }
613 +
614 + if (append) {
615 + let html = jQuery('#' + id).html();
616 + if (html == null)
617 + html = "";
618 + if (html == '') {
619 + html = content;
620 + } else {
621 + html += '<br />' + content;
622 + }
623 + jQuery('#' + id).html(html);
624 + } else {
625 + jQuery('#' + id).html(content);
626 + }
627 +
628 + jQuery('#' + id).removeClass('yellow green red');
629 + jQuery('#' + id).addClass(cls);
630 + jQuery('#' + id).show();
631 +
632 + if (scroll === undefined && scroll) {
633 + scrollElementTop(id);
634 + }
635 +
636 +};
637 +
493 638 jQuery(function () {
494 - jQuery('div.mainwp-hidden').parent().parent().css("display", "none");
639 + jQuery('div.mainwp-hidden').parent().parent().css("display", "none");
495 640 });
496 641
497 642 /**
498 643 * Security Issues
@@ -497,403 +642,277 @@
497 642 /**
498 643 * Security Issues
499 644 */
500 645
501 -let securityIssues_fixes = ['listing', 'wp_version', 'rsd', 'wlw', 'core_updates', 'plugin_updates', 'theme_updates', 'db_reporting', 'php_reporting', 'versions', 'registered_versions', 'admin', 'readme', 'wp_uptodate', 'phpversion_matched', 'sslprotocol', 'debug_disabled'];
646 +let securityIssues_fixes = ['core_updates', 'plugin_updates', 'theme_updates', 'db_reporting', 'php_reporting', 'wp_uptodate', 'phpversion_matched', 'sslprotocol', 'debug_disabled', 'sec_outdated_plugins', 'sec_inactive_plugins', 'sec_outdated_themes', 'sec_inactive_themes'];
502 647 jQuery(function () {
503 - let securityIssueSite = jQuery('#securityIssueSite');
504 - if ((securityIssueSite.val() != null) && (securityIssueSite.val() != "")) {
505 - jQuery(document).on('click', '#securityIssues_fixAll', function () {
506 - securityIssues_fix('all');
507 - });
648 + let securityIssueSite = jQuery('#securityIssueSite');
649 + if ((securityIssueSite.val() != null) && (securityIssueSite.val() != "")) {
650 + jQuery(document).on('click', '#securityIssues_refresh', function () {
651 + for (let ise of securityIssues_fixes) {
652 + let securityIssueCurrentIssue = jQuery('#' + ise + '_fix');
653 + if (securityIssueCurrentIssue) {
654 + securityIssueCurrentIssue.hide();
655 + }
656 + jQuery('#' + ise + '_extra').hide();
657 + jQuery('#' + ise + '_ok').hide();
658 + jQuery('#' + ise + '_nok').hide();
659 + jQuery('#' + ise + '_loading').show();
660 + }
661 + securityIssues_request(jQuery('#securityIssueSite').val());
662 + });
508 663
509 - jQuery(document).on('click', '#securityIssues_refresh', function () {
510 - for (let ise of securityIssues_fixes) {
511 - let securityIssueCurrentIssue = jQuery('#' + ise + '_fix');
512 - if (securityIssueCurrentIssue) {
513 - securityIssueCurrentIssue.hide();
514 - }
515 - jQuery('#' + ise + '_extra').hide();
516 - jQuery('#' + ise + '_ok').hide();
517 - jQuery('#' + ise + '_nok').hide();
518 - jQuery('#' + ise + '_loading').show();
519 - }
520 - securityIssues_request(jQuery('#securityIssueSite').val());
521 - });
664 + for (let ise of securityIssues_fixes) {
665 + if (ise === 'wp_uptodate' || ise === 'sec_inactive_themes' || ise === 'sec_inactive_plugins' || ise === 'sec_outdated_plugins' || ise === 'sec_outdated_themes') {
666 + continue;
667 + }
668 + jQuery('#' + ise + '_fix').on('click', function (what) {
669 + return function () {
670 + securityIssues_fix(what);
671 + return false;
672 + }
673 + }(ise));
522 674
523 - for (let ise of securityIssues_fixes) {
524 - jQuery('#' + ise + '_fix').on('click', function (what) {
525 - return function () {
526 - securityIssues_fix(what);
527 - return false;
675 + jQuery('#' + ise + '_unfix').on('click', function (what) {
676 + return function () {
677 + securityIssues_unfix(what);
678 + return false;
679 + }
680 + }(ise));
528 681 }
529 - }(ise));
530 -
531 - jQuery('#' + ise + '_unfix').on('click', function (what) {
532 - return function () {
533 - securityIssues_unfix(what);
534 - return false;
535 - }
536 - }(ise));
682 + securityIssues_request(securityIssueSite.val());
537 683 }
538 - securityIssues_request(securityIssueSite.val());
539 - }
540 684 });
541 -window.securityIssues_fix = function (feature) {
542 - if (feature == 'all') {
543 - for (let ise of securityIssues_fixes) {
544 - if (jQuery('#' + ise + '_nok').css('display') != 'none') {
545 - if (jQuery('#' + ise + '_fix')) {
546 - jQuery('#' + ise + '_fix').hide();
547 - }
548 - jQuery('#' + ise + '_extra').hide();
549 - jQuery('#' + ise + '_ok').hide();
550 - jQuery('#' + ise + '_nok').hide();
551 - jQuery('#' + ise + '_loading').show();
552 - }
553 - }
554 - } else {
685 +globalThis.securityIssues_fix = function (feature) {
555 686 if (jQuery('#' + feature + '_fix')) {
556 - jQuery('#' + feature + '_fix').hide();
687 + jQuery('#' + feature + '_fix').hide();
557 688 }
558 689 jQuery('#' + feature + '_extra').hide();
559 690 jQuery('#' + feature + '_ok').hide();
560 691 jQuery('#' + feature + '_nok').hide();
561 692 jQuery('#' + feature + '_loading').show();
562 - }
563 693
564 - let data = mainwp_secure_data({
565 - action: 'mainwp_security_issues_fix',
566 - feature: feature,
567 - id: jQuery('#securityIssueSite').val()
568 - });
694 + let data = mainwp_secure_data({
695 + action: 'mainwp_security_issues_fix',
696 + feature: feature,
697 + id: jQuery('#securityIssueSite').val()
698 + });
569 699
570 - jQuery.post(ajaxurl, data, function (response) {
571 - securityIssues_handle(response);
572 - }, 'json');
700 + jQuery.post(ajaxurl, data, function (response) {
701 + securityIssues_handle(response);
702 + }, 'json');
573 703 };
574 704
575 -// Securtiy issues Widget
576 -
577 -// Show/Hide the list
578 -jQuery(document).on('click', '#mainwp-show-security-issues-widget-list', function () {
579 - jQuery('#mainwp-security-issues-widget-list').toggle();
580 - return false;
581 -});
582 -
583 -// Fix all sites all security issues
584 -jQuery(document).on('click', '.fix-all-security-issues', function () {
585 -
586 - jQuery('#mainwp-secuirty-issues-loader').show();
587 -
588 - jQuery('#mainwp-security-issues-widget-list').show();
589 - mainwpVars.bulkInstallTotal = jQuery('#mainwp-security-issues-widget-list .item[status="queue"]').length;
590 - jQuery('.fix-all-site-security-issues').addClass('disabled');
591 - jQuery('.unfix-all-site-security-issues').addClass('disabled');
592 - mainwp_fix_all_security_issues_start_next();
593 -});
594 -
595 -let mainwp_fix_all_security_issues_start_next = function () {
596 - while ((siteToFix = jQuery('#mainwp-security-issues-widget-list .item[status="queue"]:first')) && (siteToFix.length > 0) && (bulkInstallCurrentThreads < bulkInstallMaxThreads)) { // NOSONAR -- modified out side the function.
597 - mainwp_fix_all_security_issues_specific(siteToFix);
598 - }
599 -}
600 -
601 -let mainwp_fix_all_security_issues_specific = function (siteToFix) {
602 -
603 - bulkInstallCurrentThreads++;
604 -
605 - siteToFix.attr('status', 'progress');
606 -
607 - let data = mainwp_secure_data({
608 - action: 'mainwp_security_issues_fix',
609 - feature: 'all',
610 - id: siteToFix.attr('siteid')
611 - });
612 -
613 - let el = siteToFix.find('.fix-all-site-security-issues');
614 - el.hide();
615 -
616 - jQuery.post(ajaxurl, data, function () {
617 - return function () {
618 - siteToFix.attr('status', 'done');
619 - el.show();
620 - bulkInstallCurrentThreads--;
621 - bulkInstallDone++;
622 - if (bulkInstallDone != 0 && (mainwpVars.bulkInstallTotal == 1 || (bulkInstallDone >= mainwpVars.bulkInstallTotal))) { // NOSONAR - modified outside the function.
623 - window.location.href = location.href;
624 - }
625 - mainwp_fix_all_security_issues_start_next();
705 +let securityIssues_unfix = function (feature) {
706 + if (jQuery('#' + feature + '_unfix')) {
707 + jQuery('#' + feature + '_unfix').hide();
626 708 }
627 - }(), 'json');
628 -}
709 + jQuery('#' + feature + '_extra').hide();
710 + jQuery('#' + feature + '_ok').hide();
711 + jQuery('#' + feature + '_nok').hide();
712 + jQuery('#' + feature + '_loading').show();
629 713
630 -// Fix all securtiy issues for a site
631 -jQuery(document).on('click', '.fix-all-site-security-issues', function () {
632 - jQuery('#mainwp-secuirty-issues-loader').show();
633 - mainwp_fix_all_security_issues(jQuery(this).closest('.item').attr('siteid'), true);
634 -});
635 -
636 -let mainwp_fix_all_security_issues = function (siteId, refresh) {
637 - let data = mainwp_secure_data({
638 - action: 'mainwp_security_issues_fix',
639 - feature: 'all',
640 - id: siteId
641 - });
642 -
643 - let el = jQuery('#mainwp-security-issues-widget-list .item[siteid="' + siteId + '"] .fix-all-site-security-issues');
644 -
645 - el.hide();
646 -
647 - jQuery('.fix-all-site-security-issues').addClass('disabled');
648 - jQuery('.unfix-all-site-security-issues').addClass('disabled');
649 -
650 - jQuery.post(ajaxurl, data, function () {
651 - el.show();
652 - if (refresh) {
653 - window.location.href = location.href;
654 - };
655 - }, 'json');
714 + let data = mainwp_secure_data({
715 + action: 'mainwp_security_issues_unfix',
716 + feature: feature,
717 + id: jQuery('#securityIssueSite').val()
718 + });
719 + jQuery.post(ajaxurl, data, function (response) {
720 + securityIssues_handle(response);
721 + }, 'json');
656 722 };
657 -
658 -jQuery(document).on('click', '.unfix-all-site-security-issues', function () {
659 -
660 - jQuery('#mainwp-secuirty-issues-loader').show();
661 -
662 - let data = mainwp_secure_data({
663 - action: 'mainwp_security_issues_unfix',
664 - feature: 'all',
665 - id: jQuery(jQuery(this).parents('.item')[0]).attr('siteid')
666 - });
667 -
668 - jQuery(this).hide();
669 - jQuery('.fix-all-site-security-issues').addClass('disabled');
670 - jQuery('.unfix-all-site-security-issues').addClass('disabled');
671 -
672 - jQuery.post(ajaxurl, data, function () {
673 - window.location.href = location.href;
674 - }, 'json');
675 -});
676 -let securityIssues_unfix = function (feature) {
677 - if (jQuery('#' + feature + '_unfix')) {
678 - jQuery('#' + feature + '_unfix').hide();
679 - }
680 - jQuery('#' + feature + '_extra').hide();
681 - jQuery('#' + feature + '_ok').hide();
682 - jQuery('#' + feature + '_nok').hide();
683 - jQuery('#' + feature + '_loading').show();
684 -
685 - let data = mainwp_secure_data({
686 - action: 'mainwp_security_issues_unfix',
687 - feature: feature,
688 - id: jQuery('#securityIssueSite').val()
689 - });
690 - jQuery.post(ajaxurl, data, function (response) {
691 - securityIssues_handle(response);
692 - }, 'json');
693 -};
694 723 let securityIssues_request = function (websiteId) {
695 - let data = mainwp_secure_data({
696 - action: 'mainwp_security_issues_request',
697 - id: websiteId
698 - });
699 - jQuery.post(ajaxurl, data, function (response) {
700 - securityIssues_handle(response);
701 - }, 'json');
724 + let data = mainwp_secure_data({
725 + action: 'mainwp_security_issues_request',
726 + id: websiteId
727 + });
728 + jQuery.post(ajaxurl, data, function (response) {
729 + securityIssues_handle(response);
730 + }, 'json');
702 731 };
732 +// eslint-disable-next-line complexity
703 733 let securityIssues_handle = function (response) { // NOSONAR - complex.
704 - let result = '';
705 - if (response.error) {
706 - result = getErrorMessage(response.error);
707 - } else {
708 - try {
709 - let res = response.result;
710 - for (let issue in res) {
711 - if (jQuery('#' + issue + '_loading')) {
712 - jQuery('#' + issue + '_loading').hide();
713 - if (res[issue] == 'Y' || res[issue] == 'Y_UNABLE') {
714 - jQuery('#' + issue + '_extra').hide();
715 - jQuery('#' + issue + '_nok').hide();
716 - if (jQuery('#' + issue + '_fix')) {
717 - jQuery('#' + issue + '_fix').hide();
718 - }
734 + let result = '';
735 + if (response.error) {
736 + result = getErrorMessage(response.error);
737 + } else {
738 + try {
739 + let res = response.result;
740 + for (let issue in res) {
741 + if (jQuery('#' + issue + '_loading')) {
742 + jQuery('#' + issue + '_loading').hide();
743 + if (res[issue] == 'Y' || res[issue] == 'Y_UNABLE') {
744 + jQuery('#' + issue + '_extra').hide();
745 + jQuery('#' + issue + '_nok').hide();
746 + if (jQuery('#' + issue + '_fix')) {
747 + jQuery('#' + issue + '_fix').hide();
748 + }
719 749
720 - if (jQuery('#' + issue + '_unfix')) {
721 - jQuery('#' + issue + '_unfix').show();
722 - if (res[issue] == 'Y_UNABLE') { // Y_UNABLE will disable unfix.
723 - jQuery('#' + issue + '_unfix').hide().after('<a href="javascript:void(0);" class="ui mini fluid button" disabled="disabled">Unfix</a>');
724 - }
725 - }
750 + if (jQuery('#' + issue + '_unfix')) {
751 + jQuery('#' + issue + '_unfix').show();
752 + if (res[issue] == 'Y_UNABLE') { // Y_UNABLE will disable unfix.
753 + jQuery('#' + issue + '_unfix').hide();
754 + }
755 + }
726 756
727 - jQuery('#' + issue + '_ok').show();
728 - jQuery('#' + issue + '-status-ok').show();
729 - jQuery('#' + issue + '-status-nok').hide();
730 - if (issue == 'readme') {
731 - jQuery('#readme-wpe-nok').hide();
732 - }
733 - } else if (res[issue] == 'N' || res[issue] == 'N_UNABLE') {
734 - jQuery('#' + issue + '_extra').hide();
735 - jQuery('#' + issue + '_ok').hide();
736 - jQuery('#' + issue + '_nok').show();
757 + jQuery('#' + issue + '_ok').show();
758 + jQuery('#' + issue + '-status-ok').show();
759 + jQuery('#' + issue + '-status-nok').hide();
760 + } else if (res[issue] == 'N' || res[issue] == 'N_UNABLE') {
761 + jQuery('#' + issue + '_extra').hide();
762 + jQuery('#' + issue + '_ok').hide();
763 + jQuery('#' + issue + '_nok').show();
737 764
738 - if (jQuery('#' + issue + '_fix')) {
739 - jQuery('#' + issue + '_fix').show();
740 - if (res[issue] == 'N_UNABLE') { // N_UNABLE will disable fix.
741 - jQuery('#' + issue + '_fix').hide().after('<a href="javascript:void(0);" class="ui mini fluid button" disabled="disabled">fix</a>');
742 - }
743 - }
765 + if (jQuery('#' + issue + '_fix')) {
766 + jQuery('#' + issue + '_fix').show();
767 + if (res[issue] == 'N_UNABLE') { // N_UNABLE will disable fix.
768 + jQuery('#' + issue + '_fix').hide().after('<a href="javascript:void(0);" class="ui mini fluid button" disabled="disabled">fix</a>');
769 + }
770 + }
744 771
745 - if (jQuery('#' + issue + '_unfix')) {
746 - jQuery('#' + issue + '_unfix').hide();
747 - }
748 - if (res[issue] != 'N') {
749 - jQuery('#' + issue + '_extra').html(res[issue]);
750 - jQuery('#' + issue + '_extra').show();
751 - }
752 - }
753 - }
754 - }
772 + if (jQuery('#' + issue + '_unfix')) {
773 + jQuery('#' + issue + '_unfix').hide();
774 + }
775 + if (res[issue] != 'N') {
776 + jQuery('#' + issue + '_extra').html(res[issue]);
777 + jQuery('#' + issue + '_extra').show();
778 + }
755 779
756 - let unSetFeatures = jQuery('#mainwp-security-issues-table').attr('un-set');
757 - if (unSetFeatures != '') {
758 - unSetFeatures = unSetFeatures.split(',');
759 - if (unSetFeatures.length > 0) {
760 - let issue;
761 - for (let ival in unSetFeatures) {
762 - issue = unSetFeatures[ival];
763 - console.log(res[issue]);
764 - if (res[issue] == 'Y') {
765 - securityIssues_unfix(issue);
780 + if ('wp_uptodate' === issue) {
781 + jQuery('#wp_upgrades').find('div[updated="-1"]').each(function () {
782 + jQuery(this).attr('updated', 0);
783 + });
784 + }
785 + jQuery('#' + issue + '-status-ok').hide();
786 + jQuery('#' + issue + '-status-nok').show();
787 + }
788 + }
766 789 }
767 - }
790 + } catch {
791 + result = '<i class="exclamation circle icon"></i> ' + MainWP.I18n.t('Undefined error!');
768 792 }
769 - }
770 -
771 - } catch (err) {
772 - result = '<i class="exclamation circle icon"></i> ' + __('Undefined error!');
773 793 }
774 - }
775 - if (result != '') {
776 - //show error!
777 - }
794 + if (result != '') {
795 + //show error!
796 + }
778 797 };
779 798
780 -window.updatesoverview_bulk_check_abandoned = function (which) {
781 - let confirmMsg;
782 - if ('plugin' == which) {
783 - confirmMsg = __("You are about to check abandoned plugins on the sites?");
784 - } else {
785 - confirmMsg = __("You are about to check abandoned themes on the sites?");
786 - }
787 - mainwp_confirm(confirmMsg, function () { mainwp_managesites_bulk_check_abandoned('all', which); });
799 +globalThis.updatesoverview_bulk_check_abandoned = function (which) {
800 + let confirmMsg;
801 + if ('plugin' == which) {
802 + confirmMsg = MainWP.I18n.t("You are about to check abandoned plugins on the sites?");
803 + } else {
804 + confirmMsg = MainWP.I18n.t("You are about to check abandoned themes on the sites?");
805 + }
806 + mainwp_confirm(confirmMsg, function () { mainwp_managesites_bulk_check_abandoned('all', which); });
788 807 }
789 808
790 -window.mainwp_managesites_bulk_check_abandoned = function (siteIds, which) {
791 - let allWebsiteIds = jQuery('.dashboard_wp_id[error-status=0]').map(function (indx, el) {
792 - return jQuery(el).val();
793 - });
809 +globalThis.mainwp_managesites_bulk_check_abandoned = function (siteIds, which) {
810 + let allWebsiteIds = jQuery('.dashboard_wp_id[error-status=0]').map(function (indx, el) {
811 + return jQuery(el).val();
812 + });
794 813
795 - if ('all' == siteIds) {
796 - siteIds = allWebsiteIds;
797 - }
814 + if ('all' == siteIds) {
815 + siteIds = allWebsiteIds;
816 + }
798 817
799 - let selectedIds = [], excludeIds = [];
800 - if (siteIds instanceof Array) {
801 - jQuery.grep(allWebsiteIds, function (el) {
802 - if (jQuery.inArray(el, siteIds) !== -1) {
803 - selectedIds.push(el);
804 - } else {
805 - excludeIds.push(el);
806 - }
807 - });
808 - for (let id of excludeIds) {
809 - dashboard_update_site_hide(id);
818 + let selectedIds = [], excludeIds = [];
819 + if (Array.isArray(siteIds)) {
820 + jQuery.grep(allWebsiteIds, function (el) {
821 + if (jQuery.inArray(el, siteIds) === -1) {
822 + excludeIds.push(el);
823 + } else {
824 + selectedIds.push(el);
825 + }
826 + });
827 + for (let id of excludeIds) {
828 + dashboard_update_site_hide(id);
829 + }
830 + allWebsiteIds = selectedIds;
810 831 }
811 - allWebsiteIds = selectedIds;
812 - }
813 832
814 - let nrOfWebsites = allWebsiteIds.length;
833 + let nrOfWebsites = allWebsiteIds.length;
815 834
816 - if (nrOfWebsites == 0) {
817 - managesites_reset_bulk_actions_params();
818 - return;
819 - }
835 + if (nrOfWebsites == 0) {
836 + managesites_reset_bulk_actions_params();
837 + return;
838 + }
820 839
821 - let siteNames = {};
840 + let siteNames = {};
822 841
823 - for (let id of allWebsiteIds) {
824 - dashboard_update_site_status(id, '<i class="clock outline icon"></i>');
825 - siteNames[id] = jQuery('.sync-site-status[siteid="' + id + '"]').attr('niceurl');
826 - }
827 - let initData = {
828 - progressMax: nrOfWebsites,
829 - title: 'Check abandoned ' + ('plugin' == which ? 'plugins' : 'themes'),
830 - statusText: __('started'),
831 - callback: function () {
832 - mainwpVars.bulkManageSitesTaskRunning = false;
833 - window.location.href = location.href;
842 + for (let id of allWebsiteIds) {
843 + dashboard_update_site_status(id, '<i class="clock outline icon"></i>');
844 + siteNames[id] = jQuery('.sync-site-status[siteid="' + id + '"]').attr('niceurl');
834 845 }
835 - };
836 - mainwpPopup('#mainwp-sync-sites-modal').init(initData);
846 + let initData = {
847 + progressMax: nrOfWebsites,
848 + title: 'Check abandoned ' + ('plugin' == which ? 'plugins' : 'themes'),
849 + statusText: MainWP.I18n.t('started'),
850 + callback: function () {
851 + mainwpVars.bulkManageSitesTaskRunning = false;
852 + mainwp_forceReload();
853 + }
854 + };
855 + mainwpPopup('#mainwp-sync-sites-modal').init(initData);
837 856
838 - mainwp_managesites_check_abandoned_all_int(allWebsiteIds, which);
857 + mainwp_managesites_check_abandoned_all_int(allWebsiteIds, which);
839 858 };
840 859
841 860 let mainwp_managesites_check_abandoned_all_int = function (websiteIds, which) {
842 - mainwpVars.websitesToUpgrade = websiteIds;
843 - mainwpVars.currentWebsite = 0;
844 - mainwpVars.websitesDone = 0;
845 - mainwpVars.websitesTotal = mainwpVars.websitesToUpgrade.length;
846 - mainwpVars.websitesLeft = mainwpVars.websitesToUpgrade.length;
861 + mainwpVars.websitesToUpgrade = websiteIds;
862 + mainwpVars.currentWebsite = 0;
863 + mainwpVars.websitesDone = 0;
864 + mainwpVars.websitesTotal = mainwpVars.websitesToUpgrade.length;
865 + mainwpVars.websitesLeft = mainwpVars.websitesToUpgrade.length;
847 866
848 - mainwpVars.bulkTaskRunning = true;
849 - mainwp_managesites_check_abandoned_all_loop_next(which);
867 + mainwpVars.bulkTaskRunning = true;
868 + mainwp_managesites_check_abandoned_all_loop_next(which);
850 869 };
851 870
852 871 let mainwp_managesites_check_abandoned_all_loop_next = function (which) {
853 - while (mainwpVars.bulkTaskRunning && (mainwpVars.currentThreads < mainwpVars.maxThreads) && (mainwpVars.websitesLeft > 0)) {
854 - mainwp_managesites_check_abandoned_all_upgrade_next(which);
855 - }
872 + while (mainwpVars.bulkTaskRunning && (mainwpVars.currentThreads < mainwpVars.maxThreads) && (mainwpVars.websitesLeft > 0)) {
873 + mainwp_managesites_check_abandoned_all_upgrade_next(which);
874 + }
856 875 };
857 876 let mainwp_managesites_check_abandoned_all_upgrade_next = function (which) {
858 - mainwpVars.currentThreads++;
859 - mainwpVars.websitesLeft--;
877 + mainwpVars.currentThreads++;
878 + mainwpVars.websitesLeft--;
860 879
861 - let websiteId = mainwpVars.websitesToUpgrade[mainwpVars.currentWebsite++];
862 - dashboard_update_site_status(websiteId, '<i class="sync alternate loading icon"></i>');
880 + let websiteId = mainwpVars.websitesToUpgrade[mainwpVars.currentWebsite++];
881 + dashboard_update_site_status(websiteId, '<i class="sync alternate loading icon"></i>');
863 882
864 - mainwp_managesites_check_abandoned_int(websiteId, which);
883 + mainwp_managesites_check_abandoned_int(websiteId, which);
865 884 };
866 885
867 886 let mainwp_managesites_check_abandoned_int = function (siteid, which) {
868 887
869 - let data = mainwp_secure_data({
870 - action: 'mainwp_check_abandoned',
871 - siteId: siteid,
872 - which: which
873 - });
888 + let data = mainwp_secure_data({
889 + action: 'mainwp_check_abandoned',
890 + siteId: siteid,
891 + which: which
892 + });
874 893
875 - jQuery.ajax({
876 - type: 'POST',
877 - url: ajaxurl,
878 - data: data,
879 - success: function (pSiteid) {
880 - return function (response) {
881 - mainwpVars.currentThreads--;
882 - mainwpVars.websitesDone++;
883 - mainwpPopup('#mainwp-sync-sites-modal').setProgressSite(mainwpVars.websitesDone);
884 - if (response.error != undefined) {
885 - dashboard_update_site_status(pSiteid, '<i class="red times icon"></i>');
886 - } else if (response.result && response.result == 'success') {
887 - dashboard_update_site_status(pSiteid, '<i class="green check icon"></i>', true);
888 - } else {
889 - dashboard_update_site_status(pSiteid, '<i class="red times icon"></i>');
890 - }
891 - mainwp_managesites_check_abandoned_all_loop_next(which);
892 - }
893 - }(siteid),
894 - dataType: 'json'
895 - });
894 + jQuery.ajax({
895 + type: 'POST',
896 + url: ajaxurl,
897 + data: data,
898 + success: function (pSiteid) {
899 + return function (response) {
900 + mainwpVars.currentThreads--;
901 + mainwpVars.websitesDone++;
902 + mainwpPopup('#mainwp-sync-sites-modal').setProgressSite(mainwpVars.websitesDone);
903 + if (response.error != undefined) {
904 + dashboard_update_site_status(pSiteid, '<i class="red times icon"></i>');
905 + } else if (response.result && response.result == 'success') {
906 + dashboard_update_site_status(pSiteid, '<i class="green check icon"></i>', true);
907 + } else {
908 + dashboard_update_site_status(pSiteid, '<i class="red times icon"></i>');
909 + }
910 + mainwp_managesites_check_abandoned_all_loop_next(which);
911 + }
912 + }(siteid),
913 + dataType: 'json'
914 + });
896 915 };
897 916
898 917 /**
899 918 * MainWP UI.
@@ -898,25 +917,25 @@
898 917 /**
899 918 * MainWP UI.
900 919 */
901 920 jQuery(function () {
902 - jQuery('#reset-overview-settings').on('click', function () {
903 - mainwp_confirm(__('Are you sure?'), function () {
904 - let which_set = jQuery('input[name=reset_overview_which_settings]').val();
905 - if ('sidebar_settings' == which_set) {
906 - jQuery('#mainwp_sidebarPosition').dropdown('set selected', 1);
907 - } else if ('overview_settings' == which_set) {
908 - jQuery('input[name=hide_update_everything]').prop('checked', false);
909 - jQuery('.mainwp_hide_wpmenu_checkboxes input[name="mainwp_show_widgets[]"]').prop('checked', true);
910 - }
911 - if (jQuery('input[name=mainwp_manageposts_show_columns_settings]').length > 0 || jQuery('input[name=mainwp_managepages_show_columns_settings]').length > 0 || jQuery('input[name=mainwp_manageusers_show_columns_settings]').length > 0) {
912 - jQuery('input[name="mainwp_show_columns[]"]').prop('checked', true);
913 - }
914 - jQuery('input[name=reset_overview_settings]').attr('value', 1);
915 - jQuery('#submit-overview-settings').click();
916 - }, false, false, true);
917 - return false;
918 - });
921 + jQuery('#reset-overview-settings').on('click', function () {
922 + mainwp_confirm(MainWP.I18n.t('Are you sure?'), function () {
923 + let which_set = jQuery('input[name=reset_overview_which_settings]').val();
924 + if ('sidebar_settings' == which_set) {
925 + jQuery('#mainwp_sidebarPosition').dropdown('set selected', 1);
926 + } else if ('overview_settings' == which_set) {
927 + jQuery('input[name=hide_update_everything]').prop('checked', false);
928 + jQuery('.mainwp_hide_wpmenu_checkboxes input[name="mainwp_show_widgets[]"]').prop('checked', true);
929 + }
930 + if (jQuery('input[name=mainwp_manageposts_show_columns_settings]').length > 0 || jQuery('input[name=mainwp_managepages_show_columns_settings]').length > 0 || jQuery('input[name=mainwp_manageusers_show_columns_settings]').length > 0) {
931 + jQuery('input[name="mainwp_show_columns[]"]').prop('checked', true);
932 + }
933 + jQuery('input[name=reset_overview_settings]').attr('value', 1);
934 + jQuery('#submit-overview-settings').click();
935 + }, false, false, true);
936 + return false;
937 + });
919 938 });
920 939
921 940 /**
922 941 * Sync Sites
@@ -922,80 +941,80 @@
922 941 * Sync Sites
923 942 */
924 943
925 944 jQuery(function () {
926 - jQuery('#mainwp-sync-sites').on('click', function () {
927 - mainwp_sync_sites_data();
928 - });
945 + jQuery('#mainwp-sync-sites').on('click', function () {
946 + mainwp_sync_sites_data();
947 + });
929 948
930 - // to compatible with extensions
931 - jQuery('#dashboard_refresh').on('click', function () {
932 - mainwp_sync_sites_data();
933 - });
934 - jQuery('.mainwp-sync-this-site').on('click', function () {
935 - let syncSiteIds = [];
936 - syncSiteIds.push(jQuery(this).attr('site-id'));
937 - mainwp_sync_sites_data(syncSiteIds);
938 - });
949 + // to compatible with extensions
950 + jQuery('#dashboard_refresh').on('click', function () {
951 + mainwp_sync_sites_data();
952 + });
953 + jQuery('.mainwp-sync-this-site').on('click', function () {
954 + let syncSiteIds = [];
955 + syncSiteIds.push(jQuery(this).attr('site-id'));
956 + mainwp_sync_sites_data(syncSiteIds);
957 + });
939 958 });
940 959
941 -window.mainwp_sync_sites_data = function (syncSiteIds, pAction) {
942 - let allWebsiteIds = [];
943 - jQuery('.dashboard_wp_id[error-status=0]').map(function (indx, el) {
944 - allWebsiteIds.push(jQuery(el).val());
945 - });
946 - let globalSync = true;
947 - let selectedIds = [], excludeIds = [];
948 - if (syncSiteIds instanceof Array) {
949 - jQuery.grep(allWebsiteIds, function (el) {
950 - if (jQuery.inArray(el, syncSiteIds) !== -1) {
951 - selectedIds.push(el);
952 - } else {
953 - excludeIds.push(el);
954 - }
960 +globalThis.mainwp_sync_sites_data = function (syncSiteIds, pAction) {
961 + let allWebsiteIds = [];
962 + jQuery('.dashboard_wp_id[error-status=0]').map(function (indx, el) {
963 + allWebsiteIds.push(jQuery(el).val());
955 964 });
956 - for (let id of excludeIds) {
957 - dashboard_update_site_hide(id);
965 + let globalSync = true;
966 + let selectedIds = [], excludeIds = [];
967 + if (Array.isArray(syncSiteIds)) {
968 + jQuery.grep(allWebsiteIds, function (el) {
969 + if (jQuery.inArray(el, syncSiteIds) === -1) {
970 + excludeIds.push(el);
971 + } else {
972 + selectedIds.push(el);
973 + }
974 + });
975 + for (let id of excludeIds) {
976 + dashboard_update_site_hide(id);
977 + }
978 + allWebsiteIds = selectedIds;
979 + globalSync = false;
958 980 }
959 - allWebsiteIds = selectedIds;
960 - globalSync = false;
961 - }
962 981
963 - for (let id of allWebsiteIds) {
964 - dashboard_update_site_status(id, '<span data-inverted="" data-position="left center" data-tooltip="' + __('Pending', 'mainwp') + '"><i class="clock outline icon"></i></span>');
965 - }
982 + for (let id of allWebsiteIds) {
983 + dashboard_update_site_status(id, '<span data-inverted="" data-position="left center" data-tooltip="' + MainWP.I18n.t('Pending') + '"><i class="clock outline icon"></i></span>');
984 + }
966 985
967 - let nrOfWebsites = allWebsiteIds.length;
986 + let nrOfWebsites = allWebsiteIds.length;
968 987
969 - mainwpPopup('#mainwp-sync-sites-modal').init({
970 - title: (pAction == 'checknow' ? __('Check Now') : __('Data Synchronization')),
971 - progressMax: nrOfWebsites,
972 - statusText: (pAction == 'checknow' ? 'checked' : 'synced'),
973 - callback: function () {
974 - mainwpVars.bulkTaskRunning = false;
975 - history.pushState("", document.title, window.location.pathname + window.location.search); // to fix issue for url with hash
976 - window.location.href = location.href;
988 + mainwpPopup('#mainwp-sync-sites-modal').init({
989 + title: (pAction == 'checknow' ? MainWP.I18n.t('Check Now') : MainWP.I18n.t('Data Synchronization')),
990 + progressMax: nrOfWebsites,
991 + statusText: (pAction == 'checknow' ? 'checked' : 'synced'),
992 + callback: function () {
993 + mainwpVars.bulkTaskRunning = false;
994 + history.pushState("", document.title, globalThis.location.pathname + globalThis.location.search); // to fix issue for url with hash
995 + mainwp_forceReload();
996 + }
997 + });
998 +
999 + if (jQuery('#mainwp-sync-sites-modal').attr('current-wpid') > 0) {
1000 + globalSync = false;
977 1001 }
978 - });
979 1002
980 - if (jQuery('#mainwp-sync-sites-modal').attr('current-wpid') > 0) {
981 - globalSync = false;
982 - }
1003 + dashboard_update(allWebsiteIds, globalSync, pAction);
983 1004
984 - dashboard_update(allWebsiteIds, globalSync, pAction);
1005 + if (pAction != 'checknow') {
1006 + if (nrOfWebsites > 0) {
1007 + let data = {
1008 + action: 'mainwp_status_saving',
1009 + status: 'last_sync_sites',
1010 + isGlobalSync: globalSync ? 1 : 0
1011 + };
1012 + jQuery.post(ajaxurl, mainwp_secure_data(data), function () {
985 1013
986 - if (pAction != 'checknow') {
987 - if (nrOfWebsites > 0) {
988 - let data = {
989 - action: 'mainwp_status_saving',
990 - status: 'last_sync_sites',
991 - isGlobalSync: globalSync ? 1 : 0
992 - };
993 - jQuery.post(ajaxurl, mainwp_secure_data(data), function () {
994 -
995 - });
1014 + });
1015 + }
996 1016 }
997 - }
998 1017 };
999 1018
1000 1019 mainwpVars.websitesToUpdate = [];
1001 1020 mainwpVars.websitesTotal = 0;
@@ -1004,1296 +1023,1548 @@
1004 1023 mainwpVars.currentWebsite = 0;
1005 1024 mainwpVars.bulkTaskRunning = false;
1006 1025 mainwpVars.currentThreads = 0;
1007 1026 mainwpVars.maxThreads = mainwpParams['maximumSyncRequests'] == undefined ? 8 : mainwpParams['maximumSyncRequests'];
1027 +mainwpVars.maxUpdateThreads = mainwpParams['maximumInstallUpdateRequests'] == undefined ? 3 : mainwpParams['maximumInstallUpdateRequests'];
1028 +
1008 1029 let globalSync = true;
1009 1030
1010 -window.dashboard_update = function (websiteIds, isGlobalSync, pAction) {
1011 - mainwpVars.websitesToUpdate = websiteIds;
1012 - mainwpVars.currentWebsite = 0;
1013 - mainwpVars.websitesDone = 0;
1014 - mainwpVars.websitesTotal = mainwpVars.websitesLeft = mainwpVars.websitesToUpdate.length;
1015 - globalSync = isGlobalSync;
1031 +globalThis.dashboard_update = function (websiteIds, isGlobalSync, pAction) {
1032 + mainwpVars.websitesToUpdate = websiteIds;
1033 + mainwpVars.currentWebsite = 0;
1034 + mainwpVars.websitesDone = 0;
1035 + mainwpVars.successCount = 0;
1036 + mainwpVars.websitesTotal = mainwpVars.websitesLeft = mainwpVars.websitesToUpdate.length;
1037 + globalSync = isGlobalSync;
1016 1038
1017 - mainwpVars.bulkTaskRunning = true;
1039 + mainwpVars.bulkTaskRunning = true;
1018 1040
1019 - if (mainwpVars.websitesTotal == 0) {
1020 - dashboard_update_done(pAction);
1021 - } else {
1022 - dashboard_loop_next(pAction);
1023 - }
1041 + if (mainwpVars.websitesTotal == 0) {
1042 + dashboard_update_done(pAction);
1043 + } else {
1044 + dashboard_loop_next(pAction);
1045 + }
1024 1046 };
1025 1047
1026 -window.dashboard_update_site_status = function (siteId, newStatus, isSuccess) {
1027 - jQuery('.sync-site-status[siteid="' + siteId + '"]').html(newStatus);
1028 - // Move successfully synced site to the bottom of the sync list
1029 - if (typeof isSuccess !== 'undefined' && isSuccess) {
1030 - let row = jQuery('.sync-site-status[siteid="' + siteId + '"]').closest('.item');
1031 - jQuery(row).insertAfter(jQuery("#sync-sites-status .item").not('.disconnected-site').last());
1032 - }
1048 +(function () {
1049 + // Create global namespace
1050 + const sync = globalThis.dashboardSync = globalThis.dashboardSync || {
1051 + container: null,
1052 + statusMap: new Map(),
1053 + rowMap: new Map(),
1054 +
1055 + data: new Map(),
1056 + queue: [],
1057 +
1058 + scheduled: false,
1059 + initialized: false,
1060 +
1061 + BATCH_SIZE: 50
1062 + };
1063 +
1064 + // -----------------------------
1065 + // INIT CACHE
1066 + // -----------------------------
1067 + function init() {
1068 + if (sync.initialized) return;
1069 +
1070 + sync.container = document.getElementById('sync-sites-status');
1071 + if (!sync.container) return;
1072 +
1073 + const nodes = sync.container.querySelectorAll('.sync-site-status');
1074 +
1075 + for (const el of nodes) {
1076 + const siteId = el.getAttribute('siteid');
1077 + sync.statusMap.set(siteId, el);
1078 + sync.rowMap.set(siteId, el.closest('.item'));
1079 + }
1080 +
1081 + sync.initialized = true;
1082 + }
1083 +
1084 + // Ensure DOM ready
1085 + if (document.readyState === 'loading') {
1086 + document.addEventListener('DOMContentLoaded', init);
1087 + } else {
1088 + init();
1089 + }
1090 +
1091 + // -----------------------------
1092 + // PUBLIC API
1093 + // -----------------------------
1094 + globalThis.dashboard_update_site_status = function (siteId, newStatus, isSuccess) {
1095 + if (!sync.initialized) return;
1096 +
1097 + sync.data.set(siteId, {
1098 + status: newStatus,
1099 + success: isSuccess
1100 + });
1101 +
1102 + sync.queue.push(siteId);
1103 +
1104 + // ✅ increment success count ONCE
1105 + if (isSuccess) {
1106 + mainwpVars.successCount = (mainwpVars.successCount || 0) + 1;
1107 + }
1108 +
1109 + if (!sync.scheduled) {
1110 + sync.scheduled = true;
1111 + requestAnimationFrame(processQueue);
1112 + }
1113 + };
1114 +
1115 + globalThis.dashboard_update_site_hide = function (siteId) {
1116 + const sync = globalThis.dashboardSync;
1117 + if (!sync?.initialized) return;
1118 +
1119 + const rowEl = sync.rowMap.get(siteId);
1120 + if (!rowEl) return;
1121 +
1122 + rowEl.style.display = 'none';
1123 + };
1124 +
1125 + // -----------------------------
1126 + // PROCESS QUEUE (BATCHED)
1127 + // -----------------------------
1128 + function processQueue() {
1129 + sync.scheduled = false;
1130 +
1131 + let count = 0;
1132 +
1133 + while (sync.queue.length && count < sync.BATCH_SIZE) {
1134 + const siteId = sync.queue.shift();
1135 + const data = sync.data.get(siteId);
1136 +
1137 + const statusEl = sync.statusMap.get(siteId);
1138 + const rowEl = sync.rowMap.get(siteId);
1139 +
1140 + if (!statusEl || !rowEl) continue;
1141 +
1142 + // Avoid DOM read → use dataset cache
1143 + if (statusEl.dataset.last !== data.status) {
1144 + statusEl.innerHTML = data.status;
1145 + statusEl.dataset.last = data.status;
1146 + }
1147 +
1148 + // No DOM move → just class toggle
1149 + if (data.success) {
1150 + rowEl.classList.add('is-success');
1151 + }
1152 +
1153 + count++;
1154 + }
1155 +
1156 + // Continue next frame if still pending
1157 + if (sync.queue.length) {
1158 + requestAnimationFrame(processQueue);
1159 + }
1160 + }
1161 +})();
1162 +
1163 +globalThis.dashboard_update_site_status_legacy = function (siteId, newStatus, isSuccess) {
1164 + jQuery('.sync-site-status[siteid="' + siteId + '"]').html(newStatus);
1165 + // Move successfully synced site to the bottom of the sync list
1166 + if (isSuccess !== undefined && isSuccess) {
1167 + let row = jQuery('.sync-site-status[siteid="' + siteId + '"]').closest('.item');
1168 + jQuery(row).insertAfter(jQuery("#sync-sites-status .item").not('.disconnected-site').last());
1169 + }
1033 1170 };
1034 1171
1035 -window.dashboard_update_site_hide = function (siteId) {
1036 - jQuery('.sync-site-status[siteid="' + siteId + '"]').closest('.item').hide();
1172 +globalThis.dashboard_update_site_hide_legacy = function (siteId) {
1173 + jQuery('.sync-site-status[siteid="' + siteId + '"]').closest('.item').hide();
1037 1174 };
1038 1175
1039 1176 let dashboard_loop_next = function (pAction) {
1040 - while (mainwpVars.bulkTaskRunning && (mainwpVars.currentThreads < mainwpVars.maxThreads) && (mainwpVars.websitesLeft > 0)) {
1041 - dashboard_update_next(pAction);
1042 - }
1177 + while (mainwpVars.bulkTaskRunning && (mainwpVars.currentThreads < mainwpVars.maxThreads) && (mainwpVars.websitesLeft > 0)) {
1178 + dashboard_update_next(pAction);
1179 + }
1043 1180 };
1044 1181
1045 1182 let dashboard_update_done = function (pAction) {
1046 - mainwpVars.currentThreads--;
1047 - if (!mainwpVars.bulkTaskRunning)
1048 - return;
1049 - mainwpVars.websitesDone++;
1050 - if (mainwpVars.websitesDone > mainwpVars.websitesTotal)
1051 - mainwpVars.websitesDone = mainwpVars.websitesTotal;
1183 + mainwpVars.currentThreads--;
1052 1184
1053 - mainwpPopup('#mainwp-sync-sites-modal').setProgressSite(mainwpVars.websitesDone);
1185 + if (!mainwpVars.bulkTaskRunning) return;
1054 1186
1055 - if (mainwpVars.websitesDone == mainwpVars.websitesTotal) {
1056 - let successSites = jQuery('#mainwp-sync-sites-modal .check.green.icon').length;
1057 - if (mainwpVars.websitesDone == successSites) {
1058 - mainwpVars.bulkTaskRunning = false;
1059 - setTimeout(function () {
1060 - mainwpPopup('#mainwp-sync-sites-modal').close(true);
1061 - }, 3000);
1062 - } else {
1063 - mainwpVars.bulkTaskRunning = false;
1187 + mainwpVars.websitesDone++;
1188 + if (mainwpVars.websitesDone > mainwpVars.websitesTotal) {
1189 + mainwpVars.websitesDone = mainwpVars.websitesTotal;
1064 1190 }
1065 - return;
1066 - }
1067 1191
1068 - dashboard_loop_next(pAction);
1069 -};
1192 + // ✅ Cache popup instance (avoid re-query)
1193 + const popup = mainwpVars._popup || (
1194 + mainwpVars._popup = mainwpPopup('#mainwp-sync-sites-modal')
1195 + );
1070 1196
1071 -let dashboard_update_next = function (pAction) {
1072 - mainwpVars.currentThreads++;
1073 - mainwpVars.websitesLeft--;
1074 - let websiteId = mainwpVars.websitesToUpdate[mainwpVars.currentWebsite++];
1075 - dashboard_update_site_status(websiteId, '<span data-inverted="" data-position="left center" data-tooltip="' + __('Syncing...', 'mainwp') + '"><i class="sync alternate loading icon"></i></span>');
1076 - let data = mainwp_secure_data({
1077 - action: ('checknow' == pAction ? 'mainwp_checksites' : 'mainwp_syncsites'),
1078 - wp_id: websiteId,
1079 - isGlobalSync: globalSync
1080 - });
1197 + popup.setProgressSite(mainwpVars.websitesDone);
1081 1198
1199 + // ✅ Avoid DOM query for success count → track in JS
1200 + if (mainwpVars.websitesDone === mainwpVars.websitesTotal) {
1082 1201
1202 + const successSites = mainwpVars.successCount || 0;
1083 1203
1084 - dashboard_update_next_int(websiteId, data, 0, pAction);
1204 + mainwpVars.bulkTaskRunning = false;
1205 +
1206 + if (mainwpVars.websitesDone === successSites) {
1207 + setTimeout(() => popup.close(true), 3000);
1208 + }
1209 +
1210 + return;
1211 + }
1212 +
1213 + dashboard_loop_next(pAction);
1085 1214 };
1086 1215
1087 -let dashboard_update_next_int = function (websiteId, data, errors, action) {
1088 - jQuery.ajax({
1089 - type: 'POST',
1090 - url: ajaxurl,
1091 - data: data,
1092 - success: function (pWebsiteId, pAction) {
1093 - return function (response) {
1094 - if (response.error) {
1095 - let extErr = response.error;
1096 - dashboard_update_site_status(pWebsiteId, '<span data-inverted="" data-position="left center" data-tooltip="' + extErr + '"><i class="exclamation red icon"></i></span>');
1216 +let dashboard_update_done_legacy = function (pAction) {
1217 + mainwpVars.currentThreads--;
1218 + if (!mainwpVars.bulkTaskRunning)
1219 + return;
1220 + mainwpVars.websitesDone++;
1221 + if (mainwpVars.websitesDone > mainwpVars.websitesTotal)
1222 + mainwpVars.websitesDone = mainwpVars.websitesTotal;
1223 +
1224 + mainwpPopup('#mainwp-sync-sites-modal').setProgressSite(mainwpVars.websitesDone);
1225 +
1226 + if (mainwpVars.websitesDone == mainwpVars.websitesTotal) {
1227 + let successSites = jQuery('#mainwp-sync-sites-modal .check.green.icon').length;
1228 + if (mainwpVars.websitesDone == successSites) {
1229 + mainwpVars.bulkTaskRunning = false;
1230 + setTimeout(function () {
1231 + mainwpPopup('#mainwp-sync-sites-modal').close(true);
1232 + }, 3000);
1097 1233 } else {
1098 - dashboard_update_site_status(websiteId, '<span data-inverted="" data-position="left center" data-tooltip="' + __('Synchronization process completed successfully.', 'mainwp') + '"><i class="check green icon"></i></span>', true);
1234 + mainwpVars.bulkTaskRunning = false;
1099 1235 }
1100 - dashboard_update_done(pAction);
1101 - }
1102 - }(websiteId, action),
1103 - error: function (pWebsiteId, pData, pErrors, pAction) {
1104 - return function () {
1105 - if (pErrors > 5) {
1106 - dashboard_update_site_status(pWebsiteId, '<span data-inverted="" data-position="left center" data-tooltip="' + __('Process timed out. Please try again.', 'mainwp') + '"><i class="exclamation yellow icon"></i></span>');
1107 - dashboard_update_done(pAction);
1108 - } else {
1109 - pErrors++;
1110 - dashboard_update_next_int(pWebsiteId, pData, pErrors, pAction);
1111 - }
1112 - }
1113 - }(websiteId, data, errors, action),
1114 - dataType: 'json'
1115 - });
1236 + return;
1237 + }
1238 +
1239 + dashboard_loop_next(pAction);
1116 1240 };
1117 1241
1242 +let dashboard_update_next = function (pAction) {
1243 + mainwpVars.currentThreads++;
1244 + mainwpVars.websitesLeft--;
1245 + let websiteId = mainwpVars.websitesToUpdate[mainwpVars.currentWebsite++];
1246 + if ('checknow' == pAction) {
1247 + dashboard_update_site_status(websiteId, '<span data-inverted="" data-position="left center" data-tooltip="' + MainWP.I18n.t('Checking uptime status...') + '"><i class="sync alternate loading icon"></i></span>');
1248 + } else {
1249 + dashboard_update_site_status(websiteId, '<span data-inverted="" data-position="left center" data-tooltip="' + MainWP.I18n.t('Syncing data...') + '"><i class="sync alternate loading icon"></i></span>');
1250 + }
1118 1251
1119 -/**
1120 - * Delete nonmainwp actions.
1121 - */
1122 -let mainwp_delete_nonmainwp_data_start = function (syncSiteIds) {
1123 - let allWebsiteIds = jQuery('.dashboard_wp_id[error-status=0]').map(function (indx, el) {
1124 - return jQuery(el).val();
1125 - });
1126 - let selectedIds = [], excludeIds = [];
1127 - if (syncSiteIds instanceof Array) {
1128 - jQuery.grep(allWebsiteIds, function (el) {
1129 - if (jQuery.inArray(el, syncSiteIds) !== -1) {
1130 - selectedIds.push(el);
1131 - } else {
1132 - excludeIds.push(el);
1133 - }
1252 + let data = mainwp_secure_data({
1253 + action: ('checknow' == pAction ? 'mainwp_checksites' : 'mainwp_syncsites'),
1254 + wp_id: websiteId,
1255 + isGlobalSync: globalSync,
1256 + bulkSync: mainwpVars.websitesTotal > 1 ? 1 : 0
1134 1257 });
1135 - for (let id of excludeIds) {
1136 - dashboard_update_site_hide(id);
1137 - }
1138 - allWebsiteIds = selectedIds;
1139 - }
1140 1258
1141 - for (let id of allWebsiteIds) {
1142 - dashboard_update_site_status(id, '<span data-inverted="" data-position="left center" data-tooltip="' + __('Pending', 'mainwp') + '"><i class="clock outline icon"></i></span>');
1143 - }
1144 1259
1145 - let nrOfWebsites = allWebsiteIds.length;
1146 1260
1147 - mainwpPopup('#mainwp-sync-sites-modal').init({
1148 - title: __('Delete Non-MainWP Changes'),
1149 - progressMax: nrOfWebsites,
1150 - statusText: 'deleted',
1151 - callback: function () {
1152 - mainwpVars.bulkTaskRunning = false;
1153 - history.pushState("", document.title, window.location.pathname + window.location.search); // to fix issue for url with hash
1154 - window.location.href = location.href;
1155 - }
1156 - });
1157 - mainwp_delete_nonmainwp_data_start_next(allWebsiteIds);
1261 + dashboard_update_next_int(websiteId, data, 0, pAction);
1158 1262 };
1159 1263
1264 +let dashboard_update_next_int = function (websiteId, data, errors, action) {
1265 + jQuery.ajax({
1266 + type: 'POST',
1267 + url: ajaxurl,
1268 + data: data,
1269 + success: function (pWebsiteId, pAction) {
1270 + return function (response) {
1271 + if (response.error) {
1272 + let extErr = response.error;
1273 + dashboard_update_site_status(pWebsiteId, '<span data-inverted="" data-position="left center" data-tooltip="' + extErr + '"><i class="exclamation red icon"></i></span>');
1274 + } else {
1275 + dashboard_update_site_status(websiteId, '<span data-inverted="" data-position="left center" data-tooltip="' + MainWP.I18n.t('Synchronization process completed successfully.') + '"><i class="check green icon"></i></span>', true);
1276 + }
1277 + dashboard_update_done(pAction);
1278 + }
1279 + }(websiteId, action),
1280 + error: function (pWebsiteId, pData, pErrors, pAction) {
1281 + return function () {
1282 + if (pErrors > 5) {
1283 + dashboard_update_site_status(pWebsiteId, '<span data-inverted="" data-position="left center" data-tooltip="' + MainWP.I18n.t('Process timed out. Please try again.') + '"><i class="exclamation yellow icon"></i></span>');
1284 + dashboard_update_done(pAction);
1285 + } else {
1286 + pErrors++;
1287 + dashboard_update_next_int(pWebsiteId, pData, pErrors, pAction);
1288 + }
1289 + }
1290 + }(websiteId, data, errors, action),
1291 + dataType: 'json'
1292 + });
1293 +};
1160 1294
1161 -let mainwp_delete_nonmainwp_data_start_next = function (websiteIds) {
1162 - mainwpVars.websitesToUpdate = websiteIds;
1163 - mainwpVars.currentWebsite = 0;
1164 - mainwpVars.websitesDone = 0;
1165 - mainwpVars.websitesTotal = mainwpVars.websitesLeft = mainwpVars.websitesToUpdate.length;
1166 1295
1167 - mainwpVars.bulkTaskRunning = true;
1296 +/**
1297 + * Delete site changes actions.
1298 + */
1168 1299
1169 - if (mainwpVars.websitesTotal == 0) {
1170 - mainwp_delete_nonmainwp_data_done();
1171 - } else {
1172 - mainwp_delete_nonmainwp_data_loop_next();
1173 - }
1174 -};
1300 +let mainwp_delete_nonmainwp_data_start = function () {
1301 + mainwp_delete_nonmainwp_data_start_next();
1302 +}
1175 1303
1304 +let mainwp_delete_nonmainwp_data_start_next = function () {
1305 + while ((checkedBox = jQuery('#mainwp-module-log-records-body-table .check-column INPUT:checkbox:checked:first')) && (checkedBox.length > 0) && (bulkManageClientsCurrentThreads < bulkManageClientsMaxThreads)) { // NOSONAR -- modified out side the function.
1306 + mainwp_delete_nonmainwp_data_next();
1307 + }
1308 +}
1176 1309
1177 -let mainwp_delete_nonmainwp_data_loop_next = function () {
1178 - while (mainwpVars.bulkTaskRunning && (mainwpVars.currentThreads < mainwpVars.maxThreads) && (mainwpVars.websitesLeft > 0)) {
1179 - mainwp_delete_nonmainwp_data_next();
1180 - }
1181 -};
1182 -
1183 1310 let mainwp_delete_nonmainwp_data_next = function () {
1184 - mainwpVars.currentThreads++;
1185 - mainwpVars.websitesLeft--;
1186 - let websiteId = mainwpVars.websitesToUpdate[mainwpVars.currentWebsite++];
1187 - dashboard_update_site_status(websiteId, '<span data-inverted="" data-position="left center" data-tooltip="' + __('Deleting...', 'mainwp') + '"><i class="sync alternate loading icon"></i></span>');
1188 - let data = mainwp_secure_data({
1189 - action: 'mainwp_delete_non_mainwp_actions',
1190 - wp_id: websiteId,
1191 - });
1192 - mainwp_delete_nonmainwp_data_next_int(websiteId, data, 0);
1311 + mainwpVars.currentThreads++;
1312 + mainwpVars.websitesLeft--;
1313 + let websiteId = mainwpVars.websitesToUpdate[mainwpVars.currentWebsite++];
1314 + dashboard_update_site_status(websiteId, '<span data-inverted="" data-position="left center" data-tooltip="' + MainWP.I18n.t('Deleting...') + '"><i class="sync alternate loading icon"></i></span>');
1315 + let data = mainwp_secure_data({
1316 + action: 'mainwp_delete_non_mainwp_actions',
1317 + wp_id: websiteId,
1318 + });
1319 + mainwp_delete_nonmainwp_data_next_int(websiteId, data, 0);
1193 1320 };
1194 1321
1195 1322 let mainwp_delete_nonmainwp_data_next_int = function (websiteId, data, errors) {
1196 - jQuery.ajax({
1197 - type: 'POST',
1198 - url: ajaxurl,
1199 - data: data,
1200 - success: function (pWebsiteId) {
1201 - return function (response) {
1202 - if (response.error) {
1203 - let extErr = response.error;
1204 - dashboard_update_site_status(pWebsiteId, '<span data-inverted="" data-position="left center" data-tooltip="' + extErr + '"><i class="exclamation red icon"></i></span>');
1205 - } else {
1206 - dashboard_update_site_status(websiteId, '<span data-inverted="" data-position="left center" data-tooltip="' + __('Process completed successfully.', 'mainwp') + '"><i class="check green icon"></i></span>', true);
1207 - }
1208 - mainwp_delete_nonmainwp_data_done();
1209 - }
1210 - }(websiteId),
1211 - error: function (pWebsiteId, pData, pErrors) {
1212 - return function () {
1213 - if (pErrors > 5) {
1214 - dashboard_update_site_status(pWebsiteId, '<span data-inverted="" data-position="left center" data-tooltip="' + __('Process timed out. Please try again.', 'mainwp') + '"><i class="exclamation yellow icon"></i></span>');
1215 - mainwp_delete_nonmainwp_data_done();
1216 - } else {
1217 - pErrors++;
1218 - mainwp_delete_nonmainwp_data_next_int(pWebsiteId, pData, pErrors);
1219 - }
1220 - }
1221 - }(websiteId, data, errors),
1222 - dataType: 'json'
1223 - });
1323 + jQuery.ajax({
1324 + type: 'POST',
1325 + url: ajaxurl,
1326 + data: data,
1327 + success: function (pWebsiteId) {
1328 + return function (response) {
1329 + if (response.error) {
1330 + let extErr = response.error;
1331 + dashboard_update_site_status(pWebsiteId, '<span data-inverted="" data-position="left center" data-tooltip="' + extErr + '"><i class="exclamation red icon"></i></span>');
1332 + } else {
1333 + dashboard_update_site_status(websiteId, '<span data-inverted="" data-position="left center" data-tooltip="' + MainWP.I18n.t('Process completed successfully.') + '"><i class="check green icon"></i></span>', true);
1334 + }
1335 + mainwp_delete_nonmainwp_data_done();
1336 + }
1337 + }(websiteId),
1338 + error: function (pWebsiteId, pData, pErrors) {
1339 + return function () {
1340 + if (pErrors > 5) {
1341 + dashboard_update_site_status(pWebsiteId, '<span data-inverted="" data-position="left center" data-tooltip="' + MainWP.I18n.t('Process timed out. Please try again.') + '"><i class="exclamation yellow icon"></i></span>');
1342 + mainwp_delete_nonmainwp_data_done();
1343 + } else {
1344 + pErrors++;
1345 + mainwp_delete_nonmainwp_data_next_int(pWebsiteId, pData, pErrors);
1346 + }
1347 + }
1348 + }(websiteId, data, errors),
1349 + dataType: 'json'
1350 + });
1224 1351 };
1225 1352
1226 1353
1227 1354 let mainwp_delete_nonmainwp_data_done = function () {
1228 - mainwpVars.currentThreads--;
1229 - if (!mainwpVars.bulkTaskRunning)
1230 - return;
1231 - mainwpVars.websitesDone++;
1232 - if (mainwpVars.websitesDone > mainwpVars.websitesTotal)
1233 - mainwpVars.websitesDone = mainwpVars.websitesTotal;
1355 + mainwpVars.currentThreads--;
1356 + if (!mainwpVars.bulkTaskRunning)
1357 + return;
1358 + mainwpVars.websitesDone++;
1359 + if (mainwpVars.websitesDone > mainwpVars.websitesTotal)
1360 + mainwpVars.websitesDone = mainwpVars.websitesTotal;
1234 1361
1235 - mainwpPopup('#mainwp-sync-sites-modal').setProgressSite(mainwpVars.websitesDone);
1362 + mainwpPopup('#mainwp-sync-sites-modal').setProgressSite(mainwpVars.websitesDone);
1236 1363
1237 - if (mainwpVars.websitesDone == mainwpVars.websitesTotal) {
1238 - jQuery("#mainwp-non-mainwp-changes-table tbody").fadeOut("slow");
1239 - let successSites = jQuery('#mainwp-sync-sites-modal .check.green.icon').length;
1240 - if (mainwpVars.websitesDone == successSites) {
1241 - mainwpVars.bulkTaskRunning = false;
1242 - setTimeout(function () {
1243 - mainwpPopup('#mainwp-sync-sites-modal').close(true);
1244 - }, 3000);
1245 - } else {
1246 - mainwpVars.bulkTaskRunning = false;
1364 + if (mainwpVars.websitesDone == mainwpVars.websitesTotal) {
1365 + jQuery("#mainwp-non-mainwp-changes-table tbody").fadeOut("slow");
1366 + let successSites = jQuery('#mainwp-sync-sites-modal .check.green.icon').length;
1367 + if (mainwpVars.websitesDone == successSites) {
1368 + mainwpVars.bulkTaskRunning = false;
1369 + setTimeout(function () {
1370 + mainwpPopup('#mainwp-sync-sites-modal').close(true);
1371 + }, 3000);
1372 + } else {
1373 + mainwpVars.bulkTaskRunning = false;
1374 + }
1375 + return;
1247 1376 }
1248 - return;
1249 - }
1250 - mainwp_delete_nonmainwp_data_loop_next();
1377 + mainwp_delete_nonmainwp_data_loop_next();
1251 1378 };
1252 1379
1253 1380
1254 1381 let mainwp_tool_disconnect_sites = function () {
1255 1382
1256 - mainwp_confirm('Are you sure that you want to disconnect your sites? This will function will break the connection and leave the MainWP Child plugin active and which makes your sites vulnerable.', function () {
1257 - let allWebsiteIds = jQuery('.dashboard_wp_id[error-status=0]').map(function (indx, el) {
1258 - return jQuery(el).val();
1259 - });
1383 + mainwp_confirm('Are you sure that you want to disconnect your sites? This will function will break the connection and leave the MainWP Child plugin active and which makes your sites vulnerable.', function () {
1384 + let allWebsiteIds = jQuery('.dashboard_wp_id[error-status=0]').map(function (indx, el) {
1385 + return jQuery(el).val();
1386 + });
1260 1387
1261 - for (let id of allWebsiteIds) {
1262 - dashboard_update_site_status(id, '<i class="clock outline icon"></i>');
1263 - }
1388 + for (let id of allWebsiteIds) {
1389 + dashboard_update_site_status(id, '<i class="clock outline icon"></i>');
1390 + }
1264 1391
1265 - let nrOfWebsites = allWebsiteIds.length;
1392 + let nrOfWebsites = allWebsiteIds.length;
1266 1393
1267 - mainwpPopup('#mainwp-sync-sites-modal').init({
1268 - title: __('Disconnect All Sites'),
1269 - progressMax: nrOfWebsites,
1270 - statusText: __('disconnected'),
1271 - callback: function () {
1272 - window.location.href = location.href;
1273 - }
1274 - });
1394 + mainwpPopup('#mainwp-sync-sites-modal').init({
1395 + title: MainWP.I18n.t('Disconnect All Sites'),
1396 + progressMax: nrOfWebsites,
1397 + statusText: MainWP.I18n.t('disconnected'),
1398 + callback: function () {
1399 + mainwp_forceReload();
1400 + }
1401 + });
1275 1402
1276 - mainwpVars.websitesToUpdate = allWebsiteIds;
1277 - mainwpVars.currentWebsite = 0;
1278 - mainwpVars.websitesDone = 0;
1279 - mainwpVars.websitesTotal = mainwpVars.websitesLeft = mainwpVars.websitesToUpdate.length;
1403 + mainwpVars.websitesToUpdate = allWebsiteIds;
1404 + mainwpVars.currentWebsite = 0;
1405 + mainwpVars.websitesDone = 0;
1406 + mainwpVars.websitesTotal = mainwpVars.websitesLeft = mainwpVars.websitesToUpdate.length;
1280 1407
1281 - mainwpVars.bulkTaskRunning = true;
1408 + mainwpVars.bulkTaskRunning = true;
1282 1409
1283 - if (mainwpVars.websitesTotal == 0) {
1284 - mainwp_tool_disconnect_sites_done();
1285 - } else {
1286 - mainwp_tool_disconnect_sites_loop_next();
1287 - }
1288 - }, false, false, false, 'DISCONNECT');
1410 + if (mainwpVars.websitesTotal == 0) {
1411 + mainwp_tool_disconnect_sites_done();
1412 + } else {
1413 + mainwp_tool_disconnect_sites_loop_next();
1414 + }
1415 + }, false, false, false, 'DISCONNECT');
1289 1416 };
1290 1417
1291 1418 let mainwp_tool_disconnect_sites_done = function () {
1292 - mainwpVars.currentThreads--;
1293 - if (!mainwpVars.bulkTaskRunning)
1294 - return;
1295 - mainwpVars.websitesDone++;
1296 - if (mainwpVars.websitesDone > mainwpVars.websitesTotal)
1297 - mainwpVars.websitesDone = mainwpVars.websitesTotal;
1419 + mainwpVars.currentThreads--;
1420 + if (!mainwpVars.bulkTaskRunning)
1421 + return;
1422 + mainwpVars.websitesDone++;
1423 + if (mainwpVars.websitesDone > mainwpVars.websitesTotal)
1424 + mainwpVars.websitesDone = mainwpVars.websitesTotal;
1298 1425
1299 - mainwpPopup('#mainwp-sync-sites-modal').setProgressSite(mainwpVars.websitesDone);
1426 + mainwpPopup('#mainwp-sync-sites-modal').setProgressSite(mainwpVars.websitesDone);
1300 1427
1301 - mainwp_tool_disconnect_sites_loop_next();
1428 + mainwp_tool_disconnect_sites_loop_next();
1302 1429 };
1303 1430
1304 1431 let mainwp_tool_disconnect_sites_loop_next = function () {
1305 - while (mainwpVars.bulkTaskRunning && (mainwpVars.currentThreads < mainwpVars.maxThreads) && (mainwpVars.websitesLeft > 0)) { // NOSONAR - vars modified outside function.
1306 - mainwp_tool_disconnect_sites_next();
1307 - }
1432 + while (mainwpVars.bulkTaskRunning && (mainwpVars.currentThreads < mainwpVars.maxThreads) && (mainwpVars.websitesLeft > 0)) { // NOSONAR - vars modified outside function.
1433 + mainwp_tool_disconnect_sites_next();
1434 + }
1308 1435 };
1309 1436
1310 1437 let mainwp_tool_disconnect_sites_next = function () {
1311 - mainwpVars.currentThreads++;
1312 - mainwpVars.websitesLeft--;
1313 - let websiteId = mainwpVars.websitesToUpdate[mainwpVars.currentWebsite++];
1314 - dashboard_update_site_status(websiteId, '<i class="sync alternate loading icon"></i>');
1315 - let data = mainwp_secure_data({
1316 - action: 'mainwp_disconnect_site',
1317 - wp_id: websiteId
1318 - });
1319 - mainwp_tool_disconnect_sites_next_int(websiteId, data, 0);
1438 + mainwpVars.currentThreads++;
1439 + mainwpVars.websitesLeft--;
1440 + let websiteId = mainwpVars.websitesToUpdate[mainwpVars.currentWebsite++];
1441 + dashboard_update_site_status(websiteId, '<i class="sync alternate loading icon"></i>');
1442 + let data = mainwp_secure_data({
1443 + action: 'mainwp_disconnect_site',
1444 + wp_id: websiteId
1445 + });
1446 + mainwp_tool_disconnect_sites_next_int(websiteId, data, 0);
1320 1447 };
1321 1448
1322 1449 let mainwp_tool_disconnect_sites_next_int = function (websiteId, data, errors) {
1323 - jQuery.ajax({
1324 - type: 'POST',
1325 - url: ajaxurl,
1326 - data: data,
1327 - success: function (pWebsiteId) {
1328 - return function (response) {
1329 - if (response?.error) {
1330 - dashboard_update_site_status(pWebsiteId, response.error + '<i class="exclamation red icon"></i>');
1331 - } else if (response && response.result == 'success') {
1332 - dashboard_update_site_status(websiteId, '<i class="check green icon"></i>', true);
1333 - } else {
1334 - dashboard_update_site_status(pWebsiteId, __('Undefined error!') + ' <i class="exclamation red icon"></i>');
1335 - }
1336 - mainwp_tool_disconnect_sites_done();
1337 - }
1338 - }(websiteId),
1339 - error: function (pWebsiteId, pData, pErrors) {
1340 - return function () {
1341 - if (pErrors > 5) {
1342 - dashboard_update_site_status(pWebsiteId, '<span data-inverted="" data-position="left center" data-tooltip="' + __('Process timed out. Please try again.', 'mainwp') + '"><i class="exclamation yellow icon"></i></span>');
1343 - mainwp_tool_disconnect_sites_done();
1344 - } else {
1345 - pErrors++;
1346 - mainwp_tool_disconnect_sites_next_int(pWebsiteId, pData, pErrors);
1347 - }
1348 - }
1349 - }(websiteId, data, errors),
1350 - dataType: 'json'
1351 - });
1450 + jQuery.ajax({
1451 + type: 'POST',
1452 + url: ajaxurl,
1453 + data: data,
1454 + success: function (pWebsiteId) {
1455 + return function (response) {
1456 + if (response?.error) {
1457 + dashboard_update_site_status(pWebsiteId, response.error + '<i class="exclamation red icon"></i>');
1458 + } else if (response?.result == 'success') {
1459 + dashboard_update_site_status(websiteId, '<i class="check green icon"></i>', true);
1460 + } else {
1461 + dashboard_update_site_status(pWebsiteId, MainWP.I18n.t('Undefined error!') + ' <i class="exclamation red icon"></i>');
1462 + }
1463 + mainwp_tool_disconnect_sites_done();
1464 + }
1465 + }(websiteId),
1466 + error: function (pWebsiteId, pData, pErrors) {
1467 + return function () {
1468 + if (pErrors > 5) {
1469 + dashboard_update_site_status(pWebsiteId, '<span data-inverted="" data-position="left center" data-tooltip="' + MainWP.I18n.t('Process timed out. Please try again.') + '"><i class="exclamation yellow icon"></i></span>');
1470 + mainwp_tool_disconnect_sites_done();
1471 + } else {
1472 + pErrors++;
1473 + mainwp_tool_disconnect_sites_next_int(pWebsiteId, pData, pErrors);
1474 + }
1475 + }
1476 + }(websiteId, data, errors),
1477 + dataType: 'json'
1478 + });
1352 1479 };
1353 1480
1354 -let mainwp_tool_clear_activation_data = function (pObj) {
1355 - let loc = jQuery(pObj).attr('href');
1356 - mainwp_confirm('Are you sure?', function () {
1357 - window.location = loc;
1358 - });
1481 +let mainwp_tool_confirm_to_process = function (pObj) {
1482 + let loc = jQuery(pObj).attr('href');
1483 + mainwp_confirm('Are you sure?', function () {
1484 + globalThis.location = loc;
1485 + });
1359 1486 };
1360 1487
1488 +
1361 1489 /**
1362 1490 * Manage sites page
1363 1491 */
1364 1492
1365 1493 jQuery(function ($) {
1366 - jQuery('#mainwp-backup-type').on('change', function () {
1367 - if (jQuery(this).val() == 'full')
1368 - jQuery('.mainwp-backup-full-exclude').show();
1369 - else
1370 - jQuery('.mainwp-backup-full-exclude').hide();
1371 - });
1372 - jQuery('.mainwp-checkbox-showhide-elements').on('click', function () {
1373 - let hiel = $(this).attr('hide-parent');
1374 - mainwp_showhide_elements(hiel, $(this).find('input').is(':checked'));
1375 - });
1494 + jQuery('#mainwp-backup-type').on('change', function () {
1495 + if (jQuery(this).val() == 'full')
1496 + jQuery('.mainwp-backup-full-exclude').show();
1497 + else
1498 + jQuery('.mainwp-backup-full-exclude').hide();
1499 + });
1500 + jQuery('.mainwp-checkbox-showhide-elements').on('click', function () {
1501 + let hiel = $(this).attr('hide-parent');
1502 + if (hiel !== undefined && hiel !== '') {
1503 + // support multi hide values.
1504 + hiel.split(';').forEach((hi) => {
1505 + mainwp_showhide_elements(hi, $(this).find('input').is(':checked'));
1506 + });
1507 + }
1508 + let hideEvent = $(this).attr('fire-event-parent') ?? '';
1509 + if (hideEvent != '') {
1510 + // to sure click events finished.
1511 + setTimeout(function () {
1512 + document.dispatchEvent(new Event(hideEvent));
1513 + }, 200);
1514 + }
1515 + });
1376 1516
1377 - jQuery('.mainwp-selecter-showhide-elements').on('change', function () {
1378 - let hiel = $(this).attr('hide-parent');
1379 - let hival = $(this).attr('hide-value');
1380 - hival = hival.split('-'); // support multi hide values.
1381 - let selectedval = $(this).val();
1382 - mainwp_showhide_elements(hiel, hival.includes(selectedval));
1383 - });
1517 + jQuery('.mainwp-selecter-showhide-elements').on('change', function () {
1518 + let hiel = $(this).attr('hide-parent');
1519 + let hival = $(this).attr('hide-value');
1520 + hival = hival.split(';'); // support multi hide values.
1521 + let selectedval = $(this).val();
1522 + mainwp_showhide_elements(hiel, hival.includes(selectedval));
1523 + });
1384 1524 });
1385 1525
1386 1526 function mainwp_showhide_elements(attEl, valHi) {
1387 - if (valHi) {
1388 - jQuery('[hide-element=' + attEl + ']').fadeOut(300);
1389 - } else {
1390 - jQuery('[hide-element=' + attEl + ']').fadeIn(200);
1391 - }
1527 + // support multi attr to hide.
1528 + if (valHi) {
1529 + attEl.split(';').forEach(function (att) {
1530 + jQuery('[hide-element=' + att.trim() + ']').fadeOut(300);
1531 + jQuery('[hide-sub-element=' + att.trim() + ']').fadeOut(300);
1532 + });
1533 + } else {
1534 + attEl.split(';').forEach(function (att) {
1535 + jQuery('[hide-element=' + att.trim() + ']').fadeIn(300);
1536 + jQuery('[hide-sub-element=' + att.trim() + ']').fadeIn(300);
1537 + });
1538 + }
1392 1539 }
1393 1540
1394 1541
1395 1542 jQuery(function ($) {
1396 - $('#mainwp_settings_verify_connection_method').on('change', function () {
1397 - let selectedval = $(this).val();
1398 - if (selectedval == 2) { // phpseclib.
1399 - $('.mainwp-hide-elemenent-sign-algo').fadeOut(200);
1400 - } else {
1401 - $('.mainwp-hide-elemenent-sign-algo').fadeIn(200);
1402 - }
1403 - });
1543 + $('#mainwp_settings_verify_connection_method').on('change', function () {
1544 + let selectedval = $(this).val();
1545 + if (selectedval == 2) { // phpseclib.
1546 + $('.mainwp-hide-elemenent-sign-algo').fadeOut(200);
1547 + } else {
1548 + $('.mainwp-hide-elemenent-sign-algo').fadeIn(200);
1549 + }
1550 + });
1404 1551
1405 - $('#mainwp_managesites_edit_verify_connection_method').on('change', function () {
1406 - let selectedval = $(this).val();
1407 - if (selectedval == 2 || selectedval == 3) { // phpseclib.
1408 - $('.mainwp-hide-elemenent-sign-algo').fadeOut(200);
1409 - } else {
1410 - $('.mainwp-hide-elemenent-sign-algo').fadeIn(200);
1411 - }
1412 - });
1552 + $('#mainwp_managesites_edit_verify_connection_method').on('change', function () {
1553 + let selectedval = $(this).val();
1554 + if (selectedval == 2 || selectedval == 3) { // phpseclib.
1555 + $('.mainwp-hide-elemenent-sign-algo').fadeOut(200);
1556 + } else {
1557 + $('.mainwp-hide-elemenent-sign-algo').fadeIn(200);
1558 + }
1559 + });
1413 1560
1414 1561
1415 - $('#mainwp_managesites_edit_openssl_alg').on('change', function () {
1416 - let selectedval = $(this).val();
1417 - if (selectedval == 1) {
1418 - $('.mainwp-hide-elemenent-sign-algo-note').fadeIn(200);
1419 - } else {
1420 - $('.mainwp-hide-elemenent-sign-algo-note').fadeOut(200);
1421 - }
1422 - });
1562 + $('#mainwp_managesites_edit_openssl_alg').on('change', function () {
1563 + let selectedval = $(this).val();
1564 + if (selectedval == 1) {
1565 + $('.mainwp-hide-elemenent-sign-algo-note').fadeIn(200);
1566 + } else {
1567 + $('.mainwp-hide-elemenent-sign-algo-note').fadeOut(200);
1568 + }
1569 + });
1423 1570
1424 - $('#mainwp_settings_openssl_alg').on('change', function () {
1425 - let selectedval = $(this).val();
1426 - if (selectedval == 1) {
1427 - $('.mainwp-hide-elemenent-sign-algo-note').fadeIn(200);
1428 - } else {
1429 - $('.mainwp-hide-elemenent-sign-algo-note').fadeOut(200);
1430 - }
1431 - });
1571 + $('#mainwp_settings_openssl_alg').on('change', function () {
1572 + let selectedval = $(this).val();
1573 + if (selectedval == 1) {
1574 + $('.mainwp-hide-elemenent-sign-algo-note').fadeIn(200);
1575 + } else {
1576 + $('.mainwp-hide-elemenent-sign-algo-note').fadeOut(200);
1577 + }
1578 + });
1432 1579
1433 1580 })
1434 1581
1435 1582 jQuery(function () {
1436 - jQuery(document).on('change', '#mainwp_managesites_add_wpurl', function () {
1437 - let url = jQuery('#mainwp_managesites_add_wpurl').val().trim();
1438 - let protocol = jQuery('#mainwp_managesites_add_wpurl_protocol').val();
1583 + jQuery(document).on('change', '#mainwp_managesites_add_wpurl', function () {
1584 + let url = jQuery('#mainwp_managesites_add_wpurl').val().trim();
1585 + let protocol = jQuery('#mainwp_managesites_add_wpurl_protocol').val();
1439 1586
1440 - if (url.lastIndexOf('http://') === 0) {
1441 - protocol = 'http';
1442 - url = url.substring(7);
1443 - } else if (url.lastIndexOf('https://') === 0) {
1444 - protocol = 'https';
1445 - url = url.substring(8);
1446 - }
1587 + if (url.lastIndexOf('http://') === 0) {
1588 + protocol = 'http';
1589 + url = url.substring(7);
1590 + } else if (url.lastIndexOf('https://') === 0) {
1591 + protocol = 'https';
1592 + url = url.substring(8);
1593 + }
1447 1594
1448 - if (jQuery('#mainwp_managesites_add_wpname').val() == '') {
1449 - jQuery('#mainwp_managesites_add_wpname').val(url);
1450 - }
1451 - jQuery('#mainwp_managesites_add_wpurl').val(url);
1452 - jQuery('#mainwp_managesites_add_wpurl_protocol').val(protocol).trigger("change");
1453 - });
1595 + if (jQuery('#mainwp_managesites_add_wpname').val() == '') {
1596 + jQuery('#mainwp_managesites_add_wpname').val(url);
1597 + }
1598 + jQuery('#mainwp_managesites_add_wpurl').val(url);
1599 + jQuery('#mainwp_managesites_add_wpurl_protocol').val(protocol).trigger("change");
1600 + });
1454 1601
1455 - // Trigger the single site reconnect process
1456 - jQuery('.mainwp-manage-wpsites-table').on('click', '.mainwp_site_reconnect', function () {
1457 - mainwp_managesites_reconnect(jQuery(this));
1458 - return false;
1459 - });
1602 + // Trigger the single site reconnect process
1603 + jQuery('.mainwp-manage-wpsites-table').on('click', '.mainwp_site_reconnect', function () {
1604 + mainwp_managesites_reconnect(jQuery(this));
1605 + return false;
1606 + });
1460 1607
1461 - jQuery('#mainwp-sites-previews').on('click', '.mainwp_site_card_reconnect', function () {
1462 - mainwp_managesites_cards_reconnect(jQuery(this));
1463 - return false;
1464 - });
1608 + jQuery('#mainwp-sites-previews').on('click', '.mainwp_site_card_reconnect', function () {
1609 + mainwp_managesites_cards_reconnect(jQuery(this));
1610 + return false;
1611 + });
1465 1612
1466 - jQuery('.mainwp-updates-overview-reconnect-site').on('click', function () {
1467 - mainwp_site_overview_reconnect(jQuery(this));
1468 - return false;
1469 - });
1613 + jQuery(document).on('click', '.mainwp-updates-overview-reconnect-site', function () {
1614 + mainwp_site_overview_reconnect(jQuery(this));
1615 + return false;
1616 + });
1470 1617
1471 - jQuery(".chk-sync-install-plugin").on('change', function () {
1472 - let parent = jQuery(this).closest('.sync-ext-row');
1473 - let opts = parent.find(".sync-options input[type='checkbox']");
1474 - if (jQuery(this).is(':checked')) {
1475 - opts.prop("checked", true);
1476 - } else {
1477 - opts.prop("checked", false);
1478 - ///opts.attr( "disabled", "disabled" );
1479 - }
1480 - });
1618 + jQuery(".chk-sync-install-plugin").on('change', function () {
1619 + let parent = jQuery(this).closest('.sync-ext-row');
1620 + let opts = parent.find(".sync-options input[type='checkbox']");
1621 + if (jQuery(this).is(':checked')) {
1622 + opts.prop("checked", true);
1623 + } else {
1624 + opts.prop("checked", false);
1625 + ///opts.attr( "disabled", "disabled" );
1626 + }
1627 + });
1481 1628
1482 - managesites_init();
1629 + managesites_init();
1483 1630 });
1484 1631
1485 1632 jQuery(document).on('change', '#mainwp_managesites_verify_installed_child', function () {
1486 - if (jQuery(this).is(':checked')) {
1487 - jQuery('#mainwp_message_verify_installed_child').hide();
1488 - }
1633 + if (jQuery(this).is(':checked')) {
1634 + jQuery('#mainwp_message_verify_installed_child').hide();
1635 + }
1489 1636 });
1490 1637
1491 -window.managesites_init = function () {
1492 - mainwp_set_message_zone('#mainwp-message-zone');
1493 - jQuery('.sync-ext-row span.status').html('');
1494 - jQuery('.sync-ext-row span.status').css('color', '#0073aa');
1638 +globalThis.managesites_init = function () {
1639 + mainwp_set_message_zone('#mainwp-message-zone');
1640 + jQuery('.sync-ext-row span.status').html('');
1641 + jQuery('.sync-ext-row span.status').css('color', '#0073aa');
1495 1642 };
1496 1643
1497 1644 let mainwp_site_overview_reconnect = function (pElement) {
1498 - feedback('mainwp-message-zone', '<i class="notched circle loading icon"></i> ' + 'Trying to reconnect. Please wait...', '');
1499 - let data = mainwp_secure_data({
1500 - action: 'mainwp_reconnectwp',
1501 - siteid: pElement.attr('siteid')
1502 - });
1645 + feedback('mainwp-message-zone', '<i class="notched circle loading icon"></i> ' + 'Trying to reconnect. Please wait...', '');
1646 + let data = mainwp_secure_data({
1647 + action: 'mainwp_reconnectwp',
1648 + siteid: pElement.attr('siteid')
1649 + });
1503 1650
1504 - jQuery.post(ajaxurl, data, function () {
1505 - return function (response) {
1506 - response = response.trim();
1507 - if (response.substring(0, 5) == 'ERROR') {
1508 - let error;
1509 - if (response.length == 5) {
1510 - error = 'Undefined error! Please try again. If the process keeps failing, please review <a href="https://kb.mainwp.com/">MainWP Knowledgebase</a>, and if you still have issues, please let us know in the <a href="https://managers.mainwp.com/c/community-support/5">MainWP Community</a>.'; // NOSONAR - noopener - open safe.
1511 - feedback('mainwp-message-zone', error, 'red');
1651 + jQuery.post(ajaxurl, data, function () {
1652 + return function (response) {
1653 + response = response.trim();
1654 + if (response.substring(0, 5) == 'ERROR') {
1655 + let error;
1656 + if (response.length == 5) {
1657 + error = 'Undefined error! Please try again. If the process keeps failing, please review <a href="https://docs.mainwp.com/">MainWP Knowledgebase</a>, and if you still have issues, please let us know in the <a href="https://community.mainwp.com/c/community-support/5">MainWP Community</a>.'; // NOSONAR - noopener - open safe.
1658 + feedback('mainwp-message-zone', error, 'red');
1659 + } else {
1660 + error = response.substring(6);
1661 + let err = mainwp_js_get_error_not_detected_connect(error, 'html_msg', 'mainwp-message-zone');
1662 + if (false === err) {
1663 + feedback('mainwp-message-zone', error, 'red'); // it is not json error string.
1664 + }
1665 + }
1666 + } else if ('reconnect_failed' === response) {
1667 + mainwp_set_message_zone('#mainwp-message-zone');
1668 +
1669 + jQuery('#mainwp-reconnect-site-with-user-passwd-modal').modal({
1670 + onHide: function () {
1671 + mainwp_forceReload();
1672 + },
1673 + closable: false
1674 + }).modal('show');
1675 + jQuery('#mainwp_managesites_add_wpadmin').val(pElement.attr('adminuser'));
1676 + jQuery(document).on('click', '#mainwp-popup-reconnect-site-btn', function () {
1677 + mainwp_reconnect_with_pw(pElement.attr('siteid'));
1678 + return false;
1679 + });
1680 + } else {
1681 + mainwp_set_message_zone('#mainwp-message-zone');
1682 + mainwp_forceReload();
1683 + }
1684 + }
1685 + }());
1686 +};
1687 +
1688 +let mainwp_reconnect_with_pw = function (siteid) {
1689 + mainwp_set_message_zone('#mainwp-message-zone-reconnect');
1690 + let errors = [];
1691 + if (jQuery('#mainwp_managesites_add_wpadmin').val().trim() == '') {
1692 + errors.push('Please enter a username of the website administrator.');
1693 + }
1694 +
1695 + if (jQuery('#mainwp_managesites_add_admin_pwd').val().trim() == '') {
1696 + errors.push('Please enter password of the website administrator.');
1697 + }
1698 +
1699 + if (errors.length > 0) {
1700 + mainwp_set_message_zone('#mainwp-message-zone-reconnect', errors.join('</br>'), 'red');
1701 + return;
1702 + }
1703 +
1704 + mainwp_set_message_zone('#mainwp-message-zone-reconnect', '<i class="notched circle loading icon"></i> ' + 'Trying to reconnect. Please wait...', 'green');
1705 + let data = mainwp_secure_data({
1706 + action: 'mainwp_reconnectwp',
1707 + managesites_add_wpadmin: jQuery('#mainwp_managesites_add_wpadmin').val(),
1708 + managesites_add_adminpwd: encodeURIComponent(jQuery('#mainwp_managesites_add_admin_pwd').val()),
1709 + siteid: siteid
1710 + });
1711 +
1712 + jQuery.post(ajaxurl, data, function (response) {
1713 + response = response.trim();
1714 + mainwp_set_message_zone('#mainwp-message-zone-reconnect');
1715 + if (response.substring(0, 5) == 'ERROR') {
1716 + let error;
1717 + if (response.length == 5) {
1718 + error = 'Undefined error! Please try again. If the process keeps failing, please review this <a href="https://docs.mainwp.com/troubleshooting/potential-issues">Knowledgebase document</a>, and if you still have issues, please let us know in the <a href="https://community.mainwp.com/c/community-support/5">MainWP Community</a>.'; // NOSONAR - noopener - open safe.
1719 + mainwp_set_message_zone('#mainwp-message-zone-reconnect', error, 'red');
1720 + } else {
1721 + error = response.substring(6);
1722 + let err = mainwp_js_get_error_not_detected_connect(error, 'html_msg', 'mainwp-message-zone-reconnect');
1723 + if (false === err) {
1724 + mainwp_set_message_zone('#mainwp-message-zone-reconnect', error, 'red'); // it is not json error string.
1725 + }
1726 + }
1727 + } else if ('reconnect_failed' === response) {
1728 + // do not show reconnect popup again.
1729 + mainwp_set_message_zone('#mainwp-message-zone-reconnect', mainwp_get_reconnect_error(response, siteid), 'red');
1512 1730 } else {
1513 - error = response.substring(6);
1514 - let err = mainwp_js_get_error_not_detected_connect(error, 'html_msg', 'mainwp-message-zone');
1515 - if (false === err) {
1516 - feedback('mainwp-message-zone', error, 'red'); // it is not json error string.
1517 - }
1731 + mainwp_set_message_zone('#mainwp-message-zone-reconnect', response, 'green');
1732 + mainwp_forceReload();
1518 1733 }
1519 - } else {
1520 - location.reload();
1521 - }
1522 - }
1523 - }());
1734 + });
1524 1735 };
1525 1736
1737 +
1526 1738 let mainwp_managesites_reconnect = function (pElement) {
1527 - let wrapElement = pElement.closest('tr');
1528 - wrapElement.html('<td colspan="999"><i class="notched circle loading icon"></i> ' + 'Trying to reconnect. Please wait...' + '</td>');
1529 - let data = mainwp_secure_data({
1530 - action: 'mainwp_reconnectwp',
1531 - siteid: wrapElement.attr('siteid')
1532 - });
1739 + let wrapElement = pElement.closest('tr');
1740 + wrapElement.html('<td colspan="999"><i class="notched circle loading icon"></i> ' + 'Trying to reconnect. Please wait...' + '</td>');
1741 + let siteid = wrapElement.attr('siteid');
1742 + let data = mainwp_secure_data({
1743 + action: 'mainwp_reconnectwp',
1744 + siteid: siteid
1745 + });
1533 1746
1534 - jQuery.post(ajaxurl, data, function (pWrapElement) {
1535 - return function (response) {
1536 - response = response.trim();
1537 - pWrapElement.hide(); // hide reconnect item
1538 - if (response.substring(0, 5) == 'ERROR') {
1539 - let error;
1540 - if (response.length == 5) {
1541 - error = 'Undefined error! Please try again. If the process keeps failing, please review this <a href="https://kb.mainwp.com/docs/potential-issues/">Knowledgebase document</a>, and if you still have issues, please let us know in the <a href="https://managers.mainwp.com/c/community-support/5">MainWP Community</a>.'; // NOSONAR - noopener - open safe.
1542 - feedback('mainwp-message-zone', error, 'red');
1543 - } else {
1544 - error = response.substring(6);
1545 - let err = mainwp_js_get_error_not_detected_connect(error, 'html_msg', 'mainwp-message-zone');
1546 - if (false === err) {
1547 - feedback('mainwp-message-zone', error, 'red'); // it is not json error string.
1548 - }
1747 + jQuery.post(ajaxurl, data, function (pWrapElement) {
1748 + return function (response) {
1749 + response = response.trim();
1750 + pWrapElement.hide(); // hide reconnect item
1751 + if (response.substring(0, 5) == 'ERROR') {
1752 + let error;
1753 + if (response.length == 5) {
1754 + error = 'Undefined error! Please try again. If the process keeps failing, please review this <a href="https://docs.mainwp.com/troubleshooting/potential-issues">Knowledgebase document</a>, and if you still have issues, please let us know in the <a href="https://community.mainwp.com/c/community-support/5">MainWP Community</a>.'; // NOSONAR - noopener - open safe.
1755 + feedback('mainwp-message-zone', error, 'red');
1756 + } else {
1757 + error = response.substring(6);
1758 + let err = mainwp_js_get_error_not_detected_connect(error, 'html_msg', 'mainwp-message-zone');
1759 + if (false === err) {
1760 + feedback('mainwp-message-zone', error, 'red'); // it is not json error string.
1761 + }
1762 + }
1763 + } else if ('reconnect_failed' === response) {
1764 + feedback('mainwp-message-zone', mainwp_get_reconnect_error(response, siteid), 'error');
1765 + } else {
1766 + feedback('mainwp-message-zone', response, 'green');
1767 + }
1768 + setTimeout(function () {
1769 + mainwp_forceReload();
1770 + }, 6000);
1549 1771 }
1550 - } else {
1551 - feedback('mainwp-message-zone', response, 'green');
1552 - }
1553 - setTimeout(function () {
1554 - window.location.reload()
1555 - }, 6000);
1556 - }
1557 1772
1558 - }(wrapElement));
1773 + }(wrapElement));
1559 1774 };
1560 1775
1561 1776 let mainwp_managesites_cards_reconnect = function (element) {
1562 - element.html('<i class="notched loading circle icon"></i> Reconnecting...');
1563 - let data = mainwp_secure_data({
1564 - action: 'mainwp_reconnectwp',
1565 - siteid: element.attr('site-id')
1566 - });
1777 + element.html('<i class="notched loading circle icon"></i> Reconnecting...');
1778 + let siteid = element.attr('site-id');
1779 + let data = mainwp_secure_data({
1780 + action: 'mainwp_reconnectwp',
1781 + siteid: siteid
1782 + });
1567 1783
1568 - jQuery.post(ajaxurl, data, function (element) {
1569 - return function (response) {
1570 - response = response.trim();
1571 - element.hide();
1572 - if (response.substring(0, 5) == 'ERROR') {
1573 - let error;
1574 - if (response.length == 5) {
1575 - error = 'Undefined error! Please try again. If the process keeps failing, please review this <a href="https://kb.mainwp.com/docs/potential-issues/">Knowledgebase document</a>, and if you still have issues, please let us know in the <a href="https://managers.mainwp.com/c/community-support/5">MainWP Community</a>.'; // NOSONAR - noopener - open safe.
1576 - feedback('mainwp-message-zone', error, 'red');
1577 - } else {
1578 - error = response.substring(6);
1579 - let err = mainwp_js_get_error_not_detected_connect(error, 'html_msg', 'mainwp-message-zone');
1580 - if (false === err) {
1581 - feedback('mainwp-message-zone', error, 'red'); // it is not json error string.
1582 - }
1784 + jQuery.post(ajaxurl, data, function (element) {
1785 + return function (response) {
1786 + response = response.trim();
1787 + element.hide();
1788 + if (response.substring(0, 5) == 'ERROR') {
1789 + let error;
1790 + if (response.length == 5) {
1791 + error = 'Undefined error! Please try again. If the process keeps failing, please review this <a href="https://docs.mainwp.com/troubleshooting/potential-issues">Knowledgebase document</a>, and if you still have issues, please let us know in the <a href="https://community.mainwp.com/c/community-support/5">MainWP Community</a>.'; // NOSONAR - noopener - open safe.
1792 + feedback('mainwp-message-zone', error, 'red');
1793 + } else {
1794 + error = response.substring(6);
1795 + let err = mainwp_js_get_error_not_detected_connect(error, 'html_msg', 'mainwp-message-zone');
1796 + if (false === err) {
1797 + feedback('mainwp-message-zone', error, 'red'); // it is not json error string.
1798 + }
1799 + }
1800 + } else if ('reconnect_failed' === response) {
1801 + feedback('mainwp-message-zone', mainwp_get_reconnect_error(response, siteid), 'error');
1802 + } else {
1803 + feedback('mainwp-message-zone', response, 'green');
1804 + }
1805 + setTimeout(function () {
1806 + mainwp_forceReload();
1807 + }, 6000);
1583 1808 }
1584 - } else {
1585 - feedback('mainwp-message-zone', response, 'green');
1586 - }
1587 - setTimeout(function () {
1588 - window.location.reload()
1589 - }, 6000);
1590 - }
1591 1809
1592 - }(element));
1810 + }(element));
1593 1811 };
1594 1812
1595 1813 // Connect a new website
1596 1814 let mainwp_managesites_add = function () {
1597 1815
1598 - managesites_init();
1816 + managesites_init();
1599 1817
1600 - let valid_input = mainwp_managesites_add_valid();
1818 + let valid_input = mainwp_managesites_add_valid();
1601 1819
1602 - if (!valid_input) {
1603 - return;
1604 - }
1820 + if (!valid_input) {
1821 + return;
1822 + }
1605 1823
1606 - feedback('mainwp-message-zone', __('Adding the site to your MainWP Dashboard. Please wait...'), 'green');
1824 + feedback('mainwp-message-zone', MainWP.I18n.t('Adding the site to your MainWP Dashboard. Please wait...'), 'green');
1607 1825
1608 - jQuery('#mainwp_managesites_add').attr('disabled', 'true'); //disable button to add..
1826 + jQuery('#mainwp_managesites_add').attr('disabled', 'true'); //disable button to add..
1609 1827
1610 - //Check if valid user & rulewp is installed?
1611 - let url = jQuery('#mainwp_managesites_add_wpurl_protocol').val() + '://' + jQuery('#mainwp_managesites_add_wpurl').val().trim();
1828 + //Check if valid user & rulewp is installed?
1829 + let url = jQuery('#mainwp_managesites_add_wpurl_protocol').val() + '://' + jQuery('#mainwp_managesites_add_wpurl').val().trim();
1612 1830
1613 - if (!url.endsWith('/')) {
1614 - url += '/';
1615 - }
1831 + if (!url.endsWith('/')) {
1832 + url += '/';
1833 + }
1616 1834
1617 - let name = jQuery('#mainwp_managesites_add_wpname').val().trim();
1618 - name = name.replace(/"/g, '&quot;');
1835 + let name = jQuery('#mainwp_managesites_add_wpname').val().trim();
1836 + name = name.replaceAll('"', '&quot;');
1619 1837
1620 - let data = mainwp_secure_data({
1621 - action: 'mainwp_checkwp',
1622 - name: name,
1623 - url: url,
1624 - admin: jQuery('#mainwp_managesites_add_wpadmin').val().trim(),
1625 - verify_certificate: jQuery('#mainwp_managesites_verify_certificate').is(':checked') ? 1 : 0,
1626 - ssl_version: jQuery('#mainwp_managesites_add_ssl_version').val(),
1627 - http_user: jQuery('#mainwp_managesites_add_http_user').val().trim(),
1628 - http_pass: jQuery('#mainwp_managesites_add_http_pass').val().trim()
1629 - });
1838 + let data = mainwp_secure_data({
1839 + action: 'mainwp_checkwp',
1840 + name: name,
1841 + url: url,
1842 + admin: jQuery('#mainwp_managesites_add_wpadmin').val().trim(),
1843 + verify_certificate: jQuery('#mainwp_managesites_verify_certificate').is(':checked') ? 1 : 0,
1844 + ssl_version: jQuery('#mainwp_managesites_add_ssl_version').val(),
1845 + http_user: jQuery('#mainwp_managesites_add_http_user').val().trim(),
1846 + http_pass: jQuery('#mainwp_managesites_add_http_pass').val().trim()
1847 + });
1630 1848
1631 - jQuery.post(ajaxurl, data, function (res_things) {
1632 - let response = res_things.response;
1633 - response = response.trim();
1634 - let errors = [];
1635 - let url = jQuery('#mainwp_managesites_add_wpurl_protocol').val() + '://' + jQuery('#mainwp_managesites_add_wpurl').val().trim();
1636 - if (!url.endsWith('/')) {
1637 - url += '/';
1638 - }
1849 + jQuery.post(ajaxurl, data, function (res_things) { // NOSONAR - function complexity.
1850 + let response = res_things.response;
1851 + response = response.trim();
1852 + let errors = [];
1853 + let url = jQuery('#mainwp_managesites_add_wpurl_protocol').val() + '://' + jQuery('#mainwp_managesites_add_wpurl').val().trim();
1854 + if (!url.endsWith('/')) {
1855 + url += '/';
1856 + }
1639 1857
1640 - url = url.replace(/"/g, '&quot;');
1858 + url = url.replaceAll('"', '&quot;');
1641 1859
1642 - let show_resp = __('Click %1here%2 to see response from the child site.', '<a href="javascript:void(0)" class="mainwp-show-response">', '</a>');
1860 + let show_resp = MainWP.I18n.t('Click %1here%2 to see response from the child site.', '<a href="javascript:void(0)" class="mainwp-show-response">', '</a>');
1643 1861
1644 - let resp_data = res_things.resp_data ? res_things.resp_data : '';
1645 - if ('0' == resp_data) {
1646 - resp_data = '';
1647 - }
1648 - jQuery('#mainwp-response-data-container').attr('resp-data', resp_data);
1862 + let resp_data = res_things.resp_data ? res_things.resp_data : '';
1863 + if ('0' == resp_data) {
1864 + resp_data = '';
1865 + }
1866 + jQuery('#mainwp-response-data-container').attr('resp-data', resp_data);
1649 1867
1650 - if (response == 'HTTPERROR') {
1651 - errors.push(__('This site can not be reached! Please use the Test Connection feature and see if the positive response will be returned. For additional help, please review this <a href="https://kb.mainwp.com/docs/potential-issues/">Knowledgebase document</a>, and if you still have issues, please let us know in the <a href="https://managers.mainwp.com/c/community-support/5">MainWP Community</a>.')); // NOSONAR - noopener - open safe.
1652 - } else if (response == 'NOMAINWP') {
1653 - errors.push(mainwp_js_get_error_not_detected_connect());
1654 - } else if (response.substring(0, 5) == 'ERROR') {
1655 - if (response.length == 5) {
1656 - errors.push(__('Undefined error occurred. Please try again. If the issue does not resolve, please review this <a href="https://kb.mainwp.com/docs/potential-issues/">Knowledgebase document</a>, and if you still have issues, please let us know in the <a href="https://managers.mainwp.com/c/community-support/5">MainWP Community</a>.')); // NOSONAR - noopener - open safe.
1657 - } else {
1658 - errors.push(__('Error detected: ') + response.substring(6));
1659 - }
1660 - } else if (response == 'OK') {
1661 - jQuery('#mainwp_managesites_add').attr('disabled', 'true'); //Disable add button
1868 + if (response == 'HTTPERROR') {
1869 + errors.push(MainWP.I18n.t('This site can not be reached! Please use the Test Connection feature and see if the positive response will be returned. For additional help, please review this <a href="https://docs.mainwp.com/troubleshooting/potential-issues/">Knowledgebase document</a>, and if you still have issues, please let us know in the <a href="https://managers.mainwp.com/c/community-support/5">MainWP Community</a>.')); // NOSONAR - noopener - open safe.
1870 + } else if (response == 'NOMAINWP') {
1871 + errors.push(mainwp_js_get_error_not_detected_connect());
1872 + } else if (response.substring(0, 5) == 'ERROR') {
1873 + if (response.length == 5) {
1874 + errors.push(MainWP.I18n.t('Undefined error occurred. Please try again. If the issue does not resolve, please review this <a href="https://docs.mainwp.com/troubleshooting/potential-issues/">Knowledgebase document</a>, and if you still have issues, please let us know in the <a href="https://managers.mainwp.com/c/community-support/5">MainWP Community</a>.')); // NOSONAR - noopener - open safe.
1875 + } else {
1876 + errors.push(MainWP.I18n.t('Error detected: ') + response.substring(6));
1877 + }
1878 + } else if (response == 'OK') {
1879 + jQuery('#mainwp_managesites_add').attr('disabled', 'true'); //Disable add button
1662 1880
1663 - let name = jQuery('#mainwp_managesites_add_wpname').val();
1664 - name = name.replace(/"/g, '&quot;');
1665 - let group_ids = jQuery('#mainwp_managesites_add_addgroups').dropdown('get value');
1666 - let client_id = jQuery('#mainwp_managesites_add_client_id').dropdown('get value');
1667 - let data = mainwp_secure_data({
1668 - action: 'mainwp_addwp',
1669 - managesites_add_wpname: name,
1670 - managesites_add_wpurl: url,
1671 - managesites_add_wpadmin: jQuery('#mainwp_managesites_add_wpadmin').val(),
1672 - managesites_add_uniqueId: jQuery('#mainwp_managesites_add_uniqueId').val(),
1673 - ssl_verify: jQuery('#mainwp_managesites_verify_certificate').is(':checked') ? 1 : 0,
1674 - ssl_version: jQuery('#mainwp_managesites_add_ssl_version').val(),
1675 - groupids: group_ids,
1676 - clientid: client_id,
1677 - selected_icon: jQuery('#mainwp_managesites_add_site_select_icon_hidden').val(),
1678 - cust_color: jQuery('#mainwp_managesites_add_site_color').val(),
1679 - uploaded_icon: jQuery('#mainwp_managesites_add_site_uploaded_icon_hidden').val(),
1680 - managesites_add_http_user: jQuery('#mainwp_managesites_add_http_user').val(),
1681 - managesites_add_http_pass: jQuery('#mainwp_managesites_add_http_pass').val(),
1682 - });
1881 + let name = jQuery('#mainwp_managesites_add_wpname').val();
1882 + name = name.replaceAll('"', '&quot;');
1883 + let group_ids = jQuery('#mainwp_managesites_add_addgroups').dropdown('get value');
1884 + let client_id = jQuery('#mainwp_managesites_add_client_id').length ? jQuery('#mainwp_managesites_add_client_id').dropdown('get value') : 0;
1885 + let data = mainwp_secure_data({
1886 + action: 'mainwp_addwp',
1887 + managesites_add_wpname: name,
1888 + managesites_add_wpurl: url,
1889 + managesites_add_wpadmin: jQuery('#mainwp_managesites_add_wpadmin').val(),
1890 + managesites_add_adminpwd: encodeURIComponent(jQuery('#mainwp_managesites_add_admin_pwd').val().trim()),
1891 + managesites_add_uniqueId: jQuery('#mainwp_managesites_add_uniqueId').val(),
1892 + ssl_verify: jQuery('#mainwp_managesites_verify_certificate').is(':checked') ? 1 : 0,
1893 + ssl_version: jQuery('#mainwp_managesites_add_ssl_version').val(),
1894 + groupids: group_ids,
1895 + clientid: client_id,
1896 + selected_icon: jQuery('#mainwp_managesites_add_site_select_icon_hidden').val(),
1897 + cust_color: jQuery('#mainwp_managesites_add_site_color').val(),
1898 + uploaded_icon: jQuery('#mainwp_managesites_add_site_uploaded_icon_hidden').val(),
1899 + managesites_add_http_user: jQuery('#mainwp_managesites_add_http_user').val(),
1900 + managesites_add_http_pass: jQuery('#mainwp_managesites_add_http_pass').val(),
1901 + });
1683 1902
1684 - // to support add client reports tokens values
1685 - jQuery("input[name^='creport_token_']").each(function () {
1686 - let tname = jQuery(this).attr('name');
1687 - let tvalue = jQuery(this).val();
1688 - data[tname] = tvalue;
1689 - });
1903 + // to support add client reports tokens values
1904 + jQuery("input[name^='creport_token_']").each(function () {
1905 + let tname = jQuery(this).attr('name');
1906 + let tvalue = jQuery(this).val();
1907 + data[tname] = tvalue;
1908 + });
1690 1909
1691 - // support hooks fields
1692 - jQuery(".mainwp_addition_fields_addsite input").each(function () {
1693 - let tname = jQuery(this).attr('name');
1694 - let tvalue = jQuery(this).val();
1695 - data[tname] = tvalue;
1696 - });
1910 + // support hooks fields
1911 + jQuery(".mainwp_addition_fields_addsite input").each(function () {
1912 + let tname = jQuery(this).attr('name');
1913 + let tvalue = jQuery(this).val();
1914 + data[tname] = tvalue;
1915 + });
1697 1916
1698 - jQuery.post(ajaxurl, data, function (res_things) {
1699 - let site_id = 0;
1700 - if (res_things.error) {
1701 - response = 'Error detected: ' + res_things.error;
1702 - } else {
1703 - response = res_things.response;
1704 - site_id = res_things.siteid;
1705 - }
1706 - response = response.trim();
1707 - managesites_init();
1917 + jQuery.post(ajaxurl, data, function (res_things) {
1918 + let site_id = 0;
1919 + if (res_things.error) {
1920 + response = 'Error detected: ' + res_things.error;
1921 + } else {
1922 + response = res_things.response;
1923 + site_id = res_things.siteid;
1924 + }
1925 + response = response.trim();
1926 + managesites_init();
1708 1927
1709 - resp_data = res_things.resp_data ? res_things.resp_data : '';
1710 - if ('0' == resp_data) {
1711 - resp_data = '';
1712 - }
1713 - jQuery('#mainwp-response-data-container').attr('resp-data', resp_data);
1928 + resp_data = res_things.resp_data ? res_things.resp_data : '';
1929 + if ('0' == resp_data) {
1930 + resp_data = '';
1931 + }
1932 + jQuery('#mainwp-response-data-container').attr('resp-data', resp_data);
1714 1933
1715 - if (response.substring(0, 5) == 'ERROR') {
1716 - mainwp_set_message_zone('#mainwp-message-zone', '', '', true);
1717 - feedback('mainwp-message-zone', response.substring(6) + (resp_data != '' ? '<br>' + show_resp : ''), 'red');
1718 - } else {
1719 - mainwp_set_message_zone('#mainwp-message-zone', '', '', true);
1720 - feedback('mainwp-message-zone', response, 'green');
1934 + if (response.substring(0, 5) == 'ERROR') {
1935 + mainwp_set_message_zone('#mainwp-message-zone', '', '', true);
1936 + feedback('mainwp-message-zone', response.substring(6) + (resp_data == '' ? '' : '<br>' + show_resp), 'red');
1937 + } else {
1938 + mainwp_set_message_zone('#mainwp-message-zone', '', '', true);
1939 + feedback('mainwp-message-zone', response, 'green');
1721 1940
1722 - if (site_id > 0) {
1723 - jQuery('.sync-ext-row').attr('status', 'queue');
1724 - setTimeout(function () {
1725 - mainwp_managesites_sync_extension_start_next(site_id);
1726 - }, 1000);
1727 - }
1941 + if (site_id > 0) {
1942 + jQuery('.sync-ext-row').attr('status', 'queue');
1943 + setTimeout(function () {
1944 + mainwp_managesites_sync_extension_start_next(site_id);
1945 + }, 1000);
1946 + }
1728 1947
1729 - //Reset fields
1730 - jQuery('#mainwp_managesites_add_wpname').val('');
1731 - jQuery('#mainwp_managesites_add_wpurl').val('');
1732 - jQuery('#mainwp_managesites_add_wpurl_protocol').val('https');
1733 - jQuery('#mainwp_managesites_add_wpadmin').val('');
1734 - jQuery('#mainwp_managesites_add_uniqueId').val('');
1735 - jQuery('#mainwp_managesites_add_addgroups').dropdown('clear');
1736 - jQuery('#mainwp_managesites_verify_certificate').val(1);
1948 + //Reset fields
1949 + jQuery('#mainwp_managesites_add_wpname').val('');
1950 + jQuery('#mainwp_managesites_add_wpurl').val('');
1951 + jQuery('#mainwp_managesites_add_wpurl_protocol').val('https');
1952 + jQuery('#mainwp_managesites_add_wpadmin').val('');
1953 + jQuery('#mainwp_managesites_add_admin_pwd').val('');
1954 + jQuery('#mainwp_managesites_add_uniqueId').val('');
1955 + jQuery('#mainwp_managesites_add_addgroups').dropdown('clear');
1956 + jQuery('#mainwp_managesites_verify_certificate').val(1);
1737 1957
1738 - jQuery("input[name^='creport_token_']").each(function () {
1739 - jQuery(this).val('');
1740 - });
1958 + jQuery("input[name^='creport_token_']").each(function () {
1959 + jQuery(this).val('');
1960 + });
1741 1961
1742 - // support hooks fields
1743 - jQuery(".mainwp_addition_fields_addsite input").each(function () {
1744 - jQuery(this).val('');
1745 - });
1962 + // support hooks fields
1963 + jQuery(".mainwp_addition_fields_addsite input").each(function () {
1964 + jQuery(this).val('');
1965 + });
1966 + }
1967 +
1968 + jQuery('#mainwp_managesites_add').prop("disabled", false); //Enable add button
1969 + }, 'json');
1746 1970 }
1747 -
1748 - jQuery('#mainwp_managesites_add').prop("disabled", false); //Enable add button
1749 - }, 'json');
1750 - }
1751 - if (errors.length > 0) {
1752 - mainwp_set_message_zone('#mainwp-message-zone', '', '', true);
1753 - managesites_init();
1754 - jQuery('#mainwp_managesites_add').prop("disabled", false); //Enable add button
1755 - if (resp_data != '') {
1756 - errors.push(show_resp);
1757 - }
1758 - feedback('mainwp-message-zone', errors.join('<br />'), 'red');
1759 - }
1760 - }, 'json');
1971 + if (errors.length > 0) {
1972 + mainwp_set_message_zone('#mainwp-message-zone', '', '', true);
1973 + managesites_init();
1974 + jQuery('#mainwp_managesites_add').prop("disabled", false); //Enable add button
1975 + if (resp_data != '') {
1976 + errors.push(show_resp);
1977 + }
1978 + feedback('mainwp-message-zone', errors.join('<br />'), 'red');
1979 + }
1980 + }, 'json');
1761 1981 };
1762 1982
1763 1983 let mainwp_managesites_add_valid = function () {
1764 1984
1765 - if (!jQuery('#mainwp_managesites_verify_installed_child').is(':checked')) {
1766 - jQuery('#mainwp_message_verify_installed_child').show();
1767 - scrollElementTop('mainwp_message_verify_installed_child');
1768 - return false;
1769 - } else {
1770 - jQuery('#mainwp_message_verify_installed_child').hide();
1771 - }
1985 + if (jQuery('#mainwp_managesites_verify_installed_child').is(':checked')) {
1986 + jQuery('#mainwp_message_verify_installed_child').hide();
1987 + } else {
1988 + jQuery('#mainwp_message_verify_installed_child').show();
1989 + scrollElementTop('mainwp_message_verify_installed_child');
1990 + return false;
1991 + }
1772 1992
1773 - let errors = [];
1993 + let errors = [];
1774 1994
1775 - if (jQuery('#mainwp_managesites_add_wpname').val().trim() == '') {
1776 - errors.push(__('Please enter a name for the website.'));
1777 - }
1778 - if (jQuery('#mainwp_managesites_add_wpurl').val().trim() == '') {
1779 - errors.push(__('Please enter a valid URL for your site.'));
1780 - } else {
1781 - let url = jQuery('#mainwp_managesites_add_wpurl').val().trim();
1782 - if (!url.endsWith('/')) {
1783 - url += '/';
1995 + if (jQuery('#mainwp_managesites_add_wpname').val().trim() == '') {
1996 + errors.push(MainWP.I18n.t('Please enter a name for the website.'));
1784 1997 }
1998 + if (jQuery('#mainwp_managesites_add_wpurl').val().trim() == '') {
1999 + errors.push(MainWP.I18n.t('Please enter a valid URL for your site.'));
2000 + } else {
2001 + let url = jQuery('#mainwp_managesites_add_wpurl').val().trim();
2002 + if (!url.endsWith('/')) {
2003 + url += '/';
2004 + }
1785 2005
1786 - jQuery('#mainwp_managesites_add_wpurl').val(url);
2006 + jQuery('#mainwp_managesites_add_wpurl').val(url);
1787 2007
1788 - if (!isUrl(jQuery('#mainwp_managesites_add_wpurl_protocol').val() + '://' + jQuery('#mainwp_managesites_add_wpurl').val())) {
1789 - errors.push(__('Please enter a valid URL for your site.'));
2008 + if (!isUrl(jQuery('#mainwp_managesites_add_wpurl_protocol').val() + '://' + jQuery('#mainwp_managesites_add_wpurl').val())) {
2009 + errors.push(MainWP.I18n.t('Please enter a valid URL for your site.'));
2010 + }
1790 2011 }
1791 - }
1792 - if (jQuery('#mainwp_managesites_add_wpadmin').val().trim() == '') {
1793 - errors.push(__('Please enter a username of the website administrator.'));
1794 - }
2012 + if (jQuery('#mainwp_managesites_add_wpadmin').val().trim() == '') {
2013 + errors.push(MainWP.I18n.t('Please enter a username of the website administrator.'));
2014 + }
1795 2015
1796 - if (errors.length > 0) {
1797 - feedback('mainwp-message-zone', errors.join('<br />'), 'yellow');
1798 - return false;
1799 - }
1800 - return true;
2016 + if (errors.length > 0) {
2017 + feedback('mainwp-message-zone', errors.join('<br />'), 'yellow');
2018 + return false;
2019 + }
2020 + return true;
1801 2021 }
1802 2022
1803 2023
1804 2024 let mainwp_managesites_sync_extension_start_next = function (siteId) {
1805 - let pluginToInstall = jQuery('.sync-ext-row[status="queue"]:first')
1806 - while (pluginToInstall && (pluginToInstall.length > 0) && (bulkInstallCurrentThreads < 1)) { // NOSONAR - modified outside the function, bulkInstallMaxThreads - to fix install plugins and apply settings failed issue.
1807 - pluginToInstall.attr('status', 'progress');
1808 - mainwp_managesites_sync_extension_start_specific(pluginToInstall, siteId);
1809 - pluginToInstall = jQuery('.sync-ext-row[status="queue"]:first');
1810 - }
2025 + let pluginToInstall = jQuery('.sync-ext-row[status="queue"]:first')
2026 + while (pluginToInstall && (pluginToInstall.length > 0) && (bulkInstallCurrentThreads < 1)) { // NOSONAR - modified outside the function, bulkInstallMaxThreads - to fix install plugins and apply settings failed issue.
2027 + pluginToInstall.attr('status', 'progress');
2028 + mainwp_managesites_sync_extension_start_specific(pluginToInstall, siteId);
2029 + pluginToInstall = jQuery('.sync-ext-row[status="queue"]:first');
2030 + }
1811 2031
1812 - if ((pluginToInstall.length == 0) && (bulkInstallCurrentThreads == 0)) { // NOSONAR - modified outside the function.
1813 - jQuery('#mwp_applying_ext_settings').remove();
1814 - }
2032 + if ((pluginToInstall.length == 0) && (bulkInstallCurrentThreads == 0)) { // NOSONAR - modified outside the function.
2033 + jQuery('#mwp_applying_ext_settings').remove();
2034 + }
1815 2035 };
1816 2036
1817 2037 let mainwp_managesites_sync_extension_start_specific = function (pPluginToInstall, pSiteId) {
1818 - let syncGlobalSettings = pPluginToInstall.find(".sync-global-options input[type='checkbox']:checked").length > 0;
1819 - let install_plugin = pPluginToInstall.find(".sync-install-plugin input[type='checkbox']:checked").length > 0;
1820 - let apply_settings = pPluginToInstall.find(".sync-options input[type='checkbox']:checked").length > 0;
2038 + let syncGlobalSettings = pPluginToInstall.find(".sync-global-options input[type='checkbox']:checked").length > 0;
2039 + let install_plugin = pPluginToInstall.find(".sync-install-plugin input[type='checkbox']:checked").length > 0;
2040 + let apply_settings = pPluginToInstall.find(".sync-options input[type='checkbox']:checked").length > 0;
1821 2041
1822 - if (syncGlobalSettings) {
1823 - mainwp_extension_apply_plugin_settings(pPluginToInstall, pSiteId, true);
1824 - } else if (install_plugin) {
1825 - mainwp_extension_prepareinstallplugin(pPluginToInstall, pSiteId);
1826 - } else if (apply_settings) {
1827 - mainwp_extension_apply_plugin_settings(pPluginToInstall, pSiteId, false);
1828 - } else {
1829 - mainwp_managesites_sync_extension_start_next(pSiteId);
1830 - return;
1831 - }
2042 + if (syncGlobalSettings) {
2043 + mainwp_extension_apply_plugin_settings(pPluginToInstall, pSiteId, true);
2044 + } else if (install_plugin) {
2045 + mainwp_extension_prepareinstallplugin(pPluginToInstall, pSiteId);
2046 + } else if (apply_settings) {
2047 + mainwp_extension_apply_plugin_settings(pPluginToInstall, pSiteId, false);
2048 + } else {
2049 + mainwp_managesites_sync_extension_start_next(pSiteId);
2050 + return;
2051 + }
1832 2052 };
1833 2053
1834 2054 let mainwp_extension_prepareinstallplugin = function (pPluginToInstall, pSiteId) {
1835 - let site_Ids = [];
1836 - site_Ids.push(pSiteId);
1837 - bulkInstallCurrentThreads++;
1838 - let plugin_slug = pPluginToInstall.find(".sync-install-plugin").attr('slug');
1839 - let workingEl = pPluginToInstall.find(".sync-install-plugin i");
1840 - let statusEl = pPluginToInstall.find(".sync-install-plugin span.status");
2055 + let site_Ids = [];
2056 + site_Ids.push(pSiteId);
2057 + bulkInstallCurrentThreads++;
2058 + let plugin_slug = pPluginToInstall.find(".sync-install-plugin").attr('slug');
2059 + let workingEl = pPluginToInstall.find(".sync-install-plugin i");
2060 + let statusEl = pPluginToInstall.find(".sync-install-plugin span.status");
1841 2061
1842 - let data = {
1843 - action: 'mainwp_ext_prepareinstallplugintheme',
1844 - type: 'plugin',
1845 - slug: plugin_slug,
1846 - 'selected_sites[]': site_Ids,
1847 - selected_by: 'site',
1848 - };
2062 + let data = {
2063 + action: 'mainwp_ext_prepareinstallplugintheme',
2064 + type: 'plugin',
2065 + slug: plugin_slug,
2066 + 'selected_sites[]': site_Ids,
2067 + selected_by: 'site',
2068 + };
1849 2069
1850 - workingEl.show();
1851 - statusEl.html(__('Preparing for installation...'));
2070 + workingEl.show();
2071 + statusEl.html(MainWP.I18n.t('Preparing for installation...'));
1852 2072
1853 - jQuery.post(ajaxurl, data, function (response) {
1854 - workingEl.hide();
1855 - if (response?.sites[pSiteId] != undefined) {
1856 - statusEl.html(__('Installing...'));
1857 - let data = mainwp_secure_data({
1858 - action: 'mainwp_ext_performinstallplugintheme',
1859 - type: 'plugin',
1860 - url: response.url,
1861 - siteId: pSiteId,
1862 - activatePlugin: true,
1863 - overwrite: false,
1864 - });
1865 - workingEl.show();
1866 - jQuery.post(ajaxurl, data, function (response) {
2073 + jQuery.post(ajaxurl, data, function (response) {
1867 2074 workingEl.hide();
1868 - let apply_settings = false;
1869 - let syc_msg = '';
1870 - let _success = false;
1871 - if ((response?.ok[pSiteId] != undefined)) {
1872 - syc_msg = __('Installation successful!');
1873 - statusEl.html(syc_msg);
1874 - apply_settings = pPluginToInstall.find(".sync-options input[type='checkbox']:checked").length > 0;
1875 - if (apply_settings) {
1876 - mainwp_extension_apply_plugin_settings(pPluginToInstall, pSiteId, false);
1877 - }
1878 - _success = true;
1879 - } else if (response?.errors[pSiteId] != undefined) {
1880 - syc_msg = __('Installation failed!') + ': ' + response.errors[pSiteId][1];
1881 - statusEl.html(syc_msg);
1882 - statusEl.css('color', 'red');
2075 + if (response?.sites[pSiteId] === undefined) {
2076 + statusEl.css('color', 'red');
2077 + statusEl.html(MainWP.I18n.t('Error while preparing the installation. Please, try again.'));
2078 + bulkInstallCurrentThreads--;
1883 2079 } else {
1884 - syc_msg = __('Installation failed!');
1885 - statusEl.html(syc_msg);
1886 - statusEl.css('color', 'red');
1887 - }
2080 + statusEl.html(MainWP.I18n.t('Installing...'));
2081 + let data = mainwp_secure_data({
2082 + action: 'mainwp_ext_performinstallplugintheme',
2083 + type: 'plugin',
2084 + url: response.url,
2085 + siteId: pSiteId,
2086 + activatePlugin: true,
2087 + overwrite: false,
2088 + });
2089 + workingEl.show();
2090 + jQuery.post(ajaxurl, data, function (response) {
2091 + workingEl.hide();
2092 + let apply_settings = false;
2093 + let syc_msg = '';
2094 + let _success = false;
2095 + if ((response?.ok[pSiteId] != undefined)) {
2096 + syc_msg = MainWP.I18n.t('Installation successful!');
2097 + statusEl.html(syc_msg);
2098 + apply_settings = pPluginToInstall.find(".sync-options input[type='checkbox']:checked").length > 0;
2099 + if (apply_settings) {
2100 + mainwp_extension_apply_plugin_settings(pPluginToInstall, pSiteId, false);
2101 + }
2102 + _success = true;
2103 + } else if (response?.errors[pSiteId] === undefined) {
2104 + syc_msg = MainWP.I18n.t('Installation failed!');
2105 + statusEl.html(syc_msg);
2106 + statusEl.css('color', 'red');
2107 + } else {
2108 + syc_msg = MainWP.I18n.t('Installation failed!') + ': ' + response.errors[pSiteId][1];
2109 + statusEl.html(syc_msg);
2110 + statusEl.css('color', 'red');
2111 + }
1888 2112
1889 - if (syc_msg != '') {
1890 - if (_success)
1891 - syc_msg = '<span style="color:#0073aa">' + syc_msg + '!</span>';
1892 - else
1893 - syc_msg = '<span style="color:red">' + syc_msg + '!</span>';
1894 - jQuery('#mainwp-message-zone').append('<br/>' + pPluginToInstall.find(".sync-install-plugin").attr('plugin_name') + ' ' + syc_msg);
1895 - }
2113 + if (syc_msg != '') {
2114 + if (_success)
2115 + syc_msg = '<span style="color:#0073aa">' + syc_msg + '!</span>';
2116 + else
2117 + syc_msg = '<span style="color:red">' + syc_msg + '!</span>';
2118 + jQuery('#mainwp-message-zone').append('<br/>' + pPluginToInstall.find(".sync-install-plugin").attr('plugin_name') + ' ' + syc_msg);
2119 + }
1896 2120
1897 - if (!apply_settings) {
1898 - bulkInstallCurrentThreads--;
1899 - mainwp_managesites_sync_extension_start_next(pSiteId);
2121 + if (!apply_settings) {
2122 + bulkInstallCurrentThreads--;
2123 + mainwp_managesites_sync_extension_start_next(pSiteId);
2124 + }
2125 + }, 'json');
1900 2126 }
1901 - }, 'json');
1902 - } else {
1903 - statusEl.css('color', 'red');
1904 - statusEl.html(__('Error while preparing the installation. Please, try again.'));
1905 - bulkInstallCurrentThreads--;
1906 - }
1907 - }, 'json');
2127 + }, 'json');
1908 2128 }
1909 2129
1910 2130 let mainwp_extension_apply_plugin_settings = function (pPluginToInstall, pSiteId, pGlobal) {
1911 - let extSlug = pPluginToInstall.attr('slug');
1912 - let workingEl = pPluginToInstall.find(".options-row i");
1913 - let statusEl = pPluginToInstall.find(".options-row span.status");
1914 - if (pGlobal)
1915 - bulkInstallCurrentThreads++;
2131 + let extSlug = pPluginToInstall.attr('slug');
2132 + let workingEl = pPluginToInstall.find(".options-row i");
2133 + let statusEl = pPluginToInstall.find(".options-row span.status");
2134 + if (pGlobal)
2135 + bulkInstallCurrentThreads++;
1916 2136
1917 - let data = mainwp_secure_data({
1918 - action: 'mainwp_ext_applypluginsettings',
1919 - ext_dir_slug: extSlug,
1920 - siteId: pSiteId
1921 - });
2137 + let data = mainwp_secure_data({
2138 + action: 'mainwp_ext_applypluginsettings',
2139 + ext_dir_slug: extSlug,
2140 + siteId: pSiteId
2141 + });
1922 2142
1923 - workingEl.show();
1924 - statusEl.html(__('Applying settings...'));
1925 - jQuery.post(ajaxurl, data, function (response) { // NOSONAR - complex.
1926 - workingEl.hide();
1927 - let syc_msg = '';
1928 - let _success = false;
1929 - if (response) {
1930 - if (response.result && response.result == 'success') {
1931 - let msg = '';
1932 - if (response.message != undefined) {
1933 - msg = ' ' + response.message;
2143 + workingEl.show();
2144 + statusEl.html(MainWP.I18n.t('Applying settings...'));
2145 + jQuery.post(ajaxurl, data, function (response) { // NOSONAR - complex.
2146 + workingEl.hide();
2147 + let syc_msg = '';
2148 + let _success = false;
2149 + if (response) {
2150 + if (response.result && response.result == 'success') {
2151 + let msg = '';
2152 + if (response.message != undefined) {
2153 + msg = ' ' + response.message;
2154 + }
2155 + statusEl.html(MainWP.I18n.t('Applying settings successful!') + msg);
2156 + syc_msg = MainWP.I18n.t('Successful');
2157 + _success = true
2158 + } else if (response.error === undefined) {
2159 + statusEl.html(MainWP.I18n.t('Applying settings failed!'));
2160 + statusEl.css('color', 'red');
2161 + syc_msg = MainWP.I18n.t('failed');
2162 + } else {
2163 + statusEl.html(response.error);
2164 + statusEl.css('color', 'red');
2165 + syc_msg = response.error;
2166 + }
2167 + } else {
2168 + statusEl.html(MainWP.I18n.t('Undefined error!'));
2169 + statusEl.css('color', 'red');
2170 + syc_msg = MainWP.I18n.t('failed');
1934 2171 }
1935 - statusEl.html(__('Applying settings successful!') + msg);
1936 - syc_msg = __('Successful');
1937 - _success = true
1938 - } else if (response.error != undefined) {
1939 - statusEl.html(__('Applying settings failed!') + ': ' + response.error);
1940 - statusEl.css('color', 'red');
1941 - syc_msg = __('failed');
1942 - } else {
1943 - statusEl.html(__('Applying settings failed!'));
1944 - statusEl.css('color', 'red');
1945 - syc_msg = __('failed');
1946 - }
1947 - } else {
1948 - statusEl.html(__('Undefined error!'));
1949 - statusEl.css('color', 'red');
1950 - syc_msg = __('failed');
1951 - }
1952 2172
1953 - if (syc_msg != '') {
1954 - if (_success)
1955 - syc_msg = '<span style="color:#0073aa">' + syc_msg + '!</span>';
1956 - else
1957 - syc_msg = '<span style="color:red">' + syc_msg + '!</span>';
1958 - if (pGlobal) {
1959 - syc_msg = __('Apply global %1 options', pPluginToInstall.attr('ext_name')) + ' ' + syc_msg;
1960 - } else {
1961 - syc_msg = __('Apply %1 settings', pPluginToInstall.find('.sync-install-plugin').attr('plugin_name')) + ' ' + syc_msg;
1962 - }
1963 - jQuery('#mainwp-message-zone').append('<br/>' + syc_msg);
1964 - }
1965 - bulkInstallCurrentThreads--;
1966 - mainwp_managesites_sync_extension_start_next(pSiteId);
1967 - }, 'json');
2173 + if (syc_msg != '') {
2174 + if (_success)
2175 + syc_msg = '<span style="color:#0073aa">' + syc_msg + '!</span>';
2176 + else
2177 + syc_msg = '<span style="color:red">' + syc_msg + '!</span>';
2178 + if (pGlobal) {
2179 + syc_msg = MainWP.I18n.t('Apply global %1 options', pPluginToInstall.attr('ext_name')) + ' ' + syc_msg;
2180 + } else {
2181 + syc_msg = MainWP.I18n.t('Apply %1 settings', pPluginToInstall.find('.sync-install-plugin').attr('plugin_name')) + ' ' + syc_msg;
2182 + }
2183 + jQuery('#mainwp-message-zone').append('<br/>' + syc_msg);
2184 + }
2185 + bulkInstallCurrentThreads--;
2186 + mainwp_managesites_sync_extension_start_next(pSiteId);
2187 + }, 'json');
1968 2188 }
1969 2189
1970 2190 // Test Connection (Add Site Page)
1971 2191 let mainwp_managesites_test = function () {
1972 2192
1973 - let errors = [];
2193 + let errors = [];
1974 2194
1975 - if (jQuery('#mainwp_managesites_add_wpurl').val().trim() == '') {
1976 - errors.push(__('Please enter a valid URL for your site.'));
1977 - } else {
1978 - let clean_url = jQuery('#mainwp_managesites_add_wpurl').val().trim();
1979 - let protocol = jQuery('#mainwp_managesites_add_wpurl_protocol').val();
1980 - let url = protocol + '://' + clean_url;
1981 - if (!url.endsWith('/')) {
1982 - url += '/';
1983 - }
2195 + if (jQuery('#mainwp_managesites_add_wpurl').val().trim() == '') {
2196 + errors.push(MainWP.I18n.t('Please enter a valid URL for your site.'));
2197 + } else {
2198 + let clean_url = jQuery('#mainwp_managesites_add_wpurl').val().trim();
2199 + let protocol = jQuery('#mainwp_managesites_add_wpurl_protocol').val();
2200 + let url = protocol + '://' + clean_url;
2201 + if (!url.endsWith('/')) {
2202 + url += '/';
2203 + }
1984 2204
1985 - if (!isUrl(url)) {
1986 - errors.push(__('Please enter a valid URL for your site'));
2205 + if (!isUrl(url)) {
2206 + errors.push(MainWP.I18n.t('Please enter a valid URL for your site'));
2207 + }
1987 2208 }
1988 - }
1989 2209
1990 - if (errors.length > 0) {
1991 - feedback('mainwp-message-zone', errors.join('<br />'), 'red');
1992 - } else {
1993 - jQuery('#mainwp-test-connection-modal').modal('setting', 'closable', false).modal('show');
1994 - jQuery('#mainwp-test-connection-modal .dimmer').show();
1995 - jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result').hide();
2210 + if (errors.length > 0) {
2211 + feedback('mainwp-message-zone', errors.join('<br />'), 'red');
2212 + } else {
2213 + jQuery('#mainwp-test-connection-modal').modal('setting', 'closable', false).modal('show');
2214 + jQuery('#mainwp-test-connection-modal .dimmer').show();
2215 + jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result').hide();
1996 2216
1997 - let clean_url = jQuery('#mainwp_managesites_add_wpurl').val().trim();
1998 - let protocol = jQuery('#mainwp_managesites_add_wpurl_protocol').val();
1999 - let url = protocol + '://' + clean_url;
2217 + let clean_url = jQuery('#mainwp_managesites_add_wpurl').val().trim();
2218 + let protocol = jQuery('#mainwp_managesites_add_wpurl_protocol').val();
2219 + let url = protocol + '://' + clean_url;
2000 2220
2001 - if (!url.endsWith('/')) {
2002 - url += '/';
2003 - }
2221 + if (!url.endsWith('/')) {
2222 + url += '/';
2223 + }
2004 2224
2005 - let data = mainwp_secure_data({
2006 - action: 'mainwp_testwp',
2007 - url: url,
2008 - test_verify_cert: jQuery('#mainwp_managesites_verify_certificate').is(':checked') ? 1 : 0,
2009 - ssl_version: jQuery('#mainwp_managesites_add_ssl_version').val(),
2010 - http_user: jQuery('#mainwp_managesites_add_http_user').val(),
2011 - http_pass: jQuery('#mainwp_managesites_add_http_pass').val()
2012 - });
2225 + let data = mainwp_secure_data({
2226 + action: 'mainwp_testwp',
2227 + url: url,
2228 + test_verify_cert: jQuery('#mainwp_managesites_verify_certificate').is(':checked') ? 1 : 0,
2229 + ssl_version: jQuery('#mainwp_managesites_add_ssl_version').val(),
2230 + http_user: jQuery('#mainwp_managesites_add_http_user').val(),
2231 + http_pass: jQuery('#mainwp_managesites_add_http_pass').val()
2232 + });
2013 2233
2014 - jQuery.post(ajaxurl, data, function (response) { // NOSONAR - complex.
2015 - jQuery('#mainwp-test-connection-modal .dimmer').hide();
2016 - jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result i').removeClass('red green check times');
2017 - jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result .content span').html('');
2018 - jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result .content .sub.header').html('');
2019 - if (response.error) {
2020 - if (response.httpCode) {
2021 - jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result').show();
2022 - jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result i').addClass('red times');
2023 - jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result .content span').html(__('Connection failed!'));
2024 - jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result .content .sub.header').html(__('URL:') + ' ' + response.host + ' - ' + __('HTTP-code:') + ' ' + response.httpCode + (response.httpCodeString ? ' (' + response.httpCodeString + ')' : '') + ' - ' + __('Error message: ') + ' ' + response.error);
2025 - } else {
2026 - jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result').show();
2027 - jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result i').addClass('red times');
2028 - jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result .content span').html(__('Connection test failed.'));
2029 - jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result .content .sub.header').html(__('Error message:') + ' ' + response.error);
2030 - }
2031 - } else if (response.httpCode) {
2032 - if (response.httpCode == '200') {
2033 - jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result').show();
2034 - jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result i').addClass('green check');
2035 - jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result .content span').html(__('Connection successful!'));
2036 - jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result .content .sub.header').html(__('URL:') + ' ' + response.host + (response.ip != undefined ? ' (IP: ' + response.ip + ')' : '') + ' - ' + __('Received HTTP-code') + ' ' + response.httpCode + (response.httpCodeString ? ' (' + response.httpCodeString + ')' : ''));
2037 - } else {
2038 - jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result').show();
2039 - jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result i').addClass('red times');
2040 - jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result .content span').html(__('Connection test failed.'));
2041 - jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result .content .sub.header').html(__('URL:') + ' ' + response.host + (response.ip != undefined ? ' (IP: ' + response.ip + ')' : '') + ' - ' + __('Received HTTP-code:') + ' ' + response.httpCode + (response.httpCodeString ? ' (' + response.httpCodeString + ')' : ''));
2042 - }
2043 - } else {
2044 - jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result').show('');
2045 - jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result i').addClass('red times');
2046 - jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result .content span').html(__('Connection test failed.'));
2047 - jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result .content .sub.header').html(__('Invalid response from the server, please try again.'));
2048 - }
2049 - }, 'json');
2050 - }
2234 + jQuery.post(ajaxurl, data, function (response) { // NOSONAR - complex.
2235 + jQuery('#mainwp-test-connection-modal .dimmer').hide();
2236 + jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result i').removeClass('red green check times');
2237 + jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result .content span').html('');
2238 + jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result .content .sub.header').html('');
2239 + if (response.error) {
2240 + if (response.httpCode) {
2241 + jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result').show();
2242 + jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result i').addClass('red times');
2243 + jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result .content span').html(MainWP.I18n.t('Connection failed!'));
2244 + jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result .content .sub.header').html(MainWP.I18n.t('URL:') + ' ' + response.host + ' - ' + MainWP.I18n.t('HTTP-code:') + ' ' + response.httpCode + (response.httpCodeString ? ' (' + response.httpCodeString + ')' : '') + ' - ' + MainWP.I18n.t('Error message: ') + ' ' + response.error);
2245 + } else {
2246 + jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result').show();
2247 + jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result i').addClass('red times');
2248 + jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result .content span').html(MainWP.I18n.t('Connection test failed.'));
2249 + jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result .content .sub.header').html(MainWP.I18n.t('Error message:') + ' ' + response.error);
2250 + }
2251 + } else if (response.httpCode) {
2252 + if (response.httpCode == '200') {
2253 + jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result').show();
2254 + jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result i').addClass('green check');
2255 + jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result .content span').html(MainWP.I18n.t('Connection successful!'));
2256 + jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result .content .sub.header').html(MainWP.I18n.t('URL:') + ' ' + response.host + (response.ip === undefined ? '' : ' (IP: ' + response.ip + ')') + ' - ' + MainWP.I18n.t('Received HTTP-code') + ' ' + response.httpCode + (response.httpCodeString ? ' (' + response.httpCodeString + ')' : ''));
2257 + } else {
2258 + jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result').show();
2259 + jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result i').addClass('red times');
2260 + jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result .content span').html(MainWP.I18n.t('Connection test failed.'));
2261 + jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result .content .sub.header').html(MainWP.I18n.t('URL:') + ' ' + response.host + (response.ip === undefined ? '' : ' (IP: ' + response.ip + ')') + ' - ' + MainWP.I18n.t('Received HTTP-code:') + ' ' + response.httpCode + (response.httpCodeString ? ' (' + response.httpCodeString + ')' : ''));
2262 + }
2263 + } else {
2264 + jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result').show('');
2265 + jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result i').addClass('red times');
2266 + jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result .content span').html(MainWP.I18n.t('Connection test failed.'));
2267 + jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result .content .sub.header').html(MainWP.I18n.t('Invalid response from the server, please try again.'));
2268 + }
2269 + }, 'json');
2270 + }
2051 2271 };
2052 2272
2053 2273 // Test Connection (Edit Site Page)
2054 2274 let mainwp_managesites_edit_test = function () {
2055 2275
2056 - let clean_url = jQuery('#mainwp_managesites_edit_siteurl').val();
2057 - let protocol = jQuery('#mainwp_managesites_edit_siteurl_protocol').val();
2276 + let clean_url = jQuery('#mainwp_managesites_edit_siteurl').val();
2277 + let protocol = jQuery('#mainwp_managesites_edit_siteurl_protocol').val();
2278 + let with_www = jQuery('input[name=mainwp_managesites_edit_wpurl_with_www]').val();
2279 + with_www = with_www === 'www' ? with_www + '.' : '';
2058 2280
2059 - let url = protocol + '://' + clean_url;
2281 + let url = protocol + '://' + with_www + clean_url;
2060 2282
2061 - if (!url.endsWith('/')) {
2062 - url += '/';
2063 - }
2283 + if (!url.endsWith('/')) {
2284 + url += '/';
2285 + }
2064 2286
2065 - jQuery('#mainwp-test-connection-modal').modal('setting', 'closable', false).modal('show');
2066 - jQuery('#mainwp-test-connection-modal .dimmer').show();
2067 - jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result').hide();
2287 + jQuery('#mainwp-test-connection-modal').modal('setting', 'closable', false).modal('show');
2288 + jQuery('#mainwp-test-connection-modal .dimmer').show();
2289 + jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result').hide();
2068 2290
2069 - let data = mainwp_secure_data({
2070 - action: 'mainwp_testwp',
2071 - url: url,
2072 - test_verify_cert: jQuery('#mainwp_managesites_edit_verifycertificate').val(),
2073 - ssl_version: jQuery('#mainwp_managesites_edit_ssl_version').val(),
2074 - http_user: jQuery('#mainwp_managesites_edit_http_user').val(),
2075 - http_pass: jQuery('#mainwp_managesites_edit_http_pass').val()
2076 - });
2291 + let data = mainwp_secure_data({
2292 + action: 'mainwp_testwp',
2293 + url: url,
2294 + test_verify_cert: jQuery('#mainwp_managesites_edit_verifycertificate').val(),
2295 + ssl_version: jQuery('#mainwp_managesites_edit_ssl_version').val(),
2296 + http_user: jQuery('#mainwp_managesites_edit_http_user').val(),
2297 + http_pass: jQuery('#mainwp_managesites_edit_http_pass').val()
2298 + });
2077 2299
2078 - jQuery.post(ajaxurl, data, function (response) { // NOSONAR - complex.
2079 - jQuery('#mainwp-test-connection-modal .dimmer').hide();
2080 - jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result i').removeClass('red green check times');
2081 - jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result .content span').html('');
2082 - jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result .content .sub.header').html('');
2083 - if (response.error) {
2084 - if (response.httpCode) {
2085 - jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result').show();
2086 - jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result i').addClass('red times');
2087 - jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result .content span').html(__('Connection failed!'));
2088 - jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result .content .sub.header').html(__('URL:') + ' ' + response.host + ' - ' + __('HTTP-code:') + ' ' + response.httpCode + (response.httpCodeString ? ' (' + response.httpCodeString + ')' : '') + ' - ' + __('Error message: ') + ' ' + response.error);
2089 - } else {
2090 - jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result').show();
2091 - jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result i').addClass('red times');
2092 - jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result .content span').html(__('Connection test failed.'));
2093 - jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result .content .sub.header').html(__('Error message:') + ' ' + response.error);
2094 - }
2095 - } else if (response.httpCode) {
2096 - if (response.httpCode == '200') {
2097 - jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result').show();
2098 - jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result i').addClass('green check');
2099 - jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result .content span').html(__('Connection successful!'));
2100 - jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result .content .sub.header').html(__('URL:') + ' ' + response.host + (response.ip != undefined ? ' (IP: ' + response.ip + ')' : '') + ' - ' + __('Received HTTP-code') + ' ' + response.httpCode + (response.httpCodeString ? ' (' + response.httpCodeString + ')' : ''));
2101 - } else {
2102 - jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result').show();
2103 - jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result i').addClass('red times');
2104 - jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result .content span').html(__('Connection test failed.'));
2105 - jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result .content .sub.header').html(__('URL:') + ' ' + response.host + (response.ip != undefined ? ' (IP: ' + response.ip + ')' : '') + ' - ' + __('Received HTTP-code:') + ' ' + response.httpCode + (response.httpCodeString ? ' (' + response.httpCodeString + ')' : ''));
2106 - }
2107 - } else {
2108 - jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result').show('');
2109 - jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result i').addClass('red times');
2110 - jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result .content span').html(__('Connection test failed.'));
2111 - jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result .content .sub.header').html(__('Invalid response from the server, please try again.'));
2112 - }
2113 - }, 'json');
2300 + jQuery.post(ajaxurl, data, function (response) { // NOSONAR - complex.
2301 + jQuery('#mainwp-test-connection-modal .dimmer').hide();
2302 + jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result i').removeClass('red green check times');
2303 + jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result .content span').html('');
2304 + jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result .content .sub.header').html('');
2305 + if (response.error) {
2306 + if (response.httpCode) {
2307 + jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result').show();
2308 + jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result i').addClass('red times');
2309 + jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result .content span').html(MainWP.I18n.t('Connection failed!'));
2310 + jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result .content .sub.header').html(MainWP.I18n.t('URL:') + ' ' + response.host + ' - ' + MainWP.I18n.t('HTTP-code:') + ' ' + response.httpCode + (response.httpCodeString ? ' (' + response.httpCodeString + ')' : '') + ' - ' + MainWP.I18n.t('Error message: ') + ' ' + response.error);
2311 + } else {
2312 + jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result').show();
2313 + jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result i').addClass('red times');
2314 + jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result .content span').html(MainWP.I18n.t('Connection test failed.'));
2315 + jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result .content .sub.header').html(MainWP.I18n.t('Error message:') + ' ' + response.error);
2316 + }
2317 + } else if (response.httpCode) {
2318 + if (response.httpCode == '200') {
2319 + jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result').show();
2320 + jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result i').addClass('green check');
2321 + jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result .content span').html(MainWP.I18n.t('Connection successful!'));
2322 + jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result .content .sub.header').html(MainWP.I18n.t('URL:') + ' ' + response.host + (response.ip === undefined ? '' : ' (IP: ' + response.ip + ')') + ' - ' + MainWP.I18n.t('Received HTTP-code') + ' ' + response.httpCode + (response.httpCodeString ? ' (' + response.httpCodeString + ')' : ''));
2323 + } else {
2324 + jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result').show();
2325 + jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result i').addClass('red times');
2326 + jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result .content span').html(MainWP.I18n.t('Connection test failed.'));
2327 + jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result .content .sub.header').html(MainWP.I18n.t('URL:') + ' ' + response.host + (response.ip === undefined ? '' : ' (IP: ' + response.ip + ')') + ' - ' + MainWP.I18n.t('Received HTTP-code:') + ' ' + response.httpCode + (response.httpCodeString ? ' (' + response.httpCodeString + ')' : ''));
2328 + }
2329 + } else {
2330 + jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result').show('');
2331 + jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result i').addClass('red times');
2332 + jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result .content span').html(MainWP.I18n.t('Connection test failed.'));
2333 + jQuery('#mainwp-test-connection-modal .content #mainwp-test-connection-result .content .sub.header').html(MainWP.I18n.t('Invalid response from the server, please try again.'));
2334 + }
2335 + }, 'json');
2114 2336 };
2115 2337
2116 2338 let managesites_remove = function (obj) {
2117 - managesites_init();
2339 + managesites_init();
2118 2340
2119 - let name = jQuery(obj).attr('site-name');
2120 - let id = jQuery(obj).attr('site-id');
2341 + let name = jQuery(obj).attr('site-name');
2342 + let id = jQuery(obj).attr('site-id');
2121 2343
2122 - let msg = sprintf(__('Are you sure you want to remove %1 from your MainWP Dashboard?', name));
2344 + let msg = MainWP.I18n.t('Are you sure you want to remove') + ' ' + name + ' ' + MainWP.I18n.t('from your MainWP Dashboard?');
2123 2345
2124 - mainwp_confirm(msg, function () {
2125 - jQuery('tr#child-site-' + id).html('<td colspan="999"><i class="notched circle loading icon"></i> ' + 'Removing and deactivating the MainWP Child plugin! Please wait...' + '</td>');
2126 - let data = mainwp_secure_data({
2127 - action: 'mainwp_removesite',
2128 - id: id
2129 - });
2346 + mainwp_confirm(msg, function () {
2347 + jQuery('tr#child-site-' + id).html('<td colspan="999"><i class="notched circle loading icon"></i> ' + 'Removing and deactivating the MainWP Child plugin! Please wait...' + '</td>');
2348 + let data = mainwp_secure_data({
2349 + action: 'mainwp_removesite',
2350 + id: id
2351 + });
2130 2352
2131 - jQuery.post(ajaxurl, data, function (response) {
2353 + jQuery.post(ajaxurl, data, function (response) {
2132 2354
2133 - managesites_init();
2355 + managesites_init();
2134 2356
2135 - let result = '';
2136 - let error = '';
2357 + let result = '';
2358 + let error = '';
2137 2359
2138 - if (response.error != undefined) {
2139 - error = response.error;
2140 - } else if (response.result == 'SUCCESS') {
2141 - result = '<i class="close icon"></i>' + __('The site has been removed and the MainWP Child plugin has been disabled.');
2142 - } else if (response.result == 'NOSITE') {
2143 - error = '<i class="close icon"></i>' + __('The requested site has not been found.');
2144 - } else {
2145 - result = '<i class="close icon"></i>' + __('The site has been removed. Please make sure that the MainWP Child plugin has been deactivated properly.');
2146 - }
2360 + if (response.error != undefined) {
2361 + error = response.error;
2362 + } else if (response.result == 'SUCCESS') {
2363 + result = '<i class="close icon"></i>' + MainWP.I18n.t('The site has been removed and the MainWP Child plugin has been disabled.');
2364 + } else if (response.result == 'NOSITE') {
2365 + error = '<i class="close icon"></i>' + MainWP.I18n.t('The requested site has not been found.');
2366 + } else {
2367 + result = '<i class="close icon"></i>' + MainWP.I18n.t('The site has been removed. Please make sure that the MainWP Child plugin has been deactivated properly.');
2368 + }
2147 2369
2148 - if (error != '') {
2149 - feedback('mainwp-message-zone', error, 'red');
2150 - }
2370 + if (error != '') {
2371 + feedback('mainwp-message-zone', error, 'red');
2372 + }
2151 2373
2152 - if (result != '') {
2153 - feedback('mainwp-message-zone', result, 'green');
2154 - }
2374 + if (result != '') {
2375 + feedback('mainwp-message-zone', result, 'green');
2376 + }
2155 2377
2156 - jQuery('tr#child-site-' + id).remove();
2378 + jQuery('tr#child-site-' + id).remove();
2157 2379
2158 - }, 'json');
2159 - }, false, false, false, 'REMOVE');
2160 - return false;
2380 + }, 'json');
2381 + }, false, false, false, 'REMOVE');
2382 + return false;
2161 2383 };
2162 2384
2163 2385 jQuery(function () {
2164 2386
2165 - jQuery(document).on('click', '#mainwp_managesites_add', function () {
2166 - mainwp_managesites_add();
2167 - });
2387 + jQuery(document).on('click', '#mainwp_managesites_add', function () {
2388 + mainwp_managesites_add();
2389 + });
2168 2390
2169 - jQuery(document).on('click', '#mainwp_managesites_bulkadd', function () {
2170 - if (jQuery('#mainwp_managesites_file_bulkupload').val() == '') {
2171 - setHtml('#mainwp-message-zone', __('Please enter csv file for upload.'), false);
2172 - } else {
2173 - jQuery('#mainwp_managesites_bulkadd_form').submit();
2174 - }
2175 - return false;
2176 - });
2391 + // Hanlde click submit form import website
2392 + jQuery(document).on('click', '#mainwp_managesites_bulkadd', function () {
2177 2393
2178 - // Trigger Connection Test (Add Site Page)
2179 - jQuery(document).on('click', '#mainwp_managesites_test', function () {
2180 - mainwp_managesites_test();
2181 - });
2394 + let error_messages = mainwp_managesites_import_handle_form_before_submit();
2395 + // If there is an error, prevent submission and display the error
2396 + if (error_messages.length > 0) {
2397 + feedback('mainwp-message-zone', error_messages.join("<br/>"), "red");
2398 + } else {
2399 + jQuery('#mainwp_managesites_bulkadd_form').submit();
2400 + }
2401 + return false;
2402 + });
2182 2403
2183 - // Trigger Connection Test (Edit Site Page)
2184 - jQuery(document).on('click', '#mainwp_managesites_edit_test', function () {
2185 - mainwp_managesites_edit_test();
2186 - });
2404 + // Trigger Connection Test (Add Site Page)
2405 + jQuery(document).on('click', '#mainwp_managesites_test', function () {
2406 + mainwp_managesites_test();
2407 + });
2187 2408
2409 + // Trigger Connection Test (Edit Site Page)
2410 + jQuery(document).on('click', '#mainwp_managesites_edit_test', function () {
2411 + mainwp_managesites_edit_test();
2412 + });
2413 +
2414 + // Use detected URL (Edit Site Page): set the protocol and www selectors to the child-reported address; no autosave.
2415 + jQuery(document).on('click', '#mainwp_managesites_edit_use_detected', function () {
2416 + let scheme = jQuery(this).attr('data-scheme');
2417 + let with_www = jQuery(this).attr('data-www');
2418 + if (scheme === 'http' || scheme === 'https') {
2419 + jQuery('#mainwp_managesites_edit_siteurl_protocol').dropdown('set selected', scheme);
2420 + }
2421 + if (with_www === 'www' || with_www === 'none-www') {
2422 + jQuery('#mainwp-edit-site-edit-url-www').dropdown('set selected', with_www);
2423 + }
2424 + return false;
2425 + });
2426 +
2427 + // Handle submit add multi website
2428 + jQuery(document).on('click', '#mainwp_managesites_add_multi_site', function () {
2429 + let error_messages = [];
2430 + let has_table_data = false;
2431 + has_table_data = mainwp_managesites_validate_import_rows(error_messages, true);
2432 + // If there is an error, prevent submission and display the error
2433 + if (error_messages.length > 0 && !has_table_data) {
2434 + feedback('mainwp-add-multi-new-site-message-zone', error_messages.join("<br/>"), "red");
2435 + } else {
2436 + jQuery('#mainwp_managesites_add_form').submit();
2437 + }
2438 + return false;
2439 + });
2440 +
2441 + // Handle click remove website on management webiste.
2442 + jQuery(document).on('click', '#mainwp-managesites-remove-site', function () {
2443 + jQuery('#mainwp-remove-site-button').trigger('click');
2444 + });
2188 2445 });
2189 2446
2190 2447 /**
2191 2448 * Add new user
2192 2449 */
2450 +function mainwp_gen_passsword(len = 24) {
2451 + const chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_+{}[]<>?';
2452 + const arr = new Uint32Array(len);
2453 + crypto.getRandomValues(arr);
2454 + return Array.from(arr, x => chars[x % chars.length]).join('');
2455 +}
2456 +
2457 +jQuery('.mainwp-generate-password-button').on('click', function (e) {
2458 + e.preventDefault();
2459 + jQuery('#createuser #password, #mainwp-update-admin-password-form #password').val(mainwp_gen_passsword(24)).trigger('change');
2460 +});
2461 +
2193 2462 jQuery(function () {
2194 - jQuery(document).on('click', '#bulk_add_createuser', function () {
2195 - mainwp_createuser();
2196 - });
2197 - jQuery('#bulk_import_createuser').on('click', function () {
2198 - mainwp_bulkupload_users();
2199 - });
2463 + jQuery(document).on('click', '#bulk_add_createuser', function () {
2464 + mainwp_createuser();
2465 + });
2466 + jQuery('#bulk_import_createuser').on('click', function () {
2467 + mainwp_bulkupload_users();
2468 + });
2200 2469 });
2201 2470
2202 2471 let mainwp_createuser = function () {
2203 - let cont = true;
2204 - if (jQuery('#user_login').val() == '') {
2205 - feedback('mainwp-message-zone', __('Username field is required! Please enter a username.'), 'yellow');
2206 - cont = false;
2207 - }
2472 + let cont = true;
2473 + if (jQuery('#user_login').val() == '') {
2474 + feedback('mainwp-message-zone', MainWP.I18n.t('Username field is required! Please enter a username.'), 'yellow');
2475 + cont = false;
2476 + }
2208 2477
2209 - if (jQuery('#email').val() == '') {
2210 - feedback('mainwp-message-zone', __('E-mail field is required! Please enter an email address.'), 'yellow');
2211 - cont = false;
2212 - }
2478 + if (jQuery('#email').val() == '') {
2479 + feedback('mainwp-message-zone', MainWP.I18n.t('E-mail field is required! Please enter an email address.'), 'yellow');
2480 + cont = false;
2481 + }
2213 2482
2214 - if (jQuery('#password').val() == '') {
2215 - feedback('mainwp-message-zone', __('Password field is required! Please enter the wanted password or generate a random one.'), 'yellow');
2216 - cont = false;
2217 - }
2483 + if (jQuery('#password').val() == '') {
2484 + feedback('mainwp-message-zone', MainWP.I18n.t('Password field is required! Please enter the wanted password or generate a random one.'), 'yellow');
2485 + cont = false;
2486 + }
2218 2487
2219 - let selected_sites = [];
2220 - let selected_clients = [];
2221 - let selected_groups = [];
2488 + let selected_sites = [];
2489 + let selected_clients = [];
2490 + let selected_groups = [];
2222 2491
2223 - if (jQuery('#select_by').val() == 'site') {
2224 - jQuery("input[name='selected_sites[]']:checked").each(function () {
2225 - selected_sites.push(jQuery(this).val());
2226 - });
2227 - if (selected_sites.length == 0) {
2228 - feedback('mainwp-message-zone', __('Please select at least one website or group or client.'), 'yellow');
2229 - cont = false;
2492 + if (jQuery('input[name="select_by"]').val() == 'site') {
2493 + jQuery("input[name='selected_sites[]']:checked").each(function () {
2494 + selected_sites.push(jQuery(this).val());
2495 + });
2496 + if (selected_sites.length == 0) {
2497 + feedback('mainwp-message-zone', MainWP.I18n.t('Please select at least one website or group or client.'), 'yellow');
2498 + cont = false;
2499 + }
2500 + } else if (jQuery('input[name="select_by"]').val() == 'client') {
2501 + jQuery("input[name='selected_clients[]']:checked").each(function () {
2502 + selected_clients.push(jQuery(this).val());
2503 + });
2504 + if (selected_clients.length == 0) {
2505 + feedback('mainwp-message-zone', MainWP.I18n.t('Please select at least one website or group or client.'), 'yellow');
2506 + cont = false;
2507 + }
2508 + } else {
2509 + jQuery("input[name='selected_groups[]']:checked").each(function () {
2510 + selected_groups.push(jQuery(this).val());
2511 + });
2512 + if (selected_groups.length == 0) {
2513 + feedback('mainwp-message-zone', MainWP.I18n.t('Please select at least one website or group or client.'), 'yellow');
2514 + cont = false;
2515 + }
2230 2516 }
2231 - } else if (jQuery('#select_by').val() == 'client') {
2232 - jQuery("input[name='selected_clients[]']:checked").each(function () {
2233 - selected_clients.push(jQuery(this).val());
2234 - });
2235 - if (selected_clients.length == 0) {
2236 - feedback('mainwp-message-zone', __('Please select at least one website or group or client.'), 'yellow');
2237 - cont = false;
2238 - }
2239 - } else {
2240 - jQuery("input[name='selected_groups[]']:checked").each(function () {
2241 - selected_groups.push(jQuery(this).val());
2242 - });
2243 - if (selected_groups.length == 0) {
2244 - feedback('mainwp-message-zone', __('Please select at least one website or group or client.'), 'yellow');
2245 - cont = false;
2246 - }
2247 - }
2248 2517
2249 - if (cont) {
2250 - mainwp_set_message_zone('#mainwp-message-zone', '<i class="notched circle loading icon"></i> ' + __('Creating the user. Please wait...'), '', true);
2251 - jQuery('#bulk_add_createuser').attr('disabled', 'disabled');
2252 - //Add user via ajax!!
2253 - let data = mainwp_secure_data({
2254 - action: 'mainwp_bulkadduser',
2255 - 'select_by': jQuery('#select_by').val(),
2256 - 'selected_groups[]': selected_groups,
2257 - 'selected_sites[]': selected_sites,
2258 - 'selected_clients[]': selected_clients,
2259 - 'user_login': jQuery('#user_login').val(),
2260 - 'email': jQuery('#email').val(),
2261 - 'url': jQuery('#url').val(),
2262 - 'first_name': jQuery('#first_name').val(),
2263 - 'last_name': jQuery('#last_name').val(),
2264 - 'pass1': jQuery('#password').val(),
2265 - 'pass2': jQuery('#password').val(),
2266 - 'send_password': jQuery('#send_password').attr('checked'),
2267 - 'role': jQuery('#role').val()
2268 - });
2518 + if (cont) {
2519 + mainwp_set_message_zone('#mainwp-message-zone', '<i class="notched circle loading icon"></i> ' + MainWP.I18n.t('Creating the user. Please wait...'), '', true);
2520 + jQuery('#bulk_add_createuser').attr('disabled', 'disabled');
2521 + const is_send_password = jQuery('#send_password').is(':checked') ? 1 : 0;
2522 + //Add user via ajax!!
2523 + let data = mainwp_secure_data({
2524 + action: "mainwp_bulkadduser",
2525 + select_by: jQuery("input[name='select_by']").val(),
2526 + "selected_groups[]": selected_groups,
2527 + "selected_sites[]": selected_sites,
2528 + "selected_clients[]": selected_clients,
2529 + user_login: jQuery("#user_login").val(),
2530 + email: jQuery("#email").val(),
2531 + url: jQuery("#url").val(),
2532 + first_name: jQuery("#first_name").val(),
2533 + last_name: jQuery("#last_name").val(),
2534 + pass1: jQuery("#password").val(),
2535 + pass2: jQuery("#password").val(),
2536 + send_password: is_send_password,
2537 + role: jQuery("#role").val(),
2538 + });
2269 2539
2270 - jQuery.post(ajaxurl, data, function (response) {
2271 - response = response.trim();
2272 - mainwp_set_message_zone('#mainwp-message-zone');
2273 - jQuery('#bulk_add_createuser').prop("disabled", false);
2274 - if (response.substring(0, 5) == 'ERROR') {
2275 - let responseObj = JSON.parse(response.substring(6));
2276 - if (responseObj.error == undefined) {
2277 - let errorMessageList = responseObj[1];
2278 - let errorMessage = '';
2279 - for (let iem of errorMessageList) {
2280 - if (errorMessage != '') {
2281 - errorMessage = errorMessage + "<br />";
2540 + jQuery.post(ajaxurl, data, function (response) {
2541 + response = response.trim();
2542 + mainwp_set_message_zone('#mainwp-message-zone');
2543 + jQuery('#bulk_add_createuser').prop("disabled", false);
2544 + if (response.substring(0, 5) == 'ERROR') {
2545 + let responseObj = JSON.parse(response.substring(6));
2546 + if (responseObj.error == undefined) {
2547 + let errorMessageList = responseObj[1];
2548 + let errorMessage = '';
2549 + for (let iem of errorMessageList) {
2550 + if (errorMessage != '') {
2551 + errorMessage = errorMessage + "<br />";
2552 + }
2553 + errorMessage = errorMessage + iem;
2554 + }
2555 + if (errorMessage != '') {
2556 + feedback('mainwp-message-zone', errorMessage, 'red');
2557 + }
2558 + }
2559 + } else {
2560 + jQuery('#mainwp-add-new-user-form').append(response);
2561 + jQuery('#mainwp-creating-new-user-modal').modal({
2562 + closable: false,
2563 + }).modal('show');
2282 2564 }
2283 - errorMessage = errorMessage + iem;
2284 - }
2285 - if (errorMessage != '') {
2286 - feedback('mainwp-message-zone', errorMessage, 'red');
2287 - }
2288 - }
2289 - } else {
2290 - jQuery('#mainwp-add-new-user-form').append(response);
2291 - jQuery('#mainwp-creating-new-user-modal').modal('setting', 'closable', false).modal('show');
2292 -
2293 - }
2294 - });
2295 - }
2565 + });
2566 + }
2296 2567 };
2297 2568
2298 2569 /**
2299 2570 * InstallPlugins/Themes
@@ -2298,83 +2569,86 @@
2298 2569 /**
2299 2570 * InstallPlugins/Themes
2300 2571 */
2301 2572 jQuery(function () {
2302 - jQuery('#MainWPInstallBulkNavSearch').on('click', function (event) {
2303 - event.preventDefault();
2304 - jQuery('#mainwp_plugin_bulk_install_btn').attr('bulk-action', 'install');
2305 - jQuery('.mainwp-browse-plugins').show();
2306 - jQuery('.mainwp-upload-plugin').hide();
2307 - jQuery('#mainwp-search-plugins-form').show();
2308 - });
2309 - jQuery('#MainWPInstallBulkNavUpload').on('click', function (event) {
2310 - event.preventDefault();
2311 - jQuery('#mainwp_plugin_bulk_install_btn').attr('bulk-action', 'upload');
2312 - jQuery('.mainwp-upload-plugin').show();
2313 - jQuery('.mainwp-browse-plugins').hide();
2314 - jQuery('#mainwp-search-plugins-form').hide();
2315 - });
2573 + jQuery('#MainWPInstallBulkNavSearch').on('click', function (event) {
2574 + event.preventDefault();
2575 + jQuery('#mainwp_plugin_bulk_install_btn').attr('bulk-action', 'install');
2576 + jQuery('.mainwp-bulk-install-showhide-content').hide();
2577 + jQuery('.mainwp-browse-plugins').show();
2578 + jQuery('#mainwp-search-plugins-form').show();
2579 + jQuery('.mainwp-bulk-install-tabs-header-btn').removeClass('green');
2580 + jQuery(this).addClass('green');
2581 + });
2582 + jQuery('#MainWPInstallBulkNavUpload').on('click', function (event) {
2583 + event.preventDefault();
2584 + jQuery('#mainwp_plugin_bulk_install_btn').attr('bulk-action', 'upload');
2585 + jQuery('.mainwp-bulk-install-showhide-content').hide();
2586 + jQuery('.mainwp-upload-plugin').show();
2587 + jQuery('.mainwp-bulk-install-tabs-header-btn').removeClass('green');
2588 + jQuery(this).addClass('green');
2589 + });
2316 2590
2317 - // not used?
2318 - jQuery(document).on('click', '.filter-links li.plugin-install a', function (event) {
2319 - event.preventDefault();
2320 - jQuery('.filter-links li.plugin-install a').removeClass('current');
2321 - jQuery(this).addClass('current');
2322 - let tab = jQuery(this).parent().attr('tab');
2323 - if (tab == 'search') {
2324 - mainwp_install_search(event);
2325 - } else {
2326 - jQuery('#mainwp_installbulk_s').val('');
2327 - jQuery('#mainwp_installbulk_tab').val(tab);
2328 - mainwp_install_plugin_tab_search('tab:' + tab);
2329 - }
2330 - });
2591 + // not used?
2592 + jQuery(document).on('click', '.filter-links li.plugin-install a', function (event) {
2593 + event.preventDefault();
2594 + jQuery('.filter-links li.plugin-install a').removeClass('current');
2595 + jQuery(this).addClass('current');
2596 + let tab = jQuery(this).parent().attr('tab');
2597 + if (tab == 'search') {
2598 + mainwp_install_search(event);
2599 + } else {
2600 + jQuery('#mainwp_installbulk_s').val('');
2601 + jQuery('#mainwp_installbulk_tab').val(tab);
2602 + mainwp_install_plugin_tab_search('tab:' + tab);
2603 + }
2604 + });
2331 2605
2332 - jQuery(document).on('click', '#mainwp_plugin_bulk_install_btn', function () {
2333 - let act = jQuery(this).attr('bulk-action');
2334 - if (act == 'install') {
2335 - let selected = jQuery("input[type='radio'][name='install-plugin']:checked");
2336 - if (selected.length == 0) {
2337 - feedback('mainwp-message-zone', __('Please select plugin to install files.'), 'yellow');
2338 - } else {
2339 - let selectedId = /^install-([^-]*)-(.*)$/.exec(selected.attr('id'));
2340 - if (selectedId) {
2341 - mainwp_install_bulk('plugin', selectedId[2], selected.attr('plugin-name'));
2606 + jQuery(document).on('click', '#mainwp_plugin_bulk_install_btn', function () {
2607 + let act = jQuery(this).attr('bulk-action');
2608 + if (act == 'install') {
2609 + let selected = jQuery("input[type='radio'][name='install-plugin']:checked");
2610 + if (selected.length == 0) {
2611 + feedback('mainwp-message-zone', MainWP.I18n.t('Please select plugin to install files.'), 'yellow');
2612 + } else {
2613 + let selectedId = /^install-([^-]*)-(.*)$/.exec(selected.attr('id'));
2614 + if (selectedId) {
2615 + mainwp_install_bulk('plugin', selectedId[2], selected.attr('plugin-name'));
2616 + }
2617 + }
2618 + } else if (act == 'upload') {
2619 + mainwp_upload_bulk('plugins');
2342 2620 }
2343 - }
2344 - } else if (act == 'upload') {
2345 - mainwp_upload_bulk('plugins');
2346 - }
2347 2621
2348 - return false;
2349 - });
2622 + return false;
2623 + });
2350 2624
2351 - jQuery(document).on('click', '#mainwp_theme_bulk_install_btn', function () {
2352 - let act = jQuery(this).attr('bulk-action');
2353 - if (act == 'install') {
2354 - let selected = jQuery("input[type='radio'][name='install-theme']:checked");
2355 - if (selected.length == 0) {
2356 - feedback('mainwp-message-zone', __('Please select theme to install files.'), 'yellow');
2357 - } else {
2358 - let selectedId = /^install-([^-]*)-(.*)$/.exec(selected.attr('id'));
2359 - if (selectedId)
2360 - mainwp_install_bulk('theme', selectedId[2], selected.attr('theme-name'));
2361 - }
2362 - } else if (act == 'upload') {
2363 - mainwp_upload_bulk('themes');
2364 - }
2365 - return false;
2366 - });
2625 + jQuery(document).on('click', '#mainwp_theme_bulk_install_btn', function () {
2626 + let act = jQuery(this).attr('bulk-action');
2627 + if (act == 'install') {
2628 + let selected = jQuery("input[type='radio'][name='install-theme']:checked");
2629 + if (selected.length == 0) {
2630 + feedback('mainwp-message-zone', MainWP.I18n.t('Please select theme to install files.'), 'yellow');
2631 + } else {
2632 + let selectedId = /^install-([^-]*)-(.*)$/.exec(selected.attr('id'));
2633 + if (selectedId)
2634 + mainwp_install_bulk('theme', selectedId[2], selected.attr('theme-name'));
2635 + }
2636 + } else if (act == 'upload') {
2637 + mainwp_upload_bulk('themes');
2638 + }
2639 + return false;
2640 + });
2367 2641 });
2368 2642
2369 2643 // Generate the Go to WP Admin link
2370 -window.mainwp_links_visit_site_and_admin = function (url, siteId) {
2371 - let links = '';
2372 - if (url != '') {
2373 - links += '<a href="' + url + '" target="_blank" class="mainwp-may-hide-referrer"><i class="external alternate icon"></i></a> ';
2374 - }
2375 - links += '<a href="admin.php?page=SiteOpen&newWindow=yes&websiteid=' + siteId + '&_opennonce=' + mainwpParams._wpnonce + '" target="_blank"><i class="sign in alternate icon"></i></a>';
2376 - return links;
2644 +globalThis.mainwp_links_visit_site_and_admin = function (url, siteId) {
2645 + let links = '';
2646 + if (url != '') {
2647 + links += '<a href="' + url + '" target="_blank" class="mainwp-may-hide-referrer"><i class="external alternate icon"></i></a> ';
2648 + }
2649 + links += '<a href="admin.php?page=SiteOpen&newWindow=yes&websiteid=' + siteId + '&_opennonce=' + mainwpParams._wpnonce + '" target="_blank"><i class="sign in alternate icon"></i></a>';
2650 + return links;
2377 2651 }
2378 2652
2379 2653 mainwpVars.bulkInstallTotal = 0;
2380 2654 bulkInstallDone = 0;
@@ -2389,94 +2663,94 @@
2389 2663 *
2390 2664 * @return void
2391 2665 */
2392 2666 let mainwp_install_bulk = function (type, slug, name) {
2393 - let data = mainwp_secure_data({
2394 - action: 'mainwp_preparebulkinstallplugintheme',
2395 - type: type,
2396 - slug: slug,
2397 - name: name,
2398 - selected_by: jQuery('#select_by').val()
2399 - });
2400 - let placeholder = '<div class="ui placeholder"><div class="paragraph"><div class="line"></div><div class="line"></div><div class="line"></div><div class="line"></div><div class="line"></div></div></div>';
2667 + let data = mainwp_secure_data({
2668 + action: 'mainwp_preparebulkinstallplugintheme',
2669 + type: type,
2670 + slug: slug,
2671 + name: name,
2672 + selected_by: jQuery('input[name="select_by"]').val()
2673 + });
2674 + let placeholder = '<div class="ui placeholder"><div class="paragraph"><div class="line"></div><div class="line"></div><div class="line"></div><div class="line"></div><div class="line"></div></div></div>';
2401 2675
2402 - if (jQuery('#select_by').val() == 'site') {
2676 + if (jQuery('input[name="select_by"]').val() == 'site') {
2403 2677
2404 - let selected_sites = [];
2678 + let selected_sites = [];
2405 2679
2406 - jQuery("input[name='selected_sites[]']:checked").each(function () {
2407 - selected_sites.push(jQuery(this).val());
2408 - });
2680 + jQuery("input[name='selected_sites[]']:checked").each(function () {
2681 + selected_sites.push(jQuery(this).val());
2682 + });
2409 2683
2410 - if (selected_sites.length == 0) {
2411 - feedback('mainwp-message-zone', __('Please select at least one website or a group or client.', 'mainwp'), 'yellow');
2412 - return;
2413 - }
2684 + if (selected_sites.length == 0) {
2685 + feedback('mainwp-message-zone', MainWP.I18n.t('Please select at least one website or a group or client.'), 'yellow');
2686 + return;
2687 + }
2414 2688
2415 - data['selected_sites[]'] = selected_sites;
2689 + data['selected_sites[]'] = selected_sites;
2416 2690
2417 - } else if (jQuery('#select_by').val() == 'client') {
2691 + } else if (jQuery('input[name="select_by"]').val() == 'client') {
2418 2692
2419 - let selected_clients = [];
2693 + let selected_clients = [];
2420 2694
2421 - jQuery("input[name='selected_clients[]']:checked").each(function () {
2422 - selected_clients.push(jQuery(this).val());
2423 - });
2695 + jQuery("input[name='selected_clients[]']:checked").each(function () {
2696 + selected_clients.push(jQuery(this).val());
2697 + });
2424 2698
2425 - if (selected_clients.length == 0) {
2426 - feedback('mainwp-message-zone', __('Please select at least one website or a group or client.', 'mainwp'), 'yellow');
2427 - return;
2428 - }
2699 + if (selected_clients.length == 0) {
2700 + feedback('mainwp-message-zone', MainWP.I18n.t('Please select at least one website or a group or client.'), 'yellow');
2701 + return;
2702 + }
2429 2703
2430 - data['selected_clients[]'] = selected_clients;
2704 + data['selected_clients[]'] = selected_clients;
2431 2705
2432 - } else {
2433 - let selected_groups = [];
2706 + } else {
2707 + let selected_groups = [];
2434 2708
2435 - jQuery("input[name='selected_groups[]']:checked").each(function () {
2436 - selected_groups.push(jQuery(this).val());
2437 - });
2709 + jQuery("input[name='selected_groups[]']:checked").each(function () {
2710 + selected_groups.push(jQuery(this).val());
2711 + });
2438 2712
2439 - if (selected_groups.length == 0) {
2440 - feedback('mainwp-message-zone', __('Please select at least one website or a group or client.', 'mainwp'), 'yellow');
2441 - return;
2442 - }
2713 + if (selected_groups.length == 0) {
2714 + feedback('mainwp-message-zone', MainWP.I18n.t('Please select at least one website or a group or client.'), 'yellow');
2715 + return;
2716 + }
2443 2717
2444 - data['selected_groups[]'] = selected_groups;
2718 + data['selected_groups[]'] = selected_groups;
2445 2719
2446 - }
2720 + }
2447 2721
2448 - jQuery('#plugintheme-installation-queue').html(placeholder);
2449 - jQuery.post(ajaxurl, data, function (type, activatePlugin, overwrite) {
2450 - return function (response) {
2451 - let installQueueContent = '';
2452 - bulkInstallDone = 0;
2453 - installQueueContent += '<div id="bulk_install_info"></div>';
2454 - installQueueContent += '<div class="ui middle aligned divided selection list">';
2722 + jQuery('#plugintheme-installation-queue').html(placeholder);
2723 + jQuery.post(ajaxurl, data, function (type, activatePlugin, overwrite) {
2724 + return function (response) {
2725 + let installQueueContent = '';
2726 + bulkInstallDone = 0;
2727 + installQueueContent += '<div id="bulk_install_info"></div>';
2728 + installQueueContent += '<div class="ui middle aligned divided list">';
2455 2729
2456 - for (let siteId in response.sites) {
2457 - let site = response.sites[siteId];
2458 - installQueueContent +=
2459 - '<div class="siteBulkInstall item" siteid="' + siteId + '" status="queue">' +
2460 - '<div class="right floated content">' +
2461 - '<span class="queue" data-inverted="" data-position="left center" data-tooltip="' + __('Queued') + '"><i class="clock outline icon"></i></span>' +
2462 - '<span class="progress" data-inverted="" data-position="left center" data-tooltip="' + __('Installing...') + '" style="display:none"><i class="notched circle loading icon"></i></span>' +
2463 - '<span class="status"></span>' +
2464 - '</div>' +
2465 - '<div class="content">' + mainwp_links_visit_site_and_admin('', siteId) + ' ' + '<a href="' + site['url'] + '">' + site['name'].replace(/\\(.)/mg, "$1") + '</a></div>' +
2466 - '</div>';
2467 - mainwpVars.bulkInstallTotal++;
2468 - }
2730 + for (let siteId in response.sites) {
2731 + let site = response.sites[siteId];
2732 + installQueueContent +=
2733 + '<div class="siteBulkInstall item" siteid="' + siteId + '" status="queue">' +
2734 + '<div class="right floated content">' +
2735 + '<span class="queue" data-inverted="" data-position="left center" data-tooltip="' + MainWP.I18n.t('Queued') + '"><i class="clock outline icon"></i></span>' +
2736 + '<span class="progress" data-inverted="" data-position="left center" data-tooltip="' + MainWP.I18n.t('Installing...') + '" style="display:none"><i class="notched circle loading icon"></i></span>' +
2737 + '<span class="status"></span>' +
2738 + '</div>' +
2739 + '<div class="content">' + mainwp_links_visit_site_and_admin('', siteId) + ' ' + '<a href="' + site['url'] + '">' + site.name.replace(/\\(.)/g, '$1') + '</a></div>' + // NOSONAR - no safe replaceAll alternative.
2740 + '</div>';
2741 + mainwpVars.bulkInstallTotal++;
2742 + }
2469 2743
2470 - installQueueContent += '</div>';
2744 + installQueueContent += '</div>';
2471 2745
2472 - jQuery('#plugintheme-installation-queue').html(installQueueContent);
2473 - jQuery('#plugintheme-installation-progress-modal .mainwp-modal-progress').progress({ value: 0, total: mainwpVars.bulkInstallTotal });
2474 - mainwp_install_bulk_start_next(type, response.url, activatePlugin, overwrite, slug, response);
2475 - }
2476 - }(type, jQuery('#chk_activate_plugin').is(':checked'), jQuery('#chk_overwrite').is(':checked')), 'json');
2746 + jQuery('#plugintheme-installation-queue').html(installQueueContent);
2747 + jQuery('#plugintheme-installation-progress-modal .mainwp-modal-progress').progress({ value: 0, total: mainwpVars.bulkInstallTotal });
2748 + mainwp_install_bulk_start_next(type, response.url, activatePlugin, overwrite, slug, response);
2749 + }
2750 + }(type, jQuery('#chk_activate_plugin').is(':checked'), jQuery('#chk_overwrite').is(':checked')), 'json');
2477 2751
2478 - jQuery('#plugintheme-installation-progress-modal').modal('setting', 'closable', false).modal('show');
2752 + jQuery('#plugintheme-installation-progress-modal').modal('setting', 'closable', false).modal('show');
2479 2753
2480 2754 };
2481 2755
2482 2756
@@ -2492,31 +2766,31 @@
2492 2766 *
2493 2767 * @return void
2494 2768 */
2495 2769 let mainwp_install_bulk_start_next = function (type, url, activatePlugin, overwrite, slug, installResults) { // NOSONAR - complex.
2496 - while ((siteToInstall = jQuery('.siteBulkInstall[status="queue"]:first')) && (siteToInstall.length > 0) && (bulkInstallCurrentThreads < bulkInstallMaxThreads)) { // NOSONAR - modified outside the function.
2497 - mainwp_install_bulk_start_specific(type, url, activatePlugin, overwrite, siteToInstall, slug, installResults);
2498 - }
2499 - if (bulkInstallDone == mainwpVars.bulkInstallTotal && mainwpVars.bulkInstallTotal != 0) {
2500 - jQuery('#bulk_install_info').before('<div class="ui info message">' + mainwp_install_bulk_you_know_msg(type, 1) + '</div>');
2501 - if (jQuery('.mainwp-cost-tracker-assistant-add-to-cost-tracker-button').length > 0) { // to support add to cost tracker pro.
2502 - if (installResults.add_to_cost_tracker_id != undefined) {
2503 - if (installResults.add_to_cost_tracker_id > 0) {
2504 - jQuery('.mainwp-cost-tracker-assistant-add-to-cost-tracker-button').text(_('Edit Cost Tracker'));
2505 - jQuery('#mainwp-cost-tracker-assistant-add-to-tracker-modal .header').text(_('Edit Cost Tracker'));
2770 + while ((siteToInstall = jQuery('.siteBulkInstall[status="queue"]:first')) && (siteToInstall.length > 0) && (bulkInstallCurrentThreads < bulkInstallMaxThreads)) { // NOSONAR - modified outside the function.
2771 + mainwp_install_bulk_start_specific(type, url, activatePlugin, overwrite, siteToInstall, slug, installResults);
2772 + }
2773 + if (bulkInstallDone == mainwpVars.bulkInstallTotal && mainwpVars.bulkInstallTotal != 0) {
2774 + jQuery('#bulk_install_info').before('<div class="ui info message">' + mainwp_install_bulk_you_know_msg(type, 1) + '</div>');
2775 + if (jQuery('.mainwp-cost-tracker-assistant-add-to-cost-tracker-button').length > 0) { // to support add to cost tracker pro.
2776 + if (installResults.add_to_cost_tracker_id != undefined) {
2777 + if (installResults.add_to_cost_tracker_id > 0) {
2778 + jQuery('.mainwp-cost-tracker-assistant-add-to-cost-tracker-button').text(_('Edit Cost Tracker'));
2779 + jQuery('#mainwp-cost-tracker-assistant-add-to-tracker-modal .header').text(_('Edit Cost Tracker'));
2780 + }
2781 + jQuery('.mainwp-cost-tracker-assistant-add-to-cost-tracker-button').attr('disabled', false);
2782 + jQuery('.mainwp-cost-tracker-assistant-add-to-cost-tracker-button').removeClass('disabled');
2783 + jQuery('.mainwp-cost-tracker-assistant-add-to-cost-tracker-button').attr('item-slug', slug);
2784 + jQuery('.mainwp-cost-tracker-assistant-add-to-cost-tracker-button').attr('item-type', type);
2785 + jQuery('.mainwp-cost-tracker-assistant-add-to-cost-tracker-button').attr('item-name', installResults.name);
2786 + jQuery('.mainwp-cost-tracker-assistant-add-to-cost-tracker-button').attr('cost-id', installResults.add_to_cost_tracker_id);
2787 + if (installResults.installed_sites != undefined) {
2788 + jQuery('.mainwp-cost-tracker-assistant-add-to-cost-tracker-button').attr('installed-sites', installResults.installed_sites.join(','));
2789 + }
2790 + }
2506 2791 }
2507 - jQuery('.mainwp-cost-tracker-assistant-add-to-cost-tracker-button').attr('disabled', false);
2508 - jQuery('.mainwp-cost-tracker-assistant-add-to-cost-tracker-button').removeClass('disabled');
2509 - jQuery('.mainwp-cost-tracker-assistant-add-to-cost-tracker-button').attr('item-slug', slug);
2510 - jQuery('.mainwp-cost-tracker-assistant-add-to-cost-tracker-button').attr('item-type', type);
2511 - jQuery('.mainwp-cost-tracker-assistant-add-to-cost-tracker-button').attr('item-name', installResults.name);
2512 - jQuery('.mainwp-cost-tracker-assistant-add-to-cost-tracker-button').attr('cost-id', installResults.add_to_cost_tracker_id);
2513 - if (installResults.installed_sites != undefined) {
2514 - jQuery('.mainwp-cost-tracker-assistant-add-to-cost-tracker-button').attr('installed-sites', installResults.installed_sites.join(','));
2515 - }
2516 - }
2517 2792 }
2518 - }
2519 2793 };
2520 2794
2521 2795 /**
2522 2796 * Install Plugin/Theme from WP.org.
@@ -2531,85 +2805,85 @@
2531 2805 *
2532 2806 * @return void
2533 2807 */
2534 2808 let mainwp_install_bulk_start_specific = function (type, url, activatePlugin, overwrite, siteToInstall, slug, installResults) {
2535 - bulkInstallCurrentThreads++;
2809 + bulkInstallCurrentThreads++;
2536 2810
2537 - siteToInstall.attr('status', 'progress');
2538 - siteToInstall.find('.queue').hide();
2539 - siteToInstall.find('.progress').show();
2540 - let data = mainwp_secure_data({
2541 - action: 'mainwp_installbulkinstallplugintheme',
2542 - type: type,
2543 - url: url,
2544 - activatePlugin: activatePlugin,
2545 - overwrite: overwrite,
2546 - siteId: siteToInstall.attr('siteid')
2547 - });
2811 + siteToInstall.attr('status', 'progress');
2812 + siteToInstall.find('.queue').hide();
2813 + siteToInstall.find('.progress').show();
2814 + let data = mainwp_secure_data({
2815 + action: 'mainwp_installbulkinstallplugintheme',
2816 + type: type,
2817 + url: url,
2818 + activatePlugin: activatePlugin,
2819 + overwrite: overwrite,
2820 + siteId: siteToInstall.attr('siteid')
2821 + });
2548 2822
2549 - jQuery.post(ajaxurl, data, function (type, url, activatePlugin, overwrite, siteToInstall) {
2550 - return function (response) {
2551 - siteToInstall.attr('status', 'done');
2552 - siteToInstall.find('.progress').hide();
2553 - let statusEl = siteToInstall.find('.status');
2554 - statusEl.show();
2555 - let _error = '';
2556 - if (response.error != undefined) {
2557 - statusEl.html(response.error);
2558 - statusEl.css('color', 'red');
2559 - } else if (response?.ok[siteToInstall.attr('siteid')]) {
2560 - statusEl.html('<span data-inverted="" data-position="left center" data-tooltip="' + __('Installation completed successfully.', 'mainwp') + '"><i class="check green icon"></i></span>');
2561 - if (installResults.installed_sites == undefined) {
2562 - installResults.installed_sites = [];
2563 - }
2564 - installResults.installed_sites.push(siteToInstall.attr('siteid'));
2565 - } else if (response?.errors[siteToInstall.attr('siteid')]) {
2566 - _error = response.errors[siteToInstall.attr('siteid')][1];
2567 - } else {
2568 - _error = __('Undefined error occurred. Please try again.', 'mainwp');
2569 - }
2823 + jQuery.post(ajaxurl, data, function (type, url, activatePlugin, overwrite, siteToInstall) {
2824 + return function (response) {
2825 + siteToInstall.attr('status', 'done');
2826 + siteToInstall.find('.progress').hide();
2827 + let statusEl = siteToInstall.find('.status');
2828 + statusEl.show();
2829 + let _error = '';
2830 + if (response.error != undefined) {
2831 + statusEl.html(response.error);
2832 + statusEl.css('color', 'red');
2833 + } else if (response?.ok[siteToInstall.attr('siteid')]) {
2834 + statusEl.html('<span data-inverted="" data-position="left center" data-tooltip="' + MainWP.I18n.t('Installation completed successfully.') + '"><i class="check green icon"></i></span>');
2835 + if (installResults.installed_sites == undefined) {
2836 + installResults.installed_sites = [];
2837 + }
2838 + installResults.installed_sites.push(siteToInstall.attr('siteid'));
2839 + } else if (response?.errors[siteToInstall.attr('siteid')]) {
2840 + _error = response.errors[siteToInstall.attr('siteid')][1];
2841 + } else {
2842 + _error = MainWP.I18n.t('Undefined error occurred. Please try again.');
2843 + }
2570 2844
2571 - if (_error !== '') {
2572 - statusEl.html('<span data-inverted="" data-position="left center" data-tooltip="' + _error + '"><i class="times red icon"></i></span>');
2573 - }
2845 + if (_error !== '') {
2846 + statusEl.html('<span data-inverted="" data-position="left center" data-tooltip="' + _error + '"><i class="times red icon"></i></span>');
2847 + }
2574 2848
2575 - bulkInstallCurrentThreads--;
2576 - bulkInstallDone++;
2849 + bulkInstallCurrentThreads--;
2850 + bulkInstallDone++;
2577 2851
2578 - jQuery('#plugintheme-installation-progress-modal .mainwp-modal-progress').progress('set progress', bulkInstallDone);
2579 - jQuery('#plugintheme-installation-progress-modal .mainwp-modal-progress').find('.label').html(bulkInstallDone + '/' + mainwpVars.bulkInstallTotal + ' ' + __('Installed'));
2580 - mainwp_install_bulk_start_next(type, url, activatePlugin, overwrite, slug, installResults);
2581 - }
2582 - }(type, url, activatePlugin, overwrite, siteToInstall), 'json');
2852 + jQuery('#plugintheme-installation-progress-modal .mainwp-modal-progress').progress('set progress', bulkInstallDone);
2853 + jQuery('#plugintheme-installation-progress-modal .mainwp-modal-progress').find('.label').html(bulkInstallDone + '/' + mainwpVars.bulkInstallTotal + ' ' + MainWP.I18n.t('Installed'));
2854 + mainwp_install_bulk_start_next(type, url, activatePlugin, overwrite, slug, installResults);
2855 + }
2856 + }(type, url, activatePlugin, overwrite, siteToInstall), 'json');
2583 2857 };
2584 2858
2585 2859
2586 2860 let mainwp_install_bulk_you_know_msg = function (type, total) { // NOSONAR - complex.
2587 - let msg = '';
2588 - if (mainwpParams.installedBulkSettingsManager && mainwpParams.installedBulkSettingsManager == 1) {
2589 - if (type == 'plugin') {
2590 - if (total == 1)
2591 - msg = __('Would you like to use the Bulk Settings Manager with this plugin? Check out the %1Documentation%2.', '<a href="https://kb.mainwp.com/docs/bulk-settings-manager-extension/" target="_blank">', '</a>'); // NOSONAR - noopener - open safe.
2592 - else
2593 - msg = __('Would you like to use the Bulk Settings Manager with these plugins? Check out the %1Documentation%2.', '<a href="https://kb.mainwp.com/docs/bulk-settings-manager-extension/" target="_blank">', '</a>'); // NOSONAR - noopener - open safe.
2861 + let msg = '';
2862 + if (mainwpParams.installedBulkSettingsManager && mainwpParams.installedBulkSettingsManager == 1) {
2863 + if (type == 'plugin') {
2864 + if (total == 1)
2865 + msg = MainWP.I18n.t('Would you like to use the Bulk Settings Manager with this plugin? Check out the %1Documentation%2.', '<a href="https://docs.mainwp.com/add-ons/administrative/bulk-settings-manager-extension" target="_blank">', '</a>'); // NOSONAR - noopener - open safe.
2866 + else
2867 + msg = MainWP.I18n.t('Would you like to use the Bulk Settings Manager with these plugins? Check out the %1Documentation%2.', '<a href="https://docs.mainwp.com/add-ons/administrative/bulk-settings-manager-extension" target="_blank">', '</a>'); // NOSONAR - noopener - open safe.
2868 + } else if (type == 'theme') {
2869 + if (total == 1)
2870 + msg = MainWP.I18n.t('Would you like to use the Bulk Settings Manager with this theme? Check out the %1Documentation%2.', '<a href="https://docs.mainwp.com/add-ons/administrative/bulk-settings-manager-extension" target="_blank">', '</a>'); // NOSONAR - noopener - open safe.
2871 + else
2872 + msg = MainWP.I18n.t('Would you like to use the Bulk Settings Manager with these themes? Check out the %1Documentation%2.', '<a href="https://docs.mainwp.com/add-ons/administrative/bulk-settings-manager-extension" target="_blank">', '</a>'); // NOSONAR - noopener - open safe.
2873 + }
2874 + } else if (type == 'plugin') {
2875 + if (total == 1)
2876 + msg = MainWP.I18n.t('Did you know with the %1 you can control the settings of this plugin directly from your MainWP Dashboard?', '<a href="https://mainwp.com/add-on/bulk-settings-manager/" target="_blank">Bulk Settings Extension</a>'); // NOSONAR - noopener - open safe.
2877 + else
2878 + msg = MainWP.I18n.t('Did you know with the %1 you can control the settings of these plugins directly from your MainWP Dashboard?', '<a href="https://mainwp.com/add-on/bulk-settings-manager/" target="_blank">Bulk Settings Extension</a>'); // NOSONAR - noopener - open safe.
2594 2879 } else if (type == 'theme') {
2595 - if (total == 1)
2596 - msg = __('Would you like to use the Bulk Settings Manager with this theme? Check out the %1Documentation%2.', '<a href="https://kb.mainwp.com/docs/bulk-settings-manager-extension/" target="_blank">', '</a>'); // NOSONAR - noopener - open safe.
2597 - else
2598 - msg = __('Would you like to use the Bulk Settings Manager with these themes? Check out the %1Documentation%2.', '<a href="https://kb.mainwp.com/docs/bulk-settings-manager-extension/" target="_blank">', '</a>'); // NOSONAR - noopener - open safe.
2880 + if (total == 1)
2881 + msg = MainWP.I18n.t('Did you know with the %1 you can control the settings of this theme directly from your MainWP Dashboard?', '<a href="https://mainwp.com/add-on/bulk-settings-manager/" target="_blank">Bulk Settings Extension</a>'); // NOSONAR - noopener - open safe.
2882 + else
2883 + msg = MainWP.I18n.t('Did you know with the %1 you can control the settings of these themes directly from your MainWP Dashboard?', '<a href="https://mainwp.com/add-on/bulk-settings-manager/" target="_blank">Bulk Settings Extension</a>'); // NOSONAR - noopener - open safe.
2599 2884 }
2600 - } else if (type == 'plugin') {
2601 - if (total == 1)
2602 - msg = __('Did you know with the %1 you can control the settings of this plugin directly from your MainWP Dashboard?', '<a href="https://mainwp.com/extension/bulk-settings-manager/" target="_blank">Bulk Settings Extension</a>'); // NOSONAR - noopener - open safe.
2603 - else
2604 - msg = __('Did you know with the %1 you can control the settings of these plugins directly from your MainWP Dashboard?', '<a href="https://mainwp.com/extension/bulk-settings-manager/" target="_blank">Bulk Settings Extension</a>'); // NOSONAR - noopener - open safe.
2605 - } else if (type == 'theme') {
2606 - if (total == 1)
2607 - msg = __('Did you know with the %1 you can control the settings of this theme directly from your MainWP Dashboard?', '<a href="https://mainwp.com/extension/bulk-settings-manager/" target="_blank">Bulk Settings Extension</a>'); // NOSONAR - noopener - open safe.
2608 - else
2609 - msg = __('Did you know with the %1 you can control the settings of these themes directly from your MainWP Dashboard?', '<a href="https://mainwp.com/extension/bulk-settings-manager/" target="_blank">Bulk Settings Extension</a>'); // NOSONAR - noopener - open safe.
2610 - }
2611 - return msg;
2885 + return msg;
2612 2886 }
2613 2887
2614 2888 /**
2615 2889 * Install Plugin/Theme by Upload.
@@ -2621,115 +2895,115 @@
2621 2895 * @return void
2622 2896 */
2623 2897 let mainwp_upload_bulk = function (type) {
2624 2898
2625 - if (type == 'plugins') {
2626 - type = 'plugin';
2627 - } else {
2628 - type = 'theme';
2629 - }
2899 + if (type == 'plugins') {
2900 + type = 'plugin';
2901 + } else {
2902 + type = 'theme';
2903 + }
2630 2904
2631 - let files = [];
2905 + let files = [];
2632 2906
2633 - jQuery(".qq-upload-file").each(function () {
2634 - if (jQuery(this).closest('.file-uploaded-item').hasClass('qq-upload-success')) {
2635 - files.push(jQuery(this).attr('filename'));
2636 - }
2637 - });
2907 + jQuery(".qq-upload-file").each(function () {
2908 + if (jQuery(this).closest('.file-uploaded-item').hasClass('qq-upload-success')) {
2909 + files.push(jQuery(this).attr('filename'));
2910 + }
2911 + });
2638 2912
2639 - if (files.length == 0) {
2640 - if (type == 'plugin') {
2641 - feedback('mainwp-message-zone', __('Please upload at least one plugin to install.', 'mainwp'), 'yellow');
2642 - } else {
2643 - feedback('mainwp-message-zone', __('Please upload at least one theme to install.', 'mainwp'), 'yellow');
2913 + if (files.length == 0) {
2914 + if (type == 'plugin') {
2915 + feedback('mainwp-message-zone', MainWP.I18n.t('Please upload at least one plugin to install.'), 'yellow');
2916 + } else {
2917 + feedback('mainwp-message-zone', MainWP.I18n.t('Please upload at least one theme to install.'), 'yellow');
2918 + }
2919 + return;
2644 2920 }
2645 - return;
2646 - }
2647 2921
2648 - let data = mainwp_secure_data({
2649 - action: 'mainwp_preparebulkuploadplugintheme',
2650 - type: type,
2651 - selected_by: jQuery('#select_by').val()
2652 - });
2922 + let data = mainwp_secure_data({
2923 + action: 'mainwp_preparebulkuploadplugintheme',
2924 + type: type,
2925 + selected_by: jQuery('input[name="select_by"]').val()
2926 + });
2653 2927
2654 - let placeholder = '<div class="ui placeholder"><div class="paragraph"><div class="line"></div><div class="line"></div><div class="line"></div><div class="line"></div><div class="line"></div></div></div>';
2928 + let placeholder = '<div class="ui placeholder"><div class="paragraph"><div class="line"></div><div class="line"></div><div class="line"></div><div class="line"></div><div class="line"></div></div></div>';
2655 2929
2656 - if (jQuery('#select_by').val() == 'site') {
2657 - let selected_sites = [];
2658 - jQuery("input[name='selected_sites[]']:checked").each(function () {
2659 - selected_sites.push(jQuery(this).val());
2660 - });
2930 + if (jQuery('input[name="select_by"]').val() == 'site') {
2931 + let selected_sites = [];
2932 + jQuery("input[name='selected_sites[]']:checked").each(function () {
2933 + selected_sites.push(jQuery(this).val());
2934 + });
2661 2935
2662 - if (selected_sites.length == 0) {
2663 - feedback('mainwp-message-zone', __('Please select at least one website or a group or client.', 'mainwp'), 'yellow');
2664 - return;
2665 - }
2666 - data['selected_sites[]'] = selected_sites;
2667 - } else if (jQuery('#select_by').val() == 'client') {
2668 - let selected_clients = [];
2669 - jQuery("input[name='selected_clients[]']:checked").each(function () {
2670 - selected_clients.push(jQuery(this).val());
2671 - });
2936 + if (selected_sites.length == 0) {
2937 + feedback('mainwp-message-zone', MainWP.I18n.t('Please select at least one website or a group or client.'), 'yellow');
2938 + return;
2939 + }
2940 + data['selected_sites[]'] = selected_sites;
2941 + } else if (jQuery('input[name="select_by"]').val() == 'client') {
2942 + let selected_clients = [];
2943 + jQuery("input[name='selected_clients[]']:checked").each(function () {
2944 + selected_clients.push(jQuery(this).val());
2945 + });
2672 2946
2673 - if (selected_clients.length == 0) {
2674 - feedback('mainwp-message-zone', __('Please select at least one website or a group or client.', 'mainwp'), 'yellow');
2675 - return;
2947 + if (selected_clients.length == 0) {
2948 + feedback('mainwp-message-zone', MainWP.I18n.t('Please select at least one website or a group or client.'), 'yellow');
2949 + return;
2950 + }
2951 + data['selected_clients[]'] = selected_clients;
2952 + } else {
2953 + let selected_groups = [];
2954 + jQuery("input[name='selected_groups[]']:checked").each(function () {
2955 + selected_groups.push(jQuery(this).val());
2956 + });
2957 + if (selected_groups.length == 0) {
2958 + feedback('mainwp-message-zone', MainWP.I18n.t('Please select at least one website or a group or client.'), 'yellow');
2959 + return;
2960 + }
2961 + data['selected_groups[]'] = selected_groups;
2676 2962 }
2677 - data['selected_clients[]'] = selected_clients;
2678 - } else {
2679 - let selected_groups = [];
2680 - jQuery("input[name='selected_groups[]']:checked").each(function () {
2681 - selected_groups.push(jQuery(this).val());
2682 - });
2683 - if (selected_groups.length == 0) {
2684 - feedback('mainwp-message-zone', __('Please select at least one website or a group or client.', 'mainwp'), 'yellow');
2685 - return;
2686 - }
2687 - data['selected_groups[]'] = selected_groups;
2688 - }
2689 2963
2690 - data['files[]'] = files;
2964 + data['files[]'] = files;
2691 2965
2692 - jQuery('#plugintheme-installation-queue').html(placeholder);
2966 + jQuery('#plugintheme-installation-queue').html(placeholder);
2693 2967
2694 - jQuery.post(ajaxurl, data, function (type, files, activatePlugin, overwrite) {
2695 - return function (response) {
2696 - let installQueue = '';
2697 - mainwpVars.bulkInstallTotal = 0;
2698 - bulkInstallDone = 0;
2968 + jQuery.post(ajaxurl, data, function (type, files, activatePlugin, overwrite) {
2969 + return function (response) {
2970 + let installQueue = '';
2971 + mainwpVars.bulkInstallTotal = 0;
2972 + bulkInstallDone = 0;
2699 2973
2700 - installQueue += '<div class="ui middle aligned selection divided list">';
2974 + installQueue += '<div class="ui middle aligned selection divided list">';
2701 2975
2702 - for (let siteId in response.sites) {
2703 - let site = response.sites[siteId];
2976 + for (let siteId in response.sites) {
2977 + let site = response.sites[siteId];
2704 2978
2705 - installQueue +=
2706 - '<div class="siteBulkInstall item" siteid="' + siteId + '" status="queue">' +
2707 - '<div class="right floated content">' +
2708 - '<span class="queue" data-inverted="" data-position="left center" data-tooltip="' + __('Queued', 'mainwp') + '"><i class="clock outline icon"></i></span>' +
2709 - '<span class="progress" data-inverted="" data-position="left center" data-tooltip="' + __('Installing...', 'mainwp') + '" style="display:none"><i class="notched circle loading icon"></i></span>' +
2710 - '<span class="status"></span>' +
2711 - '</div>' +
2712 - '<div class="content">' + mainwp_links_visit_site_and_admin('', siteId) + ' ' + '<a href="' + site['url'] + '">' + site['name'].replace(/\\(.)/mg, "$1") + '</a></div>' +
2713 - '<div class="installation-entries"></div>' +
2714 - '</div>';
2715 - mainwpVars.bulkInstallTotal++;
2716 - }
2979 + installQueue +=
2980 + '<div class="siteBulkInstall item" siteid="' + siteId + '" status="queue">' +
2981 + '<div class="right floated content">' +
2982 + '<span class="queue" data-inverted="" data-position="left center" data-tooltip="' + MainWP.I18n.t('Queued') + '"><i class="clock outline icon"></i></span>' +
2983 + '<span class="progress" data-inverted="" data-position="left center" data-tooltip="' + MainWP.I18n.t('Installing...') + '" style="display:none"><i class="notched circle loading icon"></i></span>' +
2984 + '<span class="status"></span>' +
2985 + '</div>' +
2986 + '<div class="content">' + mainwp_links_visit_site_and_admin('', siteId) + ' ' + '<a href="' + site['url'] + '">' + site.name.replace(/\\(.)/g, '$1') + '</a></div>' + // NOSONAR - no safe replaceAll alternative.
2987 + '<div class="installation-entries"></div>' +
2988 + '</div>';
2989 + mainwpVars.bulkInstallTotal++;
2990 + }
2717 2991
2718 - installQueue += '</div>';
2992 + installQueue += '</div>';
2719 2993
2720 - jQuery('#plugintheme-installation-queue').html(installQueue);
2994 + jQuery('#plugintheme-installation-queue').html(installQueue);
2721 2995
2722 - jQuery('#plugintheme-installation-progress-modal .mainwp-modal-progress').progress({ value: 0, total: mainwpVars.bulkInstallTotal });
2723 - mainwp_upload_bulk_start_next(type, response.urls, activatePlugin, overwrite);
2724 - }
2725 - }(type, files, jQuery('#chk_activate_plugin').is(':checked'), jQuery('#chk_overwrite').is(':checked')), 'json');
2996 + jQuery('#plugintheme-installation-progress-modal .mainwp-modal-progress').progress({ value: 0, total: mainwpVars.bulkInstallTotal });
2997 + mainwp_upload_bulk_start_next(type, response.urls, activatePlugin, overwrite);
2998 + }
2999 + }(type, files, jQuery('#chk_activate_plugin').is(':checked'), jQuery('#chk_overwrite').is(':checked')), 'json');
2726 3000
2727 - jQuery('#plugintheme-installation-progress-modal').modal('setting', 'closable', false).modal('show');
3001 + jQuery('#plugintheme-installation-progress-modal').modal('setting', 'closable', false).modal('show');
2728 3002
2729 - jQuery('.qq-upload-list').html(''); // empty files list!
3003 + jQuery('.qq-upload-list').html(''); // empty files list!
2730 3004
2731 - return false;
3005 + return false;
2732 3006 };
2733 3007
2734 3008 /**
2735 3009 * Install Plugin/Theme by Upload.
@@ -2743,55 +3017,55 @@
2743 3017 *
2744 3018 * @return void
2745 3019 */
2746 3020 let mainwp_upload_bulk_start_next = function (type, urls, activatePlugin, overwrite) {
2747 - while ((siteToInstall = jQuery('.siteBulkInstall[status="queue"]:first')) && (siteToInstall.length > 0) && (bulkInstallCurrentThreads < bulkInstallMaxThreads)) { // NOSONAR - modified outside the function.
2748 - mainwp_upload_bulk_start_specific(type, urls, activatePlugin, overwrite, siteToInstall);
2749 - }
3021 + while ((siteToInstall = jQuery('.siteBulkInstall[status="queue"]:first')) && (siteToInstall.length > 0) && (bulkInstallCurrentThreads < bulkInstallMaxThreads)) { // NOSONAR - modified outside the function.
3022 + mainwp_upload_bulk_start_specific(type, urls, activatePlugin, overwrite, siteToInstall);
3023 + }
2750 3024
2751 - if ((siteToInstall.length == 0) && (bulkInstallCurrentThreads == 0)) { // NOSONAR - modified outside the function.
2752 - let data = mainwp_secure_data({
2753 - action: 'mainwp_cleanbulkuploadplugintheme',
2754 - });
3025 + if ((siteToInstall.length == 0) && (bulkInstallCurrentThreads == 0)) { // NOSONAR - modified outside the function.
3026 + let data = mainwp_secure_data({
3027 + action: 'mainwp_cleanbulkuploadplugintheme',
3028 + });
2755 3029
2756 - jQuery.post(ajaxurl, data, function () {
2757 - jQuery('.file-uploaded-item.qq-upload-completed').remove();
2758 - });
3030 + jQuery.post(ajaxurl, data, function () {
3031 + jQuery('.file-uploaded-item.qq-upload-completed').remove();
3032 + });
2759 3033
2760 - let msg = mainwp_install_bulk_you_know_msg(type, jQuery('#bulk_upload_info').attr('number-files'));
3034 + let msg = mainwp_install_bulk_you_know_msg(type, jQuery('#bulk_upload_info').attr('number-files'));
2761 3035
2762 - jQuery('#bulk_upload_info').html('<div class="mainwp-notice mainwp-notice-blue">' + msg + '</div>');
3036 + jQuery('#bulk_upload_info').html('<div class="bui blue message">' + msg + '</div>');
2763 3037
2764 - if (jQuery('.mainwp_cost_tracker_assistant_installed_items').length > 0) { // to support add to cost tracker pro.
2765 - let cost_tracker_items = [];
2766 - let cost_tracker_check_slugs = [];
2767 - jQuery('.mainwp_cost_tracker_assistant_installed_items').each(function () {
2768 - let slug = jQuery(this).attr('item-slug');
2769 - let items_slug = {};
2770 - if (!cost_tracker_check_slugs.includes(slug)) {
2771 - cost_tracker_check_slugs.push(slug);
2772 - let siteids = [];
2773 - jQuery('.mainwp_cost_tracker_assistant_installed_items[item-slug="' + slug + '"]').each(function () {
2774 - siteids.push(jQuery(this).attr('item-siteid'));
2775 - });
2776 - items_slug.slug = slug;
2777 - items_slug.name = jQuery(this).attr('item-name');
2778 - items_slug.type = jQuery(this).attr('item-type');
2779 - items_slug.cost_id = jQuery(this).attr('cost-id');
2780 - items_slug.sites_ids = siteids;
2781 - cost_tracker_items.push(items_slug);
3038 + if (jQuery('.mainwp_cost_tracker_assistant_installed_items').length > 0) { // to support add to cost tracker pro.
3039 + let cost_tracker_items = [];
3040 + let cost_tracker_check_slugs = [];
3041 + jQuery('.mainwp_cost_tracker_assistant_installed_items').each(function () {
3042 + let slug = jQuery(this).attr('item-slug');
3043 + let items_slug = {};
3044 + if (!cost_tracker_check_slugs.includes(slug)) {
3045 + cost_tracker_check_slugs.push(slug);
3046 + let siteids = [];
3047 + jQuery('.mainwp_cost_tracker_assistant_installed_items[item-slug="' + slug + '"]').each(function () {
3048 + siteids.push(jQuery(this).attr('item-siteid'));
3049 + });
3050 + items_slug.slug = slug;
3051 + items_slug.name = jQuery(this).attr('item-name');
3052 + items_slug.type = jQuery(this).attr('item-type');
3053 + items_slug.cost_id = jQuery(this).attr('cost-id');
3054 + items_slug.sites_ids = siteids;
3055 + cost_tracker_items.push(items_slug);
3056 + }
3057 + });
3058 +
3059 + if (cost_tracker_items.length > 0) {
3060 + jQuery('.mainwp-cost-tracker-assistant-add-buttons-wrapper').html('');
3061 + let multiAddTo = cost_tracker_items.length > 1 ? 1 : 0;
3062 + cost_tracker_items.forEach(item => {
3063 + jQuery('.mainwp-cost-tracker-assistant-add-buttons-wrapper').append('<a href="javascript:void(0)" item-type="' + item.type + '" item-slug="' + item.slug + '" cost-id="' + item.cost_id + '" item-name="' + item.name + '" installed-sites="' + item.sites_ids.join(',') + '" multi-add-to="' + multiAddTo + '" class="ui mini button mainwp-cost-tracker-assistant-add-to-cost-tracker-button">' + ((item.cost_id != undefined && item.cost_id > 0) ? MainWP.I18n.t('Edit Cost Tracker') + ' (' + item.name + ')' : MainWP.I18n.t('Add to Cost Tracker') + ' (' + item.name + ')') + '</a>');
3064 + });
3065 + }
2782 3066 }
2783 - });
2784 -
2785 - if (cost_tracker_items.length > 0) {
2786 - jQuery('.mainwp-cost-tracker-assistant-add-buttons-wrapper').html('');
2787 - let multiAddTo = cost_tracker_items.length > 1 ? 1 : 0;
2788 - cost_tracker_items.forEach(item => {
2789 - jQuery('.mainwp-cost-tracker-assistant-add-buttons-wrapper').append('<a href="javascript:void(0)" item-type="' + item.type + '" item-slug="' + item.slug + '" cost-id="' + item.cost_id + '" item-name="' + item.name + '" installed-sites="' + item.sites_ids.join(',') + '" multi-add-to="' + multiAddTo + '" class="ui mini button mainwp-cost-tracker-assistant-add-to-cost-tracker-button">' + ((item.cost_id != undefined && item.cost_id > 0) ? __('Edit Cost Tracker') : __('Add to Cost Tracker')) + '</a>');
2790 - });
2791 - }
2792 3067 }
2793 - }
2794 3068 };
2795 3069
2796 3070 /**
2797 3071 * Install Plugin/Theme by Upload.
@@ -2806,193 +3080,704 @@
2806 3080 *
2807 3081 * @return void
2808 3082 */
2809 3083 let mainwp_upload_bulk_start_specific = function (type, urls, activatePlugin, overwrite, siteToInstall) {
2810 - bulkInstallCurrentThreads++;
2811 - siteToInstall.attr('status', 'progress');
3084 + bulkInstallCurrentThreads++;
3085 + siteToInstall.attr('status', 'progress');
2812 3086
2813 - siteToInstall.find('.queue').hide();
2814 - siteToInstall.find('.progress').show();
3087 + siteToInstall.find('.queue').hide();
3088 + siteToInstall.find('.progress').show();
2815 3089
2816 - let data = mainwp_secure_data({
2817 - action: 'mainwp_installbulkuploadplugintheme',
2818 - type: type,
2819 - urls: urls,
2820 - activatePlugin: activatePlugin,
2821 - overwrite: overwrite,
2822 - siteId: siteToInstall.attr('siteid')
2823 - });
3090 + let data = mainwp_secure_data({
3091 + action: 'mainwp_installbulkuploadplugintheme',
3092 + type: type,
3093 + urls: urls,
3094 + activatePlugin: activatePlugin,
3095 + overwrite: overwrite,
3096 + siteId: siteToInstall.attr('siteid')
3097 + });
2824 3098
2825 - jQuery.post(ajaxurl, data, function (type, urls, activatePlugin, overwrite, siteToInstall) {
2826 - return function (response) {
2827 - siteToInstall.attr('status', 'done');
2828 - siteToInstall.find('.progress').hide();
2829 - let statusEl = siteToInstall.find('.status');
2830 - let siteid = siteToInstall.attr('siteid');
2831 - statusEl.show();
3099 + jQuery.post(ajaxurl, data, function (type, urls, activatePlugin, overwrite, siteToInstall) {
3100 + return function (response) {
3101 + siteToInstall.attr('status', 'done');
3102 + siteToInstall.find('.progress').hide();
3103 + let statusEl = siteToInstall.find('.status');
3104 + let siteid = siteToInstall.attr('siteid');
3105 + statusEl.show();
2832 3106
2833 - if (response.error != undefined) {
2834 - statusEl.html(response.error);
2835 - statusEl.css('color', 'red');
2836 - } else if (response?.ok[siteid] != undefined) {
2837 - let results = '';
2838 - if (response?.results[siteid] != undefined) {
2839 - let entries = Object.entries(response.results[siteid]);
2840 - results += '<div class="ui tiny middle aligned selection list">';
2841 - for (let entry of entries) {
2842 - results += '<div class="item"><div class="right floated content">' + (entry[1] ? '<i class="check green icon"></i>' : '<i class="times red icon"></i>') + '</div><div class="content">' + entry[0] + '</div></div>';
2843 - }
2844 - results += '</div>';
3107 + if (response.error != undefined) {
3108 + statusEl.html(response.error);
3109 + statusEl.css('color', 'red');
3110 + } else if (response?.ok[siteid] != undefined) {
3111 + let results = '';
3112 + if (response?.results[siteid] != undefined) {
3113 + let entries = Object.entries(response.results[siteid]);
3114 + results += '<div class="ui tiny middle aligned list">';
3115 + for (let entry of entries) {
3116 + results += '<div class="item"><div class="right floated content">' + (entry[1] ? '<i class="check green icon"></i>' : '<i class="times red icon"></i>') + '</div><div class="content">' + entry[0] + '</div></div>';
3117 + }
3118 + results += '</div>';
3119 + }
3120 + jQuery('div[siteId="' + siteid + '"] .installation-entries').html(results);
3121 + if (response.cost_tracker_installed_info != undefined) { // to support add to cost tracker pro.
3122 + jQuery('div[siteId="' + siteid + '"] .installation-entries').after(response.cost_tracker_installed_info);
3123 + }
3124 + statusEl.html('<span data-inverted="" data-position="left center" data-tooltip="' + MainWP.I18n.t('Installation completed successfully.') + '"><i class="check green icon"></i></span>');
3125 + } else if (response?.errors[siteid] === undefined) {
3126 + statusEl.html('<span data-inverted="" data-position="left center" data-tooltip="' + MainWP.I18n.t('Undefined error occurred. Please try again.') + '"><i class="times red icon"></i></span>');
3127 + } else {
3128 + statusEl.html('<span data-inverted="" data-position="left center" data-tooltip="' + response.errors[siteid][1] + '"><i class="times red icon"></i></span>');
3129 + }
3130 +
3131 + bulkInstallCurrentThreads--;
3132 + bulkInstallDone++;
3133 + jQuery('#plugintheme-installation-progress-modal .mainwp-modal-progress').progress('set progress', bulkInstallDone);
3134 + jQuery('#plugintheme-installation-progress-modal .mainwp-modal-progress').find('.label').html(bulkInstallDone + '/' + mainwpVars.bulkInstallTotal + ' ' + MainWP.I18n.t('Installed'));
3135 + mainwp_upload_bulk_start_next(type, urls, activatePlugin, overwrite);
2845 3136 }
2846 - jQuery('div[siteId="' + siteid + '"] .installation-entries').html(results);
2847 - if (response.cost_tracker_installed_info != undefined) { // to support add to cost tracker pro.
2848 - jQuery('div[siteId="' + siteid + '"] .installation-entries').after(response.cost_tracker_installed_info);
3137 + }(type, urls, activatePlugin, overwrite, siteToInstall), 'json');
3138 +};
3139 +
3140 +jQuery(function ($) {
3141 + jQuery(document).on('click', '.open-plugin-details-modal', (event) => {
3142 +
3143 + const $el = jQuery(event.currentTarget);
3144 +
3145 + const openwpp = $el.attr('open-wpplugin');
3146 + let openwpp_site = '';
3147 +
3148 + if (openwpp === 'yes') {
3149 + const findNext = $el
3150 + .closest('tr')
3151 + .next()
3152 + .find('tr[open-wpplugin-siteid]');
3153 +
3154 + if (findNext.length > 0) {
3155 + openwpp_site =
3156 + '&wpplugin=' + findNext.attr('open-wpplugin-siteid');
3157 + }
2849 3158 }
2850 - statusEl.html('<span data-inverted="" data-position="left center" data-tooltip="' + __('Installation completed successfully.', 'mainwp') + '"><i class="check green icon"></i></span>');
2851 - } else if (response?.errors[siteid] != undefined) {
2852 - statusEl.html('<span data-inverted="" data-position="left center" data-tooltip="' + response.errors[siteid][1] + '"><i class="times red icon"></i></span>');
2853 - } else {
2854 - statusEl.html('<span data-inverted="" data-position="left center" data-tooltip="' + __('Undefined error occurred. Please try again.', 'mainwp') + '"><i class="times red icon"></i></span>');
2855 - }
2856 3159
2857 - bulkInstallCurrentThreads--;
2858 - bulkInstallDone++;
2859 - jQuery('#plugintheme-installation-progress-modal .mainwp-modal-progress').progress('set progress', bulkInstallDone);
2860 - jQuery('#plugintheme-installation-progress-modal .mainwp-modal-progress').find('.label').html(bulkInstallDone + '/' + mainwpVars.bulkInstallTotal + ' ' + __('Installed'));
2861 - mainwp_upload_bulk_start_next(type, urls, activatePlugin, overwrite);
3160 + $('#mainwp-plugin-details-modal')
3161 + .modal({
3162 + onHide: function () { },
3163 + onShow: () => {
3164 + $('#mainwp-plugin-details-modal')
3165 + .find('.ui.embed')
3166 + .embed({
3167 + source: 'WP',
3168 + url: $el.attr('href') + openwpp_site,
3169 + });
3170 + }
3171 + })
3172 + .modal('show');
3173 +
3174 + return false;
3175 + });
3176 +});
3177 +
3178 +
3179 +/**
3180 + *
3181 + * Widget plugins/themes changes history
3182 + *
3183 + */
3184 +
3185 +let pluginChangesLoadData = {};
3186 +let themeChangesLoadData = {};
3187 +
3188 +jQuery(function ($) {
3189 +
3190 + $(document).on('click', '.mainwp-show-history', function (e) {
3191 +
3192 + e.preventDefault();
3193 + e.stopPropagation();
3194 +
3195 + const view = $(this).attr('history-view');
3196 + let parent = false;
3197 + let type = 'plugin'; // default.
3198 + let title = '';
3199 + let info = '';
3200 + let name = '';
3201 + let slug = '';
3202 + let siteId = 0;
3203 +
3204 + switch (view) {
3205 + case 'update-plugins-individual':
3206 + parent = $(this).closest('.plugins-bulk-updates');
3207 + siteId = $(parent).attr('site_id');
3208 + info = $(parent).attr('site_name') + ' (' + $(parent).attr('site_url') + ') ' + $(parent).attr('tz-info');
3209 + title = $(this).closest('tr').attr('plugin_name');
3210 + slug = decodeURIComponent($(this).closest('tr').attr('plugin_slug'));
3211 + name = $(this).closest('tr').attr('plugin_name');
3212 + break;
3213 + case 'update-themes-individual':
3214 + parent = $(this).closest('.themes-bulk-updates');
3215 + siteId = $(parent).attr('site_id');
3216 + info = $(parent).attr('site_name') + ' (' + $(parent).attr('site_url') + ') ' + $(parent).attr('tz-info');
3217 + title = $(this).closest('tr').attr('theme_name');
3218 + slug = $(this).closest('tr').attr('theme_slug');
3219 + name = $(this).closest('tr').attr('theme_name');
3220 + type = 'theme';
3221 + break;
3222 + case 'manage-plugins-per-sites':
3223 + case 'manage-plugins-per-items':
3224 + parent = $(this).closest('.mainwp-manage-plugin-item-website');
3225 + title = $(parent).attr('plugin-name');
3226 + info = $(parent).attr('site-name') + ' (' + $(parent).attr('site-url') + ') ' + $(parent).attr('tz-info');
3227 + slug = decodeURIComponent($(parent).attr('plugin-slug'));
3228 + siteId = $(parent).attr('site-id');
3229 + break;
3230 + case 'manage-themes-per-sites':
3231 + case 'manage-themes-per-items':
3232 + parent = $(this).closest('.mainwp-manage-theme-item-website');
3233 + title = $(parent).attr('theme-name');
3234 + name = $(parent).attr('theme-name');
3235 + info = $(parent).attr('site-name') + ' (' + $(parent).attr('site-url') + ') ' + $(parent).attr('tz-info');
3236 + slug = decodeURIComponent($(parent).attr('theme-slug'));
3237 + siteId = $(parent).attr('site-id');
3238 + type = 'theme';
3239 + break;
3240 + case 'widget-plugins':
3241 + parent = $(this).closest('.row-manage-item');
3242 + title = $(parent).attr('plugin-name');
3243 + info = $('#mainwp-widget-active-plugins').attr('site-info');
3244 + slug = $(parent).attr('plugin-slug');
3245 + siteId = $('#mainwp-widget-active-plugins').attr('site-id');
3246 + break;
3247 + case 'widget-themes':
3248 + parent = $(this).closest('.row-manage-item');
3249 + title = $(parent).find('.themeName').val();
3250 + info = $('#mainwp-widget-inactive-themes').attr('site-info');
3251 + slug = $(parent).find('.themeSlug').val();
3252 + name = $(parent).find('.themeName').val();
3253 + siteId = $('#mainwp-widget-inactive-themes').attr('site-id');
3254 + type = 'theme';
3255 + break;
3256 + case 'update-plugin-per-item':
3257 + parent = $(this).closest('tr');
3258 + siteId = $(parent).attr('site_id');
3259 + info = $(parent).attr('site_name') + ' (' + $(parent).attr('site_url') + ') ' + $(parent).attr('tz-info');
3260 + title = $(parent).attr('plugin_name');
3261 + slug = decodeURIComponent($(parent).attr('plugin_slug'));
3262 + break;
3263 + case 'update-theme-per-item':
3264 + parent = $(this).closest('tr');
3265 + siteId = $(parent).attr('site_id');
3266 + info = $(parent).attr('site_name') + ' (' + decodeURIComponent($(parent).attr('site_url')) + ') ' + $(parent).attr('tz-info');
3267 + title = $(parent).attr('theme_name');
3268 + name = $(parent).attr('theme_name');
3269 + slug = decodeURIComponent($(parent).attr('theme_slug'));
3270 + type = 'theme';
3271 + break;
3272 + case 'update-plugin-per-site': // NOSONAR - same as above.
3273 + parent = $(this).closest('.plugins-bulk-updates');
3274 + siteId = $(parent).attr('site_id');
3275 + info = $(parent).attr('site_name') + ' (' + $(parent).attr('site_url') + ') ' + $(parent).attr('tz-info');
3276 + title = $(this).closest('tr').attr('plugin_name');
3277 + slug = decodeURIComponent($(this).closest('tr').attr('plugin_slug'));
3278 + name = $(this).closest('tr').attr('plugin_name');
3279 + break;
3280 + case 'update-theme-per-site': // NOSONAR - same above.
3281 + parent = $(this).closest('.themes-bulk-updates');
3282 + siteId = $(parent).attr('site_id');
3283 + info = $(parent).attr('site_name') + ' (' + $(parent).attr('site_url') + ') ' + $(parent).attr('tz-info');
3284 + title = $(this).closest('tr').attr('theme_name');
3285 + slug = $(this).closest('tr').attr('theme_slug');
3286 + name = $(this).closest('tr').attr('theme_name');
3287 + type = 'theme';
3288 + break;
3289 + case 'update-plugin-per-tag':
3290 + parent = $(this).closest('.plugins-bulk-updates');
3291 + siteId = $(parent).attr('site_id');
3292 + info = $(parent).attr('site_name') + ' (' + $(parent).attr('site_url') + ') ' + $(parent).attr('tz-info');
3293 + title = $(this).closest('tr').attr('plugin_name');
3294 + slug = decodeURIComponent($(this).closest('tr').attr('plugin_slug'));
3295 + break;
3296 + case 'update-theme-per-tag':
3297 + parent = $(this).closest('.themes-bulk-updates');
3298 + siteId = $(parent).attr('site_id');
3299 + info = $(parent).attr('site_name') + ' (' + $(parent).attr('site_url') + ') ' + $(parent).attr('tz-info');
3300 + title = $(this).closest('tr').attr('theme_name');
3301 + name = $(this).closest('tr').attr('theme_name');
3302 + slug = $(this).closest('tr').attr('theme_slug');
3303 + type = 'theme';
3304 + break;
3305 + }
3306 +
3307 + if (type === 'plugin') {
3308 + pluginChangesLoadData = mainwp_secure_data({
3309 + action: 'mainwp_changes_logs_get_item_changes',
3310 + type: 'plugin',
3311 + slug: slug,
3312 + siteId: siteId,
3313 + from_date: '' // current date.
3314 + });
3315 + } else if (type === 'theme') {
3316 + themeChangesLoadData = mainwp_secure_data({
3317 + action: 'mainwp_changes_logs_get_item_changes',
3318 + type: 'theme',
3319 + slug: slug,
3320 + siteId: siteId,
3321 + name: name,
3322 + from_date: '' // current date.
3323 + });
3324 + }
3325 +
3326 + $('#mainwp-plugin-theme-history-changes-modal').modal({
3327 + onHide: function () {
3328 + },
3329 + onShow: function () {
3330 + mainwp_changes_history_box_init(type, title, info);
3331 + jQuery('#mainwp-plugin-theme-history-changes-modal').find('.content.ui').html('<div class="ui active centered inline loader history-actions-loading"></div>');
3332 + mainwp_item_changes_load();
3333 + }
3334 + }).modal('show');
3335 + });
3336 +});
3337 +
3338 +let mainwp_changes_history_box_init = function (type, title, info) {
3339 + const hd = jQuery('#mainwp-plugin-theme-history-changes-modal > div.header');
3340 + hd.find('.main-text').text(title + ' ' + MainWP.I18n.t('History')); // safe for escape.
3341 + hd.find('.sub.header').text(info).show();
3342 + jQuery('#mainwp-plugin-theme-history-changes-modal').attr('history-type', type);
3343 + jQuery('#mainwp-plugin-theme-history-changes-modal').find('.scrolling.content').html('');
3344 +}
3345 +
3346 +let mainwp_item_changes_load = function (btnObj, load_more_date = '') {
3347 +
3348 + let md = jQuery('#mainwp-plugin-theme-history-changes-modal');
3349 + let parentContent = false;
3350 + if (btnObj) {
3351 + parentContent = jQuery(btnObj).closest('.ui.accordion').find('.ui.content');
3352 + } else {
3353 + parentContent = jQuery(md).find('.scrolling.content')
2862 3354 }
2863 - }(type, urls, activatePlugin, overwrite, siteToInstall), 'json');
2864 -};
2865 3355
2866 -jQuery(function ($) {
2867 - jQuery(document).on('click', '.open-plugin-details-modal', function () {
2868 - let itemDetail = this;
3356 + jQuery(md).find('.actions .col-left').html('');
3357 + jQuery(md).find('.actions .col-right').html('');
2869 3358
2870 - let openwpp = jQuery(this).attr('open-wpplugin');
2871 - let openwpp_site = '';
2872 - if (typeof openwpp != "undefined" && 'yes' == openwpp) {
2873 - let findNext = jQuery(this).closest('tr').next().find('tr[open-wpplugin-siteid]');
2874 - if (findNext.length > 0) {
2875 - openwpp_site = '&wpplugin=' + jQuery(findNext).attr('open-wpplugin-siteid');
2876 - }
3359 + const type = jQuery(md).attr('history-type');
3360 + let load_more = false;
3361 +
3362 + // set load date if provided
3363 + if (typeof load_more_date === 'string' && load_more_date !== '') {
3364 + if ('theme' === type) {
3365 + themeChangesLoadData.from_date = load_more_date;
3366 + } else {
3367 + pluginChangesLoadData.from_date = load_more_date;
3368 + }
3369 + load_more = true;
2877 3370 }
2878 - $('#mainwp-plugin-details-modal').modal({
2879 - onHide: function () {
2880 - },
2881 - onShow: function () {
2882 - $('#mainwp-plugin-details-modal').find('.ui.embed').embed({
2883 - source: 'WP',
2884 - url: $(itemDetail).attr('href') + openwpp_site,
2885 - });
2886 - }
2887 - }).modal('show');
3371 +
3372 + let data = 'plugin' === type ? pluginChangesLoadData : themeChangesLoadData;
3373 +
3374 +
3375 + jQuery.post(ajaxurl, data, function (response) { // NOSONAR - complex.
3376 + jQuery(md).find('.history-actions-loading').remove();
3377 + if (response?.error) {
3378 + if (parentContent) {
3379 + let err_content = '<div class="ui message red">' + response.error + '</div>';
3380 + jQuery(parentContent).html(err_content);
3381 + }
3382 + } else if (response?.list) {
3383 + if (response.list.length == 0) {
3384 + let msg = MainWP.I18n.t('This plugin has no recorded activity in Dashboard Insights.');
3385 + if ('theme' === type) {
3386 + msg = MainWP.I18n.t('This theme has no recorded activity in Dashboard Insights.');
3387 + }
3388 + if (parentContent) {
3389 + let msg_content = '<div class="ui info message">' + msg + '</div>';
3390 + jQuery(parentContent).html(msg_content);
3391 + }
3392 + } else {
3393 + let content = '';
3394 + Object.entries(response.list).forEach(([indexdt, records]) => {
3395 + const dt = records[0].date;
3396 + content += `<div class="ui accordion" data-date="${indexdt}">
3397 + <div class="title" format-date="${dt}">
3398 + <div class="ui container">
3399 + <div class="ui grid">
3400 + <div class="ten wide column middle aligned">
3401 + <i class="dropdown icon"></i>
3402 + ${dt}
3403 + </div>
3404 + <div class="six wide column right aligned">
3405 + <button type="button" class="ui circular blue mini button mainwp-day-history-switch-view">` + MainWP.I18n.t('Day History') + `</button> <button class="ui basic mini button actions-count1">${records.length} ` + MainWP.I18n.t('Actions') + `</button>
3406 + </div>
3407 + </div>
3408 + </div>
3409 + </div>
3410 + <div class="content ui list">`;
3411 + records.forEach(record => {
3412 + content += `<div class="item" log-id="${record.details.log_id}">
3413 + <div class="ui grid">
3414 + <div class="eight wide column middle aligned">
3415 + <i class="` + get_icon_history_event(record.details.action) + ` icon"></i>
3416 + <span class="ui text ` + get_color_changes_event(record.details.action) + `">${record.details.event}</span> ` + MainWP.I18n.t('by') + ` <strong>${record.details.author_name}</strong> ` + MainWP.I18n.t('from') + `
3417 + <strong>${record.details.source}</strong>
3418 + </div>
3419 + <div class="six wide column middle aligned">
3420 + ` + (record.details?.old_version && record.details?.version ? record.details.old_version + '&rarr;' + record.details.version : '') + `
3421 + </div>
3422 + <div class="two wide column right aligned">
3423 + ${record.details.at_hour}
3424 + </div>
3425 + </div>
3426 + </div>`;
3427 + });
3428 + content += `</div>
3429 + </div>`;
3430 + });
3431 +
3432 + if ('' !== content) {
3433 + let accordWrapper = jQuery("<div>", {
3434 + id: "change-history-according-wrapper",
3435 + html: content
3436 + });
3437 +
3438 + let name_title = '';
3439 +
3440 + if ((data?.name || data?.slug) && response?.name_title) {
3441 + name_title = response.name_title;
3442 + }
3443 +
3444 + if (name_title != '') {
3445 + jQuery(md).find('.ui.header .main-text').text(name_title + ' ' + MainWP.I18n.t('History'));
3446 + }
3447 +
3448 + if (load_more) {
3449 + jQuery(md).find('.scrolling.content').append(accordWrapper);
3450 + } else {
3451 + jQuery(md).find('.scrolling.content').html(accordWrapper);
3452 + }
3453 +
3454 + jQuery('#change-history-according-wrapper .ui.accordion').accordion({ exclusive: true });
3455 +
3456 + jQuery('.mainwp-day-history-switch-view').off('click.accordionFix').on('click.accordionFix', function (e) {
3457 + e.preventDefault();
3458 + e.stopPropagation(); // now it runs before ancestor handlers
3459 + dayHistory_SwitchViewHandler(this);
3460 + return false;
3461 + });
3462 + }
3463 +
3464 + if (response?.onward_date) {
3465 + jQuery(md).find('.actions .col-left').html('Data available from ' + response.onward_date + ' onward.');
3466 + }
3467 + if (response?.more_date) {
3468 + jQuery(md).find('.actions .col-right').html('<a href="javascript:void(0);" onclick="mainwp_item_changes_load(false,\'' + (response.more_date ?? get_local_date_string()) + '\');return false;">' + MainWP.I18n.t('Load More') + '</a>');
3469 + }
3470 + }
3471 + } else if (parentContent) {
3472 + let err_content = '<div class="ui message red">' + MainWP.I18n.t('Undefined error occurred. Please try again.') + '</div>';
3473 + jQuery(parentContent).html(err_content);
3474 + }
3475 + }, 'json');
3476 +}
3477 +
3478 +let get_icon_history_event = function (act) {
3479 + let icon = '';
3480 +
3481 + if (act === 'delete' || act === 'deleted') {
3482 + icon = 'trash red';
3483 + } else if (act === 'deactivated' || act === 'deactivate') {
3484 + icon = 'toggle off red';
3485 + } else if (act === 'activated' || act === 'activate') {
3486 + icon = 'toggle on green';
3487 + } else if (act === 'updated' || act === 'update') {
3488 + icon = 'sync orange';
3489 + } else if (act === 'installed' || act === 'install') {
3490 + icon = 'download teal';
3491 + } else {
3492 + icon = 'circle grey';
3493 + }
3494 +
3495 + return icon;
3496 +}
3497 +
3498 +let get_color_changes_event = function (act) {
3499 + const actColorMap = {
3500 + red: ['deleted', 'removed', 'revoked', 'delete', 'deactivated', 'disabled', 'suspended', 'deactivate'],
3501 + orange: ['updated', 'modified', 'update'],
3502 + grey: ['opened'],
3503 + blue: ['logged-in', 'logged-out'],
3504 + teal: ['sync', 'installed', 'install', 'uploaded'],
3505 + green: ['activated', 'activate', 'created', 'published', 'enabled', 'added']
3506 + };
3507 +
3508 + let color = '';
3509 +
3510 + for (const [c, acts] of Object.entries(actColorMap)) {
3511 + if (acts.includes(act)) {
3512 + color = c;
3513 + break;
3514 + }
3515 + }
3516 + return color;
3517 +}
3518 +
3519 +let dayHistory_SwitchViewHandler = function (btn) {
3520 +
3521 + const parent = jQuery(btn).closest('.ui.accordion');
3522 + const his_date = jQuery(btn).closest('.title').attr('format-date');
3523 +
3524 + jQuery(btn).closest('.title').hasClass('active') || jQuery(btn).closest('.title').trigger('click');
3525 +
3526 + jQuery(parent).find('.content.ui').html('<div class="ui active centered inline loader history-actions-loading"></div>');
3527 +
3528 + const dt = jQuery(parent).data('date');
3529 + let md = jQuery('#mainwp-plugin-theme-history-changes-modal');
3530 + const type = jQuery(md).attr('history-type');
3531 +
3532 + let siteId = ('plugin' === type ? pluginChangesLoadData.siteId : themeChangesLoadData.siteId) || 0;
3533 +
3534 + let data = mainwp_secure_data({
3535 + action: 'mainwp_changes_logs_get_item_changes',
3536 + type: type,
3537 + target_date: dt,
3538 + siteId: siteId
3539 + });
3540 +
3541 + jQuery.post(ajaxurl, data, function (response) { // NOSONAR - complex.
3542 +
3543 + jQuery(parent).find('.history-actions-loading').remove();
3544 +
3545 + let dayContent = jQuery(parent).find('.content');
3546 +
3547 + if (response.error != undefined) {
3548 + dayContent.append('<div class="ui message red changes-history-status">' + response.error + '</div>');
3549 + } else if (response?.list) {
3550 + if (response.list.length == 0) {
3551 + let msg = MainWP.I18n.t('This plugin has no recorded activity in Dashboard Insights.');
3552 + if ('theme' === type && '' === dt) {
3553 + msg = MainWP.I18n.t('This theme has no recorded activity in Dashboard Insights.');
3554 + } else if ('' !== dt) {
3555 + if ('plugin' === type) {
3556 + msg = MainWP.I18n.t('No history changes found for the plugin on this day.');
3557 + } else {
3558 + msg = MainWP.I18n.t('No history changes found for the theme on this day.');
3559 + }
3560 + }
3561 + dayContent.append('<div class="ui message changes-history-status">' + msg + '</div>');
3562 + } else {
3563 + let content = '';
3564 + let count_acts = 0;
3565 + Object.entries(response.list).forEach(([idxslug, records]) => {
3566 + const name = records[0].name;
3567 + content += `<div class="ui accordion list-all-actions-in-day" data-slug="${records[0].item_slug}" data-name="${records[0].item_name}" data-siteid="${records[0].site_id}">
3568 + <div class="title">
3569 + <div class="ui container">
3570 + <div class="ui grid">
3571 + <div class="ten wide column middle aligned">
3572 + <i class="dropdown icon"></i>
3573 + ${name}
3574 + </div>
3575 + <div class="six wide column right aligned">
3576 + <button type="button" class="ui circular blue mini button mainwp-list-history-switch-view">` + ('plugin' === type ? MainWP.I18n.t('Plugin History') : MainWP.I18n.t('Theme History')) + `</button> <button class="ui basic mini button ">${records.length} ` + MainWP.I18n.t('Actions') + `</button>
3577 + </div>
3578 + </div>
3579 + </div>
3580 + </div>
3581 + <div class="content ui list">`;
3582 + records.forEach(record => {
3583 + content += `<div class="item" log-id="${record.details.log_id}">
3584 + <div class="ui grid">
3585 + <div class="eight wide column middle aligned">
3586 + <i class="` + get_icon_history_event(record.details.action) + ` icon"></i>
3587 + <span class="ui text ` + get_color_changes_event(record.details.action) + `">${record.details.event}</span> ` + MainWP.I18n.t('by') + ` <strong>${record.details.author_name}</strong> ` + MainWP.I18n.t('from') + `
3588 + <strong>${record.details.source}</strong>
3589 + </div>
3590 + <div class="six wide column middle aligned">
3591 + ` + (record.details?.old_version && record.details?.version ? record.details.old_version + '&rarr;' + record.details.version : '') + `
3592 + </div>
3593 + <div class="two wide column right aligned">
3594 + ${record.details.at_hour}
3595 + </div>
3596 + </div>
3597 + </div>`;
3598 + count_acts++;
3599 + });
3600 + content += `</div>
3601 + </div>`;
3602 + });
3603 +
3604 + if ('' !== content) {
3605 + jQuery(md).find('.ui.header .main-text').text(his_date + ' ' + MainWP.I18n.t('History'));
3606 + let accordWrapper = jQuery("<div>", {
3607 + id: "change-history-according-wrapper",
3608 + html: content
3609 + });
3610 + jQuery(md).find('.scrolling.content').html(accordWrapper);
3611 + jQuery('#change-history-according-wrapper .ui.accordion').accordion({ exclusive: true });
3612 +
3613 + jQuery('.mainwp-list-history-switch-view').off('click.accordionFix2').on('click.accordionFix2', function (e) {
3614 + e.preventDefault();
3615 + e.stopPropagation(); // now it runs before ancestor handlers
3616 + listHistory_SwitchViewHandler(this);
3617 + return false;
3618 + });
3619 + }
3620 + }
3621 + } else {
3622 + dayContent.html('<div class="ui message red changes-history-status">' + MainWP.I18n.t('Undefined error occurred. Please try again.') + '</div>');
3623 + }
3624 + }, 'json');
3625 +
2888 3626 return false;
2889 - });
2890 -});
3627 +}
2891 3628
2892 3629
3630 +let listHistory_SwitchViewHandler = function (btn) {
3631 +
3632 + const parent = jQuery(btn).closest('.ui.accordion');
3633 +
3634 + jQuery(btn).closest('.title').hasClass('active') || jQuery(btn).closest('.title').trigger('click');
3635 +
3636 + jQuery(parent).find('.content.ui').html('<div class="ui active centered inline loader history-actions-loading"></div>');
3637 +
3638 + let md = jQuery('#mainwp-plugin-theme-history-changes-modal');
3639 + const type = jQuery(md).attr('history-type');
3640 +
3641 + if ('theme' === type) {
3642 + themeChangesLoadData.slug = jQuery(parent).data('slug');
3643 + themeChangesLoadData.name = jQuery(parent).data('name');
3644 + themeChangesLoadData.siteId = jQuery(parent).data('siteid');
3645 + themeChangesLoadData.from_date = '';
3646 + } else {
3647 + pluginChangesLoadData.slug = jQuery(parent).data('slug');;
3648 + pluginChangesLoadData.siteId = jQuery(parent).data('siteid');;
3649 + pluginChangesLoadData.from_date = '';
3650 + }
3651 + mainwp_item_changes_load(btn);
3652 +}
3653 +
3654 +
2893 3655 /**
2894 3656 * Install check plugins.
2895 3657 *
2896 3658 */
2897 3659
2898 -window.mainwp_install_check_plugin_prepare = function (slug) {
2899 - let selected = jQuery("input[name='install_checker[]']:checked");
2900 - if (selected.length == 0) {
2901 - feedback('mainwp-message-zone-install', __('Please select website to install plugin.'), 'yellow');
2902 - return;
2903 - } else {
2904 - selected.each(function () {
2905 - jQuery(this).closest('.siteBulkInstall').attr('status', 'queue');
3660 +globalThis.mainwp_install_check_plugin_prepare = function (slug) {
3661 + let selected = jQuery("input[name='install_checker[]']:checked");
3662 + if (selected.length == 0) {
3663 + feedback('mainwp-message-zone-install', MainWP.I18n.t('Please select website to install plugin.'), 'yellow');
3664 + return;
3665 + } else {
3666 + selected.each(function () {
3667 + jQuery(this).closest('.siteBulkInstall').attr('status', 'queue');
3668 + });
3669 + }
3670 + jQuery('#mainwp-install-check-btn').addClass('disabled');
3671 + mainwp_set_message_zone('#mainwp-message-zone-install', '<i class="notched circle loading icon"></i> ', false, true); // false: not change the color class.
3672 + let data = mainwp_secure_data({
3673 + action: 'mainwp_preparebulkinstallcheckplugin',
3674 + slug: slug,
2906 3675 });
2907 - }
2908 - jQuery('#mainwp-install-check-btn').addClass('disabled');
2909 - mainwp_set_message_zone('#mainwp-message-zone-install', '<i class="notched circle loading icon"></i> ', false, true); // false: not change the color class.
2910 - let data = mainwp_secure_data({
2911 - action: 'mainwp_preparebulkinstallcheckplugin',
2912 - slug: slug,
2913 - });
2914 - jQuery.post(ajaxurl, data, function (response) {
2915 - mainwp_set_message_zone('#mainwp-message-zone-install');
2916 - mainwp_install_check_plugin_start_next(response.url);
2917 - }, 'json');
3676 + jQuery.post(ajaxurl, data, function (response) {
3677 + mainwp_set_message_zone('#mainwp-message-zone-install');
3678 + mainwp_install_check_plugin_start_next(response.url);
3679 + }, 'json');
2918 3680 };
2919 3681
2920 3682 let mainwp_install_check_plugin_start_next = function (url) {
2921 - while ((siteToInstall = jQuery('.siteBulkInstall[status="queue"]:first')) && (siteToInstall.length > 0) && (bulkInstallCurrentThreads < bulkInstallMaxThreads)) { // NOSONAR - modified outside the function.
2922 - mainwp_install_check_plugin_start_specific(url, siteToInstall);
2923 - }
3683 + while ((siteToInstall = jQuery('.siteBulkInstall[status="queue"]:first')) && (siteToInstall.length > 0) && (bulkInstallCurrentThreads < bulkInstallMaxThreads)) { // NOSONAR - modified outside the function.
3684 + mainwp_install_check_plugin_start_specific(url, siteToInstall);
3685 + }
2924 3686 };
2925 3687
2926 3688 let mainwp_install_check_plugin_start_specific = function (url, siteToInstall) {
2927 - bulkInstallCurrentThreads++;
3689 + bulkInstallCurrentThreads++;
2928 3690
2929 - siteToInstall.attr('status', 'progress');
2930 - siteToInstall.find('.queue').hide();
2931 - siteToInstall.find('.progress').show();
3691 + siteToInstall.attr('status', 'progress');
3692 + siteToInstall.find('.queue').hide();
3693 + siteToInstall.find('.progress').show();
2932 3694
2933 - let data = mainwp_secure_data({
2934 - action: 'mainwp_installbulkinstallplugintheme',
2935 - type: 'plugin',
2936 - url: url,
2937 - activatePlugin: 'true',
2938 - siteId: siteToInstall.attr('siteid')
2939 - });
3695 + let data = mainwp_secure_data({
3696 + action: 'mainwp_installbulkinstallplugintheme',
3697 + type: 'plugin',
3698 + url: url,
3699 + activatePlugin: 'true',
3700 + siteId: siteToInstall.attr('siteid')
3701 + });
2940 3702
2941 - jQuery.post(ajaxurl, data, function (url, siteToInstall) {
2942 - return function (response) {
2943 - siteToInstall.attr('status', 'done');
2944 - siteToInstall.find('.progress').hide();
3703 + jQuery.post(ajaxurl, data, function (url, siteToInstall) {
3704 + return function (response) {
3705 + siteToInstall.attr('status', 'done');
3706 + siteToInstall.find('.progress').hide();
2945 3707
2946 - let statusEl = siteToInstall.find('.status');
2947 - statusEl.show();
3708 + let statusEl = siteToInstall.find('.status');
3709 + statusEl.show();
2948 3710
2949 - if (response.error != undefined) {
2950 - statusEl.html(response.error);
2951 - statusEl.css('color', 'red');
2952 - } else if (response?.ok[siteToInstall.attr('siteid')]) {
2953 - statusEl.html('<span data-inverted="" data-position="left center" data-tooltip="' + __('Installation completed successfully.', 'mainwp') + '"><i class="check green icon"></i></span>');
2954 - } else if (response?.errors[siteToInstall.attr('siteid')]) {
2955 - statusEl.html('<span data-inverted="" data-position="left center" data-tooltip="' + response.errors[siteToInstall.attr('siteid')][1] + '"><i class="times red icon"></i></span>');
2956 - } else {
2957 - statusEl.html('<span data-inverted="" data-position="left center" data-tooltip="' + __('Undefined error occurred. Please try again.', 'mainwp') + '"><i class="times red icon"></i></span>');
2958 - }
3711 + if (response.error != undefined) {
3712 + statusEl.html(response.error);
3713 + statusEl.css('color', 'red');
3714 + } else if (response?.ok[siteToInstall.attr('siteid')]) {
3715 + statusEl.html('<span data-inverted="" data-position="left center" data-tooltip="' + MainWP.I18n.t('Installation completed successfully.') + '"><i class="check green icon"></i></span>');
3716 + } else if (response?.errors[siteToInstall.attr('siteid')]) {
3717 + statusEl.html('<span data-inverted="" data-position="left center" data-tooltip="' + response.errors[siteToInstall.attr('siteid')][1] + '"><i class="times red icon"></i></span>');
3718 + } else {
3719 + statusEl.html('<span data-inverted="" data-position="left center" data-tooltip="' + MainWP.I18n.t('Undefined error occurred. Please try again.') + '"><i class="times red icon"></i></span>');
3720 + }
2959 3721
2960 - bulkInstallCurrentThreads--;
2961 - bulkInstallDone++;
2962 - jQuery('#plugintheme-installation-progress-modal .mainwp-modal-progress').progress('set progress', bulkInstallDone);
2963 - jQuery('#plugintheme-installation-progress-modal .mainwp-modal-progress').find('.label').html(bulkInstallDone + '/' + mainwpVars.bulkInstallTotal + ' ' + __('Installed'));
2964 - mainwp_install_check_plugin_start_next(url);
2965 - }
2966 - }(url, siteToInstall), 'json');
3722 + bulkInstallCurrentThreads--;
3723 + bulkInstallDone++;
3724 + jQuery('#plugintheme-installation-progress-modal .mainwp-modal-progress').progress('set progress', bulkInstallDone);
3725 + jQuery('#plugintheme-installation-progress-modal .mainwp-modal-progress').find('.label').html(bulkInstallDone + '/' + mainwpVars.bulkInstallTotal + ' ' + MainWP.I18n.t('Installed'));
3726 + mainwp_install_check_plugin_start_next(url);
3727 + }
3728 + }(url, siteToInstall), 'json');
2967 3729 };
2968 3730
2969 3731 function isUrl(url) {
2970 - try {
2971 - new URL(url);
2972 - return true;
2973 - } catch (e) {
3732 + try {
3733 + new URL(url);
3734 + return true;
3735 + } catch (e) {
3736 + console.log(e);
3737 + }
2974 3738 return false;
2975 - }
2976 3739 }
2977 3740
3741 +function removeUrlParams(url, params) {
3742 + try {
3743 + const urlObj = new URL(url);
3744 + jQuery(params).each(function (idx, param) {
3745 + urlObj.searchParams.delete(param);
3746 + });
3747 + return urlObj.toString();
3748 + } catch (e) {
3749 + console.log(e);
3750 + }
3751 + return '';
3752 +}
3753 +
2978 3754 function setVisible(what, vis) {
2979 - if (vis) {
2980 - jQuery(what).show();
2981 - } else {
2982 - jQuery(what).hide();
2983 - }
3755 + if (vis) {
3756 + jQuery(what).show();
3757 + } else {
3758 + jQuery(what).hide();
3759 + }
2984 3760 }
3761 +
3762 +const mainwp_scrollToElement = () => {
3763 + jQuery('html,body').animate({
3764 + scrollTop: 0
3765 + }, 1000);
3766 +
3767 + return false;
3768 +}
3769 +
2985 3770 function setHtml(what, text, ptag) {
2986 - if (typeof ptag == "undefined")
2987 - ptag = true;
3771 + if (ptag === undefined)
3772 + ptag = true;
2988 3773
2989 - setVisible(what, true);
2990 - if (ptag)
2991 - jQuery(what).html('<span>' + text + '</span>');
2992 - else
2993 - jQuery(what).html(text);
2994 - scrollToElement(what);
3774 + setVisible(what, true);
3775 + if (ptag)
3776 + jQuery(what).html('<span>' + text + '</span>');
3777 + else
3778 + jQuery(what).html(text);
3779 + mainwp_scrollToElement(); // to fix js conflict error from some other add-ons.
2995 3780 }
2996 3781
2997 3782
2998 3783 /**
@@ -2999,277 +3784,302 @@
2999 3784 * Notes
3000 3785 */
3001 3786 jQuery(function () {
3002 3787
3003 - jQuery(document).on('click', '#mainwp-notes-cancel', function () {
3004 - jQuery('#mainwp-notes-status').html('');
3005 - jQuery('#mainwp-notes-status').removeClass('red green');
3006 - mainwp_notes_hide();
3007 - return false;
3008 - });
3788 + jQuery(document).on('click', '#mainwp-notes-cancel', function () {
3789 + jQuery('#mainwp-notes-status').html('');
3790 + jQuery('#mainwp-notes-status').removeClass('red green');
3791 + mainwp_notes_hide();
3792 + return false;
3793 + });
3009 3794
3010 - jQuery(document).on('click', '#mainwp-notes-save', function () {
3011 - let which = jQuery('#mainwp-which-note').val();
3012 - if (which == 'site') {
3013 - mainwp_notes_site_save();
3014 - } else if (which == 'theme') {
3015 - mainwp_notes_theme_save();
3016 - } else if (which == 'plugin') {
3017 - mainwp_notes_plugin_save();
3018 - } else if (which == 'client') {
3019 - mainwp_notes_client_save();
3020 - }
3021 - let newnote = jQuery('#mainwp-notes-note').val();
3022 - jQuery('#mainwp-notes-html').html(newnote);
3023 - return false;
3024 - });
3795 + jQuery(document).on('click', '#mainwp-notes-save', function () {
3796 + let which = jQuery('#mainwp-which-note').val();
3797 + if (which == 'site') {
3798 + mainwp_notes_site_save();
3799 + } else if (which == 'theme') {
3800 + mainwp_notes_theme_save();
3801 + } else if (which == 'plugin') {
3802 + mainwp_notes_plugin_save();
3803 + } else if (which == 'client') {
3804 + mainwp_notes_client_save();
3805 + }
3806 + return false;
3807 + });
3025 3808
3026 - jQuery(document).on('click', '.mainwp-edit-site-note', function () {
3027 - let id = jQuery(this).attr('id').substring(13);
3028 - let note = jQuery('#mainwp-notes-' + id + '-note').html();
3029 - jQuery('#mainwp-notes-html').html(note == '' ? __('No saved notes. Click the Edit button to edit site notes.') : note);
3030 - jQuery('#mainwp-notes-note').val(note);
3031 - jQuery('#mainwp-notes-websiteid').val(id);
3032 - jQuery('#mainwp-which-note').val('site'); // to fix conflict.
3033 - mainwp_notes_show();
3034 - return false;
3035 - });
3809 + jQuery(document).on('click', '.mainwp-edit-site-note', function () {
3810 + let id = jQuery(this).attr('id').substring(13);
3811 + let note = jQuery('#mainwp-notes-' + id + '-note').html();
3812 + jQuery('#mainwp-notes-html').html(note == '' ? MainWP.I18n.t('No saved notes. Click the Edit button to edit site notes.') : note);
3813 + jQuery('#mainwp-notes-note').val(note);
3814 + jQuery('#mainwp-notes-websiteid').val(id);
3815 + jQuery('#mainwp-which-note').val('site'); // to fix conflict.
3816 + mainwp_notes_show();
3817 + if (jQuery(this).attr('add-new')) {
3818 + jQuery('#mainwp-notes-edit').trigger("click");
3819 + }
3820 + return false;
3821 + });
3036 3822
3037 - jQuery(document).on('click', '#mainwp-notes-edit', function () {
3038 - jQuery('#mainwp-notes-html').hide();
3039 - jQuery('#mainwp-notes-editor').show();
3040 - jQuery(this).hide();
3041 - jQuery('#mainwp-notes-save').show();
3042 - jQuery('#mainwp-notes-status').html('');
3043 - jQuery('#mainwp-notes-status').removeClass('red green');
3044 - return false;
3045 - });
3046 - jQuery('#redirectForm').trigger("submit");
3047 - if (jQuery('div.ui.open-site-close-window').length > 0) {
3048 - setTimeout(function () {
3049 - window.close()
3050 - }, 3000);
3051 - }
3823 + jQuery(document).on('click', '#mainwp-notes-edit', function () {
3824 + jQuery('#mainwp-notes-html').hide();
3825 + jQuery('#mainwp-notes-editor').show();
3826 + jQuery(this).hide();
3827 + jQuery('#mainwp-notes-save').show();
3828 + jQuery('#mainwp-notes-status').html('');
3829 + jQuery('#mainwp-notes-status').removeClass('red green');
3830 + return false;
3831 + });
3832 + jQuery('#redirectForm').trigger("submit");
3833 + if (jQuery('div.ui.open-site-close-window').length > 0) {
3834 + setTimeout(function () {
3835 + globalThis.close()
3836 + }, 3000);
3837 + }
3052 3838 });
3053 3839
3054 -window.mainwp_notes_show = function (reloadClose) {
3055 - if (reloadClose) {
3056 - jQuery('#mainwp-notes-modal').modal({
3057 - onHide: function () {
3058 - window.location.href = location.href
3059 - }
3060 - }).modal('show');
3061 - } else {
3062 - jQuery('#mainwp-notes-modal').modal({ closable: false }).modal('show');
3063 - }
3840 +globalThis.mainwp_notes_show = function (reloadClose) {
3841 + if (reloadClose) {
3842 + jQuery('#mainwp-notes-modal').modal({
3843 + onHide: function () {
3844 + mainwp_forceReload();
3845 + }
3846 + }).modal('show');
3847 + } else {
3848 + jQuery('#mainwp-notes-modal').modal({ closable: false }).modal('show');
3849 + }
3064 3850
3065 - jQuery('#mainwp-notes-html').show();
3066 - jQuery('#mainwp-notes-editor').hide();
3067 - jQuery('#mainwp-notes-save').hide();
3068 - jQuery('#mainwp-notes-edit').show();
3851 + jQuery('#mainwp-notes-html').show();
3852 + jQuery('#mainwp-notes-editor').hide();
3853 + jQuery('#mainwp-notes-save').hide();
3854 + jQuery('#mainwp-notes-edit').show();
3069 3855 };
3070 3856 let mainwp_notes_hide = function () {
3071 - jQuery('#mainwp-notes-modal').modal('hide');
3857 + jQuery('#mainwp-notes-modal').modal('hide');
3072 3858 };
3073 3859 let mainwp_notes_site_save = function () {
3074 - let normalid = jQuery('#mainwp-notes-websiteid').val();
3075 - let newnote = jQuery('#mainwp-notes-note').val();
3076 - newnote = newnote.replace(/(?:\r\n|\r|\n)/g, '<br>');
3077 - let data = mainwp_secure_data({
3078 - action: 'mainwp_notes_save',
3079 - websiteid: normalid,
3080 - note: newnote
3081 - });
3860 + let normalid = jQuery('#mainwp-notes-websiteid').val();
3861 + let newnote = jQuery('#mainwp-notes-note').val();
3862 + newnote = newnote.replaceAll(/\r\n|\r|\n/g, '<br>');
3863 + let data = mainwp_secure_data({
3864 + action: 'mainwp_notes_save',
3865 + websiteid: normalid,
3866 + note: newnote
3867 + });
3082 3868
3083 - jQuery('#mainwp-notes-status').html('<i class="notched circle loading icon"></i> ' + __('Saving note. Please wait...')).show();
3869 + jQuery('#mainwp-notes-status').html('<i class="notched circle loading icon"></i> ' + MainWP.I18n.t('Saving note. Please wait...')).show();
3084 3870
3085 - jQuery.post(ajaxurl, data, function (response) {
3086 - if (response.error != undefined) {
3087 - jQuery('#mainwp-notes-status').html(response.error).addClass('red');
3088 - } else if (response.result == 'SUCCESS') {
3089 - jQuery('#mainwp-notes-status').html(__('Note saved successfully.')).addClass('green');
3090 - if (jQuery('#mainwp-notes-' + normalid + '-note').length > 0) {
3091 - jQuery('#mainwp-notes-' + normalid + '-note').html(jQuery('#mainwp-notes-note').val());
3092 - }
3093 - } else {
3094 - jQuery('#mainwp-notes-status').html(__('Undefined error occured while saving your note!')).addClass('red');
3095 - }
3096 - }, 'json');
3871 + jQuery.post(ajaxurl, data, function (response) {
3872 + if (response.error != undefined) {
3873 + jQuery('#mainwp-notes-status').html(response.error).addClass('red');
3874 + } else if (response.result == 'SUCCESS') {
3875 + jQuery('#mainwp-notes-status').html(MainWP.I18n.t('Note saved successfully.')).addClass('green');
3876 + if (jQuery('#mainwp-notes-' + normalid + '-note').length > 0) {
3877 + jQuery('#mainwp-notes-' + normalid + '-note').html(response?.esc_note_content ?? '');
3878 + jQuery('#mainwp-notes-html').html(response?.esc_note_content ?? '');
3879 + }
3880 + } else {
3881 + jQuery('#mainwp-notes-status').html(MainWP.I18n.t('Undefined error occurred while saving your note!')).addClass('red');
3882 + }
3883 + }, 'json');
3097 3884
3098 - setTimeout(function () {
3099 - jQuery('#mainwp-notes-status').fadeOut(300);
3100 - }, 3000);
3885 + setTimeout(function () {
3886 + jQuery('#mainwp-notes-status').fadeOut(300);
3887 + }, 3000);
3101 3888
3102 - jQuery('#mainwp-notes-html').show();
3103 - jQuery('#mainwp-notes-editor').hide();
3104 - jQuery('#mainwp-notes-save').hide();
3105 - jQuery('#mainwp-notes-edit').show();
3889 + jQuery('#mainwp-notes-html').show();
3890 + jQuery('#mainwp-notes-editor').hide();
3891 + jQuery('#mainwp-notes-save').hide();
3892 + jQuery('#mainwp-notes-edit').show();
3106 3893
3107 3894 };
3108 3895
3109 -window.getErrorMessage = function (pError, msgOnly) { // NOSONAR - complex.
3110 - if (pError.message == 'HTTPERROR') {
3111 - return __('HTTP error') + '! ' + pError.extra;
3112 - } else if (pError.message == 'NOMAINWP' || pError == 'NOMAINWP') {
3113 - return mainwp_js_get_error_not_detected_connect();
3114 - } else if (pError.message == 'ERROR') {
3115 - return 'ERROR' + ((pError.extra != '') && (pError.extra != undefined) ? ': ' + pError.extra : '');
3116 - } else if (pError.message == 'WPERROR') {
3117 - let extrMsg = (pError.extra != '') && (pError.extra != undefined) ? pError.extra : '';
3118 - if (msgOnly != undefined && msgOnly && extrMsg != '') {
3119 - return extrMsg;
3896 +globalThis.getErrorMessage = function (pError, msgOnly) { // NOSONAR - complex.
3897 + if (pError.message == 'HTTPERROR') {
3898 + return MainWP.I18n.t('HTTP error') + '! ' + pError.extra;
3899 + } else if (pError.message == 'NOMAINWP' || pError == 'NOMAINWP') {
3900 + return mainwp_js_get_error_not_detected_connect();
3901 + } else if (pError.message == 'ERROR') {
3902 + return 'ERROR' + ((pError.extra != '') && (pError.extra != undefined) ? ': ' + pError.extra : '');
3903 + } else if (pError.message == 'WPERROR') {
3904 + let extrMsg = (pError.extra != '') && (pError.extra != undefined) ? pError.extra : '';
3905 + if (msgOnly != undefined && msgOnly && extrMsg != '') {
3906 + return extrMsg;
3907 + } else {
3908 + return MainWP.I18n.t('ERROR on the child site') + ': ' + extrMsg;
3909 + }
3910 +
3911 + } else if (pError.message != undefined && pError.message != '') {
3912 + return pError.message;
3120 3913 } else {
3121 - return __('ERROR on the child site') + ': ' + extrMsg;
3914 + return pError;
3122 3915 }
3123 -
3124 - } else if (pError.message != undefined && pError.message != '') {
3125 - return pError.message;
3126 - } else {
3127 - return pError;
3128 - }
3129 3916 };
3130 3917
3131 -window.getErrorMessageInfo = function (repError, outputType) { // NOSONAR - complex.
3132 - let msg = '';
3133 - let msgUI = '<i class="red times icon"></i>';
3918 +globalThis.getErrorMessageInfo = function (repError, outputType) { // NOSONAR - complex.
3919 + let msg = '';
3920 + let msgUI = '<i class="red times icon"></i>';
3134 3921
3135 - if (repError.errorCode != undefined && repError.errorCode == 'SUSPENDED_SITE') {
3136 - msg = __('Suspended site.');
3137 - msgUI = '<span data-inverted="" data-position="left center" data-tooltip="' + __('Suspended site.') + '"><i class="pause circular yellow inverted icon"></i></span>';
3138 - }
3922 + if (repError.errorCode != undefined && repError.errorCode == 'SUSPENDED_SITE') {
3923 + msg = MainWP.I18n.t('Suspended site.');
3924 + msgUI = '<span data-inverted="" data-position="left center" data-tooltip="' + MainWP.I18n.t('Suspended site.') + '"><i class="pause yellow icon"></i></span>';
3925 + }
3139 3926
3140 - if (repError.errorCode != undefined && repError.errorCode == 'MAINWP_NOTICE') {
3141 - if (repError.message != undefined) {
3142 - msg = repError.message;
3143 - msgUI = '<span data-inverted="" data-position="left center" data-tooltip="' + msg + '"><i class="pause circular yellow inverted icon"></i></span>';
3927 + if (repError.errorCode != undefined && repError.errorCode == 'MAINWP_NOTICE') {
3928 + if (repError.message != undefined) {
3929 + msg = repError.message;
3930 + msgUI = '<span data-inverted="" data-position="left center" data-tooltip="' + msg + '"><i class="pause circular yellow inverted icon"></i></span>';
3931 + }
3144 3932 }
3145 - }
3146 3933
3147 - if (msg == '') {
3148 - msg = getErrorMessage(repError);
3934 + if (msg == '') {
3935 + msg = getErrorMessage(repError);
3149 3936
3150 - if (repError.message == 'NOMAINWP' || repError == 'NOMAINWP') {
3151 - msg = mainwp_js_get_error_not_detected_connect();
3937 + if (repError.message == 'NOMAINWP' || repError == 'NOMAINWP') {
3938 + msg = mainwp_js_get_error_not_detected_connect();
3939 + }
3940 +
3941 + if (msg != '') {
3942 + msgUI = '<span data-inverted="" data-position="left center" data-tooltip="' + msg + '"><i class="red times icon"></i></span>';
3943 + }
3152 3944 }
3153 3945
3154 3946 if (msg != '') {
3155 - msgUI = '<span data-inverted="" data-position="left center" data-tooltip="' + msg + '"><i class="red times icon"></i></span>';
3947 + if (outputType != undefined && outputType == 'ui') {
3948 + return msgUI;
3949 + } else {
3950 + return msg;
3951 + }
3156 3952 }
3157 - }
3158 3953
3159 - if (msg != '') {
3160 - if (outputType != undefined && outputType == 'ui') {
3161 - return msgUI;
3162 - } else {
3163 - return msg;
3164 - }
3165 - }
3166 -
3167 - return repError;
3954 + return repError;
3168 3955 }
3169 3956
3170 -window.dateToHMS = function (date) {
3171 - if (mainwpParams?.time_format) {
3172 - let time = moment(date);
3173 - let format = mainwpParams['time_format'];
3174 - format = format.replace('g', 'h');
3175 - format = format.replace('i', 'mm');
3176 - format = format.replace('s', 'ss');
3177 - format = format.replace('F', 'MMMM');
3178 - format = format.replace('j', 'D');
3179 - format = format.replace('Y', 'YYYY');
3180 - return time.format(format);
3181 - }
3182 - let h = date.getHours();
3183 - let m = date.getMinutes();
3184 - let s = date.getSeconds();
3185 - return '' + (h <= 9 ? '0' + h : h) + ':' + (m <= 9 ? '0' + m : m) + ':' + (s <= 9 ? '0' + s : s);
3957 +globalThis.dateToHMS = function (date) {
3958 + if (mainwpParams?.time_format) {
3959 + let time = moment(date);
3960 + let format = mainwpParams['time_format'];
3961 + format = format.replaceAll('g', 'h');
3962 + format = format.replaceAll('i', 'mm');
3963 + format = format.replaceAll('s', 'ss');
3964 + format = format.replaceAll('F', 'MMMM');
3965 + format = format.replaceAll('j', 'D');
3966 + format = format.replaceAll('Y', 'YYYY');
3967 + return time.format(format);
3968 + }
3969 + let h = date.getHours();
3970 + let m = date.getMinutes();
3971 + let s = date.getSeconds();
3972 + return '' + (h <= 9 ? '0' + h : h) + ':' + (m <= 9 ? '0' + m : m) + ':' + (s <= 9 ? '0' + s : s);
3186 3973 };
3187 -window.appendToDiv = function (pSelector, pText, pScrolldown, pShowTime) {
3188 - if (pScrolldown == undefined)
3189 - pScrolldown = true;
3190 - if (pShowTime == undefined)
3191 - pShowTime = true;
3974 +globalThis.appendToDiv = function (pSelector, pText, pScrolldown, pShowTime) {
3975 + if (pScrolldown == undefined)
3976 + pScrolldown = true;
3977 + if (pShowTime == undefined)
3978 + pShowTime = true;
3192 3979
3193 - let theDiv = jQuery(pSelector);
3194 - theDiv.append('<br />' + (pShowTime ? dateToHMS(new Date()) + ' ' : '') + pText);
3195 - if (pScrolldown)
3196 - theDiv.animate({ scrollTop: theDiv.prop("scrollHeight") }, 100);
3980 + let theDiv = jQuery(pSelector);
3981 + theDiv.append('<br />' + (pShowTime ? dateToHMS(new Date()) + ' ' : '') + pText);
3982 + if (pScrolldown)
3983 + theDiv.animate({ scrollTop: theDiv.prop("scrollHeight") }, 100);
3197 3984 };
3198 3985
3199 3986 jQuery.fn.exists = function () {
3200 - return (this.length !== 0);
3987 + return (this.length !== 0);
3201 3988 };
3202 3989
3203 3990
3204 -function __(text, _var1, _var2, _var3) {
3205 - if (text == undefined || text == '')
3206 - return text;
3207 - let strippedText = text.replace(/\W/g, '_');
3991 +globalThis.MainWP = globalThis.MainWP || {};
3992 +globalThis.MainWP.I18n = globalThis.MainWP.I18n || {};
3208 3993
3209 - if (strippedText == '')
3210 - return text.replace('%1', _var1).replace('%2', _var2).replace('%3', _var3);
3994 +MainWP.I18n.t = function (text, ...args) {
3995 + if (!text) {
3996 + return text;
3997 + }
3211 3998
3212 - if (mainwpTranslations == undefined)
3213 - return text.replace('%1', _var1).replace('%2', _var2).replace('%3', _var3);
3214 - if (mainwpTranslations[strippedText] == undefined)
3215 - return text.replace('%1', _var1).replace('%2', _var2).replace('%3', _var3);
3999 + // Replace non-alphanumeric characters (including Unicode/accented characters) with '_'
4000 + const strippedText = text.replace(/[^\p{L}\p{N}_]/gu, '_');
3216 4001
3217 - return mainwpTranslations[strippedText].replace('%1', _var1).replace('%2', _var2).replace('%3', _var3);
4002 + let translated = text;
4003 +
4004 + if (
4005 + strippedText &&
4006 + typeof mainwpTranslations !== 'undefined' &&
4007 + mainwpTranslations[strippedText] !== undefined
4008 + ) {
4009 + translated = mainwpTranslations[strippedText];
4010 + }
4011 +
4012 + if (args.length === 0) {
4013 + return translated;
4014 + }
4015 +
4016 + // Single-pass replacement to avoid placeholder collision issues
4017 + return translated.replace(/%(\d+)/g, (match, index) => {
4018 + const argIdx = parseInt(index, 10) - 1;
4019 + return args[argIdx] !== undefined ? args[argIdx] : match;
4020 + });
4021 +};
4022 +
4023 +// Deprecated. Remove in a future release.
4024 +if (typeof globalThis.__ !== 'function') {
4025 + globalThis.__ = function (text, ...args) {
4026 + return globalThis.MainWP.I18n.t(text, ...args);
4027 + };
3218 4028 }
3219 4029
3220 -window.mainwp_secure_data = function (data, includeDts) {
3221 - if (data['action'] == undefined)
3222 - return data;
4030 +globalThis.mainwp_secure_data = function (data, includeDts) {
4031 + if (data['action'] == undefined)
4032 + return data;
3223 4033
3224 - if (security_nonces[data['action']] == undefined)
4034 + if (security_nonces[data['action']] == undefined)
4035 + return data;
4036 +
4037 + data['security'] = security_nonces[data['action']];
4038 + if (includeDts)
4039 + data['dts'] = Math.round(Date.now() / 1000);
3225 4040 return data;
3226 -
3227 - data['security'] = security_nonces[data['action']];
3228 - if (includeDts)
3229 - data['dts'] = Math.round(new Date().getTime() / 1000);
3230 - return data;
3231 4041 };
3232 4042
3233 4043
3234 -window.mainwp_uid = function () {
3235 - // always start with a letter (for DOM friendlyness)
3236 - let idstr = String.fromCharCode(Math.floor((Math.random() * 25) + 65)); // NOSONAR - safe, it's id.
3237 - do {
3238 - // between numbers and characters (48 is 0 and 90 is Z (42-48 = 90)
3239 - let ascicode = Math.floor((Math.random() * 42) + 48); // NOSONAR - safe, it's id.
3240 - if (ascicode < 58 || ascicode > 64) {
3241 - // exclude all chars between : (58) and @ (64)
3242 - idstr += String.fromCharCode(ascicode);
3243 - }
3244 - } while (idstr.length < 32);
4044 +globalThis.mainwp_uid = function () {
4045 + // always start with a letter (for DOM friendlyness)
4046 + let idstr = String.fromCodePoint(Math.floor((Math.random() * 25) + 65)); // NOSONAR - safe, it's id.
4047 + do {
4048 + // between numbers and characters (48 is 0 and 90 is Z (42-48 = 90)
4049 + let ascicode = Math.floor((Math.random() * 42) + 48); // NOSONAR - safe, it's id.
4050 + if (ascicode < 58 || ascicode > 64) {
4051 + // exclude all chars between : (58) and @ (64)
4052 + idstr += String.fromCodePoint(ascicode);
4053 + }
4054 + } while (idstr.length < 32);
3245 4055
3246 - return (idstr);
4056 + return (idstr);
3247 4057 };
3248 4058
3249 -window.scrollToElement = function () {
3250 - jQuery('html,body').animate({
3251 - scrollTop: 0
3252 - }, 1000);
4059 +globalThis.scrollToElement = function () {
4060 + jQuery('html,body').animate({
4061 + scrollTop: 0
4062 + }, 1000);
3253 4063
3254 - return false;
4064 + return false;
3255 4065 };
3256 4066
3257 4067 jQuery(function () {
3258 - jQuery('#backup_filename').on('keypress', function (e) {
3259 - let chr = String.fromCharCode(e.which);
3260 - return ("$^&*/".indexOf(chr) < 0);
3261 - });
3262 - jQuery('#backup_filename').on('change', function () {
3263 - let value = jQuery(this).val();
3264 - let notAllowed = ['$', '^', '&', '*', '/'];
3265 - for (let char of notAllowed) {
3266 - if (value.indexOf(char) >= 0) {
3267 - value = value.replace(new RegExp('\\' + char, 'g'), '');
3268 - jQuery(this).val(value);
3269 - }
3270 - }
3271 - });
4068 + jQuery('#backup_filename').on('keypress', function (e) {
4069 + let chr = String.fromCodePoint(e.which);
4070 + return !"$^&*/".includes(chr);
4071 + });
4072 + jQuery('#backup_filename').on('change', function () {
4073 + let value = jQuery(this).val();
4074 + let notAllowed = ['$', '^', '&', '*', '/'];
4075 + for (let char of notAllowed) {
4076 + if (value.includes(char)) {
4077 + value = value.replaceAll(char, '');
4078 + jQuery(this).val(value);
4079 + }
4080 + }
4081 + });
3272 4082 });
3273 4083
3274 4084 /*
3275 4085 * Server Info
@@ -3274,741 +4084,866 @@
3274 4084 /*
3275 4085 * Server Info
3276 4086 */
3277 4087
3278 -window.serverinfo_prepare_download_info = function (communi) {
3279 - let report = "";
3280 - jQuery('.mainwp-system-info-table thead, .mainwp-system-info-table tbody').each(function () {
3281 - let td_len = [35, 55, 45, 12, 12];
3282 - let th_count = 0;
3283 - let i;
3284 - if (jQuery(this).is('thead')) {
3285 - i = 0;
3286 - report = report + "\n### ";
3287 - th_count = jQuery(this).find('th:not(".mwp-not-generate-row")').length;
3288 - jQuery(this).find('th:not(".mwp-not-generate-row")').each(function () {
3289 - let len = td_len[i];
3290 - if (i == 0 || i == th_count - 1)
3291 - len = len - 4;
3292 - report = report + jQuery.mwp_strCut(jQuery(this).text().trim(), len, ' ');
3293 - i++;
3294 - });
3295 - report = report + " ###\n\n";
3296 - } else {
3297 - jQuery('tr', jQuery(this)).each(function () {
3298 - if (communi && jQuery(this).hasClass('mwp-not-generate-row'))
3299 - return;
3300 - i = 0;
3301 - jQuery(this).find('td:not(".mwp-not-generate-row")').each(function () {
3302 - if (jQuery(this).hasClass('mwp-hide-generate-row')) {
3303 - report = report + jQuery.mwp_strCut(' ', td_len[i], ' ');
3304 - i++;
3305 - return;
3306 - }
3307 - report = report + jQuery.mwp_strCut(jQuery(this).text().trim(), td_len[i], ' ');
3308 - i++;
3309 - });
3310 - report = report + "\n";
3311 - });
4088 +globalThis.serverinfo_prepare_download_info = function (communi) {
4089 + let report = "";
4090 + jQuery('.mainwp-system-info-table thead, .mainwp-system-info-table tbody').each(function () {
4091 + let td_len = [35, 55, 45, 12, 12];
4092 + let th_count = 0;
4093 + let i;
4094 + if (jQuery(this).is('thead')) {
4095 + i = 0;
4096 + report = report + "\n### ";
4097 + th_count = jQuery(this).find('th:not(".mwp-not-generate-row")').length;
4098 + jQuery(this).find('th:not(".mwp-not-generate-row")').each(function () {
4099 + let len = td_len[i];
4100 + if (i == 0 || i == th_count - 1)
4101 + len = len - 4;
4102 + report = report + jQuery.mwp_strCut(jQuery.mwp_get_serverinfo_export_text(jQuery(this), communi), len, ' ');
4103 + i++;
4104 + });
4105 + report = report + " ###\n\n";
4106 + } else {
4107 + jQuery('tr', jQuery(this)).each(function () {
4108 + if (communi && jQuery(this).hasClass('mwp-not-generate-row'))
4109 + return;
4110 + i = 0;
4111 + jQuery(this).find('td:not(".mwp-not-generate-row")').each(function () {
4112 + if (jQuery(this).hasClass('mwp-hide-generate-row')) {
4113 + report = report + jQuery.mwp_strCut(' ', td_len[i], ' ');
4114 + i++;
4115 + return;
4116 + }
4117 + let outputText = jQuery.mwp_get_serverinfo_export_text(jQuery(this), communi);
4118 + report = report + jQuery.mwp_strCut(outputText, td_len[i], ' ');
4119 + i++;
4120 + });
4121 + report = report + "\n";
4122 + });
3312 4123
4124 + }
4125 + });
4126 +
4127 + try {
4128 + if (communi) {
4129 + report = '```' + "\n" + report + "\n" + '```';
4130 + }
4131 + jQuery("#download-server-information textarea").val(report).trigger("select");
4132 + } catch {
4133 + console.log('Error:');
3313 4134 }
3314 - });
4135 + return false;
4136 +}
3315 4137
3316 - try {
3317 - if (communi) {
3318 - report = '```' + "\n" + report + "\n" + '```';
4138 +jQuery.mwp_get_serverinfo_export_text = function (element, communi) {
4139 + let cellExportText = element.attr('data-export-text');
4140 + if (typeof cellExportText !== 'undefined' && cellExportText !== '') {
4141 + return cellExportText.trim();
3319 4142 }
3320 - jQuery("#download-server-information textarea").val(report).trigger("select");
3321 - } catch (e) {
3322 - console.log('Error:');
3323 - }
3324 - return false;
3325 -}
3326 4143
3327 -jQuery(document).on('click', '#mainwp-download-system-report', function () {
3328 - serverinfo_prepare_download_info(false);
3329 - let server_info = jQuery('#download-server-information textarea').val();
3330 - let blob = new Blob([server_info], { type: "text/plain;charset=utf-8" });
3331 - saveAs(blob, "mainwp-system-report.txt");
3332 - return false;
3333 -});
4144 + let descendantExportElement = element.find('[data-export-text]').first();
4145 + if (descendantExportElement.length > 0) {
4146 + let descendantExportText = descendantExportElement.attr('data-export-text');
4147 + if (typeof descendantExportText !== 'undefined' && descendantExportText !== '') {
4148 + return descendantExportText.trim();
4149 + }
4150 + }
3334 4151
3335 -// Copies a string to the clipboard. Must be called from within an
3336 -// event handler such as click.
3337 -let mainwp_copy_to_clipboard = function (text, event) {
3338 - let clipboardDT = event.clipboardData || window.clipboardData || event.originalEvent.clipboardData; // NOSONAR - to compatible.
3339 - console.log(clipboardDT);
3340 - if (clipboardDT && clipboardDT.setData) { // NOSONAR - to compatible.
3341 - console.warn("Copy to clipboard.");
3342 - return clipboardDT.setData("Text", text);
3343 - } else {
3344 - try {
3345 - if (document?.queryCommandSupported && document.queryCommandSupported("copy")) { // NOSONAR - to compatible.
3346 - console.warn("Copy to clipboard exec.");
3347 - return document.execCommand("copy"); // NOSONAR - to compatible, security exception may be thrown by some browsers.
3348 - }
3349 - } catch (ex) {
3350 - console.warn("Copy to clipboard failed.", ex);
4152 + let communityValue = element.attr('data-community-value');
4153 + if (communi && typeof communityValue !== 'undefined') {
4154 + return communityValue;
3351 4155 }
3352 - }
4156 +
4157 + return element.text().trim();
3353 4158 }
3354 4159
3355 -jQuery(document).on('click', '#mainwp-copy-meta-system-report', function (event) {
3356 - event.preventDefault();
3357 - jQuery("#download-server-information").slideDown(); // to able to select and copy
3358 - serverinfo_prepare_download_info(true);
3359 - jQuery("#download-server-information").slideUp(); // to support 'copy' method.
3360 - mainwp_copy_to_clipboard(jQuery("#download-server-information").val(), event);
4160 +jQuery(document).on('click', '#mainwp-download-system-report', function () {
4161 + serverinfo_prepare_download_info(false);
4162 + let server_info = jQuery('#download-server-information textarea').val();
4163 + let blob = new Blob([server_info], { type: "text/plain;charset=utf-8" });
4164 + saveAs(blob, "mainwp-system-report.txt");
4165 + return false;
3361 4166 });
4167 +jQuery(document).on('click', '#mainwp-download-community-system-report', function () {
4168 + serverinfo_prepare_download_info(true);
4169 + let server_info = jQuery('#download-server-information textarea').val();
4170 + let blob = new Blob([server_info], { type: "text/plain;charset=utf-8" });
4171 + saveAs(blob, "mainwp-community-system-report.txt");
4172 + return false;
4173 +});
3362 4174
3363 4175
3364 4176 jQuery.mwp_strCut = function (i, l, s, w) {
3365 - let o = i.toString();
3366 - if (!s) {
3367 - s = '0';
3368 - }
3369 - while (o.length < parseInt(l)) {
3370 - // empty
3371 - if (w == 'undefined') {
3372 - o = s + o;
3373 - } else {
3374 - o = o + s;
4177 + let o = i.toString();
4178 + if (!s) {
4179 + s = '0';
3375 4180 }
3376 - }
3377 - return o;
4181 + while (o.length < Number.parseInt(l)) {
4182 + // empty
4183 + if (w == 'undefined') {
4184 + o = s + o;
4185 + } else {
4186 + o = o + s;
4187 + }
4188 + }
4189 + return o;
3378 4190 };
3379 4191
3380 -window.updateExcludedFolders = function () {
3381 - let excludedBackupFiles = jQuery('#excludedBackupFiles').html();
3382 - jQuery('#mainwp-kbl-content').val(excludedBackupFiles == undefined ? '' : excludedBackupFiles);
4192 +globalThis.updateExcludedFolders = function () {
4193 + let excludedBackupFiles = jQuery('#excludedBackupFiles').html();
4194 + jQuery('#mainwp-kbl-content').val(excludedBackupFiles == undefined ? '' : excludedBackupFiles);
3383 4195
3384 - let excludedCacheFiles = jQuery('#excludedCacheFiles').html();
3385 - jQuery('#mainwp-kcl-content').val(excludedCacheFiles == undefined ? '' : excludedCacheFiles);
4196 + let excludedCacheFiles = jQuery('#excludedCacheFiles').html();
4197 + jQuery('#mainwp-kcl-content').val(excludedCacheFiles == undefined ? '' : excludedCacheFiles);
3386 4198
3387 - let excludedNonWPFiles = jQuery('#excludedNonWPFiles').html();
3388 - jQuery('#mainwp-nwl-content').val(excludedNonWPFiles == undefined ? '' : excludedNonWPFiles);
4199 + let excludedNonWPFiles = jQuery('#excludedNonWPFiles').html();
4200 + jQuery('#mainwp-nwl-content').val(excludedNonWPFiles == undefined ? '' : excludedNonWPFiles);
3389 4201 };
3390 4202
3391 4203
3392 4204 jQuery(document).on('click', '.mainwp-events-notice-dismiss', function () {
3393 - let notice = jQuery(this).attr('notice');
3394 - jQuery(this).closest('.ui.message').fadeOut(500);
3395 - let data = mainwp_secure_data({
3396 - action: 'mainwp_events_notice_hide',
3397 - notice: notice
3398 - });
3399 - jQuery.post(ajaxurl, data, function () {
3400 - });
3401 - return false;
4205 + let notice = jQuery(this).attr('notice');
4206 + jQuery(this).closest('.ui.message').fadeOut(500);
4207 + let data = mainwp_secure_data({
4208 + action: 'mainwp_events_notice_hide',
4209 + notice: notice
4210 + });
4211 + jQuery.post(ajaxurl, data, function () {
4212 + });
4213 + return false;
3402 4214 });
3403 4215
3404 4216 // Turn On child plugin auto update
3405 4217 jQuery(document).on('click', '#mainwp_btn_autoupdate_and_trust', function () {
3406 - jQuery(this).attr('disabled', 'true');
3407 - let data = mainwp_secure_data({
3408 - action: 'mainwp_autoupdate_and_trust_child'
3409 - });
3410 - jQuery.post(ajaxurl, data, function (res) {
3411 - if (res == 'ok') {
3412 - location.reload(true);
3413 - } else {
3414 - jQuery(this).prop("disabled", false);
3415 - }
3416 - });
3417 - return false;
4218 + jQuery(this).attr('disabled', 'true');
4219 + let data = mainwp_secure_data({
4220 + action: 'mainwp_autoupdate_and_trust_child'
4221 + });
4222 + jQuery.post(ajaxurl, data, function (res) {
4223 + if (res == 'ok') {
4224 + location.reload(true);
4225 + } else {
4226 + jQuery(this).prop("disabled", false);
4227 + }
4228 + });
4229 + return false;
3418 4230 });
3419 4231
3420 4232 // Hide installation warning
3421 4233 jQuery(document).on('click', '#remove-mainwp-installation-warning', function () {
3422 - jQuery(this).closest('.ui.message').fadeOut("slow");
3423 - let data = mainwp_secure_data({
3424 - action: 'mainwp_installation_warning_hide'
3425 - });
3426 - jQuery.post(ajaxurl, data, function () { });
3427 - return false;
4234 + jQuery(this).closest('.ui.message').fadeOut("slow");
4235 + let data = mainwp_secure_data({
4236 + action: 'mainwp_installation_warning_hide'
4237 + });
4238 + jQuery.post(ajaxurl, data, function () { });
4239 + return false;
3428 4240 });
3429 4241
3430 4242 jQuery(document).on('click', '.mainwp-notice-hide', function () {
3431 - jQuery(this).closest('.ui.message').fadeOut("slow");
3432 - return false;
4243 + jQuery(this).closest('.ui.message').fadeOut("slow");
4244 + return false;
3433 4245 });
3434 4246
3435 4247 // Hide after installtion notices (PHP version, Trust MainWP Child, Multisite Warning and OpenSSL warning)
3436 4248 jQuery(document).on('click', '.mainwp-notice-dismiss', function () {
3437 - let notice_id = jQuery(this).attr('notice-id');
3438 - jQuery(this).closest('.ui.message').fadeOut("slow");
3439 - let data = {
3440 - action: 'mainwp_notice_status_update'
3441 - };
3442 - data['notice_id'] = notice_id;
3443 - jQuery.post(ajaxurl, mainwp_secure_data(data), function () { });
3444 - return false;
4249 + let notice_id = jQuery(this).attr('notice-id');
4250 + let shortterm = jQuery(this).attr('shortterm-notice');
4251 +
4252 + jQuery(this).closest('.ui.message').fadeOut("slow");
4253 + let data = {
4254 + action: 'mainwp_notice_status_update'
4255 + };
4256 + data['notice_id'] = notice_id;
4257 + if(shortterm === '1'){
4258 + data['short_term'] = 1;
4259 + }
4260 + jQuery.post(ajaxurl, mainwp_secure_data(data), function () { });
4261 + return false;
3445 4262 });
3446 4263
3447 4264
3448 -window.mainwp_notice_dismiss = function (notice_id, time_set) {
3449 - let data = {
3450 - action: 'mainwp_notice_status_update'
3451 - };
3452 - data['notice_id'] = notice_id;
3453 - if (typeof time_set !== "undefined") {
3454 - data['time_set'] = time_set ? 1 : 0;
3455 - }
3456 - jQuery.post(ajaxurl, mainwp_secure_data(data), function () {
3457 - console.log('dismissed');
3458 - });
3459 - return false;
4265 +globalThis.mainwp_notice_dismiss = function (notice_id, time_set) {
4266 + let data = {
4267 + action: 'mainwp_notice_status_update'
4268 + };
4269 + data['notice_id'] = notice_id;
4270 + if (time_set !== undefined) {
4271 + data['time_set'] = time_set ? 1 : 0;
4272 + }
4273 + jQuery.post(ajaxurl, mainwp_secure_data(data), function () {
4274 + });
4275 + return false;
3460 4276 }
3461 4277
3462 4278
3463 4279 jQuery(document).on('click', '.mainwp-activate-notice-dismiss', function () {
3464 - jQuery(this).closest('tr').fadeOut("slow");
3465 - let data = mainwp_secure_data({
3466 - action: 'mainwp_dismiss_activate_notice',
3467 - slug: jQuery(this).closest('tr').attr('slug')
3468 - });
3469 - jQuery.post(ajaxurl, data, function () {
3470 - });
3471 - return false;
4280 + jQuery(this).closest('tr').fadeOut("slow");
4281 + let data = mainwp_secure_data({
4282 + action: 'mainwp_dismiss_activate_notice',
4283 + slug: jQuery(this).closest('tr').attr('slug')
4284 + });
4285 + jQuery.post(ajaxurl, data, function () {
4286 + });
4287 + return false;
3472 4288 });
3473 4289
3474 4290 jQuery(document).on('click', '.mainwp-install-check-dismiss', function () {
3475 - let notice_id = jQuery(this).attr('notice-id');
3476 - jQuery(this).closest('.ui.message').fadeOut("slow");
3477 - let data = {
3478 - action: 'mainwp_notice_status_update'
3479 - };
3480 - data['notice_id'] = notice_id;
3481 - jQuery.post(ajaxurl, mainwp_secure_data(data), function () { });
3482 - return false;
4291 + let notice_id = jQuery(this).attr('notice-id');
4292 + jQuery(this).closest('.ui.message').fadeOut("slow");
4293 + let data = {
4294 + action: 'mainwp_notice_status_update'
4295 + };
4296 + data['notice_id'] = notice_id;
4297 + jQuery.post(ajaxurl, mainwp_secure_data(data), function () { });
4298 + return false;
3483 4299 });
3484 4300
3485 -jQuery(document).on('click', '.mainwp-action-dismiss', function () {
3486 - let action_id = jQuery(this).attr('action-id');
3487 - jQuery(this).closest('tr').fadeOut("slow");
3488 - let data = {
3489 - action: 'mainwp_site_actions_dismiss'
3490 - };
3491 - data['action_id'] = action_id;
3492 - jQuery.post(ajaxurl, mainwp_secure_data(data), function () {
3493 -
3494 - });
3495 - return false;
4301 +jQuery(document).on('click', '#mainwp-dismiss-sites-changes-actions-button', function () {
4302 + mainwp_confirm('You are about to dismiss the selected changes?', function () {
4303 + mainwp_delete_nonmainwp_data_start();
4304 + });
4305 + return false;
3496 4306 });
3497 4307
3498 -jQuery(document).on('click', '#mainwp-delete-all-nonmainwp-actions-button', function () {
3499 - mainwp_confirm('Are you sure you want to delete all Non-MainWP changes? This action can not be undone!', function () {
3500 - mainwp_delete_nonmainwp_data_start();
3501 - });
3502 - return false;
3503 -});
3504 -
3505 4308 let mainwp_managesites_update_childsite_value = function (siteId, uniqueId) {
3506 - let data = mainwp_secure_data({
3507 - action: 'mainwp_updatechildsite_value',
3508 - site_id: siteId,
3509 - unique_id: uniqueId
3510 - });
3511 - jQuery.post(ajaxurl, data, function () {
3512 - });
3513 - return false;
4309 + let data = mainwp_secure_data({
4310 + action: 'mainwp_updatechildsite_value',
4311 + site_id: siteId,
4312 + unique_id: uniqueId
4313 + });
4314 + jQuery.post(ajaxurl, data, function () {
4315 + });
4316 + return false;
3514 4317 };
3515 4318
3516 4319 jQuery(document).on('keyup', '#managegroups-filter', function () {
3517 - let filter = jQuery(this).val();
3518 - let groupItems = jQuery(this).parent().parent().find('li.managegroups-listitem');
3519 - for (let igr of groupItems) {
3520 - let currentElement = jQuery(igr);
3521 - if (currentElement.hasClass('managegroups-group-add')) {
3522 - continue;
4320 + let filter = jQuery(this).val();
4321 + let groupItems = jQuery(this).parent().parent().find('li.managegroups-listitem');
4322 + for (let igr of groupItems) {
4323 + let currentElement = jQuery(igr);
4324 + if (currentElement.hasClass('managegroups-group-add')) {
4325 + continue;
4326 + }
4327 + let value = currentElement.find('span.text').text();
4328 + if (value.includes(filter)) {
4329 + currentElement.show();
4330 + } else {
4331 + currentElement.hide();
4332 + }
3523 4333 }
3524 - let value = currentElement.find('span.text').text();
3525 - if (value.indexOf(filter) > -1) {
3526 - currentElement.show();
3527 - } else {
3528 - currentElement.hide();
3529 - }
3530 - }
3531 4334 });
3532 4335
3533 4336 // for normal checkboxes
3534 4337 jQuery(document).on('change', '#cb-select-all-top, #cb-select-all-bottom', function () {
3535 - let $this = jQuery(this), $table, controlChecked = $this.prop('checked');
4338 + let $this = jQuery(this), $table, controlChecked = $this.prop('checked');
3536 4339
3537 - $table = $this.closest('.dt-scroll').find('.dt-scroll-body table'); // for dt with scroll enabled.
4340 + $table = $this.closest('.dt-scroll').find('.dt-scroll-body table'); // for dt with scroll enabled.
3538 4341
3539 - // if no scrollable table.
3540 - if ($table.length == 0) {
3541 - $table = $this.closest('table.table.dataTable');
3542 - }
4342 + // if no scrollable table.
4343 + if ($table.length == 0) {
4344 + $table = $this.closest('table.table.dataTable');
4345 + }
3543 4346
3544 - if ($table.length == 0)
3545 - return false;
4347 + if ($table.length == 0)
4348 + return false;
3546 4349
3547 - $table.children('tbody').filter(':visible')
3548 - .children().children('.check-column').find(':checkbox')
3549 - .prop('checked', function () {
3550 - if (jQuery(this).is(':hidden,:disabled')) {
3551 - return false;
3552 - }
3553 - if (controlChecked) {
3554 - jQuery(this).closest('tr').addClass('selected');
3555 - return true;
3556 - }
3557 - jQuery(this).closest('tr').removeClass('selected');
3558 - return false;
4350 + $table.children('tbody').filter(':visible')
4351 + .children().children('.check-column').find(':checkbox')
4352 + .prop('checked', function () {
4353 + if (jQuery(this).is(':hidden,:disabled')) {
4354 + return false;
4355 + }
4356 + if (controlChecked) {
4357 + jQuery(this).closest('tr').addClass('selected');
4358 + return true;
4359 + }
4360 + jQuery(this).closest('tr').removeClass('selected');
4361 + return false;
4362 + });
4363 +
4364 + $table.children('thead, tfoot').filter(':visible')
4365 + .children().children('.check-column').find(':checkbox')
4366 + .prop('checked', function () {
4367 + if (controlChecked) {
4368 + jQuery(this).closest('tr').addClass('selected');
4369 + return true;
4370 + }
4371 + jQuery(this).closest('tr').removeClass('selected');
4372 + return false;
4373 + });
4374 + let dtApi = jQuery($table).dataTable().api();
4375 + let setStatus = controlChecked ? 'selected' : 'deselected';
4376 + mainwp_datatable_fix_to_update_selected_rows_status(dtApi, setStatus);
4377 +});
4378 +
4379 +
4380 +jQuery(document).on('change', '.cb-select-all-parent-top, .cb-select-all-parent-bottom', function () {
4381 +
4382 + let parentChecked = jQuery(this).is(":checked");
4383 + let parentSelector = jQuery(this).attr('cb-parent-selector') ?? false;
4384 +
4385 + if (false === parentSelector) {
4386 + return;
4387 + }
4388 + jQuery(parentSelector + ' .ui.checkbox').find(':checkbox')
4389 + .prop('checked', function () {
4390 + if (parentChecked) {
4391 + jQuery(this).closest('tr').addClass('selected');
4392 + return true;
4393 + }
4394 + jQuery(this).closest('tr').removeClass('selected');
4395 + return false;
4396 + });
4397 +
4398 +});
4399 +
4400 +jQuery(function ($) {
4401 + // Trigger the bulk actions
4402 + $('#mainwp_sites_changes_bulk_dismiss_selected_btn').on('click', function () {
4403 + if (jQuery('#mainwp-module-log-records-body-table tr').find('input[type="checkbox"]:checked').length == 0) {
4404 + return;
4405 + }
4406 + let confirmMsg = MainWP.I18n.t("You are about to dismiss the selected changes?");
4407 + mainwp_confirm(confirmMsg, function () { mainwp_sites_changes_actions_bulk_action('dismiss-selected'); });
3559 4408 });
3560 4409
3561 - $table.children('thead, tfoot').filter(':visible')
3562 - .children().children('.check-column').find(':checkbox')
3563 - .prop('checked', function () {
3564 - if (controlChecked) {
3565 - jQuery(this).closest('tr').addClass('selected');
3566 - return true;
3567 - }
3568 - jQuery(this).closest('tr').removeClass('selected');
3569 - return false;
4410 + $('#mainwp_sites_changes_bulk_dismiss_all_btn').on('click', function () {
4411 + let confirmMsg = MainWP.I18n.t("You are about to dismiss all changes?");
4412 + mainwp_confirm(confirmMsg, function () { mainwp_sites_changes_actions_bulk_action('dismiss-all'); });
3570 4413 });
3571 - let dtApi = jQuery($table).dataTable().api();
3572 - let setStatus = controlChecked ? 'selected' : 'deselected';
3573 - mainwp_datatable_fix_to_update_selected_rows_status(dtApi, setStatus);
3574 -});
3575 4414
3576 -jQuery(function ($) {
3577 - // Trigger the bulk actions
3578 - $('#mainwp_non_mainwp_actions_action_btn').on('click', function () {
3579 - let bulk_act = jQuery('#non_mainwp_actions_bulk_action').dropdown("get value");
3580 - let confirmMsg = '';
3581 - if ('delete' === bulk_act) {
3582 - confirmMsg = __("You are about to delete the selected changes?");
3583 - } else if ('dismiss' === bulk_act) {
3584 - confirmMsg = __("You are about to dismiss the selected changes?");
4415 + // Trigger the bulk actions
4416 + $('#mainwp_widget_sites_changes_bulk_dismiss_selected_btn').on('click', function () {
4417 + if (jQuery('#mainwp-module-log-records-body-table tr').find('input[type="checkbox"]:checked').length == 0) {
4418 + return;
4419 + }
4420 + let confirmMsg = MainWP.I18n.t("You are about to dismiss the selected changes?");
4421 + mainwp_confirm(confirmMsg, function () { mainwp_sites_changes_actions_bulk_action('dismiss-selected', 'widget'); });
4422 + });
4423 +
4424 + $(document).on('click', '.insights-actions-row-dismiss', function () {
4425 + return mainwp_insights_row_actions_dismiss(this);
4426 + });
4427 +
4428 + globalThis.mainwp_sites_changes_update_dismiss_button_state = function () {
4429 + let checkedCount = jQuery('#mainwp-module-log-records-body-table tr').find('input[type="checkbox"]:checked').length;
4430 + let totalRows = jQuery('#mainwp-module-log-records-body-table tr').not('.dt-empty').length;
4431 +
4432 + if (checkedCount > 0) {
4433 + jQuery('#mainwp_sites_changes_bulk_dismiss_selected_btn').removeClass('disabled');
4434 + } else {
4435 + jQuery('#mainwp_sites_changes_bulk_dismiss_selected_btn').addClass('disabled');
4436 + }
4437 +
4438 + if (totalRows > 0) {
4439 + jQuery('#mainwp_sites_changes_bulk_dismiss_all_btn').removeClass('disabled');
4440 + } else {
4441 + jQuery('#mainwp_sites_changes_bulk_dismiss_all_btn').addClass('disabled');
4442 + }
3585 4443 }
3586 - if (confirmMsg == '') {
3587 - return;
3588 - }
3589 - mainwp_confirm(confirmMsg, function () { mainwp_non_mainwp_actions_table_bulk_action(bulk_act); });
3590 - });
3591 4444
4445 + jQuery(document).on('change', '#mainwp-module-log-records-body-table input[type="checkbox"]', function () {
4446 + mainwp_sites_changes_update_dismiss_button_state();
4447 + });
3592 4448
3593 - $(document).on('click', '.non-mainwp-action-row-dismiss', function () {
3594 - mainwp_non_mainwp_row_actions_dismiss(this);
3595 - });
4449 + jQuery(document).on('change', '#cb-select-all-top, #cb-select-all-bottom', function () {
4450 + mainwp_sites_changes_update_dismiss_button_state();
4451 + });
3596 4452 })
3597 4453
4454 +let mainwp_insights_row_actions_dismiss = function (obj) {
4455 + let row = jQuery(obj).closest('tr');
4456 + let confirmMsg = MainWP.I18n.t("You are about to dismiss the selected change?");
3598 4457
3599 -let mainwp_non_mainwp_row_actions_dismiss = function (obj) {
4458 + const renderMessage = (icon, message) => {
4459 + row.html(
4460 + '<td></td><td colspan="999"><i class="' +
4461 + icon +
4462 + ' icon"></i> ' +
4463 + message +
4464 + '</td>'
4465 + );
4466 + };
3600 4467
3601 - let row = jQuery(obj).closest('tr');
3602 - let confirmMsg = __("You are about to dismiss the selected changes?");
4468 + const updateDismissButtonState = () => {
4469 + if (typeof mainwp_sites_changes_update_dismiss_button_state !== 'undefined') {
4470 + mainwp_sites_changes_update_dismiss_button_state();
4471 + }
4472 + };
3603 4473
3604 - let _callback = () => {
3605 - row.html('<td></td><td colspan="999"><i class="notched circle loading icon"></i> Please wait...</td>');
3606 - let data = mainwp_secure_data({
3607 - action: 'mainwp_non_mainwp_changes_dismiss_actions',
3608 - act_id: jQuery(row).attr('action-id')
3609 - });
3610 - jQuery.post(ajaxurl, data, function (response) {
3611 - if (response) {
3612 - if (response['error']) {
3613 - row.html('<td></td><td colspan="999"><i class="times red icon"></i> ' + response['error'] + '</td>');
3614 - } else if (response['success'] == 'yes') {
3615 - row.html('<td></td><td colspan="999"><i class="green check icon"></i> Non-MainWP Change has been dismissed.</td>');
3616 - setTimeout(function () {
3617 - jQuery(row).fadeOut("slow");
3618 - }, 2000);
3619 - } else {
3620 - row.html('<td></td><td colspan="999"><i class="times red icon"></i> Non-MainWP Change could not be dismissed.</td>');
3621 - }
3622 - } else {
3623 - row.html('<td></td><td colspan="999"><i class="times red icon"></i> Non-MainWP Change could not be dismissed.</td>');
3624 - }
3625 - }, 'json');
3626 - };
3627 - mainwp_confirm(confirmMsg, _callback);
3628 - return false;
4474 + const fadeRow = () => {
4475 + setTimeout(() => {
4476 + jQuery(row).fadeOut('slow', updateDismissButtonState);
4477 + }, 2000);
4478 + };
4479 +
4480 + let _callback = () => {
4481 + row.html('<td></td><td colspan="999"><i class="notched circle loading icon"></i> Please wait...</td>');
4482 + let data = mainwp_secure_data({
4483 + action: 'mainwp_insight_events_dismiss_actions',
4484 + log_id: jQuery(row).attr('log-id')
4485 + });
4486 + jQuery.post(ajaxurl, data, function (response) {
4487 + if (response?.success !== 'yes') {
4488 +
4489 + if (response?.error) {
4490 + renderMessage('times red', response.error);
4491 + } else {
4492 + renderMessage('times red', 'The change could not be dismissed.');
4493 + }
4494 +
4495 + return;
4496 + }
4497 + renderMessage('green check', 'The change has been dismissed.');
4498 + fadeRow();
4499 + }, 'json');
4500 + };
4501 + mainwp_confirm(confirmMsg, _callback);
4502 + return false;
3629 4503 }
3630 4504
3631 4505
3632 -
3633 4506 // Manage Bulk Actions
3634 -let mainwp_non_mainwp_actions_table_bulk_action = function (act) {
3635 - mainwpVars.bulkInstallTotal = 0;
3636 - bulkInstallCurrentThreads = 0;
3637 - bulkInstallDone = 0;
3638 - let selector = '';
3639 - if (act === 'dismiss') {
3640 - selector += '#mainwp-manage-non-mainwp-actions-table tbody tr';
3641 - jQuery(selector).addClass('queue');
3642 - mainwp_non_mainwp_actions_dismiss_start_next(selector);
3643 - }
4507 +let mainwp_sites_changes_actions_bulk_action = function (act, which_act) {
4508 + mainwpVars.bulkInstallTotal = 0;
4509 + bulkInstallCurrentThreads = 0;
4510 + bulkInstallDone = 0;
4511 + mainwpVars.bulkActionIndent = '';
4512 + if (which_act === 'widget') {
4513 + mainwpVars.bulkActionIndent = 'widget';
4514 + }
4515 + if (act === 'dismiss-selected') {
4516 + jQuery('#mainwp_sites_changes_bulk_dismiss_selected_btn').addClass('disabled');
4517 + let selector = '#mainwp-module-log-records-body-table tr';
4518 + mainwpVars.bulkInstallTotal = jQuery(selector).find('input[type="checkbox"]:checked').length;
4519 + jQuery(selector).addClass('queue');
4520 + if (jQuery(selector).length) {
4521 + if (mainwpVars.bulkActionIndent === 'widget') {
4522 + jQuery('#mainwp_widget_sites_changes_bulk_dismiss_selected_btn').addClass('disabled');
4523 + } else {
4524 + jQuery('#mainwp_sites_changes_bulk_dismiss_selected_btn').addClass('disabled');
4525 + }
4526 + }
4527 + mainwp_sites_changes_actions_dismiss_start_next(selector);
4528 + } else if (act === 'dismiss-all') {
4529 + jQuery('#mainwp_sites_changes_bulk_dismiss_all_btn').addClass('disabled');
4530 + mainwp_sites_changes_actions_dismiss_all();
4531 + }
3644 4532 }
3645 4533
3646 -let mainwp_non_mainwp_actions_dismiss_start_next = function (selector) {
3647 - if (mainwpVars.bulkInstallTotal == 0) {
3648 - mainwpVars.bulkInstallTotal = jQuery('#mainwp-manage-non-mainwp-actions-table tbody').find('input[type="checkbox"]:checked').length;
3649 - }
3650 - while ((objProcess = jQuery(selector + '.queue:first')) && (objProcess.length > 0) && (bulkInstallCurrentThreads < bulkInstallMaxThreads)) { // NOSONAR - modified outside the function.
3651 - objProcess.removeClass('queue');
3652 - if (objProcess.closest('tr').find('input[type="checkbox"]:checked').length == 0) {
3653 - continue;
4534 +let mainwp_sites_changes_actions_dismiss_start_next = function (selector) {
4535 + while ((objProcess = jQuery(selector + '.queue:first')) && (objProcess.length > 0) && (bulkInstallCurrentThreads < bulkInstallMaxThreads)) { // NOSONAR - modified outside the function.
4536 + objProcess.removeClass('queue');
4537 + if (objProcess.closest('tr').find('input[type="checkbox"]:checked').length == 0) {
4538 + continue;
4539 + }
4540 + mainwp_sites_changes_actions_dismiss_specific(objProcess, selector);
3654 4541 }
3655 - mainwp_non_mainwp_actions_dismiss_specific(objProcess, selector, true);
3656 - }
4542 +
4543 + if (mainwpVars.bulkInstallTotal == bulkInstallDone) {
4544 + if (mainwpVars.bulkActionIndent === 'widget') {
4545 + jQuery('#mainwp_widget_sites_changes_bulk_dismiss_selected_btn').removeClass('disabled');
4546 + } else {
4547 + jQuery('#mainwp_sites_changes_bulk_dismiss_selected_btn').removeClass('disabled');
4548 + }
4549 + if (typeof mainwp_sites_changes_update_dismiss_button_state !== 'undefined') {
4550 + mainwp_sites_changes_update_dismiss_button_state();
4551 + }
4552 + }
3657 4553 }
3658 4554
3659 -let mainwp_non_mainwp_actions_dismiss_specific = function (pObj, selector, bulk) {
3660 - let row = pObj.closest('tr');
3661 - let act_id = jQuery(row).attr('action-id');
4555 +let mainwp_sites_changes_actions_dismiss_specific = function (pObj, selector) {
4556 + let row = pObj.closest('tr');
4557 + let act_id = jQuery(row).attr('log-id');
3662 4558
3663 - if (bulk) {
3664 4559 bulkInstallCurrentThreads++;
3665 - }
3666 4560
3667 - let data = mainwp_secure_data({
3668 - action: 'mainwp_non_mainwp_changes_dismiss_actions',
3669 - act_id: act_id,
3670 - });
4561 + let data = mainwp_secure_data({
4562 + action: 'mainwp_insight_events_dismiss_actions',
4563 + log_id: act_id
4564 + });
3671 4565
3672 - row.html('<td></td><td colspan="999"><i class="notched circle loading icon"></i> Please wait...</td>');
4566 + row.html('<td></td><td colspan="999"><i class="notched circle loading icon"></i> Please wait...</td>');
3673 4567
3674 - jQuery.post(ajaxurl, data, function (response) {
3675 - pObj.removeClass('queue');
3676 - if (response) {
3677 - if (response['error']) {
3678 - row.html('<td></td><td colspan="999"><i class="times red icon"></i> ' + response['error'] + '</td>');
3679 - } else if (response['success'] == 'yes') {
3680 - row.html('<td></td><td colspan="999"><i class="green check icon"></i> Non-MainWP Change has been dismissed.</td>');
3681 - setTimeout(function () {
3682 - jQuery(row).fadeOut("slow");
3683 - }, 2000);
3684 - } else {
3685 - row.html('<td></td><td colspan="999"><i class="times red icon"></i> Failed. Please try again.</td>');
3686 - }
3687 - } else {
3688 - row.html('<td></td><td colspan="999"><i class="times red icon"></i> Failed. Please try again.</td>');
3689 - }
4568 + jQuery.post(ajaxurl, data, function (response) {
4569 + pObj.removeClass('queue');
4570 + if (response) {
4571 + if (response['error']) {
4572 + row.html('<td></td><td colspan="999"><i class="times red icon"></i> ' + response['error'] + '</td>');
4573 + } else if (response['success'] == 'yes') {
4574 + row.html('<td></td><td colspan="999"><i class="green check icon"></i> The change has been dismissed.</td>');
4575 + setTimeout(function () {
4576 + jQuery(row).fadeOut("slow");
4577 + }, 2000);
4578 + } else {
4579 + row.html('<td></td><td colspan="999"><i class="times red icon"></i> Failed. Please try again.</td>');
4580 + }
4581 + } else {
4582 + row.html('<td></td><td colspan="999"><i class="times red icon"></i> Failed. Please try again.</td>');
4583 + }
3690 4584
3691 - if (bulk) {
3692 - bulkInstallCurrentThreads--;
3693 - bulkInstallDone++;
3694 - mainwp_non_mainwp_actions_dismiss_start_next(selector);
3695 - if (mainwpVars.bulkInstallTotal == bulkInstallDone) {
3696 - setTimeout(function () {
3697 - window.location.reload(true);
3698 - }, 3000);
3699 - }
3700 - }
4585 + bulkInstallCurrentThreads--;
4586 + bulkInstallDone++;
4587 + mainwp_sites_changes_actions_dismiss_start_next(selector);
4588 + }, 'json');
4589 + return false;
4590 +}
3701 4591
3702 - }, 'json');
3703 - return false;
4592 +let mainwp_sites_changes_actions_dismiss_all = function () {
4593 + let data = mainwp_secure_data({
4594 + action: 'mainwp_insight_events_dismiss_all',
4595 + });
4596 + mainwp_showhide_message('mainwp-message-zone-top', '<i class="notched circle loading icon"></i> Please wait...', '');
4597 + jQuery.post(ajaxurl, data, function (response) {
4598 + if (response) {
4599 + if (response['error']) {
4600 + mainwp_showhide_message('mainwp-message-zone-top', response['error'], 'red');
4601 + } else if (response['success'] == 'yes') {
4602 + mainwp_showhide_message('mainwp-message-zone-top', 'All changes have been dismissed.', 'green');
4603 + setTimeout(function () {
4604 + mainwp_forceReload();
4605 + }, 2000);
4606 + } else {
4607 + mainwp_showhide_message('mainwp-message-zone-top', 'Failed. Please try again.', 'red');
4608 + }
4609 + } else {
4610 + mainwp_showhide_message('mainwp-message-zone-top', 'Failed. Please try again.', 'red');
4611 + }
4612 + }, 'json');
4613 + return false;
4614 +
3704 4615 }
3705 4616
3706 -window.mainwp_datatable_fix_to_update_selected_rows_status = function (dtApi, setStatus) {
3707 - if (dtApi) {
3708 - console.log('Datatable - update selected rows status.');
3709 - if ('selected' === setStatus) {
3710 - dtApi.rows('.selected').select(); // update selected status.
3711 - } else if ('deselected' === setStatus) {
3712 - dtApi.rows().deselect(); // update deselected status.
4617 +
4618 +globalThis.mainwp_datatable_fix_to_update_selected_rows_status = function (dtApi, setStatus) {
4619 + if (dtApi) {
4620 + if ('selected' === setStatus) {
4621 + dtApi.rows('.selected').select(); // update selected status.
4622 + } else if ('deselected' === setStatus) {
4623 + dtApi.rows().deselect(); // update deselected status.
4624 + }
3713 4625 }
3714 - }
3715 4626 }
3716 4627
3717 -window.mainwp_datatable_fix_to_update_rows_state = function (tblSelect) {
3718 - if (jQuery(tblSelect).length) {
3719 - let $table = jQuery(tblSelect);
4628 +globalThis.mainwp_datatable_fix_to_update_rows_state = function (tblSelect) {
4629 + if (jQuery(tblSelect).length) {
4630 + let $table = jQuery(tblSelect);
3720 4631
3721 - let dtApi = jQuery($table).dataTable().api(); // NOTE: not use DataTable().
4632 + let dtApi = jQuery($table).dataTable().api(); // NOTE: not use DataTable().
3722 4633
3723 - mainwp_datatable_fix_to_update_selected_rows_status(dtApi, 'deselected'); // clear saved state.
4634 + mainwp_datatable_fix_to_update_selected_rows_status(dtApi, 'deselected'); // clear saved state.
3724 4635
3725 - $table.children('tbody').filter(':visible').find('tr').each(function () {
3726 - if (jQuery(this).children('.check-column').find(':checkbox').is(':checked')) {
3727 - jQuery(this).addClass('selected');
3728 - } else if (jQuery(this).hasClass('selected')) {
3729 - jQuery(this).removeClass('selected');
3730 - }
3731 - });
4636 + $table.children('tbody').filter(':visible').find('tr').each(function () {
4637 + if (jQuery(this).children('.check-column').find(':checkbox').is(':checked')) {
4638 + jQuery(this).addClass('selected');
4639 + } else if (jQuery(this).hasClass('selected')) {
4640 + jQuery(this).removeClass('selected');
4641 + }
4642 + });
3732 4643
3733 - mainwp_datatable_fix_to_update_selected_rows_status(dtApi, 'selected'); // to update selected state.
3734 - console.log('Datatable - update rows state.');
3735 - }
4644 + mainwp_datatable_fix_to_update_selected_rows_status(dtApi, 'selected'); // to update selected state.
4645 + }
3736 4646 }
3737 4647
3738 -window.mainwp_datatable_fix_reorder_selected_rows_status = function () {
3739 - console.log('Fixing: reordercol selected rows.');
3740 - jQuery('.table.dataTable tbody').filter(':visible').children('tr.selected').find(':checkbox').prop('checked', true);
4648 +globalThis.mainwp_datatable_fix_reorder_selected_rows_status = function () {
4649 + jQuery('.table.dataTable tbody').filter(':visible').children('tr.selected').find(':checkbox').prop('checked', true);
3741 4650 };
3742 4651
3743 4652 // fix menu overflow with scroll tables.
3744 -window.mainwp_datatable_fix_menu_overflow = function (pTableSelector, pTop, pRight) {
3745 - let dtScrollBdCls = '.dt-scroll-body';
3746 - let dtScrollCls = '.dt-scroll';
3747 - let fix_overflow = jQuery('.mainwp-content-wrap').attr('menu-overflow');
3748 - jQuery(document).on('click', 'table td.check-column.dtr-control', function () {
3749 - if (jQuery(this).parent().hasClass('parent')) {
3750 - let chilRow = jQuery(this).parent().next();
3751 - jQuery(chilRow).find('.ui.dropdown').dropdown();
3752 - mainwp_datatable_fix_child_menu_overflow(chilRow, fix_overflow);
4653 +globalThis.mainwp_datatable_fix_menu_overflow = function (pTableSelector, pTop, pRight) {
4654 + if (pTableSelector === undefined) {
4655 + console.warn('mainwp_datatable_fix_menu_overflow: requires params - $pTableSelector');
3753 4656 }
3754 - });
3755 - let tblSelect = pTableSelector ?? 'table';
4657 + let dtScrollBdCls = '.dt-scroll-body';
4658 + let dtScrollCls = '.dt-scroll';
4659 + let fix_overflow = jQuery('.mainwp-content-wrap').attr('menu-overflow');
4660 + jQuery(document).on('click', 'table td.check-column.dtr-control', function () {
4661 + if (jQuery(this).parent().hasClass('parent')) {
4662 + let chilRow = jQuery(this).parent().next();
4663 + jQuery(chilRow).find('.ui.dropdown').dropdown();
4664 + mainwp_datatable_fix_child_menu_overflow(chilRow, fix_overflow);
4665 + }
4666 + });
4667 + let tblSelect = pTableSelector ?? 'table';
3756 4668
3757 - console.log('mainwp_datatable_fix_menu_overflow :: ' + tblSelect);
4669 + // to prevent double events.
4670 + jQuery(tblSelect + ' tr td .ui.right.pointing.dropdown').each(function () {
4671 + let parentTB = jQuery(this).closest('table');
4672 + if (parentTB.attr('fixed-menu-overflow') === undefined) {
4673 + parentTB.attr('fixed-menu-overflow', 'no'); // to init click menu events.
4674 + }
4675 + });
3758 4676
3759 - // Fix the overflow prbolem for the actions menu element (right pointing menu).
3760 - jQuery(tblSelect + ' tr td .ui.right.pointing.dropdown.button').on('click', function () {
3761 - jQuery(this).closest(dtScrollBdCls).css('position', '');
3762 - jQuery(this).closest(dtScrollCls).css('position', 'relative');
3763 - jQuery(this).css('position', 'static');
3764 - let fix_overflow = jQuery('.mainwp-content-wrap').attr('menu-overflow');
3765 - let position = jQuery(this).position();
3766 - let top = position.top;
3767 - let right = 48;
3768 - if (fix_overflow > 1) {
3769 - position = jQuery(this).closest('td').position();
3770 - top = position.top + 85;
4677 + jQuery(tblSelect + ' tr td .ui.left.pointing.dropdown').each(function () {
4678 + let parentTB = jQuery(this).closest('table');
4679 + if (parentTB.attr('fixed-menu-overflow') === undefined) {
4680 + parentTB.attr('fixed-menu-overflow', 'no'); // to init click menu events.
4681 + }
4682 + });
4683 +
4684 + // if table selector specific.
4685 + if (pTableSelector !== undefined) {
4686 + if (jQuery(pTableSelector + '[fixed-menu-overflow="yes"]').length) {
4687 + jQuery(pTableSelector + '[fixed-menu-overflow="yes"]').attr('fixed-menu-overflow', 'no'); // to init menus events click.
4688 + }
3771 4689 }
3772 - if (pTop !== undefined) {
3773 - top = top + pTop;
3774 - }
3775 - if (pRight !== undefined) {
3776 - right = right + pRight;
3777 - }
3778 - console.log('right');
3779 - console.log('top: ' + top + ' right: ' + right);
3780 - jQuery(this).find('.menu').css('min-width', '170px');
3781 - jQuery(this).find('.menu').css('top', top);
3782 - jQuery(this).find('.menu')[0].style.setProperty('right', right + 'px', 'important');
3783 - });
3784 4690
3785 - // Fix the overflow prbolem for the actions menu element (left pointing menu).
3786 - jQuery(tblSelect + ' tr td .ui.left.pointing.dropdown.button').on('click', function () {
3787 - jQuery(this).closest(dtScrollBdCls).css('position', '');
3788 - jQuery(this).closest(dtScrollCls).css('position', 'relative');
3789 - jQuery(this).css('position', 'static');
3790 - let position = jQuery(this).position();
3791 4691
3792 - let top = position.top;
3793 - let left = position.left - 159;
4692 + // Fix the overflow prbolem for the actions menu element (right pointing menu).
4693 + jQuery(tblSelect + '[fixed-menu-overflow="no"] tr td .ui.right.pointing.dropdown').on('click', function () {
4694 + jQuery(this).closest(dtScrollBdCls).css('position', '');
4695 + jQuery(this).closest(dtScrollCls).css('position', 'relative');
4696 + jQuery(this).css('position', 'static');
4697 + let fix_overflow = jQuery('.mainwp-content-wrap').attr('menu-overflow');
4698 + let position = jQuery(this).position();
4699 + let top = position.top;
4700 + let right = 50;
4701 + if (fix_overflow > 1) {
4702 + position = jQuery(this).closest('td').position();
4703 + top = position.top + 85; //85
4704 + }
3794 4705
3795 - if (fix_overflow > 1) {
3796 - position = jQuery(this).closest('td').position();
3797 - let scroll_left = jQuery(this).closest(dtScrollBdCls).scrollLeft();
3798 - top = position.top + 85;
3799 - left = position.left - scroll_left - 145;
3800 - }
4706 + if (pTop !== undefined) {
4707 + top = top + pTop;
4708 + }
4709 + if (pRight !== undefined) {
4710 + right = right + pRight;
4711 + }
3801 4712
3802 - if (pTop !== undefined) {
3803 - top = top + pTop;
3804 - }
4713 + jQuery(this).find('.menu').css('min-width', '170px');
4714 + jQuery(this).find('.menu').css('top', top);
4715 + jQuery(this).find('.menu')[0].style.setProperty('right', right + 'px', 'important');
4716 + });
3805 4717
3806 - console.log('left');
3807 - console.log('top: ' + top + ' left: ' + left);
4718 + // Fix the overflow prbolem for the actions menu element (left pointing menu).
4719 + jQuery(tblSelect + '[fixed-menu-overflow="no"] tr td .ui.left.pointing.dropdown').on('click', function () {
4720 + jQuery(this).closest(dtScrollBdCls).css('position', '');
4721 + jQuery(this).closest(dtScrollCls).css('position', 'relative');
4722 + jQuery(this).css('position', 'static');
4723 + let position = jQuery(this).position();
3808 4724
3809 - jQuery(this).find('.menu').css('min-width', '150px');
3810 - jQuery(this).removeClass('left');
3811 - jQuery(this).addClass('right');
3812 - jQuery(this).find('.menu').css('top', top);
3813 - jQuery(this).find('.menu')[0].style.setProperty('left', left + 'px', 'important');
3814 - });
3815 - mainwp_datatable_fix_reorder_selected_rows_status();
4725 + let top = position.top;
4726 + let left = position.left - 159;
4727 +
4728 + if (fix_overflow > 1) {
4729 + position = jQuery(this).closest('td').position();
4730 + let scroll_left = jQuery(this).closest(dtScrollBdCls).scrollLeft();
4731 + top = position.top + 85;
4732 + left = position.left - scroll_left - 145;
4733 + }
4734 +
4735 + if (pTop !== undefined) {
4736 + top = top + pTop;
4737 + }
4738 +
4739 + jQuery(this).find('.menu').css('min-width', '150px');
4740 + jQuery(this).removeClass('left');
4741 + jQuery(this).addClass('right');
4742 + jQuery(this).find('.menu').css('top', top);
4743 + jQuery(this).find('.menu')[0].style.setProperty('left', left + 'px', 'important');
4744 + });
4745 +
4746 + jQuery(tblSelect + '[fixed-menu-overflow="no"]').each(function () {
4747 + jQuery(this).attr('fixed-menu-overflow', 'yes');
4748 + });
4749 +
4750 + mainwp_datatable_fix_reorder_selected_rows_status();
3816 4751 }
3817 4752
4753 +
3818 4754 let mainwp_datatable_fix_child_menu_overflow = function (chilRow, fix_overflow) {
3819 - let dtScrollBdCls = '.dt-scroll-body';
3820 - let dtScrollCls = '.dt-scroll';
3821 - // Fix the overflow prbolem for the actions child menu element (pointing menu).
3822 - jQuery(chilRow).find('.ui.pointing.dropdown.button').on('click', function () {
4755 + let dtScrollBdCls = '.dt-scroll-body';
4756 + let dtScrollCls = '.dt-scroll';
4757 + // Fix the overflow prbolem for the actions child menu element (pointing menu).
4758 + jQuery(chilRow).find('.ui.pointing.dropdown').on('click', function () {
3823 4759
3824 - let position = jQuery(this).position();
3825 - let left = position.left + 30;
3826 - let top = position.top;
4760 + let position = jQuery(this).position();
4761 + let left = position.left + 30;
4762 + let top = position.top;
3827 4763
3828 - if (fix_overflow > 1) {
3829 - position = jQuery(this).closest('td.child').position();
3830 - top = position.top + jQuery(this).closest('td.child').height() + 85;
3831 - }
4764 + if (fix_overflow > 1) {
4765 + position = jQuery(this).closest('td.child').position();
4766 + top = position.top + jQuery(this).closest('td.child').height() + 85;
4767 + }
3832 4768
3833 - jQuery(this).closest(dtScrollBdCls).css('position', '');
3834 - jQuery(this).closest(dtScrollCls).css('position', 'relative');
3835 - jQuery(this).css('position', 'static');
3836 - jQuery(this).find('.menu').css('top', top);
3837 - jQuery(this).find('.menu').css('left', left);
3838 - jQuery(this).find('.menu').css('min-width', '170px');
3839 - console.log('top:' + top);
3840 - });
4769 + jQuery(this).closest(dtScrollBdCls).css('position', '');
4770 + jQuery(this).closest(dtScrollCls).css('position', 'relative');
4771 + jQuery(this).css('position', 'static');
4772 + jQuery(this).find('.menu').css('top', top);
4773 + jQuery(this).find('.menu').css('left', left);
4774 + jQuery(this).find('.menu').css('min-width', '170px');
4775 + });
3841 4776 }
3842 4777
3843 4778
3844 -window.mainwp_responsive_fix_remove_child_row = function (el) {
3845 - if (jQuery(el).hasClass('dt-hasChild')) { // to fix.
3846 - jQuery(el).next().remove();
3847 - }
4779 +globalThis.mainwp_responsive_fix_remove_child_row = function (el) {
4780 + if (jQuery(el).hasClass('dt-hasChild')) { // to fix.
4781 + jQuery(el).next().remove();
4782 + }
3848 4783 }
3849 4784
3850 4785 /* eslint-disable complexity */
3851 4786 function mainwp_according_table_sorting(pObj) { // NOSONAR - complex.
3852 - let table, th, rows, switching, i, x, y, xVal, yVal, campare = false, shouldSwitch = false, dir, switchcount = 0, n, skip = 1;
3853 - table = jQuery(pObj).closest('table')[0];
3854 - let subline_skip = 2;
3855 - if ('mainwp-wordpress-updates-table' == jQuery(table).attr('id')) {
3856 - subline_skip = 1; // for rows without subline.
3857 - skip = 0;
3858 - }
4787 + let table, th, rows, switching, i, x, y, xVal, yVal, campare = false, shouldSwitch = false, dir, switchcount = 0, n, skip = 1;
4788 + table = jQuery(pObj).closest('table')[0];
4789 + let subline_skip = 2;
4790 + if ('mainwp-wordpress-updates-table' == jQuery(table).attr('id')) {
4791 + subline_skip = 1; // for rows without subline.
4792 + skip = 0;
4793 + }
3859 4794
3860 - // get TH element
3861 - if (jQuery(pObj)[0].tagName == 'TH') {
3862 - th = jQuery(pObj)[0];
3863 - } else {
3864 - th = jQuery(pObj).closest('th')[0];
3865 - }
4795 + // get TH element
4796 + if (jQuery(pObj)[0].tagName == 'TH') {
4797 + th = jQuery(pObj)[0];
4798 + } else {
4799 + th = jQuery(pObj).closest('th')[0];
4800 + }
3866 4801
3867 - n = th.cellIndex;
3868 - switching = true;
4802 + n = th.cellIndex;
4803 + switching = true;
3869 4804
3870 - // check header and footer of according table
3871 - if (jQuery(table).children('thead,tfoot').length > 0)
3872 - skip += jQuery(table).children('thead,tfoot').length; // skip sorting header, footer
4805 + // check header and footer of according table
4806 + if (jQuery(table).children('thead,tfoot').length > 0)
4807 + skip += jQuery(table).children('thead,tfoot').length; // skip sorting header, footer
3873 4808
3874 - dir = "asc";
3875 - /* loop until switching has been done: */
3876 - while (switching) {
3877 - switching = false;
3878 - rows = table.rows;
3879 - /* Loop through all table rows */
3880 - for (i = 1; i < (rows.length - skip); i += subline_skip) { // skip content according rows, sort by title rows only
3881 - shouldSwitch = false;
3882 - /* Get the two elements you want to compare,
3883 - one from current row and one from the next-next: */
3884 - x = rows[i].getElementsByTagName("TD")[n];
3885 - y = rows[i + subline_skip].getElementsByTagName("TD")[n];
4809 + dir = "asc";
4810 + /* loop until switching has been done: */
4811 + while (switching) {
4812 + switching = false;
4813 + rows = table.rows;
4814 + /* Loop through all table rows */
4815 + for (i = 1; i < (rows.length - skip); i += subline_skip) { // skip content according rows, sort by title rows only
4816 + shouldSwitch = false;
4817 + /* Get the two elements you want to compare,
4818 + one from current row and one from the next-next: */
4819 + x = rows[i].getElementsByTagName("TD")[n];
4820 + y = rows[i + subline_skip].getElementsByTagName("TD")[n];
3886 4821
3887 - // if sort value attribute existed then sorting on that else sorting on cell value
3888 - if (x.hasAttribute('sort-value')) {
3889 - xVal = parseInt(x.getAttribute('sort-value'));
3890 - yVal = parseInt(y.getAttribute('sort-value'));
3891 - let tmp = xVal > yVal ? -1 : 1;
3892 - campare = (xVal == yVal) ? 0 : tmp;
3893 - } else {
3894 - // to prevent text() clear text content
3895 - xVal = '<p>' + x.innerHTML + '</p>';
3896 - yVal = '<p>' + y.innerHTML + '</p>';
3897 - xVal = jQuery(xVal).text().trim().toLowerCase();
3898 - yVal = jQuery(yVal).text().trim().toLowerCase();
3899 - campare = yVal.localeCompare(xVal);
3900 - }
4822 + // if sort value attribute existed then sorting on that else sorting on cell value
4823 + if (x.hasAttribute('sort-value')) {
4824 + xVal = Number.parseInt(x.getAttribute('sort-value'));
4825 + yVal = Number.parseInt(y.getAttribute('sort-value'));
4826 + let tmp = xVal > yVal ? -1 : 1;
4827 + campare = (xVal == yVal) ? 0 : tmp;
4828 + } else {
4829 + // to prevent text() clear text content
4830 + xVal = '<p>' + x.innerHTML + '</p>';
4831 + yVal = '<p>' + y.innerHTML + '</p>';
4832 + xVal = jQuery(xVal).text().trim().toLowerCase();
4833 + yVal = jQuery(yVal).text().trim().toLowerCase();
4834 + campare = yVal.localeCompare(xVal);
4835 + }
3901 4836
3902 - /* Check if the two rows should switch place */
3903 - if (dir == "asc") {
3904 - if (campare < 0) { //xVal > yVal
3905 - shouldSwitch = true;
3906 - // break the loop:
3907 - break;
4837 + /* Check if the two rows should switch place */
4838 + if (dir == "asc") {
4839 + if (campare < 0) { //xVal > yVal
4840 + shouldSwitch = true;
4841 + // break the loop:
4842 + break;
4843 + }
4844 + } else if (dir == "desc") {
4845 + if (campare > 0) { //xVal < yVal
4846 + // break the loop:
4847 + shouldSwitch = true;
4848 + break;
4849 + }
4850 + }
3908 4851 }
3909 - } else if (dir == "desc") {
3910 - if (campare > 0) { //xVal < yVal
3911 - // break the loop:
3912 - shouldSwitch = true;
3913 - break;
4852 + if (shouldSwitch) {
4853 + if (2 == subline_skip) {
4854 + rows[i].parentNode.insertBefore(rows[i + 2], rows[i]);
4855 + rows[i + 1].parentNode.insertBefore(rows[i + 3], rows[i + 1]);
4856 + } else {
4857 + rows[i].parentNode.insertBefore(rows[i + 1], rows[i]); // switch 2 rows.
4858 + }
4859 + switching = true;
4860 + // increase this count by 1, that is ok
4861 + switchcount++;
4862 + } else if (switchcount == 0 && dir == "asc") {
4863 + /* If no switching has been done AND the direction is "asc",
4864 + set the direction to "desc" and run the while loop again. */
4865 + dir = "desc";
4866 + switching = true;
3914 4867 }
3915 - }
3916 4868 }
3917 - if (shouldSwitch) {
3918 - if (2 == subline_skip) {
3919 - rows[i].parentNode.insertBefore(rows[i + 2], rows[i]);
3920 - rows[i + 1].parentNode.insertBefore(rows[i + 3], rows[i + 1]);
3921 - } else {
3922 - rows[i].parentNode.insertBefore(rows[i + 1], rows[i]); // switch 2 rows.
3923 - }
3924 - switching = true;
3925 - // increase this count by 1, that is ok
3926 - switchcount++;
3927 - } else if (switchcount == 0 && dir == "asc") {
3928 - /* If no switching has been done AND the direction is "asc",
3929 - set the direction to "desc" and run the while loop again. */
3930 - dir = "desc";
3931 - switching = true;
4869 +
4870 + // no row sorting so change direction for arrows switch
4871 + if (switchcount == 0) {
4872 + if (jQuery(pObj).hasClass('ascending')) {
4873 + dir = "desc";
4874 + } else {
4875 + dir = "asc";
4876 + }
3932 4877 }
3933 - }
3934 4878
3935 - // no row sorting so change direction for arrows switch
3936 - if (switchcount == 0) {
3937 - if (jQuery(pObj).hasClass('ascending')) {
3938 - dir = "desc";
4879 + // add/remove class for arrows displaying
4880 + if (dir == "asc") {
4881 + jQuery(pObj).addClass('ascending');
4882 + jQuery(pObj).removeClass('descending');
3939 4883 } else {
3940 - dir = "asc";
4884 + jQuery(pObj).removeClass('ascending');
4885 + jQuery(pObj).addClass('descending');
3941 4886 }
3942 - }
3943 -
3944 - // add/remove class for arrows displaying
3945 - if (dir == "asc") {
3946 - jQuery(pObj).addClass('ascending');
3947 - jQuery(pObj).removeClass('descending');
3948 - } else {
3949 - jQuery(pObj).removeClass('ascending');
3950 - jQuery(pObj).addClass('descending');
3951 - }
3952 4887 }
3953 4888 /* eslint-enable complexity */
3954 4889
3955 4890 jQuery(function () {
3956 - jQuery('.handle-accordion-sorting').on('click', function () {
3957 - mainwp_according_table_sorting(this);
3958 - return false;
3959 - });
4891 + jQuery('.handle-accordion-sorting').on('click', function () {
4892 + mainwp_according_table_sorting(this);
4893 + return false;
4894 + });
3960 4895 });
3961 4896
3962 4897 // Force Dashboard to reestablish connection by destroying sessions - Part 1
3963 4898 let mainwp_force_destroy_sessions = function () {
3964 - let confirmMsg = __('Are you sure you want to force your MainWP Dashboard to reconnect with your child sites?');
3965 - mainwp_confirm(confirmMsg, function () {
3966 - mainwp_force_destroy_sessions_websites = jQuery('.dashboard_wp_id[error-status=0]').map(function (indx, el) {
3967 - return jQuery(el).val();
4899 + let confirmMsg = MainWP.I18n.t('Are you sure you want to force your MainWP Dashboard to reconnect with your child sites?');
4900 + mainwp_confirm(confirmMsg, function () {
4901 + mainwp_force_destroy_sessions_websites = jQuery('.dashboard_wp_id[error-status=0]').map(function (indx, el) {
4902 + return jQuery(el).val();
4903 + });
4904 + mainwpPopup('#mainwp-sync-sites-modal').setTitle(MainWP.I18n.t('Re-establish Connection')); // popup displayed.
4905 + mainwpPopup('#mainwp-sync-sites-modal').init({ progressMax: mainwp_force_destroy_sessions_websites.length });
4906 + mainwp_force_destroy_sessions_part_2(0);
3968 4907 });
3969 - mainwpPopup('#mainwp-sync-sites-modal').setTitle(__('Re-establish Connection')); // popup displayed.
3970 - mainwpPopup('#mainwp-sync-sites-modal').init({ progressMax: mainwp_force_destroy_sessions_websites.length });
3971 - mainwp_force_destroy_sessions_part_2(0);
3972 - });
3973 4908 };
3974 4909
3975 4910 let mainwp_force_destroy_sessions_part_2 = function (id) {
3976 - if (id >= mainwp_force_destroy_sessions_websites.length) {
3977 - mainwp_force_destroy_sessions_websites = [];
3978 - if (mainwp_force_destroy_sessions_successed == mainwp_force_destroy_sessions_websites.length) {
3979 - setTimeout(function () {
4911 + if (id >= mainwp_force_destroy_sessions_websites.length) {
4912 + mainwp_force_destroy_sessions_websites = [];
4913 + if (mainwp_force_destroy_sessions_successed == mainwp_force_destroy_sessions_websites.length) {
4914 + setTimeout(function () {
4915 + mainwpPopup('#mainwp-sync-sites-modal').close(true);
4916 + }, 3000);
4917 + }
3980 4918 mainwpPopup('#mainwp-sync-sites-modal').close(true);
3981 - }, 3000);
4919 + return;
3982 4920 }
3983 - mainwpPopup('#mainwp-sync-sites-modal').close(true);
3984 - return;
3985 - }
3986 4921
3987 - let website_id = mainwp_force_destroy_sessions_websites[id];
3988 - dashboard_update_site_status(website_id, '<i class="sync alternate loading icon"></i>');
4922 + let website_id = mainwp_force_destroy_sessions_websites[id];
4923 + dashboard_update_site_status(website_id, '<i class="sync alternate loading icon"></i>');
3989 4924
3990 - jQuery.post(ajaxurl, { 'action': 'mainwp_force_destroy_sessions', 'website_id': website_id, 'security': security_nonces['mainwp_force_destroy_sessions'] }, function (response) {
3991 - let counter = id + 1;
3992 - mainwp_force_destroy_sessions_part_2(counter);
4925 + jQuery.post(ajaxurl, { 'action': 'mainwp_force_destroy_sessions', 'website_id': website_id, 'security': security_nonces['mainwp_force_destroy_sessions'] }, function (response) {
4926 + let counter = id + 1;
4927 + mainwp_force_destroy_sessions_part_2(counter);
3993 4928
3994 - mainwpPopup('#mainwp-sync-sites-modal').setProgressSite(counter);
4929 + mainwpPopup('#mainwp-sync-sites-modal').setProgressSite(counter);
3995 4930
3996 - if ('error' in response) {
3997 - dashboard_update_site_status(website_id, '<i class="exclamation red icon"></i>');
3998 - } else if ('success' in response) {
3999 - mainwp_force_destroy_sessions_successed += 1;
4000 - dashboard_update_site_status(website_id, '<i class="check green icon"></i>', true);
4001 - } else {
4002 - dashboard_update_site_status(website_id, '<span data-inverted="" data-position="left center" data-tooltip="' + __('Process timed out. Please try again.', 'mainwp') + '">');
4003 - }
4004 - }, 'json').fail(function () {
4005 - let counter = id + 1;
4006 - mainwp_force_destroy_sessions_part_2(counter);
4007 - mainwpPopup('#mainwp-sync-sites-modal').setProgressSite(counter);
4931 + if ('error' in response) {
4932 + dashboard_update_site_status(website_id, '<i class="exclamation red icon"></i>');
4933 + } else if ('success' in response) {
4934 + mainwp_force_destroy_sessions_successed += 1;
4935 + dashboard_update_site_status(website_id, '<i class="check green icon"></i>', true);
4936 + } else {
4937 + dashboard_update_site_status(website_id, '<span data-inverted="" data-position="left center" data-tooltip="' + MainWP.I18n.t('Process timed out. Please try again.') + '">');
4938 + }
4939 + }, 'json').fail(function () {
4940 + let counter = id + 1;
4941 + mainwp_force_destroy_sessions_part_2(counter);
4942 + mainwpPopup('#mainwp-sync-sites-modal').setProgressSite(counter);
4008 4943
4009 - dashboard_update_site_status(website_id, '<i class="exclamation red icon"></i>');
4010 - });
4944 + dashboard_update_site_status(website_id, '<i class="exclamation red icon"></i>');
4945 + });
4011 4946
4012 4947 };
4013 4948
4014 4949 let mainwp_force_destroy_sessions_successed = 0;
@@ -4015,268 +4950,270 @@
4015 4950 let mainwp_force_destroy_sessions_websites = [];
4016 4951
4017 4952
4018 4953 jQuery(document).on('change', '#mainwp_archiveFormat', function () {
4019 - let zipMethod = jQuery(this).val();
4020 - zipMethod = zipMethod.replace(/\./g, '\\.');
4021 - jQuery('span.archive_info').hide();
4022 - jQuery('span#info_' + zipMethod).show();
4954 + let zipMethod = jQuery(this).val();
4955 + zipMethod = zipMethod.replaceAll('.', '\\.'); // NOSONAR - escape is correct.
4956 + jQuery('span.archive_info').hide();
4957 + jQuery('span#info_' + zipMethod).show();
4023 4958
4024 - jQuery('tr.archive_method').hide();
4025 - jQuery('tr.archive_' + zipMethod).show();
4959 + jQuery('tr.archive_method').hide();
4960 + jQuery('tr.archive_' + zipMethod).show();
4026 4961
4027 - // compare new layout
4028 - jQuery('div.archive_method').hide();
4029 - jQuery('div.archive_' + zipMethod).show();
4962 + // compare new layout
4963 + jQuery('div.archive_method').hide();
4964 + jQuery('div.archive_' + zipMethod).show();
4030 4965 });
4031 4966
4032 4967 let mainwp_import_demo_data_action = function (obj) {
4033 - let confirmation = "Are you sure you want to import demo content into your MainWP Dashboard?";
4034 - let msg_import = (jQuery(obj).attr('page-import') == 'qsw-import') ? '&message=qsw-import' : '';
4035 - mainwp_confirm(confirmation, function () {
4036 - feedback('mainwp-message-zone', '<i class="notched circle loading icon"></i> ' + __('Importing. Please wait...', 'mainwp'), '');
4037 - let data = mainwp_secure_data({
4038 - action: 'mainwp_import_demo_data',
4968 + let confirmation = "Are you sure you want to import demo content into your MainWP Dashboard?";
4969 + let msg_import = (jQuery(obj).attr('page-import') == 'qsw-import') ? '&message=qsw-import' : '';
4970 + mainwp_confirm(confirmation, function () {
4971 + feedback('mainwp-message-zone', '<i class="notched circle loading icon"></i> ' + MainWP.I18n.t('Importing. Please wait...'), '');
4972 + let data = mainwp_secure_data({
4973 + action: 'mainwp_import_demo_data',
4974 + });
4975 +
4976 + jQuery.post(ajaxurl, data, function (response) {
4977 + let error = false;
4978 + if (response.count === undefined) {
4979 + error = true;
4980 + feedback('mainwp-message-zone', MainWP.I18n.t('Undefined error. Please try again.'), 'green');
4981 + } else {
4982 + feedback('mainwp-message-zone', MainWP.I18n.t('The demo content has been imported into your MainWP Dashboard.'), 'green');
4983 + }
4984 +
4985 + if (!error) {
4986 + setTimeout(function () {
4987 + mainwp_forceReload('admin.php?page=mainwp_tab' + msg_import);
4988 + }, 3000);
4989 + }
4990 + }, 'json');
4039 4991 });
4040 -
4041 - jQuery.post(ajaxurl, data, function (response) {
4042 - let error = false;
4043 - if (response.count != undefined) {
4044 - feedback('mainwp-message-zone', __('The demo content has been imported into your MainWP Dashboard.', 'mainwp'), 'green');
4045 - } else {
4046 - error = true;
4047 - feedback('mainwp-message-zone', __('Undefined error. Please try again.', 'mainwp'), 'green');
4048 - }
4049 - if (!error) {
4050 - setTimeout(function () {
4051 - window.location = 'admin.php?page=mainwp_tab' + msg_import;
4052 - }, 3000);
4053 - }
4054 - }, 'json');
4055 - });
4056 4992 }
4057 4993
4058 4994 let mainwp_remove_demo_data_action = function () {
4059 - let confirmation = "Are you sure you want to delete demo content from your MainWP Dashboard?";
4060 - mainwp_confirm(confirmation, function () {
4061 - feedback('mainwp-message-zone', '<i class="notched circle loading icon"></i> ' + __('Deleting. Please wait...', 'mainwp'), '');
4062 - let data = mainwp_secure_data({
4063 - action: 'mainwp_delete_demo_data',
4995 + let confirmation = "Are you sure you want to delete demo content from your MainWP Dashboard?";
4996 + mainwp_confirm(confirmation, function () {
4997 + feedback('mainwp-message-zone', '<i class="notched circle loading icon"></i> ' + MainWP.I18n.t('Deleting. Please wait...'), '');
4998 + let data = mainwp_secure_data({
4999 + action: 'mainwp_delete_demo_data',
5000 + });
5001 + jQuery.post(ajaxurl, data, function (response) {
5002 + let error = false;
5003 + if (response.success === undefined) {
5004 + error = true;
5005 + feedback('mainwp-message-zone', MainWP.I18n.t('Undefined error. Please try again.'), 'green');
5006 + } else {
5007 + feedback('mainwp-message-zone', MainWP.I18n.t('The demo content has been deleted from your MainWP Dashboard.'), 'green');
5008 + }
5009 +
5010 + if (!error) {
5011 + setTimeout(function () {
5012 + mainwp_forceReload('admin.php?page=mainwp-setup');
5013 + }, 3000);
5014 + }
5015 +
5016 + }, 'json');
4064 5017 });
4065 - jQuery.post(ajaxurl, data, function (response) {
4066 - let error = false;
4067 - if (response.success != undefined) {
4068 - feedback('mainwp-message-zone', __('The demo content has been deleted from your MainWP Dashboard.', 'mainwp'), 'green');
4069 - } else {
4070 - error = true;
4071 - feedback('mainwp-message-zone', __('Undefined error. Please try again.', 'mainwp'), 'green');
4072 - }
4073 - if (!error) {
4074 - setTimeout(function () {
4075 - window.location = 'admin.php?page=mainwp-setup';
4076 - }, 3000);
4077 - }
4078 -
4079 - }, 'json');
4080 - });
4081 5018 }
4082 5019
4083 5020 // MainWP Tools
4084 5021 jQuery(function () {
4085 - jQuery(document).on('click', '#force-destroy-sessions-button', function () {
4086 - mainwp_force_destroy_sessions();
4087 - });
5022 + jQuery(document).on('click', '#force-destroy-sessions-button', function () {
5023 + mainwp_force_destroy_sessions();
5024 + });
4088 5025
4089 - jQuery(document).on('click', '.mainwp-import-demo-data-button', function () {
4090 - mainwp_import_demo_data_action(this);
4091 - return false; //required this return.
4092 - });
5026 + jQuery(document).on('click', '.mainwp-import-demo-data-button', function (event) {
5027 + mainwp_import_demo_data_action(this);
5028 + event.preventDefault();
5029 + });
4093 5030
4094 - jQuery(document).on('click', '.mainwp-remove-demo-data-button', function () {
4095 - mainwp_remove_demo_data_action();
4096 - return false; //required this return.
4097 - });
5031 + jQuery(document).on('click', '.mainwp-remove-demo-data-button', function () {
5032 + mainwp_remove_demo_data_action();
5033 + return false; //required this return.
5034 + });
4098 5035 });
4099 5036
4100 5037
4101 5038 let mainwp_tool_renew_connections_show = function () {
4102 - jQuery('#mainwp-tool-renew-connect-modal').modal({
4103 - allowMultiple: true,
4104 - closable: false,
4105 - onHide: function () {
4106 - location.href = 'admin.php?page=MainWPTools';
4107 - },
4108 - onShow: function () {
4109 - if (jQuery('#mainwp-tool-renew-connect-modal .mainwp_selected_sites_item.item.warning').length == 0) {
4110 - jQuery('#mainwp-tool-renew-connect-modal .mainwp-ss-select-disconnected').hide();
4111 - jQuery('#mainwp-tool-renew-connect-modal .mainwp-ss-deselect-disconnected').hide();
4112 - }
4113 - }
4114 - }).modal('show');
5039 + jQuery('#mainwp-tool-renew-connect-modal').modal({
5040 + allowMultiple: true,
5041 + closable: false,
5042 + onHide: function () {
5043 + mainwp_forceReload('admin.php?page=MainWPTools');
5044 + },
5045 + onShow: function () {
5046 + if (jQuery('#mainwp-tool-renew-connect-modal .mainwp_selected_sites_item.item.warning').length == 0) {
5047 + jQuery('#mainwp-tool-renew-connect-modal .mainwp-ss-select-disconnected').hide();
5048 + jQuery('#mainwp-tool-renew-connect-modal .mainwp-ss-deselect-disconnected').hide();
5049 + }
5050 + }
5051 + }).modal('show');
4115 5052 };
4116 5053
4117 5054 let mainwp_tool_prepare_renew_connections = function (objBtn) {
4118 5055
4119 - let errors = [];
4120 - let selected_sites = [];
4121 - mainwp_set_message_zone('#mainwp-message-zone-modal');
5056 + let errors = [];
5057 + let selected_sites = [];
5058 + mainwp_set_message_zone('#mainwp-message-zone-modal');
4122 5059
4123 - jQuery("input[name='selected_sites[]']:checked").each(function () {
4124 - selected_sites.push(jQuery(this).val());
4125 - });
4126 - if (selected_sites.length == 0) {
4127 - errors.push(__('Please select at least one website to start.'));
4128 - }
5060 + jQuery("input[name='selected_sites[]']:checked").each(function () {
5061 + selected_sites.push(jQuery(this).val());
5062 + });
5063 + if (selected_sites.length == 0) {
5064 + errors.push(MainWP.I18n.t('Please select at least one website to start.'));
5065 + }
4129 5066
4130 - if (errors.length > 0) {
4131 - mainwp_set_message_zone('#mainwp-message-zone-modal', errors.join('<br />'), 'yellow');
4132 - return;
4133 - } else {
4134 - mainwp_set_message_zone('#mainwp-message-zone-modal');
4135 - }
5067 + if (errors.length > 0) {
5068 + mainwp_set_message_zone('#mainwp-message-zone-modal', errors.join('<br />'), 'yellow');
5069 + return;
5070 + } else {
5071 + mainwp_set_message_zone('#mainwp-message-zone-modal');
5072 + }
4136 5073
4137 - let confirmation = __("This process will create a new OpenSSL Key Pair on your MainWP Dashboard and Set the new Public Key to your Child site(s). Are you sure you want to proceed?");
5074 + let confirmation = MainWP.I18n.t("This process will create a new OpenSSL Key Pair on your MainWP Dashboard and Set the new Public Key to your Child site(s). Are you sure you want to proceed?");
4138 5075
4139 - mainwp_confirm(confirmation, function () {
4140 - jQuery(objBtn).attr('disabled', true);
5076 + mainwp_confirm(confirmation, function () {
5077 + jQuery(objBtn).attr('disabled', true);
4141 5078
4142 - jQuery('#mainwp-tool-renew-connect-modal .mainwp-select-sites-wrapper').hide();
5079 + jQuery('#mainwp-tool-renew-connect-modal .mainwp-select-sites-wrapper').hide();
4143 5080
4144 - let statusEl = jQuery('#mainwp-message-zone-modal');
4145 - statusEl.html('<i class="notched circle loading icon"></i> ' + __('Please wait...'));
4146 - statusEl.show();
5081 + let statusEl = jQuery('#mainwp-message-zone-modal');
5082 + statusEl.html('<i class="notched circle loading icon"></i> ' + MainWP.I18n.t('Please wait...'));
5083 + statusEl.show();
4147 5084
4148 - let data = mainwp_secure_data({
4149 - action: 'mainwp_prepare_renew_connections',
4150 - 'sites[]': selected_sites,
4151 - });
5085 + let data = mainwp_secure_data({
5086 + action: 'mainwp_prepare_renew_connections',
5087 + 'sites[]': selected_sites,
5088 + });
4152 5089
4153 - jQuery.post(ajaxurl, data, function (response) {
4154 - let undefError = false;
4155 - if (response) {
4156 - if (response.result != '') {
4157 - jQuery('#mainwp-tool-renew-connect-modal').find('#mainwp-renew-connections-list').html(response.result);
4158 - mainwpVars.bulkInstallTotal = jQuery('#mainwp-renew-connections-list .item').length;
4159 - jQuery('#mainwp-tool-renew-connect-modal .mainwp-modal-progress').show();
4160 - jQuery('#mainwp-tool-renew-connect-modal .mainwp-modal-progress').progress({ value: 0, total: mainwpVars.bulkInstallTotal });
4161 - mainwp_tool_renew_connections_start_next();
4162 - statusEl.hide();
4163 - } else if (response.error) {
4164 - statusEl.addClass('red');
4165 - statusEl.html(response.error).fadeIn();
4166 - } else {
4167 - undefError = true;
4168 - }
4169 - } else {
4170 - undefError = true;
4171 - }
5090 + jQuery.post(ajaxurl, data, function (response) {
5091 + let undefError = false;
5092 + if (response) {
5093 + if (response.result != '') {
5094 + jQuery('#mainwp-tool-renew-connect-modal').find('#mainwp-renew-connections-list').html(response.result);
5095 + mainwpVars.bulkInstallTotal = jQuery('#mainwp-renew-connections-list .item').length;
5096 + jQuery('#mainwp-tool-renew-connect-modal .mainwp-modal-progress').show();
5097 + jQuery('#mainwp-tool-renew-connect-modal .mainwp-modal-progress').progress({ value: 0, total: mainwpVars.bulkInstallTotal });
5098 + mainwp_tool_renew_connections_start_next();
5099 + statusEl.hide();
5100 + } else if (response.error) {
5101 + statusEl.addClass('red');
5102 + statusEl.html(response.error).fadeIn();
5103 + } else {
5104 + undefError = true;
5105 + }
5106 + } else {
5107 + undefError = true;
5108 + }
4172 5109
4173 - if (undefError) {
4174 - statusEl.addClass('red');
4175 - statusEl.html(__('Undefined error occurred. Please try again.')).fadeIn();
4176 - }
4177 - }, 'json');
4178 - }, false, false, true);
5110 + if (undefError) {
5111 + statusEl.addClass('red');
5112 + statusEl.html(MainWP.I18n.t('Undefined error occurred. Please try again.')).fadeIn();
5113 + }
5114 + }, 'json');
5115 + }, false, false, true);
4179 5116 }
4180 5117
4181 5118 let connection_renew_status = function (siteId, newStatus) {
4182 - jQuery('#mainwp-renew-connections-list .renew-site-status[siteid="' + siteId + '"]').html(newStatus);
5119 + jQuery('#mainwp-renew-connections-list .renew-site-status[siteid="' + siteId + '"]').html(newStatus);
4183 5120 };
4184 5121
4185 5122 let mainwp_tool_renew_connections_start_next = function () {
4186 - while ((siteToReNew = jQuery('#mainwp-renew-connections-list .item[status="queue"]:first')) && (siteToReNew.length > 0) && (bulkInstallCurrentThreads < bulkInstallMaxThreads)) { // NOSONAR - modified outside the function.
4187 - mainwp_tool_renew_connections_start_specific(siteToReNew);
4188 - }
5123 + while ((siteToReNew = jQuery('#mainwp-renew-connections-list .item[status="queue"]:first')) && (siteToReNew.length > 0) && (bulkInstallCurrentThreads < bulkInstallMaxThreads)) { // NOSONAR - modified outside the function.
5124 + mainwp_tool_renew_connections_start_specific(siteToReNew);
5125 + }
4189 5126 }
4190 5127
4191 5128 let mainwp_tool_renew_connections_start_specific = function (siteItem) {
4192 5129
4193 - bulkInstallCurrentThreads++;
5130 + bulkInstallCurrentThreads++;
4194 5131
4195 - siteItem.attr('status', 'progress');
4196 - let siteId = siteItem.find('.renew-site-status').attr('siteid');
5132 + siteItem.attr('status', 'progress');
5133 + let siteId = siteItem.find('.renew-site-status').attr('siteid');
4197 5134
4198 - let data = mainwp_secure_data({
4199 - action: 'mainwp_renew_connections',
4200 - siteid: siteId
4201 - });
5135 + let data = mainwp_secure_data({
5136 + action: 'mainwp_renew_connections',
5137 + siteid: siteId
5138 + });
4202 5139
4203 - connection_renew_status(siteId, '<span data-inverted="" data-position="left center" data-tooltip="' + __('Processing...', 'mainwp') + '"><i class="sync alternate loading icon"></i></span>');
4204 - jQuery.post(ajaxurl, data, function (response) {
4205 - if (response.error) {
4206 - connection_renew_status(siteId, '<span data-inverted="" data-position="left center" data-tooltip="' + response.error + '"><i class="times red icon"></i></span>');
4207 - } else if (response.result == 'success') {
4208 - connection_renew_status(siteId, '<span data-inverted="" data-position="left center" data-tooltip="' + __('Renew connnection process completed successfully.', 'mainwp') + '"><i class="check green icon"></i></span>');
4209 - } else {
4210 - connection_renew_status(siteId, '<span data-inverted="" data-position="left center" data-tooltip="' + __('Undefined error.') + '"><i class="times red icon"></i></span>');
5140 + connection_renew_status(siteId, '<span data-inverted="" data-position="left center" data-tooltip="' + MainWP.I18n.t('Processing...') + '"><i class="sync alternate loading icon"></i></span>');
5141 + jQuery.post(ajaxurl, data, function (response) {
5142 + if (response.error) {
5143 + connection_renew_status(siteId, '<span data-inverted="" data-position="left center" data-tooltip="' + response.error + '"><i class="times red icon"></i></span>');
5144 + } else if (response.result == 'success') {
5145 + connection_renew_status(siteId, '<span data-inverted="" data-position="left center" data-tooltip="' + MainWP.I18n.t('Renew connnection process completed successfully.') + '"><i class="check green icon"></i></span>');
5146 + } else {
5147 + connection_renew_status(siteId, '<span data-inverted="" data-position="left center" data-tooltip="' + MainWP.I18n.t('Undefined error.') + '"><i class="times red icon"></i></span>');
4211 5148
4212 - }
4213 - bulkInstallCurrentThreads--;
4214 - bulkInstallDone++;
4215 - jQuery('#mainwp-tool-renew-connect-modal .mainwp-modal-progress').progress('set progress', bulkInstallDone);
4216 - jQuery('#mainwp-tool-renew-connect-modal .mainwp-modal-progress').find('.label').html(bulkInstallDone + '/' + mainwpVars.bulkInstallTotal + ' ' + __('Processed'));
4217 - mainwp_tool_renew_connections_start_next();
4218 - }, 'json');
5149 + }
5150 + bulkInstallCurrentThreads--;
5151 + bulkInstallDone++;
5152 + jQuery('#mainwp-tool-renew-connect-modal .mainwp-modal-progress').progress('set progress', bulkInstallDone);
5153 + jQuery('#mainwp-tool-renew-connect-modal .mainwp-modal-progress').find('.label').html(bulkInstallDone + '/' + mainwpVars.bulkInstallTotal + ' ' + MainWP.I18n.t('Processed'));
5154 + mainwp_tool_renew_connections_start_next();
5155 + }, 'json');
4219 5156 }
4220 5157
4221 5158
4222 5159 jQuery(function () {
4223 - if (jQuery('body.mainwp-ui').length > 0) {
4224 - jQuery('.mainwp-ui-page .ui.dropdown:not(.not-auto-init)').dropdown();
4225 - jQuery('.mainwp-ui-page .ui.checkbox:not(.not-auto-init)').checkbox();
4226 - jQuery('.mainwp-ui-page .ui.dropdown').filter('[init-value]').each(function () {
4227 - let values = jQuery(this).attr('init-value').split(',');
4228 - jQuery(this).dropdown('set selected', values);
4229 - });
4230 - }
5160 + if (jQuery('body.mainwp-ui').length > 0) {
5161 + jQuery('.mainwp-ui-page .ui.dropdown:not(.not-auto-init)').dropdown();
5162 + jQuery('.mainwp-ui-page .ui.checkbox:not(.not-auto-init)').checkbox();
5163 + jQuery('.mainwp-ui-page .ui.dropdown').filter('[init-value]').each(function () {
5164 + let values = jQuery(this).attr('init-value').split(',');
5165 + jQuery(this).dropdown('set selected', values);
5166 + });
5167 + }
4231 5168 });
4232 5169
4233 5170 // MainWP Action Logs
4234 5171 jQuery(document).on('click', '.mainwp-action-log-show-more', function () {
4235 - let content = jQuery(this).closest('.item').find('.mainwp-action-log-site-response').text();
4236 - jQuery('#mainwp-action-log-response-modal').modal({
4237 - closable: false,
4238 - onHide: function () {
4239 - location.reload();
4240 - }
4241 - }).modal('show');
4242 - jQuery('#mainwp-action-log-response-modal .content-response').text(content);
5172 + let content = jQuery(this).closest('.item').find('.mainwp-action-log-site-response').text();
5173 + jQuery('#mainwp-action-log-response-modal').modal({
5174 + closable: false,
5175 + onHide: function () {
5176 + location.reload();
5177 + }
5178 + }).modal('show');
5179 + jQuery('#mainwp-action-log-response-modal .content-response').text(content);
4243 5180 });
4244 5181
4245 5182 // MainWP Show Response
4246 5183 jQuery(document).on('click', '.mainwp-show-response', function () {
4247 - let content = jQuery('#mainwp-response-data-container').attr('resp-data');
4248 - jQuery('#mainwp-response-data-modal').modal({
4249 - closable: false,
4250 - onHide: function () {
4251 - jQuery('#mainwp-response-data-modal .content-response').text('');
4252 - }
4253 - }).modal('show');
4254 - jQuery('#mainwp-response-data-modal .content-response').text(content);
5184 + let content = jQuery('#mainwp-response-data-container').attr('resp-data');
5185 + jQuery('#mainwp-response-data-modal').modal({
5186 + closable: false,
5187 + onHide: function () {
5188 + jQuery('#mainwp-response-data-modal .content-response').text('');
5189 + }
5190 + }).modal('show');
5191 + jQuery('#mainwp-response-data-modal .content-response').text(content);
4255 5192 });
4256 5193
4257 5194 // Copy to clipboard for response modals.
4258 5195 jQuery(document).on('click', '.mainwp-response-copy-button', function (event) {
4259 - let modal = jQuery(this).closest('.ui.modal');
4260 - let data = jQuery(modal).find('.content.content-response').text();
4261 - let $temp_txtarea = jQuery('<textarea style="opacity:0">');
4262 - jQuery('body').append($temp_txtarea);
4263 - $temp_txtarea.val(data).trigger("select"); // to support 'copy' method.
4264 - mainwp_copy_to_clipboard(data, event);
4265 - $temp_txtarea.remove();
4266 - return false;
5196 + let modal = jQuery(this).closest('.ui.modal');
5197 + let data = jQuery(modal).find('.content.content-response').text();
5198 + let $temp_txtarea = jQuery('<textarea style="opacity:0">');
5199 + jQuery('body').append($temp_txtarea);
5200 + $temp_txtarea.val(data).trigger("select"); // to support 'copy' method.
5201 + mainwp_copy_to_clipboard(data, event);
5202 + $temp_txtarea.remove();
5203 + return false;
4267 5204 });
4268 5205
4269 5206 jQuery(function () {
4270 - if (typeof postboxes !== "undefined" && typeof mainwp_postbox_page !== "undefined") {
4271 - postboxes.add_postbox_toggles(mainwp_postbox_page);
4272 - }
4273 - mainwp_setCookie();
4274 - mainwp_getCookie();
5207 + if (typeof postboxes !== "undefined" && typeof mainwp_postbox_page !== "undefined") {
5208 + postboxes.add_postbox_toggles(mainwp_postbox_page);
5209 + }
5210 + mainwp_setCookie();
5211 + mainwp_getCookie();
4275 5212 });
4276 5213
4277 5214 jQuery(document).on('click', '.close.icon', function () {
4278 - jQuery(this).parent().hide();
5215 + jQuery(this).parent().hide();
4279 5216 });
4280 5217
4281 5218 /*
4282 5219 * to compatible
@@ -4281,186 +5218,507 @@
4281 5218 /*
4282 5219 * to compatible
4283 5220 */
4284 5221 function mainwp_setCookie() {
4285 - return false;
5222 + return false;
4286 5223 }
4287 5224
4288 5225 function mainwp_getCookie() {
4289 - return false;
5226 + return false;
4290 5227 }
4291 5228
4292 -let mainwp_setttings_fields_indicator_show = function () {
4293 - // for each header indicator.
4294 - jQuery('.settings-field-header-indicator').each(function () {
4295 - let cls = jQuery(this).attr('field-indicator-wrapper-class');
4296 - if ('' != cls && jQuery('.' + cls + ' .settings-field-icon-indicator').length > 0) {
4297 - jQuery(this).attr('style', 'display:inline-block;');
4298 - jQuery(this).addClass('visible-indicator');
5229 +let mainwp_setttings_fields_indicator_show = function (specific_header_indicator) {
5230 + if (specific_header_indicator !== undefined) {
5231 + mainwp_setttings_fields_indicator_specific_show(specific_header_indicator);
5232 + return;
4299 5233 }
4300 - });
5234 + // for each header indicator.
5235 + jQuery('.settings-field-header-indicator').each(function () {
5236 + mainwp_setttings_fields_indicator_specific_show(this);
5237 + });
4301 5238 }
4302 5239
5240 +let mainwp_setttings_fields_indicator_specific_show = function (obj) {
5241 + let cls = jQuery(obj).attr('field-indicator-wrapper-class');
5242 + if ('' != cls && jQuery('.' + cls + ' .settings-field-icon-indicator.visible-indicator').length > 0) {
5243 + jQuery(this).attr('style', 'display:inline-block;');
5244 + jQuery(this).addClass('visible-indicator');
5245 + }
5246 +}
5247 +
5248 +
4303 5249 jQuery(function ($) {
4304 - if (jQuery('.mainwp-ui-page').length) {
4305 - mainwp_setttings_fields_indicator_show();
4306 - }
5250 + if (jQuery('.mainwp-ui-page').length) {
5251 + mainwp_setttings_fields_indicator_show();
5252 + }
4307 5253
4308 - jQuery(document).on('input', '.settings-field-value-change-handler', function () {
4309 - let val = $(this).val();
4310 - mainwp_settings_fields_value_on_change(this, val);
4311 - });
5254 + jQuery(document).on('input', '.settings-field-value-change-handler', function () {
5255 + let val = $(this).val();
5256 + mainwp_settings_fields_value_on_change(this, val);
5257 + });
4312 5258
4313 - jQuery(document).on('change', '.settings-field-value-change-handler', function () { // NOSONAR - complex ok.
4314 - let me = this;
4315 - let objName = $(this).prop('tagName'), val;
4316 - if ('DIV' === objName) { // ui dropdown select.
4317 - val = $(this).dropdown('get value');
4318 - } else if ($(this).is(':checkbox')) {
4319 - val = $(this).is(":checked") ? '1' : '0';
4320 - if ($(this).attr('name') === 'mainwp_show_widgets[]') {
4321 - if ($('input[type="checkbox"][name="mainwp_show_widgets[]"]:not(:checked)').length == 0) {
4322 - val = 'all';
5259 + jQuery(document).on('change', '.settings-field-value-change-handler', function () { // NOSONAR - complex ok.
5260 + let objName = $(this).prop('tagName'), val;
5261 + let me; // to fix some special case indicator not at same level with input, need to find by name.
5262 +
5263 + if ('DIV' === objName) { // ui dropdown select.
5264 + val = $(this).dropdown('get value');
5265 + } else if ($(this).is(':checkbox')) {
5266 + val = $(this).is(":checked") ? '1' : '0';
5267 + if ($(this).attr('name') === 'mainwp_show_widgets[]') {
5268 + if ($('input[type="checkbox"][name="mainwp_show_widgets[]"]:not(:checked)').length == 0) {
5269 + val = 'all';
5270 + }
5271 + } else if ($(this).attr('inverted-value')) {
5272 + val = val === '1' ? '0' : '1'; // to fix compatible with some case checked is disable, value is 0.
5273 + }
5274 + } else {
5275 + val = $(this).val();
5276 + if ($(this).attr('name') === 'mainwp_rest_api_key_edit_pers') {
5277 + val = val.split(',').length;
5278 + } else if ($(this).attr('name') === 'cost_tracker_custom_product_types[title][]') {
5279 + val = $('input[name="cost_tracker_custom_product_types[title][]"]').length; // default 0.
5280 + me = $('.settings-field-indicator-wrapper.default-product-categories');
5281 + } else if ($(this).attr('name') === 'cost_tracker_custom_payment_methods[title][]') {
5282 + val = $('input[name="cost_tracker_custom_payment_methods[title][]"]').length; // default 0.
5283 + me = $('.settings-field-indicator-wrapper.custom-payment-methods');
5284 + }
4323 5285 }
4324 - } else if ($(this).attr('inverted-value')) {
4325 - val = val === '1' ? '0' : '1'; // to fix compatible with some case checked is disable, value is 0.
4326 - }
4327 - } else {
4328 - val = $(this).val();
4329 - if ($(this).attr('name') === 'mainwp_rest_api_key_edit_pers') {
4330 - val = val.split(',').length;
4331 - } else if ($(this).attr('name') === 'cost_tracker_custom_product_types[title][]') {
4332 - val = $('input[name="cost_tracker_custom_product_types[title][]"]').length; // default 0.
4333 - me = $('.settings-field-indicator-wrapper.default-product-categories');
4334 - } else if ($(this).attr('name') === 'cost_tracker_custom_payment_methods[title][]') {
4335 - val = $('input[name="cost_tracker_custom_payment_methods[title][]"]').length; // default 0.
4336 - me = $('.settings-field-indicator-wrapper.custom-payment-methods');
4337 - }
5286 +
5287 + if (me === undefined) {
5288 + mainwp_settings_fields_value_on_change(this, val);
5289 + } else {
5290 + mainwp_settings_fields_value_on_change(me, val);
5291 + }
5292 + });
5293 +
5294 + let mainwp_settings_fields_value_on_change = function (obj, val) {
5295 + let parent = $(obj).closest('.settings-field-indicator-wrapper');
5296 + if (parent.length) {
5297 + let defval = $(parent).attr('default-indi-value') ?? ''; // put default-indi-value at wrapper because semantic ui some case move class of input too input's parent.
5298 + let indiObj = parent.find('.settings-field-icon-indicator');
5299 + if (indiObj.length) {
5300 + if (val == defval || ('0' == val && '' === defval)) { // empty and zero are same.
5301 + $(indiObj).removeClass('visible-indicator');
5302 + } else {
5303 + $(indiObj).addClass('visible-indicator');
5304 + }
5305 + }
5306 + }
4338 5307 }
4339 - console.log(objName);
4340 - console.log(val);
4341 - mainwp_settings_fields_value_on_change(me, val);
4342 - });
5308 +});
4343 5309
4344 - let mainwp_settings_fields_value_on_change = function (obj, val) {
4345 - let parent = $(obj).closest('.settings-field-indicator-wrapper');
4346 - if (parent.length) {
4347 - let defval = $(parent).attr('default-indi-value') ?? ''; // put default-indi-value at wrapper because semantic ui some case move class of input too input's parent.
4348 - let indiObj = parent.find('.settings-field-icon-indicator');
4349 - if (indiObj.length) {
4350 - console.log('value: ' + val + ' - default: ' + defval);
4351 - if (val == defval || ('0' == val && '' === defval)) { // empty and zero are same.
4352 - $(indiObj).removeClass('visible-indicator');
4353 - } else {
4354 - $(indiObj).addClass('visible-indicator');
5310 +
5311 +
5312 +let mainwp_common_filter_show_segments_modal = function (loadCallback) {
5313 + jQuery('#mainwp-common-filter-segment-modal').modal({
5314 + allowMultiple: false,
5315 + onShow: function () {
5316 + if (typeof loadCallback == 'function') {
5317 + loadCallback();
5318 + }
4355 5319 }
4356 - }
5320 + }).modal('show');
5321 +};
5322 +
5323 +jQuery(function ($) {
5324 + if (!globalThis.mainwpSegmentModalUiHandle) {
5325 + globalThis.mainwpSegmentModalUiHandle = (function () {
5326 + let _instance = {
5327 + loadingStatus: function () {
5328 + $('#mainwp-common-filter-edit-segment-status').html('<i class="notched circle loading icon"></i> ' + MainWP.I18n.t('Loading segments. Please wait...')).show();
5329 + },
5330 + savingStatus: function () {
5331 + $('#mainwp-common-filter-edit-segment-status').html('<i class="notched circle loading icon"></i> ' + MainWP.I18n.t('Saving segment. Please wait...')).show();
5332 + },
5333 + deletingStatus: function () {
5334 + $('#mainwp-common-filter-edit-segment-status').html('<i class="notched circle loading icon"></i> ' + MainWP.I18n.t('Deleting segment. Please wait...')).show();
5335 +
5336 + },
5337 + showStatus: function (status, addClass) {
5338 + if (addClass) {
5339 + $('#mainwp-common-filter-edit-segment-status').addClass(addClass);
5340 + }
5341 + $('#mainwp-common-filter-edit-segment-status').html(status).show();
5342 + },
5343 + hideSegmentStatus: function () {
5344 + $('#mainwp-common-filter-edit-segment-status').removeClass('red green').hide();
5345 + },
5346 + showSegment: function (btnObj) {
5347 + jQuery('#mainwp-common-filter-segment-modal > div.header').html(MainWP.I18n.t('Save Segment'));
5348 + jQuery('#mainwp-common-filter-segment-edit-fields').show();
5349 + jQuery('#mainwp-common-filter-edit-segment-save').show();
5350 + jQuery('#mainwp-common-filter-segment-select-fields').hide();
5351 + jQuery('#mainwp-common-filter-select-segment-choose-button').hide();
5352 + jQuery('#mainwp-common-filter-select-segment-delete-button').hide();
5353 + jQuery('#mainwp-common-filter-edit-segment-name').val(jQuery(btnObj).attr('selected-segment-name'));
5354 + this.hideSegmentStatus();
5355 + mainwp_common_filter_show_segments_modal();
5356 + },
5357 + loadSegment: function (loadCallback) {
5358 + jQuery('#mainwp-common-filter-segment-edit-fields').hide();
5359 + jQuery('#mainwp-common-filter-edit-segment-save').hide();
5360 + jQuery('#mainwp-common-filter-segment-modal > div.header').html(MainWP.I18n.t('Load Segment'));
5361 + jQuery('#mainwp-common-filter-segment-select-fields').show();
5362 + jQuery('#mainwp-common-filter-select-segment-choose-button').show();
5363 + jQuery('#mainwp-common-filter-select-segment-delete-button').show();
5364 + this.hideSegmentStatus();
5365 + mainwp_common_filter_show_segments_modal(loadCallback);
5366 + },
5367 + showResults: function (result) {
5368 + jQuery('#mainwp-common-filter-edit-segment-status').hide();
5369 + jQuery('#mainwp-common-filter-segments-lists-wrapper').html(result);
5370 + jQuery('#mainwp-common-filter-segments-lists-wrapper .ui.dropdown').dropdown();
5371 + jQuery('#mainwp-common-filter-segment-select-fields').show();
5372 + }
5373 + }
5374 + return _instance;
5375 + })();
4357 5376 }
4358 - }
4359 5377
4360 5378 });
4361 5379
5380 +let mainwp_overview_gridstack_save_layout = function (item_id, grid) {
4362 5381
5382 + if (!grid?.engine?.nodes) {
5383 + return;
5384 + }
4363 5385
4364 -let mainwp_common_filter_show_segments_modal = function (loadCallback) {
4365 - jQuery('#mainwp-common-filter-segment-modal').modal({
4366 - allowMultiple: false,
4367 - onShow: function () {
4368 - if (typeof loadCallback == 'function') {
4369 - loadCallback();
4370 - }
5386 + let orders = [];
5387 + let wgIds = [];
5388 +
5389 + grid.engine.nodes.forEach(function (node) {
5390 + if (!node?.el?.id) {
5391 + return;
5392 + }
5393 +
5394 + let obj = {
5395 + "x": node.x ?? 0,
5396 + "y": node.y ?? 0,
5397 + "w": node.w ?? 4,
5398 + "h": node.h ?? 4
5399 + };
5400 + orders.push(obj);
5401 + wgIds.push(node.el.id);
5402 + });
5403 +
5404 + if (wgIds.length === 0) {
5405 + return;
4371 5406 }
4372 - }).modal('show');
4373 -};
4374 5407
5408 + let postVars = {
5409 + action: 'mainwp_widgets_order',
5410 + page: page_sortablewidgets,
5411 + order: JSON.stringify(orders),
5412 + wgids: JSON.stringify(wgIds),
5413 + item_id: item_id,
5414 + page_widget: page_widget
5415 + };
5416 + jQuery.post(ajaxurl, mainwp_secure_data(postVars), function () { });
5417 +}
5418 +
5419 +globalThis.mainwp_init_ui_calendar = ($selectors) => {
5420 + jQuery($selectors).calendar({
5421 + type: 'date',
5422 + monthFirst: false,
5423 + today: true,
5424 + touchReadonly: false,
5425 + formatter: {
5426 + date: function (date) {
5427 + if (!date) return '';
5428 + let day = date.getDate();
5429 + let month = date.getMonth() + 1;
5430 + let year = date.getFullYear();
5431 +
5432 + if (month < 10) {
5433 + month = '0' + month;
5434 + }
5435 + if (day < 10) {
5436 + day = '0' + day;
5437 + }
5438 + return year + '-' + month + '-' + day;
5439 + }
5440 + }
5441 + });
5442 +
5443 +}
5444 +
5445 +
5446 +jQuery(document).ready(function () {
5447 + jQuery('.dt-scroll-head').css({
5448 + 'overflow-x': 'auto'
5449 + }).on('scroll', function () {
5450 + let scrollBody = jQuery(this).parent().find('.dt-scroll-body').get(0);
5451 + scrollBody.scrollLeft = this.scrollLeft;
5452 + jQuery(scrollBody).trigger('scroll');
5453 + });
5454 +});
5455 +
5456 +// Function to check valid email using regular expression.
5457 +const mainwp_validate_email = function (email) {
5458 + const re = /^[A-Za-z0-9._%+-]{1,64}@[A-Za-z0-9.-]{1,255}\.[A-Za-z]{2,}$/;
5459 + return re.test(email);
5460 +}
5461 +
5462 +
4375 5463 jQuery(function ($) {
4376 - if (!window.mainwpSegmentModalUiHandle) {
4377 - window.mainwpSegmentModalUiHandle = (function () {
4378 - let _instance = {
4379 - loadingStatus: function () {
4380 - $('#mainwp-common-filter-edit-segment-status').html('<i class="notched circle loading icon"></i> ' + __('Loading segments. Please wait...')).show();
4381 - },
4382 - savingStatus: function () {
4383 - $('#mainwp-common-filter-edit-segment-status').html('<i class="notched circle loading icon"></i> ' + __('Saving segment. Please wait...')).show();
4384 - },
4385 - deletingStatus: function () {
4386 - $('#mainwp-common-filter-edit-segment-status').html('<i class="notched circle loading icon"></i> ' + __('Deleting segment. Please wait...')).show();
4387 5464
4388 - },
4389 - showStatus: function (status, addClass) {
4390 - if (addClass) {
4391 - $('#mainwp-common-filter-edit-segment-status').addClass(addClass);
4392 - }
4393 - $('#mainwp-common-filter-edit-segment-status').html(status).show();
4394 - },
4395 - hideSegmentStatus: function () {
4396 - $('#mainwp-common-filter-edit-segment-status').removeClass('red green').hide();
4397 - },
4398 - showSegment: function (btnObj) {
4399 - jQuery('#mainwp-common-filter-segment-modal > div.header').html(__('Save Segment'));
4400 - jQuery('#mainwp-common-filter-segment-edit-fields').show();
4401 - jQuery('#mainwp-common-filter-edit-segment-save').show();
4402 - jQuery('#mainwp-common-filter-segment-select-fields').hide();
4403 - jQuery('#mainwp-common-filter-select-segment-choose-button').hide();
4404 - jQuery('#mainwp-common-filter-select-segment-delete-button').hide();
4405 - jQuery('#mainwp-common-filter-edit-segment-name').val(jQuery(btnObj).attr('selected-segment-name'));
4406 - this.hideSegmentStatus();
4407 - mainwp_common_filter_show_segments_modal();
4408 - },
4409 - loadSegment: function (loadCallback) {
4410 - jQuery('#mainwp-common-filter-segment-edit-fields').hide();
4411 - jQuery('#mainwp-common-filter-edit-segment-save').hide();
4412 - jQuery('#mainwp-common-filter-segment-modal > div.header').html(__('Load a Segment'));
4413 - jQuery('#mainwp-common-filter-segment-select-fields').show();
4414 - jQuery('#mainwp-common-filter-select-segment-choose-button').show();
4415 - jQuery('#mainwp-common-filter-select-segment-delete-button').show();
4416 - this.hideSegmentStatus();
4417 - mainwp_common_filter_show_segments_modal(loadCallback);
4418 - },
4419 - showResults: function (result) {
4420 - jQuery('#mainwp-common-filter-edit-segment-status').hide();
4421 - jQuery('#mainwp-common-filter-segments-lists-wrapper').html(result);
4422 - jQuery('#mainwp-common-filter-segments-lists-wrapper .ui.dropdown').dropdown();
4423 - jQuery('#mainwp-common-filter-segment-select-fields').show();
5465 + $(document).on('click', '#delete_uptime_monitor_btn', function () {
5466 + let is_sub = $('#monitor_edit_is_sub_url')?.val();
5467 +
5468 + let confirmation = MainWP.I18n.t("Are you sure you want to delete this uptime monitor?");
5469 +
5470 + if (is_sub) {
5471 + confirmation = MainWP.I18n.t("Are you sure you want to delete this uptime sub-page monitor?");
4424 5472 }
4425 - }
4426 - return _instance;
4427 - })();
4428 - }
5473 +
5474 + mainwp_confirm(confirmation, () => {
5475 + let wpid = $('#mainwp_edit_monitor_site_id').val();
5476 + let moid = $('#mainwp_edit_monitor_id').val();
5477 +
5478 + mainwp_uptime_monitoring_remove(wpid, moid);
5479 + }, false, false, true);
5480 + });
5481 +
5482 + let mainwp_uptime_monitoring_remove = function (wpid, moid) {
5483 +
5484 + feedback('mainwp-message-zone', '<i class="notched circle loading icon"></i> ' + MainWP.I18n.t('Removing Uptime Monitor...'), 'green');
5485 +
5486 + let data = mainwp_secure_data({
5487 + action: 'mainwp_uptime_monitoring_remove_monitor',
5488 + wpid: wpid,
5489 + moid: moid
5490 + });
5491 +
5492 + jQuery.post(ajaxurl, data, function (response) {
5493 + if (response?.success) {
5494 + feedback('mainwp-message-zone', MainWP.I18n.t('Monitor have been removed.'), 'green');
5495 + setTimeout(function () {
5496 + mainwp_forceReload('admin.php?page=managesites&id=' + wpid);
5497 + }, 2000);
5498 +
5499 + } else if (response?.error) {
5500 + feedback('mainwp-message-zone', response.error, 'red');
5501 + } else {
5502 + feedback('mainwp-message-zone', MainWP.I18n.t('Undefined error. Please try again.'), 'red');
5503 + }
5504 + }, 'json');
5505 + return false;
5506 + };
5507 +
5508 + $(document).on('click', '#increase-connection-security-btn', function () {
5509 + feedback('mainwp-message-zone', '<i class="notched circle loading icon"></i> ' + MainWP.I18n.t('Encryption in progress! Securing your OpenSSL private keys, this may take a few moments. Please wait until completed.'), 'green');
5510 + let data = mainwp_secure_data({
5511 + action: 'mainwp_increase_connection_security',
5512 + });
5513 + jQuery.post(ajaxurl, data, function (response) {
5514 + if (response?.success) {
5515 + setTimeout(function () {
5516 + mainwp_forceReload();
5517 + }, 2000);
5518 +
5519 + } else if (response?.error) {
5520 + feedback('mainwp-message-zone', response.error, 'red');
5521 + } else {
5522 + feedback('mainwp-message-zone', MainWP.I18n.t('Undefined error. Please try again.'), 'red');
5523 + }
5524 + }, 'json');
5525 + return false;
5526 + });
5527 + jQuery('#module-update-logs-db-requirement').on('click', function () {
5528 + let msg = MainWP.I18n.t('Are you sure?');
5529 + mainwp_confirm(msg, () => {
5530 + jQuery(this).closest('.ui.message').fadeOut();
5531 + mainwp_module_logs_start_update_dismissed_db();
5532 + });
5533 + return false;
5534 + });
4429 5535 });
4430 5536
4431 -window.mainwp_init_ui_calendar = ($selectors) => {
4432 - jQuery($selectors).calendar({
4433 - type: 'date',
4434 - monthFirst: false,
4435 - today: true,
4436 - touchReadonly: false,
4437 - formatter: {
4438 - date: function (date) {
4439 - if (!date) return '';
4440 - let day = date.getDate();
4441 - let month = date.getMonth() + 1;
4442 - let year = date.getFullYear();
4443 5537
4444 - if (month < 10) {
4445 - month = '0' + month;
5538 +jQuery(document).on('click', '#mainwp-sites-changes-filter-toggle-button', function () {
5539 + jQuery('#mainwp-module-log-filters-row').toggle(300);
5540 + return false;
5541 +});
5542 +
5543 +jQuery(document).on('click', '#mainwp-insights-filter-toggle-button', function () {
5544 + jQuery('#mainwp-module-log-overview-sub-header').toggle(300);
5545 + return false;
5546 +});
5547 +
5548 +
5549 +
5550 +let logs_update_db_cancelled = false;
5551 +let mainwp_module_logs_start_update_dismissed_db = function () {
5552 + let data = mainwp_secure_data({
5553 + action: 'mainwp_module_log_update_dismissed_db',
5554 + });
5555 + if (logs_update_db_cancelled) {
5556 + mainwp_set_message_zone('#module-log-update-dissmised-logs-running', '<i class="close icon"></i>' + MainWP.I18n.t("User cancelled the 'Sites Changes' database update process."), 'green');
5557 + } else {
5558 + mainwp_set_message_zone('#module-log-update-dissmised-logs-running', '<i class="ui active inline loader tiny"></i> ' + MainWP.I18n.t('Updating the \'Sites Changes\' database. Click %1here%2 to cancel.', '<a href="javascript:void(0);" id="module-update-logs-db-cancel">', '</a>'), 'green');
5559 + }
5560 + jQuery.post(ajaxurl, data, function (response) {
5561 + let status = response?.status ?? '';
5562 + if (response.error) {
5563 + mainwp_set_message_zone('#module-log-update-dissmised-logs-running', '<i class="close icon"></i>' + response.error, 'red');
5564 + } else if (status === 'finished') {
5565 + mainwp_set_message_zone('#module-log-update-dissmised-logs-running', '<i class="close icon"></i>' + MainWP.I18n.t('Logs records has been updated successfully.'), 'green');
5566 + } else if (status === 'running' && !logs_update_db_cancelled) {
5567 + setTimeout(function () {
5568 + mainwp_module_logs_start_update_dismissed_db();
5569 + }, 500);
4446 5570 }
4447 - if (day < 10) {
4448 - day = '0' + day;
5571 + }, 'json');
5572 +}
5573 +
5574 +jQuery(document).on('click', '#module-update-logs-db-cancel', function () {
5575 + logs_update_db_cancelled = true;
5576 + let data = mainwp_secure_data({
5577 + action: 'mainwp_module_log_cancel_update_dismissed_db',
5578 + });
5579 + jQuery(this).closest('.ui.message').fadeOut(300);
5580 + jQuery.post(ajaxurl, data, function (response) {
5581 + //ok.
5582 + }, 'json');
5583 + return false;
5584 +});
5585 +
5586 +
5587 +
5588 +let get_local_date_string = function () {
5589 + const today = new Date();
5590 + const y = today.getFullYear();
5591 + const m = String(today.getMonth() + 1).padStart(2, '0'); // month starts from 0
5592 + const d = String(today.getDate()).padStart(2, '0');
5593 + return `${y}-${m}-${d}`;
5594 +}
5595 +
5596 +function mainwp_forceReload(targetUrl) {
5597 + const url = targetUrl || globalThis.location.href;
5598 + // Navigate to URL (force reload from server)
5599 + globalThis.location.href = url;
5600 +}
5601 +
5602 +class TablePersistentState {
5603 + constructor(table, options = {}) {
5604 + if (!table || !(table instanceof HTMLElement)) {
5605 + throw new Error('TablePersistentState requires a table element');
4449 5606 }
4450 - return year + '-' + month + '-' + day;
4451 - }
5607 +
5608 + this.table = table;
5609 + this.tableId = table.id;
5610 + this.headers = table.querySelectorAll(
5611 + options.headerSelector || '.handle-cols-sorting'
5612 + );
5613 +
5614 + this.options = {
5615 + storage: options.storage !== false, // default true
5616 + storagePrefix: options.storagePrefix || 'mainwp_tables_sort_state',
5617 + onPersist: options.onPersist || null,
5618 + defaultSort: options.defaultSort || null, // column, direction
5619 + };
5620 +
5621 + this.init();
4452 5622 }
4453 - });
4454 5623
4455 -}
5624 + /* ---------- Storage ---------- */
4456 5625
5626 + get storageKey() {
5627 + return `${this.options.storagePrefix}:${this.tableId}`;
5628 + }
4457 5629
4458 -jQuery( document ).ready( function () {
4459 - jQuery('.dt-scroll-head').css({
4460 - 'overflow-x':'auto'
4461 - }).on('scroll', function(e){
4462 - let scrollBody = jQuery(this).parent().find('.dt-scroll-body').get(0);
4463 - scrollBody.scrollLeft = this.scrollLeft;
4464 - jQuery(scrollBody).trigger('scroll');
4465 - });
4466 -} );
5630 + saveState(column, direction) {
5631 + if (!this.options.storage || !this.tableId) return;
5632 +
5633 + localStorage.setItem(
5634 + this.storageKey,
5635 + JSON.stringify({ column, direction })
5636 + );
5637 + }
5638 +
5639 + loadState() {
5640 + if (!this.options.storage || !this.tableId) return null;
5641 +
5642 + try {
5643 + return JSON.parse(localStorage.getItem(this.storageKey));
5644 + } catch {
5645 + return null;
5646 + }
5647 + }
5648 +
5649 + /* ---------- UI helpers ---------- */
5650 +
5651 + clearIndicators() {
5652 + this.headers.forEach(th => {
5653 + th.classList.remove('sorted-asc', 'sorted-desc');
5654 + th.removeAttribute('aria-sort');
5655 + });
5656 + }
5657 +
5658 + applyIndicator(th, direction) {
5659 + th.classList.add(direction === 'asc' ? 'sorted-asc' : 'sorted-desc');
5660 + th.setAttribute('aria-sort', direction);
5661 + }
5662 +
5663 + toggleDirection(current) {
5664 + return current === 'asc' ? 'desc' : 'asc';
5665 + }
5666 +
5667 + /* ---------- Sorting flow ---------- */
5668 +
5669 + persistState(column, direction, th = null, persist = true, isrestore = false) {
5670 + if (th) {
5671 + this.clearIndicators();
5672 + this.applyIndicator(th, direction);
5673 + }
5674 +
5675 + if (persist) {
5676 + this.saveState(column, direction);
5677 + }
5678 +
5679 + if (typeof this.options.onPersist === 'function') {
5680 + this.options.onPersist({
5681 + table: this.table,
5682 + column,
5683 + direction,
5684 + isrestore
5685 + });
5686 + }
5687 + }
5688 +
5689 + /* ---------- Init ---------- */
5690 +
5691 + restore() {
5692 + const saved = this.loadState() || this.options.defaultSort;
5693 + if (!saved) return;
5694 +
5695 + const th = this.table.querySelector(
5696 + `[data-key="${saved.column}"]`
5697 + );
5698 +
5699 + if (th) {
5700 + this.persistState(saved.column, saved.direction, th, false, true);
5701 + }
5702 + }
5703 +
5704 + bindEvents() {
5705 + this.headers.forEach(th => {
5706 + th.addEventListener('click', () => {
5707 + const column = th.dataset.key;
5708 + const isAsc = th.classList.contains('sorted-asc');
5709 + const direction = this.toggleDirection(isAsc ? 'asc' : 'desc');
5710 +
5711 + this.persistState(column, direction, th);
5712 + });
5713 + });
5714 + }
5715 +
5716 + init() {
5717 + if (!this.tableId && this.options.storage) {
5718 + console.warn('TablePersistentState: table has no id, storage disabled');
5719 + }
5720 +
5721 + this.restore();
5722 + this.bindEvents();
5723 + }
5724 +}